@voxket-ai/voxket-live 1.1.44 → 1.1.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/index.cjs +14 -8
- package/dist/index.js +542 -531
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var eT=Object.defineProperty;var tT=(e,t,n)=>t in e?eT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ie=(e,t,n)=>tT(e,typeof t!="symbol"?t+"":t,n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const O=require("react"),m=require("react/jsx-runtime"),jd=require("clsx"),kt=require("lucide-react"),nT=require("@emotion/styled");require("@emotion/react");const iT=require("react-dom/client");function rT(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const D=rT(O);function sT(e,t){return t.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(i){if(i!=="default"&&!(i in e)){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}})}),Object.freeze(e)}var oT=Object.defineProperty,aT=(e,t,n)=>t in e?oT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lf=(e,t,n)=>aT(e,typeof t!="symbol"?t+"":t,n);class dn{constructor(){Lf(this,"_locking"),Lf(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let t;const n=new Promise(r=>t=()=>{this._locks-=1,r()}),i=this._locking.then(()=>t);return this._locking=this._locking.then(()=>n),i}}function Et(e,t){if(!e)throw new Error(t)}const cT=34028234663852886e22,lT=-34028234663852886e22,uT=4294967295,dT=2147483647,hT=-2147483648;function ca(e){if(typeof e!="number")throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>dT||e<hT)throw new Error("invalid int 32: "+e)}function hu(e){if(typeof e!="number")throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>uT||e<0)throw new Error("invalid uint 32: "+e)}function ey(e){if(typeof e!="number")throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>cT||e<lT))throw new Error("invalid float 32: "+e)}const ty=Symbol("@bufbuild/protobuf/enum-type");function fT(e){const t=e[ty];return Et(t,"missing enum type on enum object"),t}function ny(e,t,n,i){e[ty]=iy(t,n.map(r=>({no:r.no,name:r.name,localName:e[r.no]})))}function iy(e,t,n){const i=Object.create(null),r=Object.create(null),s=[];for(const o of t){const a=ry(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:e,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function pT(e,t,n){const i={};for(const r of t){const s=ry(r);i[s.localName]=s.no,i[s.no]=s.localName}return ny(i,e,t),i}function ry(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Ud{equals(t){return this.getType().runtime.util.equals(this.getType(),this,t)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(t,n){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(n);return r.readMessage(this,s.readerFactory(t),t.byteLength,s),this}fromJson(t,n){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(n);return r.readMessage(i,t,s,this),this}fromJsonString(t,n){let i;try{i=JSON.parse(t)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,n)}toBinary(t){const n=this.getType(),i=n.runtime.bin,r=i.makeWriteOptions(t),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(t){const n=this.getType(),i=n.runtime.json,r=i.makeWriteOptions(t);return i.writeMessage(this,r)}toJsonString(t){var n;const i=this.toJson(t);return JSON.stringify(i,null,(n=t==null?void 0:t.prettySpaces)!==null&&n!==void 0?n:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function mT(e,t,n,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(a){e.util.initFields(this),e.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new Ud),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return e.util.equals(o,a,c)}}),o}function gT(){let e=0,t=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,(n&128)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Zc(e,t,n){for(let s=0;s<28;s=s+7){const o=e>>>s,a=!(!(o>>>7)&&t==0),c=(a?o|128:o)&255;if(n.push(c),!a)return}const i=e>>>28&15|(t&7)<<4,r=t>>3!=0;if(n.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=t>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(n.push(c),!a)return}n.push(t>>>31&1)}}const la=4294967296;function Ff(e){const t=e[0]==="-";t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function s(o,a){const c=Number(e.slice(o,a));r*=n,i=i*n+c,i>=la&&(r=r+(i/la|0),i=i%la)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?oy(i,r):Bd(i,r)}function bT(e,t){let n=Bd(e,t);const i=n.hi&2147483648;i&&(n=oy(n.lo,n.hi));const r=sy(n.lo,n.hi);return i?"-"+r:r}function sy(e,t){if({lo:e,hi:t}=yT(e,t),t<=2097151)return String(la*t+e);const n=e&16777215,i=(e>>>24|t<<8)&16777215,r=t>>16&65535;let s=n+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const c=1e7;return s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+jf(o)+jf(s)}function yT(e,t){return{lo:e>>>0,hi:t>>>0}}function Bd(e,t){return{lo:e|0,hi:t|0}}function oy(e,t){return t=~t,e?e=~e+1:t+=1,Bd(e,t)}const jf=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Uf(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e=e>>>7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e=e>>7;t.push(1)}}function vT(){let e=this.buf[this.pos++],t=e&127;if((e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<7,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<14,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<21,(e&128)==0)return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let n=5;(e&128)!==0&&n<10;n++)e=this.buf[this.pos++];if((e&128)!=0)throw new Error("invalid varint");return this.assertBounds(),t>>>0}function xT(){const e=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof e.getBigInt64=="function"&&typeof e.getBigUint64=="function"&&typeof e.setBigInt64=="function"&&typeof e.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>s||l<r)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return e.setBigInt64(0,this.parse(c),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(c){return e.setBigInt64(0,this.uParse(c),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(c,l){return e.setInt32(0,c,!0),e.setInt32(4,l,!0),e.getBigInt64(0,!0)},uDec(c,l){return e.setInt32(0,c,!0),e.setInt32(4,l,!0),e.getBigUint64(0,!0)}}}const n=r=>Et(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>Et(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),n(r),Ff(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),Ff(r)},dec(r,s){return bT(r,s)},uDec(r,s){return sy(r,s)}}}const yt=xT();var ee;(function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"})(ee||(ee={}));var Vi;(function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"})(Vi||(Vi={}));function Ai(e,t,n){if(t===n)return!0;if(e==ee.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==n[i])return!1;return!0}switch(e){case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return t==n}return!1}function os(e,t){switch(e){case ee.BOOL:return!1;case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return t==0?yt.zero:"0";case ee.DOUBLE:case ee.FLOAT:return 0;case ee.BYTES:return new Uint8Array(0);case ee.STRING:return"";default:return 0}}function ay(e,t){switch(e){case ee.BOOL:return t===!1;case ee.STRING:return t==="";case ee.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Nt;(function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"})(Nt||(Nt={}));class kT{constructor(t){this.stack=[],this.textEncoder=t??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let r=0;r<this.chunks.length;r++)t+=this.chunks[r].length;let n=new Uint8Array(t),i=0;for(let r=0;r<this.chunks.length;r++)n.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,n){return this.uint32((t<<3|n)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(hu(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return ca(t),Uf(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let n=this.textEncoder.encode(t);return this.uint32(n.byteLength),this.raw(n)}float(t){ey(t);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,t,!0),this.raw(n)}double(t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),this.raw(n)}fixed32(t){hu(t);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!0),this.raw(n)}sfixed32(t){ca(t);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,t,!0),this.raw(n)}sint32(t){return ca(t),t=(t<<1^t>>31)>>>0,Uf(t,this.buf),this}sfixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),r=yt.enc(t);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}fixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),r=yt.uEnc(t);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}int64(t){let n=yt.enc(t);return Zc(n.lo,n.hi,this.buf),this}sint64(t){let n=yt.enc(t),i=n.hi>>31,r=n.lo<<1^i,s=(n.hi<<1|n.lo>>>31)^i;return Zc(r,s,this.buf),this}uint64(t){let n=yt.uEnc(t);return Zc(n.lo,n.hi,this.buf),this}}class ST{constructor(t,n){this.varint64=gT,this.uint32=vT,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=n??new TextDecoder}tag(){let t=this.uint32(),n=t>>>3,i=t&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(t,n){let i=this.pos;switch(t){case Nt.Varint:for(;this.buf[this.pos++]&128;);break;case Nt.Bit64:this.pos+=4;case Nt.Bit32:this.pos+=4;break;case Nt.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Nt.StartGroup:for(;;){const[s,o]=this.tag();if(o===Nt.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return yt.dec(...this.varint64())}uint64(){return yt.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),i=-(t&1);return t=(t>>>1|(n&1)<<31)^i,n=n>>>1^i,yt.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return yt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return yt.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 t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(){return this.textDecoder.decode(this.bytes())}}function wT(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=t.split(".").pop(),s.jsonName="[".concat(t,"]"),r=e.util.newFieldList([s]).list()[0]}return r},runtime:e}}function cy(e){const t=e.field.localName,n=Object.create(null);return n[t]=TT(e),[n,()=>n[t]]}function TT(e){const t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return os(t.T,t.L);case"message":const n=t.T,i=new n;return n.fieldWrapper?n.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function CT(e,t){if(!t.repeated&&(t.kind=="enum"||t.kind=="scalar")){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(n=>n.no===t.no)}let fi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),uc=[];for(let e=0;e<fi.length;e++)uc[fi[e].charCodeAt(0)]=e;uc[45]=fi.indexOf("+");uc[95]=fi.indexOf("/");const ly={dec(e){let t=e.length*3/4;e[e.length-2]=="="?t-=2:e[e.length-1]=="="&&(t-=1);let n=new Uint8Array(t),i=0,r=0,s,o=0;for(let a=0;a<e.length;a++){if(s=uc[e.charCodeAt(a)],s===void 0)switch(e[a]){case"=":r=0;case`
|
|
2
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:n[i++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:n[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:n[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return n.subarray(0,i)},enc(e){let t="",n=0,i,r=0;for(let s=0;s<e.length;s++)switch(i=e[s],n){case 0:t+=fi[i>>2],r=(i&3)<<4,n=1;break;case 1:t+=fi[r|i>>4],r=(i&15)<<2,n=2;break;case 2:t+=fi[r|i>>6],t+=fi[i&63],n=0;break}return n&&(t+=fi[r],t+="=",n==1&&(t+="=")),t}};function ET(e,t,n){dy(t,e);const i=t.runtime.bin.makeReadOptions(n),r=CT(e.getType().runtime.bin.listUnknownFields(e),t.field),[s,o]=cy(t);for(const a of r)t.runtime.bin.readField(s,i.readerFactory(a.data),t.field,a.wireType,i);return o()}function _T(e,t,n,i){dy(t,e);const r=t.runtime.bin.makeReadOptions(i),s=t.runtime.bin.makeWriteOptions(i);if(uy(e,t)){const l=e.getType().runtime.bin.listUnknownFields(e).filter(u=>u.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const u of l)e.getType().runtime.bin.onUnknownField(e,u.no,u.wireType,u.data)}const o=s.writerFactory();let a=t.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,n,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[l,u]=c.tag(),d=c.skip(u,l);e.getType().runtime.bin.onUnknownField(e,l,u,d)}}function uy(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(i=>i.no==t.field.no)}function dy(e,t){Et(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function hy(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?t[n]!==void 0:e.kind=="enum"?t[n]!==e.T.values[0].no:!ay(e.T,t[n]);case"message":return t[n]!==void 0;case"map":return Object.keys(t[n]).length>0}}function Bf(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?os(e.T,e.L):void 0;break;case"message":t[n]=void 0;break}}function pi(e,t){if(e===null||typeof e!="object"||!Object.getOwnPropertyNames(Ud.prototype).every(i=>i in e&&typeof e[i]=="function"))return!1;const n=e.getType();return n===null||typeof n!="function"||!("typeName"in n)||typeof n.typeName!="string"?!1:t===void 0?!0:n.typeName==t.typeName}function fy(e,t){return pi(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}ee.DOUBLE,ee.FLOAT,ee.INT64,ee.UINT64,ee.INT32,ee.UINT32,ee.BOOL,ee.STRING,ee.BYTES;const Vf={ignoreUnknownFields:!1},$f={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function RT(e){return e?Object.assign(Object.assign({},Vf),e):Vf}function AT(e){return e?Object.assign(Object.assign({},$f),e):$f}const Oa=Symbol(),ua=Symbol();function PT(){return{makeReadOptions:RT,makeWriteOptions:AT,readMessage(e,t,n,i){if(t==null||Array.isArray(t)||typeof t!="object")throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Jn(t)));i=i??new e;const r=new Map,s=n.typeRegistry;for(const[o,a]of Object.entries(t)){const c=e.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=r.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));r.set(c.oneof,o)}zf(i,a,c,n,e)}else{let l=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const u=s.findExtension(o.substring(1,o.length-1));if(u&&u.extendee.typeName==e.typeName){l=!0;const[d,h]=cy(u);zf(d,a,u.field,n,u),_T(i,u,h(),n)}}if(!l&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!hy(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues||!IT(r))continue}const o=r.oneof?e[r.oneof.localName].value:e[r.localName],a=Hf(r,o,t);a!==void 0&&(i[t.useProtoFieldName?r.name:r.jsonName]=a)}const s=t.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of n.runtime.bin.listUnknownFields(e)){const a=s.findExtensionFor(n.typeName,o.no);if(a&&uy(e,a)){const c=ET(e,a,t),l=Hf(a.field,c,t);l!==void 0&&(i[a.field.jsonName]=l)}}}catch(s){const o=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(e,t,n){return Hs(e,t,n??Vi.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||ay(e,t)))return da(e,t)},debug:Jn}}function Jn(e){if(e===null)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 zf(e,t,n,i,r){let s=n.localName;if(n.repeated){if(Et(n.kind!="map"),t===null)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t)));const o=e[s];for(const a of t){if(a===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(a)));switch(n.kind){case"message":o.push(n.T.fromJson(a,i));break;case"enum":const c=Xc(n.T,a,i.ignoreUnknownFields,!0);c!==ua&&o.push(c);break;case"scalar":try{o.push(Hs(n.T,a,n.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(a));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(n.kind=="map"){if(t===null)return;if(typeof t!="object"||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t)));const o=e[s];for(const[a,c]of Object.entries(t)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let l;try{l=NT(n.K,a)}catch(u){let d="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t));throw u instanceof Error&&u.message.length>0&&(d+=": ".concat(u.message)),new Error(d)}switch(n.V.kind){case"message":o[l]=n.V.T.fromJson(c,i);break;case"enum":const u=Xc(n.V.T,c,i.ignoreUnknownFields,!0);u!==ua&&(o[l]=u);break;case"scalar":try{o[l]=Hs(n.V.T,c,Vi.BIGINT,!0)}catch(d){let h="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t));throw d instanceof Error&&d.message.length>0&&(h+=": ".concat(d.message)),new Error(h)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const o=n.T;if(t===null&&o.typeName!="google.protobuf.Value")return;let a=e[s];pi(a)?a.fromJson(t,i):(e[s]=a=o.fromJson(t,i),o.fieldWrapper&&!n.oneof&&(e[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Xc(n.T,t,i.ignoreUnknownFields,!1);switch(c){case Oa:Bf(n,e);break;case ua:break;default:e[s]=c;break}break;case"scalar":try{const l=Hs(n.T,t,n.L,!1);switch(l){case Oa:Bf(n,e);break;default:e[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function NT(e,t){if(e===ee.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1;break}return Hs(e,t,Vi.BIGINT,!0).toString()}function Hs(e,t,n,i){if(t===null)return i?os(e,n):Oa;switch(e){case ee.DOUBLE:case ee.FLOAT:if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""||typeof t=="string"&&t.trim().length!==t.length||typeof t!="string"&&typeof t!="number")break;const r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==ee.FLOAT&&ey(r),r;case ee.INT32:case ee.FIXED32:case ee.SFIXED32:case ee.SINT32:case ee.UINT32:let s;if(typeof t=="number"?s=t:typeof t=="string"&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),s===void 0)break;return e==ee.UINT32||e==ee.FIXED32?hu(s):ca(s),s;case ee.INT64:case ee.SFIXED64:case ee.SINT64:if(typeof t!="number"&&typeof t!="string")break;const o=yt.parse(t);return n?o.toString():o;case ee.FIXED64:case ee.UINT64:if(typeof t!="number"&&typeof t!="string")break;const a=yt.uParse(t);return n?a.toString():a;case ee.BOOL:if(typeof t!="boolean")break;return t;case ee.STRING:if(typeof t!="string")break;try{encodeURIComponent(t)}catch{throw new Error("invalid UTF8")}return t;case ee.BYTES:if(t==="")return new Uint8Array(0);if(typeof t!="string")break;return ly.dec(t)}throw new Error}function Xc(e,t,n,i){if(t===null)return e.typeName=="google.protobuf.NullValue"?0:i?e.values[0].no:Oa;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(r!==void 0)return r.no;if(n)return ua;break}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Jn(t)))}function IT(e){return e.repeated||e.kind=="map"?!0:!(e.oneof||e.kind=="message"||e.opt||e.req)}function Hf(e,t,n){if(e.kind=="map"){Et(typeof t=="object"&&t!=null);const i={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=da(e.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(n);break;case"enum":const s=e.V.T;for(const[o,a]of r)i[o.toString()]=Jc(s,a,n.enumAsInteger);break}return n.emitDefaultValues||r.length>0?i:void 0}if(e.repeated){Et(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let r=0;r<t.length;r++)i.push(da(e.T,t[r]));break;case"enum":for(let r=0;r<t.length;r++)i.push(Jc(e.T,t[r],n.enumAsInteger));break;case"message":for(let r=0;r<t.length;r++)i.push(t[r].toJson(n));break}return n.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return da(e.T,t);case"enum":return Jc(e.T,t,n.enumAsInteger);case"message":return fy(e.T,t).toJson(n)}}function Jc(e,t,n){var i;if(Et(typeof t=="number"),e.typeName=="google.protobuf.NullValue")return null;if(n)return t;const r=e.findNumber(t);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:t}function da(e,t){switch(e){case ee.INT32:case ee.SFIXED32:case ee.SINT32:case ee.FIXED32:case ee.UINT32:return Et(typeof t=="number"),t;case ee.FLOAT:case ee.DOUBLE:return Et(typeof t=="number"),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case ee.STRING:return Et(typeof t=="string"),t;case ee.BOOL:return Et(typeof t=="boolean"),t;case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return Et(typeof t=="bigint"||typeof t=="string"||typeof t=="number"),t.toString();case ee.BYTES:return Et(t instanceof Uint8Array),ly.enc(t)}}const Er=Symbol("@bufbuild/protobuf/unknown-fields"),Wf={readUnknownFields:!0,readerFactory:e=>new ST(e)},qf={writeUnknownFields:!0,writerFactory:()=>new kT};function MT(e){return e?Object.assign(Object.assign({},Wf),e):Wf}function OT(e){return e?Object.assign(Object.assign({},qf),e):qf}function DT(){return{makeReadOptions:MT,makeWriteOptions:OT,listUnknownFields(e){var t;return(t=e[Er])!==null&&t!==void 0?t:[]},discardUnknownFields(e){delete e[Er]},writeUnknownFields(e,t){const i=e[Er];if(i)for(const r of i)t.tag(r.no,r.wireType).raw(r.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[Er])||(r[Er]=[]),r[Er].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const s=e.getType(),o=r?t.len:t.pos+n;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!(r===!0&&c==Nt.EndGroup));){const l=s.fields.find(a);if(!l){const u=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,u);continue}Gf(e,t,l,c,i)}if(r&&(c!=Nt.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:Gf,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber()){if(!hy(r,e)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?e[r.oneof.localName].value:e[r.localName];Kf(r,s,t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){t!==void 0&&Kf(e,t,n,i)}}}function Gf(e,t,n,i,r){let{repeated:s,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const a=n.kind=="enum"?ee.INT32:n.T;let c=Da;if(n.kind=="scalar"&&n.L>0&&(c=FT),s){let h=e[o];if(i==Nt.LengthDelimited&&a!=ee.STRING&&a!=ee.BYTES){let g=t.uint32()+t.pos;for(;t.pos<g;)h.push(c(t,a))}else h.push(c(t,a))}else e[o]=c(t,a);break;case"message":const l=n.T;s?e[o].push(ha(t,new l,r,n)):pi(e[o])?ha(t,e[o],r,n):(e[o]=ha(t,new l,r,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case"map":let[u,d]=LT(n,t,r);e[o][u]=d;break}}function ha(e,t,n,i){const r=t.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(t,e,s?i.no:e.uint32(),n,s),t}function LT(e,t,n){const i=t.uint32(),r=t.pos+i;let s,o;for(;t.pos<r;){const[a]=t.tag();switch(a){case 1:s=Da(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Da(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=ha(t,new e.V.T,n,void 0);break}break}}if(s===void 0&&(s=os(e.K,Vi.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),o===void 0)switch(e.V.kind){case"scalar":o=os(e.V.T,Vi.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T;break}return[s,o]}function FT(e,t){const n=Da(e,t);return typeof n=="bigint"?n.toString():n}function Da(e,t){switch(t){case ee.STRING:return e.string();case ee.BOOL:return e.bool();case ee.DOUBLE:return e.double();case ee.FLOAT:return e.float();case ee.INT32:return e.int32();case ee.INT64:return e.int64();case ee.UINT64:return e.uint64();case ee.FIXED64:return e.fixed64();case ee.BYTES:return e.bytes();case ee.FIXED32:return e.fixed32();case ee.SFIXED32:return e.sfixed32();case ee.SFIXED64:return e.sfixed64();case ee.SINT64:return e.sint64();case ee.UINT32:return e.uint32();case ee.SINT32:return e.sint32()}}function Kf(e,t,n,i){Et(t!==void 0);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s=e.kind=="enum"?ee.INT32:e.T;if(r)if(Et(Array.isArray(t)),e.packed)UT(n,s,e.no,t);else for(const o of t)Ws(n,s,e.no,o);else Ws(n,s,e.no,t);break;case"message":if(r){Et(Array.isArray(t));for(const o of t)Yf(n,i,e,o)}else Yf(n,i,e,t);break;case"map":Et(typeof t=="object"&&t!=null);for(const[o,a]of Object.entries(t))jT(n,i,e,o,a);break}}function jT(e,t,n,i,r){e.tag(n.no,Nt.LengthDelimited),e.fork();let s=i;switch(n.K){case ee.INT32:case ee.FIXED32:case ee.UINT32:case ee.SFIXED32:case ee.SINT32:s=Number.parseInt(i);break;case ee.BOOL:Et(i=="true"||i=="false"),s=i=="true";break}switch(Ws(e,n.K,1,s),n.V.kind){case"scalar":Ws(e,n.V.T,2,r);break;case"enum":Ws(e,ee.INT32,2,r);break;case"message":Et(r!==void 0),e.tag(2,Nt.LengthDelimited).bytes(r.toBinary(t));break}e.join()}function Yf(e,t,n,i){const r=fy(n.T,i);n.delimited?e.tag(n.no,Nt.StartGroup).raw(r.toBinary(t)).tag(n.no,Nt.EndGroup):e.tag(n.no,Nt.LengthDelimited).bytes(r.toBinary(t))}function Ws(e,t,n,i){Et(i!==void 0);let[r,s]=py(t);e.tag(n,r)[s](i)}function UT(e,t,n,i){if(!i.length)return;e.tag(n,Nt.LengthDelimited).fork();let[,r]=py(t);for(let s=0;s<i.length;s++)e[r](i[s]);e.join()}function py(e){let t=Nt.Varint;switch(e){case ee.BYTES:case ee.STRING:t=Nt.LengthDelimited;break;case ee.DOUBLE:case ee.FIXED64:case ee.SFIXED64:t=Nt.Bit64;break;case ee.FIXED32:case ee.SFIXED32:case ee.FLOAT:t=Nt.Bit32;break}const n=ee[e].toLowerCase();return[t,n]}function BT(){return{setEnumType:ny,initPartial(e,t){if(e===void 0)return;const n=t.getType();for(const i of n.fields.byMember()){const r=i.localName,s=t,o=e;if(o[r]!=null)switch(i.kind){case"oneof":const a=o[r].case;if(a===void 0)continue;const c=i.findField(a);let l=o[r].value;c&&c.kind=="message"&&!pi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===ee.BYTES&&(l=Cs(l)),s[r]={case:a,value:l};break;case"scalar":case"enum":let u=o[r];i.T===ee.BYTES&&(u=i.repeated?u.map(Cs):Cs(u)),s[r]=u;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===ee.BYTES)for(const[f,g]of Object.entries(o[r]))s[r][f]=Cs(g);else Object.assign(s[r],o[r]);break;case"message":const h=i.V.T;for(const f of Object.keys(o[r])){let g=o[r][f];h.fieldWrapper||(g=new h(g)),s[r][f]=g}break}break;case"message":const d=i.T;if(i.repeated)s[r]=o[r].map(h=>pi(h,d)?h:new d(h));else{const h=o[r];d.fieldWrapper?d.typeName==="google.protobuf.BytesValue"?s[r]=Cs(h):s[r]=h:s[r]=pi(h,d)?h:new d(h)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(i=>{const r=t[i.localName],s=n[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>Ai(i.T,o,s[a]));case"enum":return r.every((o,a)=>Ai(ee.INT32,o,s[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=r,a=s;return i.T.fieldWrapper&&(o!==void 0&&!pi(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!pi(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return Ai(ee.INT32,r,s);case"scalar":return Ai(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return Ai(ee.INT32,r.value,s.value);case"scalar":return Ai(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const u=i.V.T;return l.every(h=>u.equals(r[h],s[h]));case"enum":return l.every(h=>Ai(ee.INT32,r[h],s[h]));case"scalar":const d=i.V.T;return l.every(h=>Ai(d,r[h],s[h]))}break}})},clone(e){const t=e.getType(),n=new t,i=n;for(const r of t.fields.byMember()){const s=e[r.localName];let o;if(r.repeated)o=s.map(Fo);else if(r.kind=="map"){o=i[r.localName];for(const[a,c]of Object.entries(s))o[a]=Fo(c)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:Fo(s.value)}:{case:void 0}:o=Fo(s);i[r.localName]=o}for(const r of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return n}}}function Fo(e){if(e===void 0)return e;if(pi(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Cs(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function VT(e,t,n){return{syntax:e,json:PT(),bin:DT(),util:Object.assign(Object.assign({},BT()),{newFieldList:t,initFields:n}),makeMessageType(i,r,s){return mT(this,i,r,s)},makeEnum:pT,makeEnumType:iy,getEnumType:fT,makeExtension(i,r,s){return wT(this,i,r,s)}}}class $T{constructor(t,n){this._fields=t,this._normalizer=n}findJsonName(t){if(!this.jsonNames){const n={};for(const i of this.list())n[i.jsonName]=n[i.name]=i;this.jsonNames=n}return this.jsonNames[t]}find(t){if(!this.numbers){const n={};for(const i of this.list())n[i.no]=i;this.numbers=n}return this.numbers[t]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((t,n)=>t.no-n.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const t=this.members;let n;for(const i of this.list())i.oneof?i.oneof!==n&&(n=i.oneof,t.push(n)):t.push(i)}return this.members}}function my(e,t){const n=gy(e);return t?n:KT(GT(n))}function zT(e){return my(e,!1)}const HT=gy;function gy(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r);break}}return n.join("")}const WT=new Set(["constructor","toString","toJSON","valueOf"]),qT=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),by=e=>"".concat(e,"$"),GT=e=>qT.has(e)?by(e):e,KT=e=>WT.has(e)?by(e):e;class YT{constructor(t){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=t,this.localName=zT(t)}addField(t){Et(t.oneof===this,"field ".concat(t.name," not one of ").concat(this.name)),this.fields.push(t)}findField(t){if(!this._lookup){this._lookup=Object.create(null);for(let n=0;n<this.fields.length;n++)this._lookup[this.fields[n].localName]=this.fields[n]}return this._lookup[t]}}function ZT(e,t){var n,i,r,s,o,a;const c=[];let l;for(const u of typeof e=="function"?e():e){const d=u;if(d.localName=my(u.name,u.oneof!==void 0),d.jsonName=(n=u.jsonName)!==null&&n!==void 0?n:HT(u.name),d.repeated=(i=u.repeated)!==null&&i!==void 0?i:!1,u.kind=="scalar"&&(d.L=(r=u.L)!==null&&r!==void 0?r:Vi.BIGINT),d.delimited=(s=u.delimited)!==null&&s!==void 0?s:!1,d.req=(o=u.req)!==null&&o!==void 0?o:!1,d.opt=(a=u.opt)!==null&&a!==void 0?a:!1,u.packed===void 0&&(d.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=ee.BYTES&&u.T!=ee.STRING),u.oneof!==void 0){const h=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!l||l.name!=h)&&(l=new YT(h)),d.oneof=l,l.addField(d)}c.push(d)}return c}const V=VT("proto3",e=>new $T(e,t=>ZT(t)),e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated){i[n]=[];continue}switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=os(t.T,t.L);break}}});class un extends Ud{constructor(t){super(),this.seconds=yt.zero,this.nanos=0,V.util.initPartial(t,this)}fromJson(t,n){if(typeof t!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(V.json.debug(t)));const i=t.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 r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>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=yt.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(t){const n=Number(this.seconds)*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(n).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return un.fromDate(new Date)}static fromDate(t){const n=t.getTime();return new un({seconds:yt.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new un().fromBinary(t,n)}static fromJson(t,n){return new un().fromJson(t,n)}static fromJsonString(t,n){return new un().fromJsonString(t,n)}static equals(t,n){return V.util.equals(un,t,n)}}un.runtime=V;un.typeName="google.protobuf.Timestamp";un.fields=V.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const XT=V.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:JT,repeated:!0},{no:5,name:"events",kind:"message",T:eC,repeated:!0}]),JT=V.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:QT,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),QT=V.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"value",kind:"scalar",T:2}]),eC=V.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:un},{no:7,name:"normalized_end_timestamp",kind:"message",T:un,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),yy=V.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Un=V.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Lt=V.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"}]),Vd=V.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Us=V.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),to=V.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Vn=V.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"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),_r=V.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"}]),tC=V.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ht=V.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"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),dc=V.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:La,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:Ny}]),La=V.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),nC=V.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:V.getEnumType(Lt),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}]),pr=V.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:V.getEnumType(Zr)},{no:4,name:"tracks",kind:"message",T:Vr,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:nC},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:V.getEnumType(no)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:V.getEnumType(Vn)},{no:18,name:"kind_details",kind:"enum",T:V.getEnumType(iC),repeated:!0}]),Zr=V.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),no=V.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),iC=V.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),vn=V.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),rC=V.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:cr,repeated:!0}]),Vr=V.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:V.getEnumType(Un)},{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:V.getEnumType(Lt)},{no:10,name:"layers",kind:"message",T:cr,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:rC,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:V.getEnumType(vn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Ny},{no:19,name:"audio_features",kind:"enum",T:V.getEnumType(Ht),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:V.getEnumType(yy)}]),cr=V.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:V.getEnumType(Vd)},{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}]),ln=V.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:V.getEnumType(Be)},{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:xy,oneof:"value"},{no:3,name:"speaker",kind:"message",T:sC,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ky,oneof:"value"},{no:7,name:"transcription",kind:"message",T:oC,oneof:"value"},{no:8,name:"metrics",kind:"message",T:XT,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:fu,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Sy,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:wy,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ty,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:mu,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:gu,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:bu,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Be=V.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),sC=V.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:vy,repeated:!0}]),vy=V.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}]),xy=V.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}]),ky=V.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),oC=V.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:aC,repeated:!0}]),aC=V.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}]),fu=V.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}]),Sy=V.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}]),wy=V.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Ty=V.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:Cy,oneof:"value"}]),Cy=V.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}]),Ey=V.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),_y=V.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:V.getEnumType(Ry)},{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}]),Ry=V.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),cC=V.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:V.getEnumType(Ay)},{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}]),Ay=V.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"},{no:13,name:"UNREAL"}]),Py=V.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Zf},{no:2,name:"screen",kind:"message",T:Zf},{no:3,name:"resume_connection",kind:"enum",T:V.getEnumType(to)},{no:4,name:"disabled_codecs",kind:"message",T:lC},{no:5,name:"force_relay",kind:"enum",T:V.getEnumType(to)}]),Zf=V.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:V.getEnumType(to)}]),lC=V.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:La,repeated:!0},{no:2,name:"publish",kind:"message",T:La,repeated:!0}]),Ny=V.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),pu=V.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Iy=V.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:V.getEnumType(pu)},{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"}),My=V.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),mu=V.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:V.getEnumType(vn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Iy,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:My,oneof:"content_header"}],{localName:"DataStream_Header"}),gu=V.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"}),bu=V.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"}),Bn=V.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),yu=V.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),uC=V.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),dC=V.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:mr,oneof:"message"},{no:2,name:"answer",kind:"message",T:mr,oneof:"message"},{no:3,name:"trickle",kind:"message",T:$d,oneof:"message"},{no:4,name:"add_track",kind:"message",T:xu,oneof:"message"},{no:5,name:"mute",kind:"message",T:zd,oneof:"message"},{no:6,name:"subscription",kind:"message",T:hc,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Oy,oneof:"message"},{no:8,name:"leave",kind:"message",T:fc,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ly,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:By,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Vy,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Yn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Fy,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Hy,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Dy,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:gC,oneof:"message"}]),Xf=V.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:hC,oneof:"message"},{no:2,name:"answer",kind:"message",T:mr,oneof:"message"},{no:3,name:"offer",kind:"message",T:mr,oneof:"message"},{no:4,name:"trickle",kind:"message",T:$d,oneof:"message"},{no:5,name:"update",kind:"message",T:mC,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Hd,oneof:"message"},{no:8,name:"leave",kind:"message",T:fc,oneof:"message"},{no:9,name:"mute",kind:"message",T:zd,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:bC,oneof:"message"},{no:11,name:"room_update",kind:"message",T:yC,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:xC,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:SC,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:TC,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:CC,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:pC,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:fC,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:_C,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:PC,oneof:"message"},{no:22,name:"request_response",kind:"message",T:NC,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:IC,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:EC,oneof:"message"}]),vu=V.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),xu=V.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:V.getEnumType(Un)},{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:V.getEnumType(Lt)},{no:9,name:"layers",kind:"message",T:cr,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:vu,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:V.getEnumType(vn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:V.getEnumType(yy)},{no:17,name:"audio_features",kind:"enum",T:V.getEnumType(Ht),repeated:!0}]),$d=V.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:V.getEnumType(Bn)},{no:3,name:"final",kind:"scalar",T:8}]),zd=V.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),hC=V.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:dc},{no:2,name:"participant",kind:"message",T:pr},{no:3,name:"other_participants",kind:"message",T:pr,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:jy,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:Py},{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:_y},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:La,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),fC=V.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:jy,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Py},{no:3,name:"server_info",kind:"message",T:_y},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Hd=V.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Vr}]),pC=V.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),mr=V.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),mC=V.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:pr,repeated:!0}]),hc=V.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:Ey,repeated:!0}]),Oy=V.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:V.getEnumType(Vd)},{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}]),Dy=V.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:V.getEnumType(Ht),repeated:!0}]),gC=V.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}]),fc=V.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:V.getEnumType(Vn)},{no:3,name:"action",kind:"enum",T:V.getEnumType(Xr)},{no:4,name:"regions",kind:"message",T:RC}]),Xr=V.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ly=V.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:cr,repeated:!0}]),Fy=V.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}]),jy=V.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}]),bC=V.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:vy,repeated:!0}]),yC=V.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:dc}]),vC=V.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:V.getEnumType(Us)},{no:3,name:"score",kind:"scalar",T:2}]),xC=V.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:vC,repeated:!0}]),kC=V.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:V.getEnumType(yu)}]),SC=V.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:kC,repeated:!0}]),Wd=V.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:V.getEnumType(Vd)},{no:2,name:"enabled",kind:"scalar",T:8}]),wC=V.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Wd,repeated:!0}]),TC=V.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Wd,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:wC,repeated:!0}]),Uy=V.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}]),By=V.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Uy,repeated:!0}]),CC=V.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}]),EC=V.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:dc},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:pr},{no:4,name:"other_participants",kind:"message",T:pr,repeated:!0}]),Vy=V.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:mr},{no:2,name:"subscription",kind:"message",T:hc},{no:3,name:"publish_tracks",kind:"message",T:Hd,repeated:!0},{no:4,name:"data_channels",kind:"message",T:zy,repeated:!0},{no:5,name:"offer",kind:"message",T:mr},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:$y,repeated:!0}]),$y=V.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),zy=V.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:V.getEnumType(Bn)}]),Yn=V.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:V.getEnumType(uC),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"}]),Hy=V.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),_C=V.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),RC=V.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:AC,repeated:!0}]),AC=V.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}]),PC=V.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:V.getEnumType(tC)}]),NC=V.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:V.getEnumType(qd)},{no:3,name:"message",kind:"scalar",T:9}]),qd=V.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),IC=V.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function MC(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var fa={exports:{}},OC=fa.exports,Jf;function DC(){return Jf||(Jf=1,function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(OC,function(){var t=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(p,v){var b=p[v];if(typeof b.bind=="function")return b.bind(p);try{return Function.prototype.bind.call(b,p)}catch{return function(){return Function.prototype.apply.apply(b,[p,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&i?c:console[p]!==void 0?a(console,p):console.log!==void 0?a(console,"log"):t}function u(){for(var p=this.getLevel(),v=0;v<r.length;v++){var b=r[v];this[b]=v<p?t:this.methodFactory(b,p,this.name)}if(this.log=this.debug,typeof console===n&&p<this.levels.SILENT)return"No console available for logging"}function d(p){return function(){typeof console!==n&&(u.call(this),this[p].apply(this,arguments))}}function h(p,v,b){return l(p)||d.apply(this,arguments)}function f(p,v){var b=this,w,S,k,x="loglevel";typeof p=="string"?x+=":"+p:typeof p=="symbol"&&(x=void 0);function T(R){var I=(r[R]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=I;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+I+";"}catch{}}}function P(){var R;if(!(typeof window===n||!x)){try{R=window.localStorage[x]}catch{}if(typeof R===n)try{var I=window.document.cookie,L=encodeURIComponent(x),U=I.indexOf(L+"=");U!==-1&&(R=/^([^;]+)/.exec(I.slice(U+L.length+1))[1])}catch{}return b.levels[R]===void 0&&(R=void 0),R}}function A(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(R){var I=R;if(typeof I=="string"&&b.levels[I.toUpperCase()]!==void 0&&(I=b.levels[I.toUpperCase()]),typeof I=="number"&&I>=0&&I<=b.levels.SILENT)return I;throw new TypeError("log.setLevel() called with invalid level: "+R)}b.name=p,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=v||h,b.getLevel=function(){return k??S??w},b.setLevel=function(R,I){return k=N(R),I!==!1&&T(k),u.call(b)},b.setDefaultLevel=function(R){S=N(R),P()||b.setLevel(R,!1)},b.resetLevel=function(){k=null,A(),u.call(b)},b.enableAll=function(R){b.setLevel(b.levels.TRACE,R)},b.disableAll=function(R){b.setLevel(b.levels.SILENT,R)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var R in s)s[R].rebuild()},w=N(o?o.getLevel():"WARN");var y=P();y!=null&&(k=N(y)),u.call(b)}o=new f,o.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[v];return b||(b=s[v]=new f(v,o.methodFactory)),b};var g=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return s},o.default=o,o})}(fa)),fa.exports}var pc=DC(),ku;(function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"})(ku||(ku={}));var Hn;(function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"})(Hn||(Hn={}));let qe=pc.getLogger("livekit");const LC=Object.values(Hn).map(e=>pc.getLogger(e));qe.setDefaultLevel(ku.info);function xi(e){const t=pc.getLogger(e);return t.setDefaultLevel(qe.getLevel()),t}function FC(e,t){for(const n of LC)n.setLevel(e)}const jC=pc.getLogger("lk-e2ee"),Es=7e3,UC=[0,300,4*300,9*300,16*300,Es,Es,Es,Es,Es];class BC{constructor(t){this._retryDelays=t!==void 0?[...t]:UC}nextRetryDelayInMs(t){if(t.retryCount>=this._retryDelays.length)return null;const n=this._retryDelays[t.retryCount];return t.retryCount<=1?n:n+Math.random()*1e3}}function VC(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function M(e,t,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(e,t||[])).next())})}function Qf(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function mi(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Qf=="function"?Qf(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}var jo={exports:{}},ep;function $C(){if(ep)return jo.exports;ep=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(x,T,P){return Function.prototype.apply.call(x,T,P)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:n=function(x){return Object.getOwnPropertyNames(x)};function i(k){console&&console.warn&&console.warn(k)}var r=Number.isNaN||function(x){return x!==x};function s(){s.init.call(this)}jo.exports=s,jo.exports.once=b,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(k){if(typeof k!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof k)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(k){if(typeof k!="number"||k<0||r(k))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+k+".");o=k}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||r(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function c(k){return k._maxListeners===void 0?s.defaultMaxListeners:k._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(x){for(var T=[],P=1;P<arguments.length;P++)T.push(arguments[P]);var A=x==="error",N=this._events;if(N!==void 0)A=A&&N.error===void 0;else if(!A)return!1;if(A){var y;if(T.length>0&&(y=T[0]),y instanceof Error)throw y;var R=new Error("Unhandled error."+(y?" ("+y.message+")":""));throw R.context=y,R}var I=N[x];if(I===void 0)return!1;if(typeof I=="function")t(I,this,T);else for(var L=I.length,U=g(I,L),P=0;P<L;++P)t(U[P],this,T);return!0};function l(k,x,T,P){var A,N,y;if(a(T),N=k._events,N===void 0?(N=k._events=Object.create(null),k._eventsCount=0):(N.newListener!==void 0&&(k.emit("newListener",x,T.listener?T.listener:T),N=k._events),y=N[x]),y===void 0)y=N[x]=T,++k._eventsCount;else if(typeof y=="function"?y=N[x]=P?[T,y]:[y,T]:P?y.unshift(T):y.push(T),A=c(k),A>0&&y.length>A&&!y.warned){y.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+y.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=k,R.type=x,R.count=y.length,i(R)}return k}s.prototype.addListener=function(x,T){return l(this,x,T,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(x,T){return l(this,x,T,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(k,x,T){var P={fired:!1,wrapFn:void 0,target:k,type:x,listener:T},A=u.bind(P);return A.listener=T,P.wrapFn=A,A}s.prototype.once=function(x,T){return a(T),this.on(x,d(this,x,T)),this},s.prototype.prependOnceListener=function(x,T){return a(T),this.prependListener(x,d(this,x,T)),this},s.prototype.removeListener=function(x,T){var P,A,N,y,R;if(a(T),A=this._events,A===void 0)return this;if(P=A[x],P===void 0)return this;if(P===T||P.listener===T)--this._eventsCount===0?this._events=Object.create(null):(delete A[x],A.removeListener&&this.emit("removeListener",x,P.listener||T));else if(typeof P!="function"){for(N=-1,y=P.length-1;y>=0;y--)if(P[y]===T||P[y].listener===T){R=P[y].listener,N=y;break}if(N<0)return this;N===0?P.shift():p(P,N),P.length===1&&(A[x]=P[0]),A.removeListener!==void 0&&this.emit("removeListener",x,R||T)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(x){var T,P,A;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete P[x]),this;if(arguments.length===0){var N=Object.keys(P),y;for(A=0;A<N.length;++A)y=N[A],y!=="removeListener"&&this.removeAllListeners(y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=P[x],typeof T=="function")this.removeListener(x,T);else if(T!==void 0)for(A=T.length-1;A>=0;A--)this.removeListener(x,T[A]);return this};function h(k,x,T){var P=k._events;if(P===void 0)return[];var A=P[x];return A===void 0?[]:typeof A=="function"?T?[A.listener||A]:[A]:T?v(A):g(A,A.length)}s.prototype.listeners=function(x){return h(this,x,!0)},s.prototype.rawListeners=function(x){return h(this,x,!1)},s.listenerCount=function(k,x){return typeof k.listenerCount=="function"?k.listenerCount(x):f.call(k,x)},s.prototype.listenerCount=f;function f(k){var x=this._events;if(x!==void 0){var T=x[k];if(typeof T=="function")return 1;if(T!==void 0)return T.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function g(k,x){for(var T=new Array(x),P=0;P<x;++P)T[P]=k[P];return T}function p(k,x){for(;x+1<k.length;x++)k[x]=k[x+1];k.pop()}function v(k){for(var x=new Array(k.length),T=0;T<x.length;++T)x[T]=k[T].listener||k[T];return x}function b(k,x){return new Promise(function(T,P){function A(y){k.removeListener(x,N),P(y)}function N(){typeof k.removeListener=="function"&&k.removeListener("error",A),T([].slice.call(arguments))}S(k,x,N,{once:!0}),x!=="error"&&w(k,A,{once:!0})})}function w(k,x,T){typeof k.on=="function"&&S(k,"error",x,T)}function S(k,x,T,P){if(typeof k.on=="function")P.once?k.once(x,T):k.on(x,T);else if(typeof k.addEventListener=="function")k.addEventListener(x,function A(N){P.once&&k.removeEventListener(x,A),T(N)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof k)}return jo.exports}var ii=$C();let Wy=!0,qy=!0;function Bs(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function xr(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(o,a){if(o!==t)return r.apply(this,arguments);const c=l=>{const u=n(l);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,c),r.apply(this,[o,c])};const s=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(a))return s.apply(this,arguments);const c=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(o){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),o&&this.addEventListener(t,this["_on"+t]=o)},enumerable:!0,configurable:!0})}function zC(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(Wy=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function HC(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(qy=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Gy(){if(typeof window=="object"){if(Wy)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gd(e,t){qy&&console.warn(e+" is deprecated, please use "+t+" instead.")}function WC(e){const t={browser:null,version:null};if(typeof e>"u"||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const i=n.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Bs(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Bs(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=parseInt(Bs(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Bs(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser="Not a supported browser.",t;return t}function tp(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ky(e){return tp(e)?Object.keys(e).reduce(function(t,n){const i=tp(e[n]),r=i?Ky(e[n]):e[n],s=i&&!Object.keys(r).length;return r===void 0||s?t:Object.assign(t,{[n]:r})},{}):e}function Su(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?Su(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(r=>{Su(e,e.get(r),n)})}))}function np(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(t===null)return r;const s=[];return e.forEach(o=>{o.type==="track"&&o.trackIdentifier===t.id&&s.push(o)}),s.forEach(o=>{e.forEach(a=>{a.type===i&&a.trackId===o.id&&Su(e,a,r)})}),r}const ip=Gy;function Yy(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof a[l]=="object"?a[l]:{ideal:a[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const d=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){c.optional=c.optional||[];let h={};typeof u.ideal=="number"?(h[d("min",l)]=u.ideal,c.optional.push(h),h={},h[d("max",l)]=u.ideal,c.optional.push(h)):(h[d("",l)]=u.ideal,c.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",l)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(h,l)]=u[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},r=function(a,c){if(t.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(u,d,h){d in u&&!(h in u)&&(u[h]=u[d],delete u[d])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=t.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let d;if(l.exact==="environment"||l.ideal==="environment"?d=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(d=["front"]),d)return n.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>d.some(p=>g.label.toLowerCase().includes(p)));return!f&&h.length&&d.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),ip("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return ip("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return t.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){r(a,u=>{n.webkitGetUserMedia(u,c,d=>{l&&l(s(d))})})};if(n.getUserMedia=o.bind(n),n.mediaDevices.getUserMedia){const a=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(c){return r(c,l=>a(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function Zy(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Xy(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;e.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):s={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(r=>{let s;e.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.id):s={track:r};const o=new Event("track");o.track=r,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else xr(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function Jy(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(a,c){let l=r.apply(this,arguments);return l||(l=t(this,a),this._senders.push(l)),l};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(t(this,o))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof e=="object"&&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 i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Qy(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){const s=n.apply(this,[]);return s.forEach(o=>o._pc=this),s});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),e.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(o=>np(o,s.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(s=>s._pc=this),r}),xr(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>np(s,r.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 i=arguments[0];let r,s,o;return this.getSenders().forEach(a=>{a.track===i&&(r?o=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(s?o=!0:s=a),a.track===i)),o||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function e0(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(d=>d.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();n.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function t0(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return e0(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const u=n.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(d=>this._reverseStreams[d.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(d=>{if(this.getSenders().find(f=>f.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const d=new e.MediaStream(u.getTracks());this._streams[u.id]=d,this._reverseStreams[d.id]=u,u=d}i.apply(this,[u])};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},e.RTCPeerConnection.prototype.addTrack=function(u,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(p=>p===u))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(p=>p.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[d.id];if(g)g.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new e.MediaStream([u]);this._streams[d.id]=p,this._reverseStreams[p.id]=d,this.addStream(p)}return this.getSenders().find(p=>p.track===u)};function s(l,u){let d=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];d=d.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:d})}function o(l,u){let d=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];d=d.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:u.type,sdp:d})}["createOffer","createAnswer"].forEach(function(l){const u=e.RTCPeerConnection.prototype[l],d={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[g=>{const p=s(this,g);h[0].apply(null,[p])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):u.apply(this,arguments).then(g=>s(this,g))}};e.RTCPeerConnection.prototype[l]=d[l]});const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:s(this,l)}}),e.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(p=>u.track===p)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function wu(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const i=e.RTCPeerConnection.prototype[n],r={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=r[n]})}function n0(e,t){xr(e,"negotiationneeded",n=>{const i=n.target;if(!((t.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return n})}var rp=Object.freeze({__proto__:null,fixNegotiationNeeded:n0,shimAddTrackRemoveTrack:t0,shimAddTrackRemoveTrackWithNative:e0,shimGetSendersWithDtmf:Jy,shimGetUserMedia:Yy,shimMediaStream:Zy,shimOnTrack:Xy,shimPeerConnection:wu,shimSenderReceiverGetStats:Qy});function i0(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(r,s,o){Gd("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(r).then(s,o)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const r=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function qC(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}function r0(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Tu(e,t){if(typeof e!="object"||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=e.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};e.RTCPeerConnection.prototype[r]=o[r]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[s,o,a]=arguments;return i.apply(this,[s||null]).then(c=>{if(t.version<53&&!o)try{c.forEach(l=>{l.type=n[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,d)=>{c.set(d,Object.assign({},u,{type:n[u.type]||u.type}))})}return c}).then(o,a)}}function s0(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function o0(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i}),xr(e,"track",n=>(n.receiver._pc=n.srcElement,n)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function a0(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(n){Gd("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&n.getTracks().includes(i.track)&&this.removeTrack(i)})})}function c0(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function l0(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=t.apply(this,arguments);if(r){const{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function u0(e){if(!(typeof e=="object"&&e.RTCRtpSender))return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const i=t.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function d0(e){if(!(typeof e=="object"&&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 h0(e){if(!(typeof e=="object"&&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 sp=Object.freeze({__proto__:null,shimAddTransceiver:l0,shimCreateAnswer:h0,shimCreateOffer:d0,shimGetDisplayMedia:qC,shimGetParameters:u0,shimGetUserMedia:i0,shimOnTrack:r0,shimPeerConnection:Tu,shimRTCDataChannel:c0,shimReceiverGetStats:o0,shimRemoveStream:a0,shimSenderGetStats:s0});function f0(e){if(!(typeof e!="object"||!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(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>t.call(this,r,i)),i.getVideoTracks().forEach(r=>t.call(this,r,i))},e.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(n){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(n);if(i===-1)return;this._localStreams.splice(i,1);const r=n.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function p0(e){if(!(typeof e!="object"||!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(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const o=new Event("addstream");o.stream=s,i.dispatchEvent(o)})}),t.apply(i,arguments)}}}function m0(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(l,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h},t.createAnswer=function(l,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h};let a=function(c,l,u){const d=r.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d};t.setLocalDescription=a,a=function(c,l,u){const d=s.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d},t.setRemoteDescription=a,a=function(c,l,u){const d=o.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d},t.addIceCandidate=a}function g0(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const n=t.mediaDevices,i=n.getUserMedia.bind(n);t.mediaDevices.getUserMedia=r=>i(b0(r))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(i,r,s){t.mediaDevices.getUserMedia(i).then(r,s)}).bind(t))}function b0(e){return e&&e.video!==void 0?Object.assign({},e,{video:Ky(e.video)}):e}function y0(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(Gd("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(i.iceServers[o])}i.iceServers=s}return new t(i,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function v0(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function x0(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function k0(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var op=Object.freeze({__proto__:null,shimAudioContext:k0,shimCallbacksAPI:m0,shimConstraints:b0,shimCreateOfferLegacy:x0,shimGetUserMedia:g0,shimLocalStreamsAPI:f0,shimRTCIceServerUrls:y0,shimRemoteStreamsAPI:p0,shimTrackEventTransceiver:v0}),Qc={exports:{}},ap;function GC(){return ap||(ap=1,function(e){const t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(n){return n.trim().split(`
|
|
1
|
+
"use strict";var eT=Object.defineProperty;var tT=(e,t,n)=>t in e?eT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ie=(e,t,n)=>tT(e,typeof t!="symbol"?t+"":t,n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const O=require("react"),m=require("react/jsx-runtime"),jd=require("clsx"),kt=require("lucide-react"),nT=require("@emotion/styled");require("@emotion/react");const iT=require("react-dom/client");function rT(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const D=rT(O);function sT(e,t){return t.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(i){if(i!=="default"&&!(i in e)){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}})}),Object.freeze(e)}var oT=Object.defineProperty,aT=(e,t,n)=>t in e?oT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lf=(e,t,n)=>aT(e,typeof t!="symbol"?t+"":t,n);class dn{constructor(){Lf(this,"_locking"),Lf(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let t;const n=new Promise(r=>t=()=>{this._locks-=1,r()}),i=this._locking.then(()=>t);return this._locking=this._locking.then(()=>n),i}}function Et(e,t){if(!e)throw new Error(t)}const cT=34028234663852886e22,lT=-34028234663852886e22,uT=4294967295,dT=2147483647,hT=-2147483648;function ca(e){if(typeof e!="number")throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>dT||e<hT)throw new Error("invalid int 32: "+e)}function hu(e){if(typeof e!="number")throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>uT||e<0)throw new Error("invalid uint 32: "+e)}function e0(e){if(typeof e!="number")throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>cT||e<lT))throw new Error("invalid float 32: "+e)}const t0=Symbol("@bufbuild/protobuf/enum-type");function fT(e){const t=e[t0];return Et(t,"missing enum type on enum object"),t}function n0(e,t,n,i){e[t0]=i0(t,n.map(r=>({no:r.no,name:r.name,localName:e[r.no]})))}function i0(e,t,n){const i=Object.create(null),r=Object.create(null),s=[];for(const o of t){const a=r0(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:e,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function pT(e,t,n){const i={};for(const r of t){const s=r0(r);i[s.localName]=s.no,i[s.no]=s.localName}return n0(i,e,t),i}function r0(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Ud{equals(t){return this.getType().runtime.util.equals(this.getType(),this,t)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(t,n){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(n);return r.readMessage(this,s.readerFactory(t),t.byteLength,s),this}fromJson(t,n){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(n);return r.readMessage(i,t,s,this),this}fromJsonString(t,n){let i;try{i=JSON.parse(t)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,n)}toBinary(t){const n=this.getType(),i=n.runtime.bin,r=i.makeWriteOptions(t),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(t){const n=this.getType(),i=n.runtime.json,r=i.makeWriteOptions(t);return i.writeMessage(this,r)}toJsonString(t){var n;const i=this.toJson(t);return JSON.stringify(i,null,(n=t==null?void 0:t.prettySpaces)!==null&&n!==void 0?n:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function mT(e,t,n,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(a){e.util.initFields(this),e.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new Ud),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return e.util.equals(o,a,c)}}),o}function gT(){let e=0,t=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,(n&128)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Zc(e,t,n){for(let s=0;s<28;s=s+7){const o=e>>>s,a=!(!(o>>>7)&&t==0),c=(a?o|128:o)&255;if(n.push(c),!a)return}const i=e>>>28&15|(t&7)<<4,r=t>>3!=0;if(n.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=t>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(n.push(c),!a)return}n.push(t>>>31&1)}}const la=4294967296;function Ff(e){const t=e[0]==="-";t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function s(o,a){const c=Number(e.slice(o,a));r*=n,i=i*n+c,i>=la&&(r=r+(i/la|0),i=i%la)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?o0(i,r):Bd(i,r)}function bT(e,t){let n=Bd(e,t);const i=n.hi&2147483648;i&&(n=o0(n.lo,n.hi));const r=s0(n.lo,n.hi);return i?"-"+r:r}function s0(e,t){if({lo:e,hi:t}=yT(e,t),t<=2097151)return String(la*t+e);const n=e&16777215,i=(e>>>24|t<<8)&16777215,r=t>>16&65535;let s=n+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const c=1e7;return s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+jf(o)+jf(s)}function yT(e,t){return{lo:e>>>0,hi:t>>>0}}function Bd(e,t){return{lo:e|0,hi:t|0}}function o0(e,t){return t=~t,e?e=~e+1:t+=1,Bd(e,t)}const jf=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Uf(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e=e>>>7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e=e>>7;t.push(1)}}function vT(){let e=this.buf[this.pos++],t=e&127;if((e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<7,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<14,(e&128)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(e&127)<<21,(e&128)==0)return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let n=5;(e&128)!==0&&n<10;n++)e=this.buf[this.pos++];if((e&128)!=0)throw new Error("invalid varint");return this.assertBounds(),t>>>0}function xT(){const e=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof e.getBigInt64=="function"&&typeof e.getBigUint64=="function"&&typeof e.setBigInt64=="function"&&typeof e.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>s||l<r)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>a||l<o)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return e.setBigInt64(0,this.parse(c),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(c){return e.setBigInt64(0,this.uParse(c),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(c,l){return e.setInt32(0,c,!0),e.setInt32(4,l,!0),e.getBigInt64(0,!0)},uDec(c,l){return e.setInt32(0,c,!0),e.setInt32(4,l,!0),e.getBigUint64(0,!0)}}}const n=r=>Et(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>Et(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),n(r),Ff(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),Ff(r)},dec(r,s){return bT(r,s)},uDec(r,s){return s0(r,s)}}}const yt=xT();var ee;(function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"})(ee||(ee={}));var Vi;(function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"})(Vi||(Vi={}));function Ai(e,t,n){if(t===n)return!0;if(e==ee.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==n[i])return!1;return!0}switch(e){case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return t==n}return!1}function os(e,t){switch(e){case ee.BOOL:return!1;case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return t==0?yt.zero:"0";case ee.DOUBLE:case ee.FLOAT:return 0;case ee.BYTES:return new Uint8Array(0);case ee.STRING:return"";default:return 0}}function a0(e,t){switch(e){case ee.BOOL:return t===!1;case ee.STRING:return t==="";case ee.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Nt;(function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"})(Nt||(Nt={}));class kT{constructor(t){this.stack=[],this.textEncoder=t??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let r=0;r<this.chunks.length;r++)t+=this.chunks[r].length;let n=new Uint8Array(t),i=0;for(let r=0;r<this.chunks.length;r++)n.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,n){return this.uint32((t<<3|n)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(hu(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return ca(t),Uf(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let n=this.textEncoder.encode(t);return this.uint32(n.byteLength),this.raw(n)}float(t){e0(t);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,t,!0),this.raw(n)}double(t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),this.raw(n)}fixed32(t){hu(t);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!0),this.raw(n)}sfixed32(t){ca(t);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,t,!0),this.raw(n)}sint32(t){return ca(t),t=(t<<1^t>>31)>>>0,Uf(t,this.buf),this}sfixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),r=yt.enc(t);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}fixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),r=yt.uEnc(t);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}int64(t){let n=yt.enc(t);return Zc(n.lo,n.hi,this.buf),this}sint64(t){let n=yt.enc(t),i=n.hi>>31,r=n.lo<<1^i,s=(n.hi<<1|n.lo>>>31)^i;return Zc(r,s,this.buf),this}uint64(t){let n=yt.uEnc(t);return Zc(n.lo,n.hi,this.buf),this}}class ST{constructor(t,n){this.varint64=gT,this.uint32=vT,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=n??new TextDecoder}tag(){let t=this.uint32(),n=t>>>3,i=t&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(t,n){let i=this.pos;switch(t){case Nt.Varint:for(;this.buf[this.pos++]&128;);break;case Nt.Bit64:this.pos+=4;case Nt.Bit32:this.pos+=4;break;case Nt.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Nt.StartGroup:for(;;){const[s,o]=this.tag();if(o===Nt.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return yt.dec(...this.varint64())}uint64(){return yt.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),i=-(t&1);return t=(t>>>1|(n&1)<<31)^i,n=n>>>1^i,yt.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return yt.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return yt.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 t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(){return this.textDecoder.decode(this.bytes())}}function wT(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=t.split(".").pop(),s.jsonName="[".concat(t,"]"),r=e.util.newFieldList([s]).list()[0]}return r},runtime:e}}function c0(e){const t=e.field.localName,n=Object.create(null);return n[t]=TT(e),[n,()=>n[t]]}function TT(e){const t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return os(t.T,t.L);case"message":const n=t.T,i=new n;return n.fieldWrapper?n.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function CT(e,t){if(!t.repeated&&(t.kind=="enum"||t.kind=="scalar")){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(n=>n.no===t.no)}let fi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),uc=[];for(let e=0;e<fi.length;e++)uc[fi[e].charCodeAt(0)]=e;uc[45]=fi.indexOf("+");uc[95]=fi.indexOf("/");const l0={dec(e){let t=e.length*3/4;e[e.length-2]=="="?t-=2:e[e.length-1]=="="&&(t-=1);let n=new Uint8Array(t),i=0,r=0,s,o=0;for(let a=0;a<e.length;a++){if(s=uc[e.charCodeAt(a)],s===void 0)switch(e[a]){case"=":r=0;case`
|
|
2
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:n[i++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:n[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:n[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return n.subarray(0,i)},enc(e){let t="",n=0,i,r=0;for(let s=0;s<e.length;s++)switch(i=e[s],n){case 0:t+=fi[i>>2],r=(i&3)<<4,n=1;break;case 1:t+=fi[r|i>>4],r=(i&15)<<2,n=2;break;case 2:t+=fi[r|i>>6],t+=fi[i&63],n=0;break}return n&&(t+=fi[r],t+="=",n==1&&(t+="=")),t}};function ET(e,t,n){d0(t,e);const i=t.runtime.bin.makeReadOptions(n),r=CT(e.getType().runtime.bin.listUnknownFields(e),t.field),[s,o]=c0(t);for(const a of r)t.runtime.bin.readField(s,i.readerFactory(a.data),t.field,a.wireType,i);return o()}function _T(e,t,n,i){d0(t,e);const r=t.runtime.bin.makeReadOptions(i),s=t.runtime.bin.makeWriteOptions(i);if(u0(e,t)){const l=e.getType().runtime.bin.listUnknownFields(e).filter(u=>u.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(const u of l)e.getType().runtime.bin.onUnknownField(e,u.no,u.wireType,u.data)}const o=s.writerFactory();let a=t.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,n,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[l,u]=c.tag(),d=c.skip(u,l);e.getType().runtime.bin.onUnknownField(e,l,u,d)}}function u0(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(i=>i.no==t.field.no)}function d0(e,t){Et(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function h0(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?t[n]!==void 0:e.kind=="enum"?t[n]!==e.T.values[0].no:!a0(e.T,t[n]);case"message":return t[n]!==void 0;case"map":return Object.keys(t[n]).length>0}}function Bf(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?os(e.T,e.L):void 0;break;case"message":t[n]=void 0;break}}function pi(e,t){if(e===null||typeof e!="object"||!Object.getOwnPropertyNames(Ud.prototype).every(i=>i in e&&typeof e[i]=="function"))return!1;const n=e.getType();return n===null||typeof n!="function"||!("typeName"in n)||typeof n.typeName!="string"?!1:t===void 0?!0:n.typeName==t.typeName}function f0(e,t){return pi(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}ee.DOUBLE,ee.FLOAT,ee.INT64,ee.UINT64,ee.INT32,ee.UINT32,ee.BOOL,ee.STRING,ee.BYTES;const Vf={ignoreUnknownFields:!1},$f={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function RT(e){return e?Object.assign(Object.assign({},Vf),e):Vf}function AT(e){return e?Object.assign(Object.assign({},$f),e):$f}const Oa=Symbol(),ua=Symbol();function PT(){return{makeReadOptions:RT,makeWriteOptions:AT,readMessage(e,t,n,i){if(t==null||Array.isArray(t)||typeof t!="object")throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Jn(t)));i=i??new e;const r=new Map,s=n.typeRegistry;for(const[o,a]of Object.entries(t)){const c=e.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const l=r.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(o,'"'));r.set(c.oneof,o)}zf(i,a,c,n,e)}else{let l=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const u=s.findExtension(o.substring(1,o.length-1));if(u&&u.extendee.typeName==e.typeName){l=!0;const[d,h]=c0(u);zf(d,a,u.field,n,u),_T(i,u,h(),n)}}if(!l&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!h0(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues||!IT(r))continue}const o=r.oneof?e[r.oneof.localName].value:e[r.localName],a=Hf(r,o,t);a!==void 0&&(i[t.useProtoFieldName?r.name:r.jsonName]=a)}const s=t.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of n.runtime.bin.listUnknownFields(e)){const a=s.findExtensionFor(n.typeName,o.no);if(a&&u0(e,a)){const c=ET(e,a,t),l=Hf(a.field,c,t);l!==void 0&&(i[a.field.jsonName]=l)}}}catch(s){const o=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(e,t,n){return Hs(e,t,n??Vi.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||a0(e,t)))return da(e,t)},debug:Jn}}function Jn(e){if(e===null)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 zf(e,t,n,i,r){let s=n.localName;if(n.repeated){if(Et(n.kind!="map"),t===null)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t)));const o=e[s];for(const a of t){if(a===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(a)));switch(n.kind){case"message":o.push(n.T.fromJson(a,i));break;case"enum":const c=Xc(n.T,a,i.ignoreUnknownFields,!0);c!==ua&&o.push(c);break;case"scalar":try{o.push(Hs(n.T,a,n.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(a));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(n.kind=="map"){if(t===null)return;if(typeof t!="object"||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t)));const o=e[s];for(const[a,c]of Object.entries(t)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let l;try{l=NT(n.K,a)}catch(u){let d="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t));throw u instanceof Error&&u.message.length>0&&(d+=": ".concat(u.message)),new Error(d)}switch(n.V.kind){case"message":o[l]=n.V.T.fromJson(c,i);break;case"enum":const u=Xc(n.V.T,c,i.ignoreUnknownFields,!0);u!==ua&&(o[l]=u);break;case"scalar":try{o[l]=Hs(n.V.T,c,Vi.BIGINT,!0)}catch(d){let h="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t));throw d instanceof Error&&d.message.length>0&&(h+=": ".concat(d.message)),new Error(h)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const o=n.T;if(t===null&&o.typeName!="google.protobuf.Value")return;let a=e[s];pi(a)?a.fromJson(t,i):(e[s]=a=o.fromJson(t,i),o.fieldWrapper&&!n.oneof&&(e[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Xc(n.T,t,i.ignoreUnknownFields,!1);switch(c){case Oa:Bf(n,e);break;case ua:break;default:e[s]=c;break}break;case"scalar":try{const l=Hs(n.T,t,n.L,!1);switch(l){case Oa:Bf(n,e);break;default:e[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Jn(t));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function NT(e,t){if(e===ee.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1;break}return Hs(e,t,Vi.BIGINT,!0).toString()}function Hs(e,t,n,i){if(t===null)return i?os(e,n):Oa;switch(e){case ee.DOUBLE:case ee.FLOAT:if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""||typeof t=="string"&&t.trim().length!==t.length||typeof t!="string"&&typeof t!="number")break;const r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==ee.FLOAT&&e0(r),r;case ee.INT32:case ee.FIXED32:case ee.SFIXED32:case ee.SINT32:case ee.UINT32:let s;if(typeof t=="number"?s=t:typeof t=="string"&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),s===void 0)break;return e==ee.UINT32||e==ee.FIXED32?hu(s):ca(s),s;case ee.INT64:case ee.SFIXED64:case ee.SINT64:if(typeof t!="number"&&typeof t!="string")break;const o=yt.parse(t);return n?o.toString():o;case ee.FIXED64:case ee.UINT64:if(typeof t!="number"&&typeof t!="string")break;const a=yt.uParse(t);return n?a.toString():a;case ee.BOOL:if(typeof t!="boolean")break;return t;case ee.STRING:if(typeof t!="string")break;try{encodeURIComponent(t)}catch{throw new Error("invalid UTF8")}return t;case ee.BYTES:if(t==="")return new Uint8Array(0);if(typeof t!="string")break;return l0.dec(t)}throw new Error}function Xc(e,t,n,i){if(t===null)return e.typeName=="google.protobuf.NullValue"?0:i?e.values[0].no:Oa;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(r!==void 0)return r.no;if(n)return ua;break}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Jn(t)))}function IT(e){return e.repeated||e.kind=="map"?!0:!(e.oneof||e.kind=="message"||e.opt||e.req)}function Hf(e,t,n){if(e.kind=="map"){Et(typeof t=="object"&&t!=null);const i={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=da(e.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(n);break;case"enum":const s=e.V.T;for(const[o,a]of r)i[o.toString()]=Jc(s,a,n.enumAsInteger);break}return n.emitDefaultValues||r.length>0?i:void 0}if(e.repeated){Et(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let r=0;r<t.length;r++)i.push(da(e.T,t[r]));break;case"enum":for(let r=0;r<t.length;r++)i.push(Jc(e.T,t[r],n.enumAsInteger));break;case"message":for(let r=0;r<t.length;r++)i.push(t[r].toJson(n));break}return n.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return da(e.T,t);case"enum":return Jc(e.T,t,n.enumAsInteger);case"message":return f0(e.T,t).toJson(n)}}function Jc(e,t,n){var i;if(Et(typeof t=="number"),e.typeName=="google.protobuf.NullValue")return null;if(n)return t;const r=e.findNumber(t);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:t}function da(e,t){switch(e){case ee.INT32:case ee.SFIXED32:case ee.SINT32:case ee.FIXED32:case ee.UINT32:return Et(typeof t=="number"),t;case ee.FLOAT:case ee.DOUBLE:return Et(typeof t=="number"),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case ee.STRING:return Et(typeof t=="string"),t;case ee.BOOL:return Et(typeof t=="boolean"),t;case ee.UINT64:case ee.FIXED64:case ee.INT64:case ee.SFIXED64:case ee.SINT64:return Et(typeof t=="bigint"||typeof t=="string"||typeof t=="number"),t.toString();case ee.BYTES:return Et(t instanceof Uint8Array),l0.enc(t)}}const Er=Symbol("@bufbuild/protobuf/unknown-fields"),Wf={readUnknownFields:!0,readerFactory:e=>new ST(e)},qf={writeUnknownFields:!0,writerFactory:()=>new kT};function MT(e){return e?Object.assign(Object.assign({},Wf),e):Wf}function OT(e){return e?Object.assign(Object.assign({},qf),e):qf}function DT(){return{makeReadOptions:MT,makeWriteOptions:OT,listUnknownFields(e){var t;return(t=e[Er])!==null&&t!==void 0?t:[]},discardUnknownFields(e){delete e[Er]},writeUnknownFields(e,t){const i=e[Er];if(i)for(const r of i)t.tag(r.no,r.wireType).raw(r.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[Er])||(r[Er]=[]),r[Er].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const s=e.getType(),o=r?t.len:t.pos+n;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!(r===!0&&c==Nt.EndGroup));){const l=s.fields.find(a);if(!l){const u=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,u);continue}Gf(e,t,l,c,i)}if(r&&(c!=Nt.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:Gf,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber()){if(!h0(r,e)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?e[r.oneof.localName].value:e[r.localName];Kf(r,s,t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){t!==void 0&&Kf(e,t,n,i)}}}function Gf(e,t,n,i,r){let{repeated:s,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const a=n.kind=="enum"?ee.INT32:n.T;let c=Da;if(n.kind=="scalar"&&n.L>0&&(c=FT),s){let h=e[o];if(i==Nt.LengthDelimited&&a!=ee.STRING&&a!=ee.BYTES){let g=t.uint32()+t.pos;for(;t.pos<g;)h.push(c(t,a))}else h.push(c(t,a))}else e[o]=c(t,a);break;case"message":const l=n.T;s?e[o].push(ha(t,new l,r,n)):pi(e[o])?ha(t,e[o],r,n):(e[o]=ha(t,new l,r,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case"map":let[u,d]=LT(n,t,r);e[o][u]=d;break}}function ha(e,t,n,i){const r=t.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(t,e,s?i.no:e.uint32(),n,s),t}function LT(e,t,n){const i=t.uint32(),r=t.pos+i;let s,o;for(;t.pos<r;){const[a]=t.tag();switch(a){case 1:s=Da(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Da(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=ha(t,new e.V.T,n,void 0);break}break}}if(s===void 0&&(s=os(e.K,Vi.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),o===void 0)switch(e.V.kind){case"scalar":o=os(e.V.T,Vi.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T;break}return[s,o]}function FT(e,t){const n=Da(e,t);return typeof n=="bigint"?n.toString():n}function Da(e,t){switch(t){case ee.STRING:return e.string();case ee.BOOL:return e.bool();case ee.DOUBLE:return e.double();case ee.FLOAT:return e.float();case ee.INT32:return e.int32();case ee.INT64:return e.int64();case ee.UINT64:return e.uint64();case ee.FIXED64:return e.fixed64();case ee.BYTES:return e.bytes();case ee.FIXED32:return e.fixed32();case ee.SFIXED32:return e.sfixed32();case ee.SFIXED64:return e.sfixed64();case ee.SINT64:return e.sint64();case ee.UINT32:return e.uint32();case ee.SINT32:return e.sint32()}}function Kf(e,t,n,i){Et(t!==void 0);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s=e.kind=="enum"?ee.INT32:e.T;if(r)if(Et(Array.isArray(t)),e.packed)UT(n,s,e.no,t);else for(const o of t)Ws(n,s,e.no,o);else Ws(n,s,e.no,t);break;case"message":if(r){Et(Array.isArray(t));for(const o of t)Yf(n,i,e,o)}else Yf(n,i,e,t);break;case"map":Et(typeof t=="object"&&t!=null);for(const[o,a]of Object.entries(t))jT(n,i,e,o,a);break}}function jT(e,t,n,i,r){e.tag(n.no,Nt.LengthDelimited),e.fork();let s=i;switch(n.K){case ee.INT32:case ee.FIXED32:case ee.UINT32:case ee.SFIXED32:case ee.SINT32:s=Number.parseInt(i);break;case ee.BOOL:Et(i=="true"||i=="false"),s=i=="true";break}switch(Ws(e,n.K,1,s),n.V.kind){case"scalar":Ws(e,n.V.T,2,r);break;case"enum":Ws(e,ee.INT32,2,r);break;case"message":Et(r!==void 0),e.tag(2,Nt.LengthDelimited).bytes(r.toBinary(t));break}e.join()}function Yf(e,t,n,i){const r=f0(n.T,i);n.delimited?e.tag(n.no,Nt.StartGroup).raw(r.toBinary(t)).tag(n.no,Nt.EndGroup):e.tag(n.no,Nt.LengthDelimited).bytes(r.toBinary(t))}function Ws(e,t,n,i){Et(i!==void 0);let[r,s]=p0(t);e.tag(n,r)[s](i)}function UT(e,t,n,i){if(!i.length)return;e.tag(n,Nt.LengthDelimited).fork();let[,r]=p0(t);for(let s=0;s<i.length;s++)e[r](i[s]);e.join()}function p0(e){let t=Nt.Varint;switch(e){case ee.BYTES:case ee.STRING:t=Nt.LengthDelimited;break;case ee.DOUBLE:case ee.FIXED64:case ee.SFIXED64:t=Nt.Bit64;break;case ee.FIXED32:case ee.SFIXED32:case ee.FLOAT:t=Nt.Bit32;break}const n=ee[e].toLowerCase();return[t,n]}function BT(){return{setEnumType:n0,initPartial(e,t){if(e===void 0)return;const n=t.getType();for(const i of n.fields.byMember()){const r=i.localName,s=t,o=e;if(o[r]!=null)switch(i.kind){case"oneof":const a=o[r].case;if(a===void 0)continue;const c=i.findField(a);let l=o[r].value;c&&c.kind=="message"&&!pi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===ee.BYTES&&(l=Cs(l)),s[r]={case:a,value:l};break;case"scalar":case"enum":let u=o[r];i.T===ee.BYTES&&(u=i.repeated?u.map(Cs):Cs(u)),s[r]=u;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===ee.BYTES)for(const[f,g]of Object.entries(o[r]))s[r][f]=Cs(g);else Object.assign(s[r],o[r]);break;case"message":const h=i.V.T;for(const f of Object.keys(o[r])){let g=o[r][f];h.fieldWrapper||(g=new h(g)),s[r][f]=g}break}break;case"message":const d=i.T;if(i.repeated)s[r]=o[r].map(h=>pi(h,d)?h:new d(h));else{const h=o[r];d.fieldWrapper?d.typeName==="google.protobuf.BytesValue"?s[r]=Cs(h):s[r]=h:s[r]=pi(h,d)?h:new d(h)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(i=>{const r=t[i.localName],s=n[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>Ai(i.T,o,s[a]));case"enum":return r.every((o,a)=>Ai(ee.INT32,o,s[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=r,a=s;return i.T.fieldWrapper&&(o!==void 0&&!pi(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!pi(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return Ai(ee.INT32,r,s);case"scalar":return Ai(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return Ai(ee.INT32,r.value,s.value);case"scalar":return Ai(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const u=i.V.T;return l.every(h=>u.equals(r[h],s[h]));case"enum":return l.every(h=>Ai(ee.INT32,r[h],s[h]));case"scalar":const d=i.V.T;return l.every(h=>Ai(d,r[h],s[h]))}break}})},clone(e){const t=e.getType(),n=new t,i=n;for(const r of t.fields.byMember()){const s=e[r.localName];let o;if(r.repeated)o=s.map(Fo);else if(r.kind=="map"){o=i[r.localName];for(const[a,c]of Object.entries(s))o[a]=Fo(c)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:Fo(s.value)}:{case:void 0}:o=Fo(s);i[r.localName]=o}for(const r of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return n}}}function Fo(e){if(e===void 0)return e;if(pi(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Cs(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function VT(e,t,n){return{syntax:e,json:PT(),bin:DT(),util:Object.assign(Object.assign({},BT()),{newFieldList:t,initFields:n}),makeMessageType(i,r,s){return mT(this,i,r,s)},makeEnum:pT,makeEnumType:i0,getEnumType:fT,makeExtension(i,r,s){return wT(this,i,r,s)}}}class $T{constructor(t,n){this._fields=t,this._normalizer=n}findJsonName(t){if(!this.jsonNames){const n={};for(const i of this.list())n[i.jsonName]=n[i.name]=i;this.jsonNames=n}return this.jsonNames[t]}find(t){if(!this.numbers){const n={};for(const i of this.list())n[i.no]=i;this.numbers=n}return this.numbers[t]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((t,n)=>t.no-n.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const t=this.members;let n;for(const i of this.list())i.oneof?i.oneof!==n&&(n=i.oneof,t.push(n)):t.push(i)}return this.members}}function m0(e,t){const n=g0(e);return t?n:KT(GT(n))}function zT(e){return m0(e,!1)}const HT=g0;function g0(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r);break}}return n.join("")}const WT=new Set(["constructor","toString","toJSON","valueOf"]),qT=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),b0=e=>"".concat(e,"$"),GT=e=>qT.has(e)?b0(e):e,KT=e=>WT.has(e)?b0(e):e;class YT{constructor(t){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=t,this.localName=zT(t)}addField(t){Et(t.oneof===this,"field ".concat(t.name," not one of ").concat(this.name)),this.fields.push(t)}findField(t){if(!this._lookup){this._lookup=Object.create(null);for(let n=0;n<this.fields.length;n++)this._lookup[this.fields[n].localName]=this.fields[n]}return this._lookup[t]}}function ZT(e,t){var n,i,r,s,o,a;const c=[];let l;for(const u of typeof e=="function"?e():e){const d=u;if(d.localName=m0(u.name,u.oneof!==void 0),d.jsonName=(n=u.jsonName)!==null&&n!==void 0?n:HT(u.name),d.repeated=(i=u.repeated)!==null&&i!==void 0?i:!1,u.kind=="scalar"&&(d.L=(r=u.L)!==null&&r!==void 0?r:Vi.BIGINT),d.delimited=(s=u.delimited)!==null&&s!==void 0?s:!1,d.req=(o=u.req)!==null&&o!==void 0?o:!1,d.opt=(a=u.opt)!==null&&a!==void 0?a:!1,u.packed===void 0&&(d.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=ee.BYTES&&u.T!=ee.STRING),u.oneof!==void 0){const h=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!l||l.name!=h)&&(l=new YT(h)),d.oneof=l,l.addField(d)}c.push(d)}return c}const V=VT("proto3",e=>new $T(e,t=>ZT(t)),e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated){i[n]=[];continue}switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=os(t.T,t.L);break}}});class un extends Ud{constructor(t){super(),this.seconds=yt.zero,this.nanos=0,V.util.initPartial(t,this)}fromJson(t,n){if(typeof t!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(V.json.debug(t)));const i=t.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 r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>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=yt.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(t){const n=Number(this.seconds)*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(n).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return un.fromDate(new Date)}static fromDate(t){const n=t.getTime();return new un({seconds:yt.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new un().fromBinary(t,n)}static fromJson(t,n){return new un().fromJson(t,n)}static fromJsonString(t,n){return new un().fromJsonString(t,n)}static equals(t,n){return V.util.equals(un,t,n)}}un.runtime=V;un.typeName="google.protobuf.Timestamp";un.fields=V.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const XT=V.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:JT,repeated:!0},{no:5,name:"events",kind:"message",T:eC,repeated:!0}]),JT=V.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:QT,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),QT=V.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:un},{no:3,name:"value",kind:"scalar",T:2}]),eC=V.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:un},{no:7,name:"normalized_end_timestamp",kind:"message",T:un,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),y0=V.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Un=V.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Lt=V.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"}]),Vd=V.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Us=V.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),to=V.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Vn=V.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"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),_r=V.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"}]),tC=V.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ht=V.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"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),dc=V.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:La,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:N0}]),La=V.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),nC=V.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:V.getEnumType(Lt),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}]),pr=V.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:V.getEnumType(Zr)},{no:4,name:"tracks",kind:"message",T:Vr,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:nC},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:V.getEnumType(no)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:V.getEnumType(Vn)},{no:18,name:"kind_details",kind:"enum",T:V.getEnumType(iC),repeated:!0}]),Zr=V.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),no=V.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),iC=V.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),vn=V.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),rC=V.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:cr,repeated:!0}]),Vr=V.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:V.getEnumType(Un)},{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:V.getEnumType(Lt)},{no:10,name:"layers",kind:"message",T:cr,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:rC,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:V.getEnumType(vn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:N0},{no:19,name:"audio_features",kind:"enum",T:V.getEnumType(Ht),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:V.getEnumType(y0)}]),cr=V.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:V.getEnumType(Vd)},{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}]),ln=V.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:V.getEnumType(Be)},{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:x0,oneof:"value"},{no:3,name:"speaker",kind:"message",T:sC,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:k0,oneof:"value"},{no:7,name:"transcription",kind:"message",T:oC,oneof:"value"},{no:8,name:"metrics",kind:"message",T:XT,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:fu,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:S0,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:w0,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:T0,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:mu,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:gu,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:bu,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Be=V.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),sC=V.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:v0,repeated:!0}]),v0=V.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}]),x0=V.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}]),k0=V.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),oC=V.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:aC,repeated:!0}]),aC=V.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}]),fu=V.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}]),S0=V.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}]),w0=V.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),T0=V.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:C0,oneof:"value"}]),C0=V.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}]),E0=V.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),_0=V.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:V.getEnumType(R0)},{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}]),R0=V.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),cC=V.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:V.getEnumType(A0)},{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}]),A0=V.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"},{no:13,name:"UNREAL"}]),P0=V.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Zf},{no:2,name:"screen",kind:"message",T:Zf},{no:3,name:"resume_connection",kind:"enum",T:V.getEnumType(to)},{no:4,name:"disabled_codecs",kind:"message",T:lC},{no:5,name:"force_relay",kind:"enum",T:V.getEnumType(to)}]),Zf=V.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:V.getEnumType(to)}]),lC=V.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:La,repeated:!0},{no:2,name:"publish",kind:"message",T:La,repeated:!0}]),N0=V.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),pu=V.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),I0=V.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:V.getEnumType(pu)},{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"}),M0=V.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),mu=V.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:V.getEnumType(vn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:I0,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:M0,oneof:"content_header"}],{localName:"DataStream_Header"}),gu=V.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"}),bu=V.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"}),Bn=V.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),yu=V.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),uC=V.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),dC=V.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:mr,oneof:"message"},{no:2,name:"answer",kind:"message",T:mr,oneof:"message"},{no:3,name:"trickle",kind:"message",T:$d,oneof:"message"},{no:4,name:"add_track",kind:"message",T:xu,oneof:"message"},{no:5,name:"mute",kind:"message",T:zd,oneof:"message"},{no:6,name:"subscription",kind:"message",T:hc,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:O0,oneof:"message"},{no:8,name:"leave",kind:"message",T:fc,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:L0,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:B0,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:V0,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Yn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:F0,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:H0,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:D0,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:gC,oneof:"message"}]),Xf=V.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:hC,oneof:"message"},{no:2,name:"answer",kind:"message",T:mr,oneof:"message"},{no:3,name:"offer",kind:"message",T:mr,oneof:"message"},{no:4,name:"trickle",kind:"message",T:$d,oneof:"message"},{no:5,name:"update",kind:"message",T:mC,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Hd,oneof:"message"},{no:8,name:"leave",kind:"message",T:fc,oneof:"message"},{no:9,name:"mute",kind:"message",T:zd,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:bC,oneof:"message"},{no:11,name:"room_update",kind:"message",T:yC,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:xC,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:SC,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:TC,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:CC,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:pC,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:fC,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:_C,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:PC,oneof:"message"},{no:22,name:"request_response",kind:"message",T:NC,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:IC,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:EC,oneof:"message"}]),vu=V.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),xu=V.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:V.getEnumType(Un)},{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:V.getEnumType(Lt)},{no:9,name:"layers",kind:"message",T:cr,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:vu,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:V.getEnumType(vn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:V.getEnumType(y0)},{no:17,name:"audio_features",kind:"enum",T:V.getEnumType(Ht),repeated:!0}]),$d=V.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:V.getEnumType(Bn)},{no:3,name:"final",kind:"scalar",T:8}]),zd=V.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),hC=V.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:dc},{no:2,name:"participant",kind:"message",T:pr},{no:3,name:"other_participants",kind:"message",T:pr,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:j0,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:P0},{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:_0},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:La,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),fC=V.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:j0,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:P0},{no:3,name:"server_info",kind:"message",T:_0},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Hd=V.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Vr}]),pC=V.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),mr=V.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),mC=V.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:pr,repeated:!0}]),hc=V.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:E0,repeated:!0}]),O0=V.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:V.getEnumType(Vd)},{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}]),D0=V.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:V.getEnumType(Ht),repeated:!0}]),gC=V.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}]),fc=V.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:V.getEnumType(Vn)},{no:3,name:"action",kind:"enum",T:V.getEnumType(Xr)},{no:4,name:"regions",kind:"message",T:RC}]),Xr=V.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),L0=V.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:cr,repeated:!0}]),F0=V.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}]),j0=V.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}]),bC=V.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:v0,repeated:!0}]),yC=V.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:dc}]),vC=V.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:V.getEnumType(Us)},{no:3,name:"score",kind:"scalar",T:2}]),xC=V.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:vC,repeated:!0}]),kC=V.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:V.getEnumType(yu)}]),SC=V.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:kC,repeated:!0}]),Wd=V.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:V.getEnumType(Vd)},{no:2,name:"enabled",kind:"scalar",T:8}]),wC=V.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Wd,repeated:!0}]),TC=V.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Wd,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:wC,repeated:!0}]),U0=V.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}]),B0=V.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:U0,repeated:!0}]),CC=V.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}]),EC=V.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:dc},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:pr},{no:4,name:"other_participants",kind:"message",T:pr,repeated:!0}]),V0=V.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:mr},{no:2,name:"subscription",kind:"message",T:hc},{no:3,name:"publish_tracks",kind:"message",T:Hd,repeated:!0},{no:4,name:"data_channels",kind:"message",T:z0,repeated:!0},{no:5,name:"offer",kind:"message",T:mr},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:$0,repeated:!0}]),$0=V.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),z0=V.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:V.getEnumType(Bn)}]),Yn=V.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:V.getEnumType(uC),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"}]),H0=V.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),_C=V.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),RC=V.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:AC,repeated:!0}]),AC=V.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}]),PC=V.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:V.getEnumType(tC)}]),NC=V.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:V.getEnumType(qd)},{no:3,name:"message",kind:"scalar",T:9}]),qd=V.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),IC=V.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function MC(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var fa={exports:{}},OC=fa.exports,Jf;function DC(){return Jf||(Jf=1,function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(OC,function(){var t=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(p,v){var b=p[v];if(typeof b.bind=="function")return b.bind(p);try{return Function.prototype.bind.call(b,p)}catch{return function(){return Function.prototype.apply.apply(b,[p,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&i?c:console[p]!==void 0?a(console,p):console.log!==void 0?a(console,"log"):t}function u(){for(var p=this.getLevel(),v=0;v<r.length;v++){var b=r[v];this[b]=v<p?t:this.methodFactory(b,p,this.name)}if(this.log=this.debug,typeof console===n&&p<this.levels.SILENT)return"No console available for logging"}function d(p){return function(){typeof console!==n&&(u.call(this),this[p].apply(this,arguments))}}function h(p,v,b){return l(p)||d.apply(this,arguments)}function f(p,v){var b=this,w,S,k,x="loglevel";typeof p=="string"?x+=":"+p:typeof p=="symbol"&&(x=void 0);function T(R){var I=(r[R]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=I;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+I+";"}catch{}}}function P(){var R;if(!(typeof window===n||!x)){try{R=window.localStorage[x]}catch{}if(typeof R===n)try{var I=window.document.cookie,L=encodeURIComponent(x),U=I.indexOf(L+"=");U!==-1&&(R=/^([^;]+)/.exec(I.slice(U+L.length+1))[1])}catch{}return b.levels[R]===void 0&&(R=void 0),R}}function A(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(R){var I=R;if(typeof I=="string"&&b.levels[I.toUpperCase()]!==void 0&&(I=b.levels[I.toUpperCase()]),typeof I=="number"&&I>=0&&I<=b.levels.SILENT)return I;throw new TypeError("log.setLevel() called with invalid level: "+R)}b.name=p,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=v||h,b.getLevel=function(){return k??S??w},b.setLevel=function(R,I){return k=N(R),I!==!1&&T(k),u.call(b)},b.setDefaultLevel=function(R){S=N(R),P()||b.setLevel(R,!1)},b.resetLevel=function(){k=null,A(),u.call(b)},b.enableAll=function(R){b.setLevel(b.levels.TRACE,R)},b.disableAll=function(R){b.setLevel(b.levels.SILENT,R)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var R in s)s[R].rebuild()},w=N(o?o.getLevel():"WARN");var y=P();y!=null&&(k=N(y)),u.call(b)}o=new f,o.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[v];return b||(b=s[v]=new f(v,o.methodFactory)),b};var g=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return s},o.default=o,o})}(fa)),fa.exports}var pc=DC(),ku;(function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"})(ku||(ku={}));var Hn;(function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"})(Hn||(Hn={}));let qe=pc.getLogger("livekit");const LC=Object.values(Hn).map(e=>pc.getLogger(e));qe.setDefaultLevel(ku.info);function xi(e){const t=pc.getLogger(e);return t.setDefaultLevel(qe.getLevel()),t}function FC(e,t){for(const n of LC)n.setLevel(e)}const jC=pc.getLogger("lk-e2ee"),Es=7e3,UC=[0,300,4*300,9*300,16*300,Es,Es,Es,Es,Es];class BC{constructor(t){this._retryDelays=t!==void 0?[...t]:UC}nextRetryDelayInMs(t){if(t.retryCount>=this._retryDelays.length)return null;const n=this._retryDelays[t.retryCount];return t.retryCount<=1?n:n+Math.random()*1e3}}function VC(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}function M(e,t,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(e,t||[])).next())})}function Qf(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function mi(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Qf=="function"?Qf(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}var jo={exports:{}},ep;function $C(){if(ep)return jo.exports;ep=1;var e=typeof Reflect=="object"?Reflect:null,t=e&&typeof e.apply=="function"?e.apply:function(x,T,P){return Function.prototype.apply.call(x,T,P)},n;e&&typeof e.ownKeys=="function"?n=e.ownKeys:Object.getOwnPropertySymbols?n=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:n=function(x){return Object.getOwnPropertyNames(x)};function i(k){console&&console.warn&&console.warn(k)}var r=Number.isNaN||function(x){return x!==x};function s(){s.init.call(this)}jo.exports=s,jo.exports.once=b,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(k){if(typeof k!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof k)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(k){if(typeof k!="number"||k<0||r(k))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+k+".");o=k}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||r(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function c(k){return k._maxListeners===void 0?s.defaultMaxListeners:k._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(x){for(var T=[],P=1;P<arguments.length;P++)T.push(arguments[P]);var A=x==="error",N=this._events;if(N!==void 0)A=A&&N.error===void 0;else if(!A)return!1;if(A){var y;if(T.length>0&&(y=T[0]),y instanceof Error)throw y;var R=new Error("Unhandled error."+(y?" ("+y.message+")":""));throw R.context=y,R}var I=N[x];if(I===void 0)return!1;if(typeof I=="function")t(I,this,T);else for(var L=I.length,U=g(I,L),P=0;P<L;++P)t(U[P],this,T);return!0};function l(k,x,T,P){var A,N,y;if(a(T),N=k._events,N===void 0?(N=k._events=Object.create(null),k._eventsCount=0):(N.newListener!==void 0&&(k.emit("newListener",x,T.listener?T.listener:T),N=k._events),y=N[x]),y===void 0)y=N[x]=T,++k._eventsCount;else if(typeof y=="function"?y=N[x]=P?[T,y]:[y,T]:P?y.unshift(T):y.push(T),A=c(k),A>0&&y.length>A&&!y.warned){y.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+y.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=k,R.type=x,R.count=y.length,i(R)}return k}s.prototype.addListener=function(x,T){return l(this,x,T,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(x,T){return l(this,x,T,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(k,x,T){var P={fired:!1,wrapFn:void 0,target:k,type:x,listener:T},A=u.bind(P);return A.listener=T,P.wrapFn=A,A}s.prototype.once=function(x,T){return a(T),this.on(x,d(this,x,T)),this},s.prototype.prependOnceListener=function(x,T){return a(T),this.prependListener(x,d(this,x,T)),this},s.prototype.removeListener=function(x,T){var P,A,N,y,R;if(a(T),A=this._events,A===void 0)return this;if(P=A[x],P===void 0)return this;if(P===T||P.listener===T)--this._eventsCount===0?this._events=Object.create(null):(delete A[x],A.removeListener&&this.emit("removeListener",x,P.listener||T));else if(typeof P!="function"){for(N=-1,y=P.length-1;y>=0;y--)if(P[y]===T||P[y].listener===T){R=P[y].listener,N=y;break}if(N<0)return this;N===0?P.shift():p(P,N),P.length===1&&(A[x]=P[0]),A.removeListener!==void 0&&this.emit("removeListener",x,R||T)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(x){var T,P,A;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete P[x]),this;if(arguments.length===0){var N=Object.keys(P),y;for(A=0;A<N.length;++A)y=N[A],y!=="removeListener"&&this.removeAllListeners(y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=P[x],typeof T=="function")this.removeListener(x,T);else if(T!==void 0)for(A=T.length-1;A>=0;A--)this.removeListener(x,T[A]);return this};function h(k,x,T){var P=k._events;if(P===void 0)return[];var A=P[x];return A===void 0?[]:typeof A=="function"?T?[A.listener||A]:[A]:T?v(A):g(A,A.length)}s.prototype.listeners=function(x){return h(this,x,!0)},s.prototype.rawListeners=function(x){return h(this,x,!1)},s.listenerCount=function(k,x){return typeof k.listenerCount=="function"?k.listenerCount(x):f.call(k,x)},s.prototype.listenerCount=f;function f(k){var x=this._events;if(x!==void 0){var T=x[k];if(typeof T=="function")return 1;if(T!==void 0)return T.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function g(k,x){for(var T=new Array(x),P=0;P<x;++P)T[P]=k[P];return T}function p(k,x){for(;x+1<k.length;x++)k[x]=k[x+1];k.pop()}function v(k){for(var x=new Array(k.length),T=0;T<x.length;++T)x[T]=k[T].listener||k[T];return x}function b(k,x){return new Promise(function(T,P){function A(y){k.removeListener(x,N),P(y)}function N(){typeof k.removeListener=="function"&&k.removeListener("error",A),T([].slice.call(arguments))}S(k,x,N,{once:!0}),x!=="error"&&w(k,A,{once:!0})})}function w(k,x,T){typeof k.on=="function"&&S(k,"error",x,T)}function S(k,x,T,P){if(typeof k.on=="function")P.once?k.once(x,T):k.on(x,T);else if(typeof k.addEventListener=="function")k.addEventListener(x,function A(N){P.once&&k.removeEventListener(x,A),T(N)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof k)}return jo.exports}var ii=$C();let W0=!0,q0=!0;function Bs(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function xr(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(o,a){if(o!==t)return r.apply(this,arguments);const c=l=>{const u=n(l);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,c),r.apply(this,[o,c])};const s=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(a))return s.apply(this,arguments);const c=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(o){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),o&&this.addEventListener(t,this["_on"+t]=o)},enumerable:!0,configurable:!0})}function zC(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(W0=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function HC(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(q0=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function G0(){if(typeof window=="object"){if(W0)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Gd(e,t){q0&&console.warn(e+" is deprecated, please use "+t+" instead.")}function WC(e){const t={browser:null,version:null};if(typeof e>"u"||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const i=n.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Bs(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Bs(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=parseInt(Bs(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Bs(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser="Not a supported browser.",t;return t}function tp(e){return Object.prototype.toString.call(e)==="[object Object]"}function K0(e){return tp(e)?Object.keys(e).reduce(function(t,n){const i=tp(e[n]),r=i?K0(e[n]):e[n],s=i&&!Object.keys(r).length;return r===void 0||s?t:Object.assign(t,{[n]:r})},{}):e}function Su(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?Su(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(r=>{Su(e,e.get(r),n)})}))}function np(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(t===null)return r;const s=[];return e.forEach(o=>{o.type==="track"&&o.trackIdentifier===t.id&&s.push(o)}),s.forEach(o=>{e.forEach(a=>{a.type===i&&a.trackId===o.id&&Su(e,a,r)})}),r}const ip=G0;function Y0(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const u=typeof a[l]=="object"?a[l]:{ideal:a[l]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const d=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){c.optional=c.optional||[];let h={};typeof u.ideal=="number"?(h[d("min",l)]=u.ideal,c.optional.push(h),h={},h[d("max",l)]=u.ideal,c.optional.push(h)):(h[d("",l)]=u.ideal,c.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",l)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(h,l)]=u[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},r=function(a,c){if(t.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const l=function(u,d,h){d in u&&!(h in u)&&(u[h]=u[d],delete u[d])};a=JSON.parse(JSON.stringify(a)),l(a.audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const u=t.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let d;if(l.exact==="environment"||l.ideal==="environment"?d=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(d=["front"]),d)return n.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>d.some(p=>g.label.toLowerCase().includes(p)));return!f&&h.length&&d.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),ip("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return ip("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return t.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,l){r(a,u=>{n.webkitGetUserMedia(u,c,d=>{l&&l(s(d))})})};if(n.getUserMedia=o.bind(n),n.mediaDevices.getUserMedia){const a=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(c){return r(c,l=>a(l).then(u=>{if(l.audio&&!u.getAudioTracks().length||l.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function Z0(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function X0(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;e.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):s={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(r=>{let s;e.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.id):s={track:r};const o=new Event("track");o.track=r,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else xr(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function J0(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(a,c){let l=r.apply(this,arguments);return l||(l=t(this,a),this._senders.push(l)),l};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(t(this,o))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof e=="object"&&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 i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Q0(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){const s=n.apply(this,[]);return s.forEach(o=>o._pc=this),s});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),e.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(o=>np(o,s.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(s=>s._pc=this),r}),xr(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>np(s,r.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 i=arguments[0];let r,s,o;return this.getSenders().forEach(a=>{a.track===i&&(r?o=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(s?o=!0:s=a),a.track===i)),o||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ey(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(l=>{if(this.getSenders().find(d=>d.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();n.apply(this,arguments);const c=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function ty(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ey(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const u=n.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(d=>this._reverseStreams[d.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(d=>{if(this.getSenders().find(f=>f.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const d=new e.MediaStream(u.getTracks());this._streams[u.id]=d,this._reverseStreams[d.id]=u,u=d}i.apply(this,[u])};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},e.RTCPeerConnection.prototype.addTrack=function(u,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(p=>p===u))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(p=>p.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[d.id];if(g)g.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new e.MediaStream([u]);this._streams[d.id]=p,this._reverseStreams[p.id]=d,this.addStream(p)}return this.getSenders().find(p=>p.track===u)};function s(l,u){let d=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];d=d.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:d})}function o(l,u){let d=u.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];d=d.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:u.type,sdp:d})}["createOffer","createAnswer"].forEach(function(l){const u=e.RTCPeerConnection.prototype[l],d={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[g=>{const p=s(this,g);h[0].apply(null,[p])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):u.apply(this,arguments).then(g=>s(this,g))}};e.RTCPeerConnection.prototype[l]=d[l]});const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:s(this,l)}}),e.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(p=>u.track===p)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function wu(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const i=e.RTCPeerConnection.prototype[n],r={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=r[n]})}function ny(e,t){xr(e,"negotiationneeded",n=>{const i=n.target;if(!((t.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return n})}var rp=Object.freeze({__proto__:null,fixNegotiationNeeded:ny,shimAddTrackRemoveTrack:ty,shimAddTrackRemoveTrackWithNative:ey,shimGetSendersWithDtmf:J0,shimGetUserMedia:Y0,shimMediaStream:Z0,shimOnTrack:X0,shimPeerConnection:wu,shimSenderReceiverGetStats:Q0});function iy(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(r,s,o){Gd("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(r).then(s,o)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const r=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function qC(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}function ry(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Tu(e,t){if(typeof e!="object"||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=e.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};e.RTCPeerConnection.prototype[r]=o[r]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[s,o,a]=arguments;return i.apply(this,[s||null]).then(c=>{if(t.version<53&&!o)try{c.forEach(l=>{l.type=n[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((u,d)=>{c.set(d,Object.assign({},u,{type:n[u.type]||u.type}))})}return c}).then(o,a)}}function sy(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function oy(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i}),xr(e,"track",n=>(n.receiver._pc=n.srcElement,n)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ay(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(n){Gd("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&n.getTracks().includes(i.track)&&this.removeTrack(i)})})}function cy(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ly(e){if(!(typeof e=="object"&&e.RTCPeerConnection))return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=t.apply(this,arguments);if(r){const{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function uy(e){if(!(typeof e=="object"&&e.RTCRtpSender))return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const i=t.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function dy(e){if(!(typeof e=="object"&&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 hy(e){if(!(typeof e=="object"&&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 sp=Object.freeze({__proto__:null,shimAddTransceiver:ly,shimCreateAnswer:hy,shimCreateOffer:dy,shimGetDisplayMedia:qC,shimGetParameters:uy,shimGetUserMedia:iy,shimOnTrack:ry,shimPeerConnection:Tu,shimRTCDataChannel:cy,shimReceiverGetStats:oy,shimRemoveStream:ay,shimSenderGetStats:sy});function fy(e){if(!(typeof e!="object"||!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(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>t.call(this,r,i)),i.getVideoTracks().forEach(r=>t.call(this,r,i))},e.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(n){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(n);if(i===-1)return;this._localStreams.splice(i,1);const r=n.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function py(e){if(!(typeof e!="object"||!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(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const o=new Event("addstream");o.stream=s,i.dispatchEvent(o)})}),t.apply(i,arguments)}}}function my(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(l,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h},t.createAnswer=function(l,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[d]);return u?(h.then(l,u),Promise.resolve()):h};let a=function(c,l,u){const d=r.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d};t.setLocalDescription=a,a=function(c,l,u){const d=s.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d},t.setRemoteDescription=a,a=function(c,l,u){const d=o.apply(this,[c]);return u?(d.then(l,u),Promise.resolve()):d},t.addIceCandidate=a}function gy(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const n=t.mediaDevices,i=n.getUserMedia.bind(n);t.mediaDevices.getUserMedia=r=>i(by(r))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(i,r,s){t.mediaDevices.getUserMedia(i).then(r,s)}).bind(t))}function by(e){return e&&e.video!==void 0?Object.assign({},e,{video:K0(e.video)}):e}function yy(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(Gd("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(i.iceServers[o])}i.iceServers=s}return new t(i,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function vy(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function xy(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function ky(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var op=Object.freeze({__proto__:null,shimAudioContext:ky,shimCallbacksAPI:my,shimConstraints:by,shimCreateOfferLegacy:xy,shimGetUserMedia:gy,shimLocalStreamsAPI:fy,shimRTCIceServerUrls:yy,shimRemoteStreamsAPI:py,shimTrackEventTransceiver:vy}),Qc={exports:{}},ap;function GC(){return ap||(ap=1,function(e){const t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(n){return n.trim().split(`
|
|
3
3
|
`).map(i=>i.trim())},t.splitSections=function(n){return n.split(`
|
|
4
4
|
m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
|
|
5
5
|
`)},t.getDescription=function(n){const i=t.splitSections(n);return i&&i[0]},t.getMediaSections=function(n){const i=t.splitSections(n);return i.shift(),i},t.matchPrefix=function(n,i){return t.splitLines(n).filter(r=>r.indexOf(i)===0)},t.parseCandidate=function(n){let i;n.indexOf("a=candidate:")===0?i=n.substring(12).split(" "):i=n.substring(10).split(" ");const r={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let s=8;s<i.length;s+=2)switch(i[s]){case"raddr":r.relatedAddress=i[s+1];break;case"rport":r.relatedPort=parseInt(i[s+1],10);break;case"tcptype":r.tcpType=i[s+1];break;case"ufrag":r.ufrag=i[s+1],r.usernameFragment=i[s+1];break;default:r[i[s]]===void 0&&(r[i[s]]=i[s+1]);break}return r},t.writeCandidate=function(n){const i=[];i.push(n.foundation);const r=n.component;r==="rtp"?i.push(1):r==="rtcp"?i.push(2):i.push(r),i.push(n.protocol.toUpperCase()),i.push(n.priority),i.push(n.address||n.ip),i.push(n.port);const s=n.type;return i.push("typ"),i.push(s),s!=="host"&&n.relatedAddress&&n.relatedPort&&(i.push("raddr"),i.push(n.relatedAddress),i.push("rport"),i.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(i.push("ufrag"),i.push(n.usernameFragment||n.ufrag)),"candidate:"+i.join(" ")},t.parseIceOptions=function(n){return n.substring(14).split(" ")},t.parseRtpMap=function(n){let i=n.substring(9).split(" ");const r={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),r.name=i[0],r.clockRate=parseInt(i[1],10),r.channels=i.length===3?parseInt(i[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(n){let i=n.payloadType;n.preferredPayloadType!==void 0&&(i=n.preferredPayloadType);const r=n.channels||n.numChannels||1;return"a=rtpmap:"+i+" "+n.name+"/"+n.clockRate+(r!==1?"/"+r:"")+`\r
|
|
@@ -30,12 +30,12 @@ a=ice-pwd:`+n.password+`\r
|
|
|
30
30
|
o=`+(r||"thisisadapterortc")+" "+s+" "+o+` IN IP4 127.0.0.1\r
|
|
31
31
|
s=-\r
|
|
32
32
|
t=0 0\r
|
|
33
|
-
`},t.getDirection=function(n,i){const r=t.splitLines(n);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(n){return t.splitLines(n)[0].split(" ")[0].substring(2)},t.isRejected=function(n){return n.split(" ",2)[1]==="0"},t.parseMLine=function(n){const r=t.splitLines(n)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(n){const r=t.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=t.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},e.exports=t}(Qc)),Qc.exports}var
|
|
33
|
+
`},t.getDirection=function(n,i){const r=t.splitLines(n);for(let s=0;s<r.length;s++)switch(r[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[s].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(n){return t.splitLines(n)[0].split(" ")[0].substring(2)},t.isRejected=function(n){return n.split(" ",2)[1]==="0"},t.parseMLine=function(n){const r=t.splitLines(n)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(n){const r=t.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=t.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},e.exports=t}(Qc)),Qc.exports}var Sy=GC(),Jr=MC(Sy),KC=sT({__proto__:null,default:Jr},[Sy]);function pa(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new t(i),s=Jr.parseCandidate(i.candidate);for(const o in s)o in r||Object.defineProperty(r,o,{value:s[o]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(i)},e.RTCIceCandidate.prototype=t.prototype,xr(e,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new e.RTCIceCandidate(n.candidate),writable:"false"}),n))}function Cu(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||xr(e,"icecandidate",t=>{if(t.candidate){const n=Jr.parseCandidate(t.candidate.candidate);n.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.priority>>24])}return t})}function ma(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const n=function(a){if(!a||!a.sdp)return!1;const c=Jr.splitSections(a.sdp);return c.shift(),c.some(l=>{const u=Jr.parseMLine(l);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},r=function(a){let c=65536;return t.browser==="firefox"&&(t.version<57?a===-1?c=16384:c=2147483637:t.version<60?c=t.version===57?65535:65536:c=2147483637),c},s=function(a,c){let l=65536;t.browser==="firefox"&&t.version===57&&(l=65535);const u=Jr.matchPrefix(a.sdp,"a=max-message-size:");return u.length>0?l=parseInt(u[0].substring(19),10):t.browser==="firefox"&&c!==-1&&(l=2147483637),l},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const c=i(arguments[0]),l=r(c),u=s(arguments[0],c);let d;l===0&&u===0?d=Number.POSITIVE_INFINITY:l===0||u===0?d=Math.max(l,u):d=Math.min(l,u);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return d}}),this._sctp=h}return o.apply(this,arguments)}}function ga(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(i,r){const s=i.send;i.send=function(){const a=arguments[0],c=a.length||a.size||a.byteLength;if(i.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return t(r,this),r},xr(e,"datachannel",i=>(t(i.channel,i.target),i))}function Eu(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(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{const i=t[n];t[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",r);s.dispatchEvent(o)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function _u(e,t){if(!e.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t._safariVersion>=13.1)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
|
|
34
34
|
a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
35
35
|
`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
|
|
36
|
-
`);e.RTCSessionDescription&&r instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function ba(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ya(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var YC=Object.freeze({__proto__:null,removeExtmapAllowMixed:_u,shimAddIceCandidateNullOrEmpty:ba,shimConnectionState:Eu,shimMaxMessageSize:ma,shimParameterlessSetLocalDescription:ya,shimRTCIceCandidate:pa,shimRTCIceCandidateRelayProtocol:Cu,shimSendThrowTypeError:ga});function ZC(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Gy,i=WC(e),r={browserDetails:i,commonShim:YC,extractVersion:Bs,disableLog:zC,disableWarnings:HC,sdp:KC};switch(i.browser){case"chrome":if(!rp||!wu||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=rp,ba(e,i),ya(e),Yy(e,i),Zy(e),wu(e,i),Xy(e),t0(e,i),Jy(e),Qy(e),n0(e,i),pa(e),Cu(e),Eu(e),ma(e,i),ga(e),_u(e,i);break;case"firefox":if(!sp||!Tu||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=sp,ba(e,i),ya(e),i0(e,i),Tu(e,i),r0(e),a0(e),s0(e),o0(e),c0(e),l0(e),u0(e),d0(e),h0(e),pa(e),Eu(e),ma(e,i),ga(e);break;case"safari":if(!op||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=op,ba(e,i),ya(e),y0(e),x0(e),m0(e),f0(e),p0(e),v0(e),g0(e),k0(e),pa(e),Cu(e),ma(e,i),ga(e),_u(e,i);break;default:n("Unsupported browser!");break}return r}ZC({window:typeof window>"u"?void 0:window});const XC=10,_s="lk_e2ee",JC="LKFrameEncryptionKey",QC={sharedKey:!1,ratchetSalt:JC,ratchetWindowSize:8,failureTolerance:XC,keyringSize:16};var Ui;(function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"})(Ui||(Ui={}));var cp;(function(e){e.KeyRatcheted="keyRatcheted"})(cp||(cp={}));var Fi;(function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"})(Fi||(Fi={}));var lp;(function(e){e.Error="cryptorError"})(lp||(lp={}));function eE(){return tE()||Ru()}function Ru(){return typeof window.RTCRtpScriptTransform<"u"}function tE(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class K4 extends ii.EventEmitter{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{qe.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},QC),t),this.on(Ui.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const r={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(Ui.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,n){this.emit(Ui.RatchetRequest,t,n)}}class Gi extends Error{constructor(t,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=t}}var Ge;(function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"})(Ge||(Ge={}));class ut extends Gi{constructor(t,n,i,r){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Ge[n]}}class Kd extends Gi{constructor(t){super(21,t??"device is unsupported"),this.name="DeviceUnsupportedError"}}class gi extends Gi{constructor(t){super(20,t??"track is invalid"),this.name="TrackInvalidError"}}class nE extends Gi{constructor(t){super(10,t??"unsupported server"),this.name="UnsupportedServer"}}class Bt extends Gi{constructor(t){super(12,t??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Au extends Gi{constructor(t){super(13,t??"unable to negotiate"),this.name="NegotiationError"}}class up extends Gi{constructor(t,n){super(15,t),this.name="PublishTrackError",this.status=n}}class dp extends Gi{constructor(t,n){super(15,t),this.reason=n,this.reasonName=typeof n=="string"?n:qd[n]}}var Fa;(function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"})(Fa||(Fa={}));(function(e){function t(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?e.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?e.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?e.DeviceInUse:e.Other}e.getFailure=t})(Fa||(Fa={}));var hp;(function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"})(hp||(hp={}));var j;(function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"})(j||(j={}));var Q;(function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"})(Q||(Q={}));var fe;(function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"})(fe||(fe={}));var he;(function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"})(he||(he={}));function iE(e){return typeof e>"u"?e:typeof structuredClone=="function"?typeof e=="object"&&e!==null?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}const rE=/version\/(\d+(\.?_?\d+)+)/i;let el;function kn(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(el===void 0||t){const i=sE.find(r=>{let{test:s}=r;return s.test(n)});el=i==null?void 0:i.describe(n)}return el}const sE=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:"Firefox",version:va(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:tl(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:"Chrome",version:va(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:tl(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:"Safari",version:va(rE,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:tl(e)}}}];function va(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function tl(e){return e.includes("mac os")?va(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var oE="2.13.8";const aE=oE,cE=16;class Zt{}Zt.setTimeout=function(){return setTimeout(...arguments)};Zt.setInterval=function(){return setInterval(...arguments)};Zt.clearTimeout=function(){return clearTimeout(...arguments)};Zt.clearInterval=function(){return clearInterval(...arguments)};const lE=5e3,Rs=[];var Pn;(function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"})(Pn||(Pn={}));class B extends ii.EventEmitter{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=B.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=qe,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),lE):this.handleAppVisibilityChanged()},this.log=xi((r=i.loggerName)!==null&&r!==void 0?r:Hn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=B.Source.Unknown}get logContext(){var t;return Object.assign(Object.assign({},(t=this.loggerContextCb)===null||t===void 0?void 0:t.call(this)),He(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===B.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===B.Kind.Video&&this.addAppVisibilityListener(),t||(n==="audio"&&(Rs.forEach(s=>{s.parentElement===null&&!t&&(t=s)}),t&&Rs.splice(Rs.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),$r(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return t.play().then(()=>{this.emit(r?he.AudioPlaybackStarted:he.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?he.AudioPlaybackFailed:he.VideoPlaybackFailed,s):s.name==="AbortError"?qe.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):qe.warn("could not playback ".concat(r?"audio":"video"),s),r&&t&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(he.ElementAttached,t),t}detach(t){try{if(t){Qr(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(he.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach(i=>{Qr(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(he.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&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(t){t.loggerName&&(this.log=xi(t.loggerName)),t.loggerContextCb&&(this.loggerContextCb=t.loggerContextCb)}recycleElement(t){if(t instanceof HTMLAudioElement){let n=!0;t.pause(),Rs.forEach(i=>{i.parentElement||(n=!1)}),n&&Rs.push(t)}}handleAppVisibilityChanged(){return M(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===B.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(t=>t.play().catch(()=>{})),0)})}addAppVisibilityListener(){hn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){hn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function $r(e,t){let n;t.srcObject instanceof MediaStream?n=t.srcObject:n=new MediaStream;let i;e.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(e)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(e)),(!gr()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(gr()||as())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function Qr(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(t=e.Kind||(e.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=e.Source||(e.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=e.StreamState||(e.StreamState={}));function r(l){switch(l){case t.Audio:return Un.AUDIO;case t.Video:return Un.VIDEO;default:return Un.DATA}}e.kindToProto=r;function s(l){switch(l){case Un.AUDIO:return t.Audio;case Un.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=s;function o(l){switch(l){case n.Camera:return Lt.CAMERA;case n.Microphone:return Lt.MICROPHONE;case n.ScreenShare:return Lt.SCREEN_SHARE;case n.ScreenShareAudio:return Lt.SCREEN_SHARE_AUDIO;default:return Lt.UNKNOWN}}e.sourceToProto=o;function a(l){switch(l){case Lt.CAMERA:return n.Camera;case Lt.MICROPHONE:return n.Microphone;case Lt.SCREEN_SHARE:return n.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=a;function c(l){switch(l){case yu.ACTIVE:return i.Active;case yu.PAUSED:return i.Paused;default:return i.Unknown}}e.streamStateFromProto=c})(B||(B={}));class st{constructor(t,n,i,r,s){if(typeof t=="object")this.width=t.width,this.height=t.height,this.aspectRatio=t.aspectRatio,this.encoding={maxBitrate:t.maxBitrate,maxFramerate:t.maxFramerate,priority:t.priority};else if(n!==void 0&&i!==void 0)this.width=t,this.height=n,this.aspectRatio=t/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const uE=["vp8","h264"],dE=["vp8","h264","vp9","av1"];function hE(e){return!!uE.find(t=>t===e)}var fp;(function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"})(fp||(fp={}));var Pu;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(Pu||(Pu={}));const io={h90:new st(160,90,9e4,20),h180:new st(320,180,16e4,20),h216:new st(384,216,18e4,20),h360:new st(640,360,45e4,20),h540:new st(960,540,8e5,25),h720:new st(1280,720,17e5,30),h1080:new st(1920,1080,3e6,30),h1440:new st(2560,1440,5e6,30),h2160:new st(3840,2160,8e6,30)},Nu={h120:new st(160,120,7e4,20),h180:new st(240,180,125e3,20),h240:new st(320,240,14e4,20),h360:new st(480,360,33e4,20),h480:new st(640,480,5e5,20),h540:new st(720,540,6e5,25),h720:new st(960,720,13e5,30),h1080:new st(1440,1080,23e5,30),h1440:new st(1920,1440,38e5,30)},Yd={h360fps3:new st(640,360,2e5,3,"medium"),h360fps15:new st(640,360,4e5,15,"medium"),h720fps5:new st(1280,720,8e5,5,"medium"),h720fps15:new st(1280,720,15e5,15,"medium"),h720fps30:new st(1280,720,2e6,30,"medium"),h1080fps15:new st(1920,1080,25e5,15,"medium"),h1080fps30:new st(1920,1080,5e6,30,"medium"),original:new st(0,0,7e6,30,"medium")},fE="|",pp="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function pE(e){const t=e.split(fE);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}function pn(e){return M(this,void 0,void 0,function*(){return new Promise(t=>Zt.setTimeout(t,e))})}function Iu(){return"addTransceiver"in RTCPeerConnection.prototype}function Mu(){return"addTrack"in RTCPeerConnection.prototype}function mE(){if(!("getCapabilities"in RTCRtpSender)||gr())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e){for(const n of e.codecs)if(n.mimeType==="video/AV1"){t=!0;break}}return t}function gE(){if(!("getCapabilities"in RTCRtpSender)||as())return!1;if(gr()){const n=kn();if(n!=null&&n.version&&br(n.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e){for(const n of e.codecs)if(n.mimeType==="video/VP9"){t=!0;break}}return t}function yi(e){return e==="av1"||e==="vp9"}function Ou(e){return document?(e||(e=document.createElement("audio")),"setSinkId"in e):!1}function bE(){return typeof RTCPeerConnection>"u"?!1:Iu()||Mu()}function as(){var e;return((e=kn())===null||e===void 0?void 0:e.name)==="Firefox"}function gr(){var e;return((e=kn())===null||e===void 0?void 0:e.name)==="Safari"}function mp(){const e=kn();return(e==null?void 0:e.name)==="Safari"||(e==null?void 0:e.os)==="iOS"}function yE(){const e=kn();return(e==null?void 0:e.name)==="Safari"&&e.version.startsWith("17.")}function vE(e){return e||(e=kn()),(e==null?void 0:e.name)==="Safari"&&br(e.version,"18.3")>0}function w0(){var e,t;return hn()?(t=(e=navigator.userAgentData)===null||e===void 0?void 0:e.mobile)!==null&&t!==void 0?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function xE(){const e=kn(),t="17.2";if(e)return e.name!=="Safari"&&e.os!=="iOS"||e.os==="iOS"&&e.osVersion&&br(t,e.osVersion)>=0?!0:e.name==="Safari"&&br(t,e.version)>=0}function hn(){return typeof document<"u"}function ni(){return navigator.product=="ReactNative"}function Du(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function T0(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function C0(){if(!ni())return;let e=T0();if(e)return e.platform}function gp(){if(hn())return window.devicePixelRatio;if(ni()){let e=T0();if(e)return e.devicePixelRatio}return 1}function br(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return e===""&&t!==""?-1:t===""?1:n.length==i.length?0:n.length<i.length?-1:1}function kE(e){for(const t of e)t.target.handleResize(t)}function SE(e){for(const t of e)t.target.handleVisibilityChanged(t)}let nl=null;const bp=()=>(nl||(nl=new ResizeObserver(kE)),nl);let il=null;const yp=()=>(il||(il=new IntersectionObserver(SE,{root:null,rootMargin:"0px"})),il);function wE(){var e;const t=new cC({sdk:Ay.JS,protocol:cE,version:aE});return ni()&&(t.os=(e=C0())!==null&&e!==void 0?e:""),t}function vp(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let As;function rl(){if(!As){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[As]=i.stream.getAudioTracks(),!As)throw Error("Could not get empty media stream audio track");As.enabled=!1}return As.clone()}class zr{constructor(t,n){this.onFinally=n,this.promise=new Promise((i,r)=>M(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,t&&(yield t(i,r))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function TE(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=Xd();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),o=i.createAnalyser();o.minDecibels=n.minDecibels,o.maxDecibels=n.maxDecibels,o.fftSize=n.fftSize,o.smoothingTimeConstant=n.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let u=0;for(const h of a)u+=Math.pow(h/255,2);return Math.sqrt(u/a.length)},analyser:o,cleanup:()=>M(this,void 0,void 0,function*(){yield i.close(),n.cloneTrack&&r.stop()})}}function CE(e){return dE.includes(e)}function Bi(e){if(typeof e=="string"||typeof e=="number")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 EE(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}function Lu(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function _E(e,t){return e.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const u=(l=t.get(i))!==null&&l!==void 0?l:Date.now(),d=Date.now();return c?t.delete(i):t.set(i,u),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:u,lastReceivedTime:d}})}function RE(e){const{id:t,timestamp:n,message:i,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function xp(e){switch(e.reason){case Ge.LeaveRequest:return e.context;case Ge.Cancelled:return Vn.CLIENT_INITIATED;case Ge.NotAllowed:return Vn.USER_REJECTED;case Ge.ServerUnreachable:return Vn.JOIN_FAILURE;default:return Vn.UNKNOWN_REASON}}function xa(e){return e!==void 0?Number(e):void 0}function ir(e){return e!==void 0?BigInt(e):void 0}function es(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Qn(e){return!!e&&e.kind==B.Kind.Audio}function ps(e){return!!e&&e.kind==B.Kind.Video}function Pi(e){return es(e)&&ps(e)}function di(e){return es(e)&&Qn(e)}function Fu(e){return!!e&&!e.isLocal}function AE(e){return!!e&&!e.isLocal}function sl(e){return Fu(e)&&ps(e)}function PE(e){return e.isLocal}function NE(e,t){const n=[];let i=new TextEncoder().encode(e);for(;i.length>t;){let r=t;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function E0(e,t,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=R0(e??{}),u=t==null?void 0:t.processor,d=n==null?void 0:n.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(ju(h.audio,t),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(h.audio.processor=c??u)),h.video&&(ju(h.video,n),(r=(o=h.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||d)&&(h.video.processor=l??d)),h}function ju(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function Zd(e){var t,n,i,r;const s={};if(e.video)if(typeof e.video=="object"){const o={},a=o,c=e.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":ju(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(t=(i=s.video).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})}else s.video=e.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return e.audio?typeof e.audio=="object"?(s.audio=e.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function _0(e){return M(this,arguments,void 0,function(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=Xd();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([t.mediaStreamTrack])).connect(r),yield pn(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1}()})}function Xd(){var e;const t=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(t){const n=new t({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((e=window.document)===null||e===void 0)&&e.body)){const i=()=>M(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function IE(e){return e==="audioinput"?B.Source.Microphone:e==="videoinput"?B.Source.Camera:B.Source.Unknown}function Uu(e){return e===B.Source.Microphone?"audioinput":e===B.Source.Camera?"videoinput":void 0}function ME(e){var t,n;let i=(t=e.video)!==null&&t!==void 0?t:!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i=typeof i=="boolean"?{}:i,gr()?i=Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:(n=e.audio)!==null&&n!==void 0?n:!1,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function ka(e){return e.split("/")[1].toLowerCase()}function OE(e){const t=[];return e.forEach(n=>{n.track!==void 0&&t.push(new Hd({cid:n.track.mediaStreamID,track:n.trackInfo}))}),t}function He(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?He(e.track):{})}}function DE(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function LE(e,t){var n;e===void 0&&(e={}),t===void 0&&(t={});const i=[...Object.keys(t),...Object.keys(e)],r={};for(const s of i)e[s]!==t[s]&&(r[s]=(n=t[s])!==null&&n!==void 0?n:"");return r}function R0(e){const t=Object.assign({},e);let n,i;return typeof t.audio=="object"&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video=="object"&&t.video.processor&&(i=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:iE(t)}}function FE(e){switch(e){case Lt.CAMERA:return B.Source.Camera;case Lt.MICROPHONE:return B.Source.Microphone;case Lt.SCREEN_SHARE:return B.Source.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return B.Source.ScreenShareAudio;default:return B.Source.Unknown}}class jE extends ii.EventEmitter{constructor(t){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":qe.error(o.error.message),this.emit(Fi.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(Fi.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(Fi.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(Ui.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{qe.error("e2ee worker encountered an error:",{error:n.error}),this.emit(Fi.EncryptionError,n.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(t){if(!eE())throw new Kd("tried to setup end-to-end encryption on an unsupported browser");if(qe.info("setting up e2ee"),t!==this.room){this.room=t,this.setupEventListeners(t,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:jC.getLevel()}};this.worker&&(qe.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(t,n){qe.debug("set e2ee to ".concat(t," for participant ").concat(n)),this.postEnable(t,n)}setSifTrailer(t){!t||t.length===0?qe.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(t)}setupEngine(t){t.on(fe.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(t,n){t.on(j.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==vn.NONE,r.identity)),t.on(j.ConnectionStateChanged,i=>{i===$e.Connected&&t.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==vn.NONE,r.identity)})})}).on(j.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(j.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(j.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),t.localParticipant.on(Q.LocalTrackPublished,i=>M(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),n.on(Ui.SetKey,i=>this.postKey(i)).on(Ui.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(t,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:t,keyIndex:n}};this.worker.postMessage(i)}postKey(t){let{key:n,participantIdentity:i,keyIndex:r}=t;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(t,n){if(this.worker){const i={kind:"enable",data:{enabled:t,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(t){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(t){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:t}};this.worker.postMessage(n)}setupE2EEReceiver(t,n,i){if(t.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(t.receiver,t.mediaStreamID,n,t.kind==="video"?ka(i.mimeType):void 0)}}setupE2EESender(t,n){if(!es(t)||!n){n||qe.warn("early return because sender is not ready");return}this.handleSender(n,t.mediaStreamID,void 0)}handleReceiver(t,n,i,r){return M(this,void 0,void 0,function*(){if(this.worker){if(Ru()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};t.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(_s in t&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=t.writableStream,o=t.readableStream;if(!s||!o){const c=t.createEncodedStreams();t.writableStream=c.writable,s=c.writable,t.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:_s in t}};this.worker.postMessage(a,[o,s])}t[_s]=!0}})}handleSender(t,n,i){var r;if(!(_s in t||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ru()){qe.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};t.transform=new RTCRtpScriptTransform(this.worker,s)}else{qe.info("initialize encoded streams");const s=t.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}t[_s]=!0}}}const ol="default";class Wt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Wt),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=Wt.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){qe.debug("awaiting getUserMedia promise");try{n?yield Wt.userMediaPromiseMap.get(n):yield Promise.all(Wt.userMediaPromiseMap.values())}catch{qe.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(gr()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",u=n?c.kind===n:!0;return l&&u}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o}()})}normalizeDeviceId(t,n,i){return M(this,void 0,void 0,function*(){if(n!==ol)return n;const r=yield this.getDevices(t),s=r.find(a=>a.deviceId===ol);if(!s){qe.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==ol&&a.groupId===(i??s.groupId));if(!o){qe.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(t){return t?Wt.userMediaPromiseMap.has(t):Wt.userMediaPromiseMap.size>0}}Wt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Wt.userMediaPromiseMap=new Map;var qs;(function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"})(qs||(qs={}));class UE{constructor(){this.pendingTasks=new Map,this.taskMutex=new dn,this.nextTaskIndex=0}run(t){return M(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:qs.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=qs.RUNNING,yield t()}finally{n.status=qs.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return M(this,void 0,void 0,function*(){return this.run(()=>M(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function BE(e,t){const n=new URL(EE(e));return t.forEach((i,r)=>{n.searchParams.set(r,i)}),A0(n,"rtc")}function VE(e){const t=new URL(Lu(e));return A0(t,"validate")}function $E(e){return e.endsWith("/")?e:"".concat(e,"/")}function A0(e,t){return e.pathname="".concat($E(e.pathname)).concat(t),e.toString()}const zE=["syncState","trickle","offer","answer","simulate","leave"];function HE(e){const t=zE.indexOf(e.case)>=0;return qe.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}var gt;(function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"})(gt||(gt={}));class Jd{get currentState(){return this.state}get isDisconnected(){return this.state===gt.DISCONNECTING||this.state===gt.DISCONNECTED}get isEstablishingConnection(){return this.state===gt.CONNECTING||this.state===gt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=gt.DISCONNECTED,this.log=qe,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=xi((i=n.loggerName)!==null&&i!==void 0?i:Hn.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=t,this.requestQueue=new UE,this.queuedRequests=[],this.closingLock=new dn,this.connectionLock=new dn,this.state=gt.DISCONNECTED}get logContext(){var t,n;return(n=(t=this.loggerContextCb)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:{}}join(t,n,i,r){return M(this,void 0,void 0,function*(){return this.state=gt.CONNECTING,this.options=i,yield this.connect(t,n,i,r)})}reconnect(t,n,i,r){return M(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=gt.RECONNECTING,this.clearPingInterval(),yield this.connect(t,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(t,n,i,r){this.connectOptions=i;const s=wE(),o=WE(n,s,i),a=BE(t,o),c=VE(a);return new Promise((l,u)=>M(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const h=()=>M(this,void 0,void 0,function*(){this.close(),clearTimeout(f),u(new ut("room connection has been cancelled (signal)",Ge.Cancelled))}),f=setTimeout(()=>{this.close(),u(new ut("room connection has timed out (signal)",Ge.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const g=new URL(a);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=p=>M(this,void 0,void 0,function*(){if(this.state!==gt.CONNECTED){this.state=gt.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(c);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();u(new ut(b,Ge.NotAllowed,v.status))}else u(new ut("Encountered unknown websocket error during connection: ".concat(p.toString()),Ge.InternalError,v.status))}catch(v){u(new ut(v instanceof Error?v.message:"server was not reachable",Ge.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>M(this,void 0,void 0,function*(){var v,b,w;let S;if(typeof p.data=="string"){const k=JSON.parse(p.data);S=Xf.fromJson(k,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)S=Xf.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==gt.CONNECTED){let k=!1;if(((v=S.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=gt.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=S.message.value.pingTimeout,this.pingIntervalDuration=S.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()),l(S.message.value)):this.state===gt.RECONNECTING&&S.message.case!=="leave"?(this.state=gt.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=S.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(S.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),k=!0)):this.isEstablishingConnection&&S.message.case==="leave"?u(new ut("Received leave request while trying to (re)connect",Ge.LeaveRequest,void 0,S.message.value.reason)):i.reconnect||u(new ut("did not receive join response, got ".concat((w=S.message)===null||w===void 0?void 0:w.case," instead"),Ge.InternalError)),!k)return}this.signalLatency&&(yield pn(this.signalLatency)),this.handleSignalResponse(S)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new ut("Websocket got closed during a (re)connection attempt",Ge.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{d()}}))}close(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield t.closingLock.lock();try{if(t.clearPingInterval(),n&&(t.state=gt.DISCONNECTING),t.ws){t.ws.onmessage=null,t.ws.onopen=null,t.ws.onclose=null;const r=new Promise(s=>{t.ws?t.ws.onclose=()=>{s()}:s()});t.ws.readyState<t.ws.CLOSING&&(t.ws.close(),yield Promise.race([r,pn(250)])),t.ws=void 0}}finally{n&&(t.state=gt.DISCONNECTED),i()}}()})}sendOffer(t,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:t.sdp})),this.sendRequest({case:"offer",value:ja(t,n)})}sendAnswer(t,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:t.sdp})),this.sendRequest({case:"answer",value:ja(t,n)})}sendIceCandidate(t,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:t})),this.sendRequest({case:"trickle",value:new $d({candidateInit:JSON.stringify(t),target:n})})}sendMuteTrack(t,n){return this.sendRequest({case:"mute",value:new zd({sid:t,muted:n})})}sendAddTrack(t){return this.sendRequest({case:"addTrack",value:t})}sendUpdateLocalMetadata(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new Fy({requestId:a,metadata:i,name:r,attributes:o})}),a}()})}sendUpdateTrackSettings(t){this.sendRequest({case:"trackSetting",value:t})}sendUpdateSubscription(t){return this.sendRequest({case:"subscription",value:t})}sendSyncState(t){return this.sendRequest({case:"syncState",value:t})}sendUpdateVideoLayers(t,n){return this.sendRequest({case:"updateLayers",value:new Ly({trackSid:t,layers:n})})}sendUpdateSubscriptionPermissions(t,n){return this.sendRequest({case:"subscriptionPermission",value:new By({allParticipants:t,trackPermissions:n})})}sendSimulateScenario(t){return this.sendRequest({case:"simulate",value:t})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:yt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Hy({timestamp:yt.parse(Date.now()),rtt:yt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(t,n){return this.sendRequest({case:"updateAudioTrack",value:new Dy({trackSid:t,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new fc({reason:Vn.CLIENT_INITIATED,action:Xr.DISCONNECT})})}sendRequest(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!HE(n)&&i.state===gt.RECONNECTING){i.queuedRequests.push(()=>M(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield pn(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new dC({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}}()})}handleSignalResponse(t){var n,i;const r=t.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=kp(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=kp(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const t=this.queuedRequests.shift();t&&this.requestQueue.run(t)}}handleOnClose(t){return M(this,void 0,void 0,function*(){if(this.state===gt.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(t),Object.assign(Object.assign({},this.logContext),{reason:t})),n&&n(t)})}handleWSError(t){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:t}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Zt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Zt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Zt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Zt.clearInterval(this.pingInterval)}}function kp(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type;break}return t}function ja(e,t){return new mr({sdp:e.sdp,type:e.type,id:t})}function WE(e,t,n){var i;const r=new URLSearchParams;return r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",ni()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class Sp{constructor(){this.buffer=[],this._totalSize=0}push(t){this.buffer.push(t),this._totalSize+=t.data.byteLength}pop(){const t=this.buffer.shift();return t&&(this._totalSize-=t.data.byteLength),t}getAll(){return this.buffer.slice()}popToSequence(t){for(;this.buffer.length>0&&this.buffer[0].sequence<=t;)this.pop()}alignBufferedAmount(t){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=t)break;this.pop()}}get length(){return this.buffer.length}}class qE{constructor(t){this._map=new Map,this._lastCleanup=0,this.ttl=t}set(t,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(t,{value:n,expiresAt:r}),this}get(t){const n=this._map.get(t);if(n){if(n.expiresAt<Date.now()){this._map.delete(t);return}return n.value}}has(t){const n=this._map.get(t);return n?n.expiresAt<Date.now()?(this._map.delete(t),!1):!0:!1}delete(t){return this._map.delete(t)}clear(){this._map.clear()}cleanup(){const t=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<t&&this._map.delete(n);this._lastCleanup=t}get size(){return this.cleanup(),this._map.size}forEach(t){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&t(i.value,n,this.asValueMap())}map(t){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(t(s,r,i));return n}asValueMap(){const t=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&t.set(n,i.value);return t}}var Dn={},al={},cl={exports:{}},wp;function Qd(){if(wp)return cl.exports;wp=1;var e=cl.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(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return t.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(t){return t.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return t.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(t){var n="candidate:%s %d %s %d %s %d typ %s";return n+=t.raddr!=null?" raddr %s rport %d":"%v%v",n+=t.tcptype!=null?" tcptype %s":"%v",t.generation!=null&&(n+=" generation %d"),n+=t["network-id"]!=null?" network-id %d":"%v",n+=t["network-cost"]!=null?" network-cost %d":"%v",n}},{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(t){var n="ssrc:%d";return t.attribute!=null&&(n+=" %s",t.value!=null&&(n+=":%s")),n}},{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(t){return t.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(t){return t.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(t){return"imageattr:%s %s %s"+(t.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(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(t.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var n="mediaclk:";return n+=t.id!=null?"id=%s %s":"%v%s",n+=t.mediaClockValue!=null?"=%s":"",n+=t.rateNumerator!=null?" rate=%s":"",n+=t.rateDenominator!=null?"/%s":"",n}},{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){var n=e[t];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),cl.exports}var Tp;function GE(){return Tp||(Tp=1,function(e){var t=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,u){if(u&&!l)c[u]=t(a[1]);else for(var d=0;d<l.length;d+=1)a[d+1]!=null&&(c[l[d]]=t(a[d+1]))},i=function(a,c,l){var u=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:u&&!c[a.name]&&(c[a.name]={});var d=a.push?{}:u?c[a.name]:c;n(l.match(a.reg),d,a.names,a.name),a.push&&c[a.push].push(d)},r=Qd(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(a){var c={},l=[],u=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var g=0;g<(r[h]||[]).length;g+=1){var p=r[h][g];if(p.reg.test(f))return i(p,u,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=t(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};e.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(a){return a.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(t),u=0;u<l.length;u+=3)c.push({component:l[u],ip:l[u+1],port:l[u+2]});return c},e.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var u,d=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),d=!0),{scid:u,paused:d}})})}}(al)),al}var ll,Cp;function KE(){if(Cp)return ll;Cp=1;var e=Qd(),t=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(t,function(u){if(a>=l)return u;var d=c[a];switch(a+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,u=[o+"="+l];if(a.names)for(var d=0;d<a.names.length;d+=1){var h=a.names[d];a.name?u.push(c[a.name][h]):u.push(c[a.names[d]])}else u.push(c[a.name]);return n.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return ll=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,u=[];return c.forEach(function(d){e[d].forEach(function(h){h.name in o&&o[h.name]!=null?u.push(i(d,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){u.push(i(d,h,f))})})}),o.media.forEach(function(d){u.push(i("m",e.m[0],d)),l.forEach(function(h){e[h].forEach(function(f){f.name in d&&d[f.name]!=null?u.push(i(h,f,d)):f.push in d&&d[f.push]!=null&&d[f.push].forEach(function(g){u.push(i(h,f,g))})})})}),u.join(`\r
|
|
36
|
+
`);e.RTCSessionDescription&&r instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return n.apply(this,arguments)}}function ba(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ya(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return n.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?n.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>n.apply(this,[o]))})}var YC=Object.freeze({__proto__:null,removeExtmapAllowMixed:_u,shimAddIceCandidateNullOrEmpty:ba,shimConnectionState:Eu,shimMaxMessageSize:ma,shimParameterlessSetLocalDescription:ya,shimRTCIceCandidate:pa,shimRTCIceCandidateRelayProtocol:Cu,shimSendThrowTypeError:ga});function ZC(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=G0,i=WC(e),r={browserDetails:i,commonShim:YC,extractVersion:Bs,disableLog:zC,disableWarnings:HC,sdp:KC};switch(i.browser){case"chrome":if(!rp||!wu||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=rp,ba(e,i),ya(e),Y0(e,i),Z0(e),wu(e,i),X0(e),ty(e,i),J0(e),Q0(e),ny(e,i),pa(e),Cu(e),Eu(e),ma(e,i),ga(e),_u(e,i);break;case"firefox":if(!sp||!Tu||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=sp,ba(e,i),ya(e),iy(e,i),Tu(e,i),ry(e),ay(e),sy(e),oy(e),cy(e),ly(e),uy(e),dy(e),hy(e),pa(e),Eu(e),ma(e,i),ga(e);break;case"safari":if(!op||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=op,ba(e,i),ya(e),yy(e),xy(e),my(e),fy(e),py(e),vy(e),gy(e),ky(e),pa(e),Cu(e),ma(e,i),ga(e),_u(e,i);break;default:n("Unsupported browser!");break}return r}ZC({window:typeof window>"u"?void 0:window});const XC=10,_s="lk_e2ee",JC="LKFrameEncryptionKey",QC={sharedKey:!1,ratchetSalt:JC,ratchetWindowSize:8,failureTolerance:XC,keyringSize:16};var Ui;(function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"})(Ui||(Ui={}));var cp;(function(e){e.KeyRatcheted="keyRatcheted"})(cp||(cp={}));var Fi;(function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"})(Fi||(Fi={}));var lp;(function(e){e.Error="cryptorError"})(lp||(lp={}));function eE(){return tE()||Ru()}function Ru(){return typeof window.RTCRtpScriptTransform<"u"}function tE(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class K4 extends ii.EventEmitter{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(n,i,r)=>{qe.debug("key ratcheted event received",{ratchetResult:n,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},QC),t),this.on(Ui.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const r={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(n??"shared","-").concat(i??0),r),this.emit(Ui.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,n){this.emit(Ui.RatchetRequest,t,n)}}class Gi extends Error{constructor(t,n){super(n||"an error has occured"),this.name="LiveKitError",this.code=t}}var Ge;(function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"})(Ge||(Ge={}));class ut extends Gi{constructor(t,n,i,r){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=Ge[n]}}class Kd extends Gi{constructor(t){super(21,t??"device is unsupported"),this.name="DeviceUnsupportedError"}}class gi extends Gi{constructor(t){super(20,t??"track is invalid"),this.name="TrackInvalidError"}}class nE extends Gi{constructor(t){super(10,t??"unsupported server"),this.name="UnsupportedServer"}}class Bt extends Gi{constructor(t){super(12,t??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Au extends Gi{constructor(t){super(13,t??"unable to negotiate"),this.name="NegotiationError"}}class up extends Gi{constructor(t,n){super(15,t),this.name="PublishTrackError",this.status=n}}class dp extends Gi{constructor(t,n){super(15,t),this.reason=n,this.reasonName=typeof n=="string"?n:qd[n]}}var Fa;(function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"})(Fa||(Fa={}));(function(e){function t(n){if(n&&"name"in n)return n.name==="NotFoundError"||n.name==="DevicesNotFoundError"?e.NotFound:n.name==="NotAllowedError"||n.name==="PermissionDeniedError"?e.PermissionDenied:n.name==="NotReadableError"||n.name==="TrackStartError"?e.DeviceInUse:e.Other}e.getFailure=t})(Fa||(Fa={}));var hp;(function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"})(hp||(hp={}));var j;(function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"})(j||(j={}));var Q;(function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"})(Q||(Q={}));var fe;(function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"})(fe||(fe={}));var he;(function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"})(he||(he={}));function iE(e){return typeof e>"u"?e:typeof structuredClone=="function"?typeof e=="object"&&e!==null?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}const rE=/version\/(\d+(\.?_?\d+)+)/i;let el;function kn(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const n=navigator.userAgent.toLowerCase();if(el===void 0||t){const i=sE.find(r=>{let{test:s}=r;return s.test(n)});el=i==null?void 0:i.describe(n)}return el}const sE=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:"Firefox",version:va(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:tl(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:"Chrome",version:va(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:tl(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:"Safari",version:va(rE,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:tl(e)}}}];function va(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function tl(e){return e.includes("mac os")?va(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var oE="2.13.8";const aE=oE,cE=16;class Zt{}Zt.setTimeout=function(){return setTimeout(...arguments)};Zt.setInterval=function(){return setInterval(...arguments)};Zt.clearTimeout=function(){return clearTimeout(...arguments)};Zt.clearInterval=function(){return clearInterval(...arguments)};const lE=5e3,Rs=[];var Pn;(function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"})(Pn||(Pn={}));class B extends ii.EventEmitter{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=B.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=qe,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),lE):this.handleAppVisibilityChanged()},this.log=xi((r=i.loggerName)!==null&&r!==void 0?r:Hn.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=B.Source.Unknown}get logContext(){var t;return Object.assign(Object.assign({},(t=this.loggerContextCb)===null||t===void 0?void 0:t.call(this)),He(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===B.Kind.Video&&(n="video"),this.attachedElements.length===0&&this.kind===B.Kind.Video&&this.addAppVisibilityListener(),t||(n==="audio"&&(Rs.forEach(s=>{s.parentElement===null&&!t&&(t=s)}),t&&Rs.splice(Rs.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),$r(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return t.play().then(()=>{this.emit(r?he.AudioPlaybackStarted:he.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?he.AudioPlaybackFailed:he.VideoPlaybackFailed,s):s.name==="AbortError"?qe.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):qe.warn("could not playback ".concat(r?"audio":"video"),s),r&&t&&i.some(o=>o.kind==="video")&&s.name==="NotAllowedError"&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(he.ElementAttached,t),t}detach(t){try{if(t){Qr(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(he.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach(i=>{Qr(this.mediaStreamTrack,i),n.push(i),this.recycleElement(i),this.emit(he.ElementDetached,i)}),this.attachedElements=[],n}finally{this.attachedElements.length===0&&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(t){t.loggerName&&(this.log=xi(t.loggerName)),t.loggerContextCb&&(this.loggerContextCb=t.loggerContextCb)}recycleElement(t){if(t instanceof HTMLAudioElement){let n=!0;t.pause(),Rs.forEach(i=>{i.parentElement||(n=!1)}),n&&Rs.push(t)}}handleAppVisibilityChanged(){return M(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===B.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(t=>t.play().catch(()=>{})),0)})}addAppVisibilityListener(){hn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){hn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function $r(e,t){let n;t.srcObject instanceof MediaStream?n=t.srcObject:n=new MediaStream;let i;e.kind==="audio"?i=n.getAudioTracks():i=n.getVideoTracks(),i.includes(e)||(i.forEach(r=>{n.removeTrack(r)}),n.addTrack(e)),(!gr()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(gr()||as())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function Qr(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(t=e.Kind||(e.Kind={}));let n;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(n=e.Source||(e.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=e.StreamState||(e.StreamState={}));function r(l){switch(l){case t.Audio:return Un.AUDIO;case t.Video:return Un.VIDEO;default:return Un.DATA}}e.kindToProto=r;function s(l){switch(l){case Un.AUDIO:return t.Audio;case Un.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=s;function o(l){switch(l){case n.Camera:return Lt.CAMERA;case n.Microphone:return Lt.MICROPHONE;case n.ScreenShare:return Lt.SCREEN_SHARE;case n.ScreenShareAudio:return Lt.SCREEN_SHARE_AUDIO;default:return Lt.UNKNOWN}}e.sourceToProto=o;function a(l){switch(l){case Lt.CAMERA:return n.Camera;case Lt.MICROPHONE:return n.Microphone;case Lt.SCREEN_SHARE:return n.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=a;function c(l){switch(l){case yu.ACTIVE:return i.Active;case yu.PAUSED:return i.Paused;default:return i.Unknown}}e.streamStateFromProto=c})(B||(B={}));class st{constructor(t,n,i,r,s){if(typeof t=="object")this.width=t.width,this.height=t.height,this.aspectRatio=t.aspectRatio,this.encoding={maxBitrate:t.maxBitrate,maxFramerate:t.maxFramerate,priority:t.priority};else if(n!==void 0&&i!==void 0)this.width=t,this.height=n,this.aspectRatio=t/n,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const uE=["vp8","h264"],dE=["vp8","h264","vp9","av1"];function hE(e){return!!uE.find(t=>t===e)}var fp;(function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"})(fp||(fp={}));var Pu;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(Pu||(Pu={}));const io={h90:new st(160,90,9e4,20),h180:new st(320,180,16e4,20),h216:new st(384,216,18e4,20),h360:new st(640,360,45e4,20),h540:new st(960,540,8e5,25),h720:new st(1280,720,17e5,30),h1080:new st(1920,1080,3e6,30),h1440:new st(2560,1440,5e6,30),h2160:new st(3840,2160,8e6,30)},Nu={h120:new st(160,120,7e4,20),h180:new st(240,180,125e3,20),h240:new st(320,240,14e4,20),h360:new st(480,360,33e4,20),h480:new st(640,480,5e5,20),h540:new st(720,540,6e5,25),h720:new st(960,720,13e5,30),h1080:new st(1440,1080,23e5,30),h1440:new st(1920,1440,38e5,30)},Yd={h360fps3:new st(640,360,2e5,3,"medium"),h360fps15:new st(640,360,4e5,15,"medium"),h720fps5:new st(1280,720,8e5,5,"medium"),h720fps15:new st(1280,720,15e5,15,"medium"),h720fps30:new st(1280,720,2e6,30,"medium"),h1080fps15:new st(1920,1080,25e5,15,"medium"),h1080fps30:new st(1920,1080,5e6,30,"medium"),original:new st(0,0,7e6,30,"medium")},fE="|",pp="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function pE(e){const t=e.split(fE);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}function pn(e){return M(this,void 0,void 0,function*(){return new Promise(t=>Zt.setTimeout(t,e))})}function Iu(){return"addTransceiver"in RTCPeerConnection.prototype}function Mu(){return"addTrack"in RTCPeerConnection.prototype}function mE(){if(!("getCapabilities"in RTCRtpSender)||gr())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e){for(const n of e.codecs)if(n.mimeType==="video/AV1"){t=!0;break}}return t}function gE(){if(!("getCapabilities"in RTCRtpSender)||as())return!1;if(gr()){const n=kn();if(n!=null&&n.version&&br(n.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e){for(const n of e.codecs)if(n.mimeType==="video/VP9"){t=!0;break}}return t}function yi(e){return e==="av1"||e==="vp9"}function Ou(e){return document?(e||(e=document.createElement("audio")),"setSinkId"in e):!1}function bE(){return typeof RTCPeerConnection>"u"?!1:Iu()||Mu()}function as(){var e;return((e=kn())===null||e===void 0?void 0:e.name)==="Firefox"}function gr(){var e;return((e=kn())===null||e===void 0?void 0:e.name)==="Safari"}function mp(){const e=kn();return(e==null?void 0:e.name)==="Safari"||(e==null?void 0:e.os)==="iOS"}function yE(){const e=kn();return(e==null?void 0:e.name)==="Safari"&&e.version.startsWith("17.")}function vE(e){return e||(e=kn()),(e==null?void 0:e.name)==="Safari"&&br(e.version,"18.3")>0}function wy(){var e,t;return hn()?(t=(e=navigator.userAgentData)===null||e===void 0?void 0:e.mobile)!==null&&t!==void 0?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function xE(){const e=kn(),t="17.2";if(e)return e.name!=="Safari"&&e.os!=="iOS"||e.os==="iOS"&&e.osVersion&&br(t,e.osVersion)>=0?!0:e.name==="Safari"&&br(t,e.version)>=0}function hn(){return typeof document<"u"}function ni(){return navigator.product=="ReactNative"}function Du(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ty(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Cy(){if(!ni())return;let e=Ty();if(e)return e.platform}function gp(){if(hn())return window.devicePixelRatio;if(ni()){let e=Ty();if(e)return e.devicePixelRatio}return 1}function br(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let s=0;s<r;++s){const o=parseInt(n[s],10),a=parseInt(i[s],10);if(o>a)return 1;if(o<a)return-1;if(s===r-1&&o===a)return 0}return e===""&&t!==""?-1:t===""?1:n.length==i.length?0:n.length<i.length?-1:1}function kE(e){for(const t of e)t.target.handleResize(t)}function SE(e){for(const t of e)t.target.handleVisibilityChanged(t)}let nl=null;const bp=()=>(nl||(nl=new ResizeObserver(kE)),nl);let il=null;const yp=()=>(il||(il=new IntersectionObserver(SE,{root:null,rootMargin:"0px"})),il);function wE(){var e;const t=new cC({sdk:A0.JS,protocol:cE,version:aE});return ni()&&(t.os=(e=Cy())!==null&&e!==void 0?e:""),t}function vp(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=e,r.height=t;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let As;function rl(){if(!As){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[As]=i.stream.getAudioTracks(),!As)throw Error("Could not get empty media stream audio track");As.enabled=!1}return As.clone()}class zr{constructor(t,n){this.onFinally=n,this.promise=new Promise((i,r)=>M(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,t&&(yield t(i,r))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function TE(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=Xd();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([r])),o=i.createAnalyser();o.minDecibels=n.minDecibels,o.maxDecibels=n.maxDecibels,o.fftSize=n.fftSize,o.smoothingTimeConstant=n.smoothingTimeConstant,s.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let u=0;for(const h of a)u+=Math.pow(h/255,2);return Math.sqrt(u/a.length)},analyser:o,cleanup:()=>M(this,void 0,void 0,function*(){yield i.close(),n.cloneTrack&&r.stop()})}}function CE(e){return dE.includes(e)}function Bi(e){if(typeof e=="string"||typeof e=="number")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 EE(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}function Lu(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function _E(e,t){return e.segments.map(n=>{let{id:i,text:r,language:s,startTime:o,endTime:a,final:c}=n;var l;const u=(l=t.get(i))!==null&&l!==void 0?l:Date.now(),d=Date.now();return c?t.delete(i):t.set(i,u),{id:i,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:c,language:s,firstReceivedTime:u,lastReceivedTime:d}})}function RE(e){const{id:t,timestamp:n,message:i,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function xp(e){switch(e.reason){case Ge.LeaveRequest:return e.context;case Ge.Cancelled:return Vn.CLIENT_INITIATED;case Ge.NotAllowed:return Vn.USER_REJECTED;case Ge.ServerUnreachable:return Vn.JOIN_FAILURE;default:return Vn.UNKNOWN_REASON}}function xa(e){return e!==void 0?Number(e):void 0}function ir(e){return e!==void 0?BigInt(e):void 0}function es(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Qn(e){return!!e&&e.kind==B.Kind.Audio}function ps(e){return!!e&&e.kind==B.Kind.Video}function Pi(e){return es(e)&&ps(e)}function di(e){return es(e)&&Qn(e)}function Fu(e){return!!e&&!e.isLocal}function AE(e){return!!e&&!e.isLocal}function sl(e){return Fu(e)&&ps(e)}function PE(e){return e.isLocal}function NE(e,t){const n=[];let i=new TextEncoder().encode(e);for(;i.length>t;){let r=t;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}n.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&n.push(i),n}function Ey(e,t,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:l}=Ry(e??{}),u=t==null?void 0:t.processor,d=n==null?void 0:n.processor,h=a??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(ju(h.audio,t),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(h.audio.processor=c??u)),h.video&&(ju(h.video,n),(r=(o=h.video).deviceId)!==null&&r!==void 0||(o.deviceId={ideal:"default"}),(l||d)&&(h.video.processor=l??d)),h}function ju(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function Zd(e){var t,n,i,r;const s={};if(e.video)if(typeof e.video=="object"){const o={},a=o,c=e.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":ju(a,c.resolution);break;default:a[l]=c[l]}}),s.video=o,(t=(i=s.video).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})}else s.video=e.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return e.audio?typeof e.audio=="object"?(s.audio=e.audio,(n=(r=s.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function _y(e){return M(this,arguments,void 0,function(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=Xd();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,o=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([t.mediaStreamTrack])).connect(r),yield pn(n),r.getByteTimeDomainData(o);const c=o.some(l=>l!==128&&l!==0);return i.close(),!c}return!1}()})}function Xd(){var e;const t=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(t){const n=new t({latencyHint:"interactive"});if(n.state==="suspended"&&typeof window<"u"&&(!((e=window.document)===null||e===void 0)&&e.body)){const i=()=>M(this,void 0,void 0,function*(){var r;try{n.state==="suspended"&&(yield n.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return n}}function IE(e){return e==="audioinput"?B.Source.Microphone:e==="videoinput"?B.Source.Camera:B.Source.Unknown}function Uu(e){return e===B.Source.Microphone?"audioinput":e===B.Source.Camera?"videoinput":void 0}function ME(e){var t,n;let i=(t=e.video)!==null&&t!==void 0?t:!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i=typeof i=="boolean"?{}:i,gr()?i=Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:(n=e.audio)!==null&&n!==void 0?n:!1,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function ka(e){return e.split("/")[1].toLowerCase()}function OE(e){const t=[];return e.forEach(n=>{n.track!==void 0&&t.push(new Hd({cid:n.track.mediaStreamID,track:n.trackInfo}))}),t}function He(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?He(e.track):{})}}function DE(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function LE(e,t){var n;e===void 0&&(e={}),t===void 0&&(t={});const i=[...Object.keys(t),...Object.keys(e)],r={};for(const s of i)e[s]!==t[s]&&(r[s]=(n=t[s])!==null&&n!==void 0?n:"");return r}function Ry(e){const t=Object.assign({},e);let n,i;return typeof t.audio=="object"&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video=="object"&&t.video.processor&&(i=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:iE(t)}}function FE(e){switch(e){case Lt.CAMERA:return B.Source.Camera;case Lt.MICROPHONE:return B.Source.Microphone;case Lt.SCREEN_SHARE:return B.Source.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return B.Source.ScreenShareAudio;default:return B.Source.Unknown}}class jE extends ii.EventEmitter{constructor(t){super(),this.onWorkerMessage=n=>{var i,r;const{kind:s,data:o}=n.data;switch(s){case"error":qe.error(o.error.message),this.emit(Fi.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(a=>{this.postKey(a)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(Fi.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const a=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!a)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(Fi.ParticipantEncryptionStatusChanged,o.enabled,a)}break;case"ratchetKey":this.keyProvider.emit(Ui.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break}},this.onWorkerError=n=>{qe.error("e2ee worker encountered an error:",{error:n.error}),this.emit(Fi.EncryptionError,n.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(t){if(!eE())throw new Kd("tried to setup end-to-end encryption on an unsupported browser");if(qe.info("setting up e2ee"),t!==this.room){this.room=t,this.setupEventListeners(t,this.keyProvider);const n={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:jC.getLevel()}};this.worker&&(qe.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(n))}}setParticipantCryptorEnabled(t,n){qe.debug("set e2ee to ".concat(t," for participant ").concat(n)),this.postEnable(t,n)}setSifTrailer(t){!t||t.length===0?qe.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(t)}setupEngine(t){t.on(fe.RTPVideoMapUpdate,n=>{this.postRTPMap(n)})}setupEventListeners(t,n){t.on(j.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==vn.NONE,r.identity)),t.on(j.ConnectionStateChanged,i=>{i===$e.Connected&&t.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==vn.NONE,r.identity)})})}).on(j.TrackUnsubscribed,(i,r,s)=>{var o;const a={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(o=this.worker)===null||o===void 0||o.postMessage(a)}).on(j.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(j.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),t.localParticipant.on(Q.LocalTrackPublished,i=>M(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),n.on(Ui.SetKey,i=>this.postKey(i)).on(Ui.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(t,n){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:t,keyIndex:n}};this.worker.postMessage(i)}postKey(t){let{key:n,participantIdentity:i,keyIndex:r}=t;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:n,keyIndex:r}};this.worker.postMessage(o)}postEnable(t,n){if(this.worker){const i={kind:"enable",data:{enabled:t,participantIdentity:n}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(t){var n;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((n=this.room)===null||n===void 0)&&n.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(t){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const n={kind:"setSifTrailer",data:{trailer:t}};this.worker.postMessage(n)}setupE2EEReceiver(t,n,i){if(t.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(t.receiver,t.mediaStreamID,n,t.kind==="video"?ka(i.mimeType):void 0)}}setupE2EESender(t,n){if(!es(t)||!n){n||qe.warn("early return because sender is not ready");return}this.handleSender(n,t.mediaStreamID,void 0)}handleReceiver(t,n,i,r){return M(this,void 0,void 0,function*(){if(this.worker){if(Ru()){const s={kind:"decode",participantIdentity:i,trackId:n,codec:r};t.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(_s in t&&r){const c={kind:"updateCodec",data:{trackId:n,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=t.writableStream,o=t.readableStream;if(!s||!o){const c=t.createEncodedStreams();t.writableStream=c.writable,s=c.writable,t.readableStream=c.readable,o=c.readable}const a={kind:"decode",data:{readableStream:o,writableStream:s,trackId:n,codec:r,participantIdentity:i,isReuse:_s in t}};this.worker.postMessage(a,[o,s])}t[_s]=!0}})}handleSender(t,n,i){var r;if(!(_s in t||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Ru()){qe.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:n,codec:i};t.transform=new RTCRtpScriptTransform(this.worker,s)}else{qe.info("initialize encoded streams");const s=t.createEncodedStreams(),o={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:n,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[s.readable,s.writable])}t[_s]=!0}}}const ol="default";class Wt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Wt),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=Wt.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){qe.debug("awaiting getUserMedia promise");try{n?yield Wt.userMediaPromiseMap.get(n):yield Promise.all(Wt.userMediaPromiseMap.values())}catch{qe.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(r&&!(gr()&&i.hasDeviceInUse(n))&&(o.filter(c=>c.kind===n).length===0||o.some(c=>{const l=c.label==="",u=n?c.kind===n:!0;return l&&u}))){const c={video:n!=="audioinput"&&n!=="audiooutput",audio:n!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);o=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=o,n&&(o=o.filter(a=>a.kind===n)),o}()})}normalizeDeviceId(t,n,i){return M(this,void 0,void 0,function*(){if(n!==ol)return n;const r=yield this.getDevices(t),s=r.find(a=>a.deviceId===ol);if(!s){qe.warn("could not reliably determine default device");return}const o=r.find(a=>a.deviceId!==ol&&a.groupId===(i??s.groupId));if(!o){qe.warn("could not reliably determine default device");return}return o==null?void 0:o.deviceId})}hasDeviceInUse(t){return t?Wt.userMediaPromiseMap.has(t):Wt.userMediaPromiseMap.size>0}}Wt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Wt.userMediaPromiseMap=new Map;var qs;(function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"})(qs||(qs={}));class UE{constructor(){this.pendingTasks=new Map,this.taskMutex=new dn,this.nextTaskIndex=0}run(t){return M(this,void 0,void 0,function*(){const n={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:qs.WAITING};this.pendingTasks.set(n.id,n);const i=yield this.taskMutex.lock();try{return n.executedAt=Date.now(),n.status=qs.RUNNING,yield t()}finally{n.status=qs.COMPLETED,this.pendingTasks.delete(n.id),i()}})}flush(){return M(this,void 0,void 0,function*(){return this.run(()=>M(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function BE(e,t){const n=new URL(EE(e));return t.forEach((i,r)=>{n.searchParams.set(r,i)}),Ay(n,"rtc")}function VE(e){const t=new URL(Lu(e));return Ay(t,"validate")}function $E(e){return e.endsWith("/")?e:"".concat(e,"/")}function Ay(e,t){return e.pathname="".concat($E(e.pathname)).concat(t),e.toString()}const zE=["syncState","trickle","offer","answer","simulate","leave"];function HE(e){const t=zE.indexOf(e.case)>=0;return qe.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}var gt;(function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"})(gt||(gt={}));class Jd{get currentState(){return this.state}get isDisconnected(){return this.state===gt.DISCONNECTING||this.state===gt.DISCONNECTED}get isEstablishingConnection(){return this.state===gt.CONNECTING||this.state===gt.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=gt.DISCONNECTED,this.log=qe,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=xi((i=n.loggerName)!==null&&i!==void 0?i:Hn.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=t,this.requestQueue=new UE,this.queuedRequests=[],this.closingLock=new dn,this.connectionLock=new dn,this.state=gt.DISCONNECTED}get logContext(){var t,n;return(n=(t=this.loggerContextCb)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:{}}join(t,n,i,r){return M(this,void 0,void 0,function*(){return this.state=gt.CONNECTING,this.options=i,yield this.connect(t,n,i,r)})}reconnect(t,n,i,r){return M(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=gt.RECONNECTING,this.clearPingInterval(),yield this.connect(t,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(t,n,i,r){this.connectOptions=i;const s=wE(),o=WE(n,s,i),a=BE(t,o),c=VE(a);return new Promise((l,u)=>M(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const h=()=>M(this,void 0,void 0,function*(){this.close(),clearTimeout(f),u(new ut("room connection has been cancelled (signal)",Ge.Cancelled))}),f=setTimeout(()=>{this.close(),u(new ut("room connection has timed out (signal)",Ge.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const g=new URL(a);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(a),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=p=>M(this,void 0,void 0,function*(){if(this.state!==gt.CONNECTED){this.state=gt.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(c);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();u(new ut(b,Ge.NotAllowed,v.status))}else u(new ut("Encountered unknown websocket error during connection: ".concat(p.toString()),Ge.InternalError,v.status))}catch(v){u(new ut(v instanceof Error?v.message:"server was not reachable",Ge.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>M(this,void 0,void 0,function*(){var v,b,w;let S;if(typeof p.data=="string"){const k=JSON.parse(p.data);S=Xf.fromJson(k,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)S=Xf.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==gt.CONNECTED){let k=!1;if(((v=S.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=gt.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=S.message.value.pingTimeout,this.pingIntervalDuration=S.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()),l(S.message.value)):this.state===gt.RECONNECTING&&S.message.case!=="leave"?(this.state=gt.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=S.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(S.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),k=!0)):this.isEstablishingConnection&&S.message.case==="leave"?u(new ut("Received leave request while trying to (re)connect",Ge.LeaveRequest,void 0,S.message.value.reason)):i.reconnect||u(new ut("did not receive join response, got ".concat((w=S.message)===null||w===void 0?void 0:w.case," instead"),Ge.InternalError)),!k)return}this.signalLatency&&(yield pn(this.signalLatency)),this.handleSignalResponse(S)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new ut("Websocket got closed during a (re)connection attempt",Ge.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{d()}}))}close(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield t.closingLock.lock();try{if(t.clearPingInterval(),n&&(t.state=gt.DISCONNECTING),t.ws){t.ws.onmessage=null,t.ws.onopen=null,t.ws.onclose=null;const r=new Promise(s=>{t.ws?t.ws.onclose=()=>{s()}:s()});t.ws.readyState<t.ws.CLOSING&&(t.ws.close(),yield Promise.race([r,pn(250)])),t.ws=void 0}}finally{n&&(t.state=gt.DISCONNECTED),i()}}()})}sendOffer(t,n){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:t.sdp})),this.sendRequest({case:"offer",value:ja(t,n)})}sendAnswer(t,n){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:t.sdp})),this.sendRequest({case:"answer",value:ja(t,n)})}sendIceCandidate(t,n){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:t})),this.sendRequest({case:"trickle",value:new $d({candidateInit:JSON.stringify(t),target:n})})}sendMuteTrack(t,n){return this.sendRequest({case:"mute",value:new zd({sid:t,muted:n})})}sendAddTrack(t){return this.sendRequest({case:"addTrack",value:t})}sendUpdateLocalMetadata(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const a=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new F0({requestId:a,metadata:i,name:r,attributes:o})}),a}()})}sendUpdateTrackSettings(t){this.sendRequest({case:"trackSetting",value:t})}sendUpdateSubscription(t){return this.sendRequest({case:"subscription",value:t})}sendSyncState(t){return this.sendRequest({case:"syncState",value:t})}sendUpdateVideoLayers(t,n){return this.sendRequest({case:"updateLayers",value:new L0({trackSid:t,layers:n})})}sendUpdateSubscriptionPermissions(t,n){return this.sendRequest({case:"subscriptionPermission",value:new B0({allParticipants:t,trackPermissions:n})})}sendSimulateScenario(t){return this.sendRequest({case:"simulate",value:t})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:yt.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new H0({timestamp:yt.parse(Date.now()),rtt:yt.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(t,n){return this.sendRequest({case:"updateAudioTrack",value:new D0({trackSid:t,features:n})})}sendLeave(){return this.sendRequest({case:"leave",value:new fc({reason:Vn.CLIENT_INITIATED,action:Xr.DISCONNECT})})}sendRequest(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!HE(n)&&i.state===gt.RECONNECTING){i.queuedRequests.push(()=>M(i,void 0,void 0,function*(){yield this.sendRequest(n,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield pn(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(n==null?void 0:n.case),i.logContext);return}const o=new dC({message:n});try{i.useJSON?i.ws.send(o.toJsonString()):i.ws.send(o.toBinary())}catch(a){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:a}))}}()})}handleSignalResponse(t){var n,i;const r=t.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const o=kp(r.value);this.onAnswer&&this.onAnswer(o,r.value.id)}else if(r.case==="offer"){const o=kp(r.value);this.onOffer&&this.onOffer(o,r.value.id)}else if(r.case==="trickle"){const o=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(o,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((n=r.value.participants)!==null&&n!==void 0?n:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const t=this.queuedRequests.shift();t&&this.requestQueue.run(t)}}handleOnClose(t){return M(this,void 0,void 0,function*(){if(this.state===gt.DISCONNECTED)return;const n=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(t),Object.assign(Object.assign({},this.logContext),{reason:t})),n&&n(t)})}handleWSError(t){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:t}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Zt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Zt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Zt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Zt.clearInterval(this.pingInterval)}}function kp(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type;break}return t}function ja(e,t){return new mr({sdp:e.sdp,type:e.type,id:t})}function WE(e,t,n){var i;const r=new URLSearchParams;return r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",ni()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}class Sp{constructor(){this.buffer=[],this._totalSize=0}push(t){this.buffer.push(t),this._totalSize+=t.data.byteLength}pop(){const t=this.buffer.shift();return t&&(this._totalSize-=t.data.byteLength),t}getAll(){return this.buffer.slice()}popToSequence(t){for(;this.buffer.length>0&&this.buffer[0].sequence<=t;)this.pop()}alignBufferedAmount(t){for(;this.buffer.length>0;){const n=this.buffer[0];if(this._totalSize-n.data.byteLength<=t)break;this.pop()}}get length(){return this.buffer.length}}class qE{constructor(t){this._map=new Map,this._lastCleanup=0,this.ttl=t}set(t,n){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const r=i+this.ttl;return this._map.set(t,{value:n,expiresAt:r}),this}get(t){const n=this._map.get(t);if(n){if(n.expiresAt<Date.now()){this._map.delete(t);return}return n.value}}has(t){const n=this._map.get(t);return n?n.expiresAt<Date.now()?(this._map.delete(t),!1):!0:!1}delete(t){return this._map.delete(t)}clear(){this._map.clear()}cleanup(){const t=Date.now();for(const[n,i]of this._map.entries())i.expiresAt<t&&this._map.delete(n);this._lastCleanup=t}get size(){return this.cleanup(),this._map.size}forEach(t){this.cleanup();for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&t(i.value,n,this.asValueMap())}map(t){this.cleanup();const n=[],i=this.asValueMap();for(const[r,s]of i.entries())n.push(t(s,r,i));return n}asValueMap(){const t=new Map;for(const[n,i]of this._map.entries())i.expiresAt>=Date.now()&&t.set(n,i.value);return t}}var Dn={},al={},cl={exports:{}},wp;function Qd(){if(wp)return cl.exports;wp=1;var e=cl.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(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return t.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(t){return t.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return t.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(t){var n="candidate:%s %d %s %d %s %d typ %s";return n+=t.raddr!=null?" raddr %s rport %d":"%v%v",n+=t.tcptype!=null?" tcptype %s":"%v",t.generation!=null&&(n+=" generation %d"),n+=t["network-id"]!=null?" network-id %d":"%v",n+=t["network-cost"]!=null?" network-cost %d":"%v",n}},{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(t){var n="ssrc:%d";return t.attribute!=null&&(n+=" %s",t.value!=null&&(n+=":%s")),n}},{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(t){return t.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(t){return t.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(t){return"imageattr:%s %s %s"+(t.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(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(t.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var n="mediaclk:";return n+=t.id!=null?"id=%s %s":"%v%s",n+=t.mediaClockValue!=null?"=%s":"",n+=t.rateNumerator!=null?" rate=%s":"",n+=t.rateDenominator!=null?"/%s":"",n}},{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){var n=e[t];n.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),cl.exports}var Tp;function GE(){return Tp||(Tp=1,function(e){var t=function(a){return String(Number(a))===a?Number(a):a},n=function(a,c,l,u){if(u&&!l)c[u]=t(a[1]);else for(var d=0;d<l.length;d+=1)a[d+1]!=null&&(c[l[d]]=t(a[d+1]))},i=function(a,c,l){var u=a.name&&a.names;a.push&&!c[a.push]?c[a.push]=[]:u&&!c[a.name]&&(c[a.name]={});var d=a.push?{}:u?c[a.name]:c;n(l.match(a.reg),d,a.names,a.name),a.push&&c[a.push].push(d)},r=Qd(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(a){var c={},l=[],u=c;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var g=0;g<(r[h]||[]).length;g+=1){var p=r[h][g];if(p.reg.test(f))return i(p,u,f)}}),c.media=l,c};var o=function(a,c){var l=c.split(/=(.+)/,2);return l.length===2?a[l[0]]=t(l[1]):l.length===1&&c.length>1&&(a[l[0]]=void 0),a};e.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(a){return a.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(a){for(var c=[],l=a.split(" ").map(t),u=0;u<l.length;u+=3)c.push({component:l[u],ip:l[u+1],port:l[u+2]});return c},e.parseImageAttributes=function(a){return a.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(o,{})})},e.parseSimulcastStreamList=function(a){return a.split(";").map(function(c){return c.split(",").map(function(l){var u,d=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),d=!0),{scid:u,paused:d}})})}}(al)),al}var ll,Cp;function KE(){if(Cp)return ll;Cp=1;var e=Qd(),t=/%[sdv%]/g,n=function(o){var a=1,c=arguments,l=c.length;return o.replace(t,function(u){if(a>=l)return u;var d=c[a];switch(a+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(o,a,c){var l=a.format instanceof Function?a.format(a.push?c:c[a.name]):a.format,u=[o+"="+l];if(a.names)for(var d=0;d<a.names.length;d+=1){var h=a.names[d];a.name?u.push(c[a.name][h]):u.push(c[a.names[d]])}else u.push(c[a.name]);return n.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return ll=function(o,a){a=a||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var c=a.outerOrder||r,l=a.innerOrder||s,u=[];return c.forEach(function(d){e[d].forEach(function(h){h.name in o&&o[h.name]!=null?u.push(i(d,h,o)):h.push in o&&o[h.push]!=null&&o[h.push].forEach(function(f){u.push(i(d,h,f))})})}),o.media.forEach(function(d){u.push(i("m",e.m[0],d)),l.forEach(function(h){e[h].forEach(function(f){f.name in d&&d[f.name]!=null?u.push(i(h,f,d)):f.push in d&&d[f.push]!=null&&d[f.push].forEach(function(g){u.push(i(h,f,g))})})})}),u.join(`\r
|
|
37
37
|
`)+`\r
|
|
38
|
-
`},ll}var Ep;function YE(){if(Ep)return Dn;Ep=1;var e=GE(),t=KE(),n=Qd();return Dn.grammar=n,Dn.write=t,Dn.parse=e.parse,Dn.parseParams=e.parseParams,Dn.parseFmtpConfig=e.parseFmtpConfig,Dn.parsePayloads=e.parsePayloads,Dn.parseRemoteCandidates=e.parseRemoteCandidates,Dn.parseImageAttributes=e.parseImageAttributes,Dn.parseSimulcastStreamList=e.parseSimulcastStreamList,Dn}var Oi=YE();function eh(e,t,n){var i,r,s;t===void 0&&(t=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+t>=c)return c-f}return t}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(p,v){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var S=e.apply(g,f);a&&a(S),u.forEach(function(k){return(0,k.resolve)(S)}),u=[]}},d()),b){var w=e.apply(g,f);return a&&a(w),p(w)}u.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(g){return(0,g.reject)(f)}),u=[]},h}const ZE=.7,XE=20,ts={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _p extends ii.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=qe,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=eh(r=>M(this,void 0,void 0,function*(){this.emit(ts.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),XE),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=xi((i=n.loggerName)!==null&&i!==void 0?i:Hn.PCTransport),this.loggerOptions=n,this.config=t,this._pc=this.createPC()}createPC(){const t=new RTCPeerConnection(this.config);return t.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},t.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},t.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,t.iceConnectionState)},t.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,t.signalingState)},t.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,t.connectionState)},t.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},t.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},t}get logContext(){var t,n;return Object.assign({},(n=(t=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(t))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(t){return M(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(t);this.pendingCandidates.push(t)})}setRemoteDescription(t,n){return M(this,void 0,void 0,function*(){var i;if(t.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(t.type==="offer"){let{stereoMids:s,nackMids:o}=JE(t);this.remoteStereoMids=s,this.remoteNackMids=o}else if(t.type==="answer"){const s=Oi.parse((i=t.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(c=u.payload,!0):!1),c===0)return!0;let l=!1;for(const u of o.fmtp)if(u.payload===c){u.config=u.config.split(";").filter(d=>!d.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=Oi.write(s)}return yield this.setMungedSDP(t,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):t.type==="answer"&&(this.emit(ts.NegotiationComplete),t.sdp&&Oi.parse(t.sdp).media.forEach(o=>{o.type==="video"&&this.emit(ts.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(t){return M(this,void 0,void 0,function*(){var n;const i=this.latestOfferId+1;if(this.latestOfferId=i,this.onOffer===void 0)return;if(t!=null&&t.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(t!=null&&t.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(t);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const s=Oi.parse((n=r.sdp)!==null&&n!==void 0?n:"");if(s.media.forEach(o=>{Ap(o),o.type==="audio"?Rp(o,[],[]):o.type==="video"&&this.trackBitrates.some(a=>{if(!o.msid||!a.cid||!o.msid.includes(a.cid))return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(c=u.payload,!0):!1),c===0||(yi(a.codec)&&this.ensureVideoDDExtensionForSVC(o,s),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*ZE);for(const u of o.fmtp)if(u.payload===c){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(r,Oi.write(s)),this.onOffer(r,this.latestOfferId)})}createAndSetAnswer(){return M(this,void 0,void 0,function*(){var t;const n=yield this.pc.createAnswer(),i=Oi.parse((t=n.sdp)!==null&&t!==void 0?t:"");return i.media.forEach(r=>{Ap(r),r.type==="audio"&&Rp(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Oi.write(i)),n})}createDataChannel(t,n){return this.pc.createDataChannel(t,n)}addTransceiver(t,n){return this.pc.addTransceiver(t,n)}addTrack(t){if(!this._pc)throw new Bt("PC closed, cannot add track");return this._pc.addTrack(t)}setTrackCodecBitrate(t){this.trackBitrates.push(t)}setConfiguration(t){var n;if(!this._pc)throw new Bt("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(t)}canRemoveTrack(){var t;return!!(!((t=this._pc)===null||t===void 0)&&t.removeTrack)}removeTrack(t){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(t)}getConnectionState(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var t;return(t=this._pc)===null||t===void 0?void 0:t.localDescription}getRemoteDescription(){var t;return(t=this.pc)===null||t===void 0?void 0:t.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return M(this,void 0,void 0,function*(){var t;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(t=i.get(n))===null||t===void 0?void 0:t.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(t,n,i){return M(this,void 0,void 0,function*(){if(n){const r=t.sdp;t.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t);return}catch(s){this.log.warn("not able to set ".concat(t.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),t.sdp=r}}try{i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:t.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(t.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Au(s)}})}ensureVideoDDExtensionForSVC(t,n){var i,r;if(!((i=t.ext)===null||i===void 0?void 0:i.some(o=>o.uri===pp))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=t.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:pp})}}}function Rp(e,t,n){let i=0;e.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(e.mid)&&!e.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&e.rtcpFb.push({payload:i,type:"nack"}),t.includes(e.mid)&&e.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function JE(e){var t;const n=[],i=[],r=Oi.parse((t=e.sdp)!==null&&t!==void 0?t:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function Ap(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const Bu="vp8",QE={audioPreset:Pu.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Yd.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Bu,backupCodec:!0,preConnectBuffer:!1},P0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},N0={deviceId:{ideal:"default"},resolution:io.h720.resolution},e_={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new BC,disconnectOnPageLeave:!0,webAudioMix:!1},th={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ct;(function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"})(Ct||(Ct={}));class t_{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,n,i){var r;this.peerConnectionTimeout=th.peerConnectionTimeout,this.log=qe,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=Ct.CONNECTED:a.some(c=>c==="failed")?this.state=Ct.FAILED:a.some(c=>c==="connecting")?this.state=Ct.CONNECTING:a.every(c=>c==="closed")?this.state=Ct.CLOSED:a.some(c=>c==="closed")?this.state=Ct.CLOSING:a.every(c=>c==="new")&&(this.state=Ct.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Ct[o]," to ").concat(Ct[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=xi((r=i.loggerName)!==null&&r!==void 0?r:Hn.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new _p(t,i),this.subscriber=new _p(t,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=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,Bn.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,Bn.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=Ct.NEW,this.connectionLock=new dn,this.remoteOfferLock=new dn}get logContext(){var t,n;return Object.assign({},(n=(t=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(t))}requirePublisher(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=t,this.updateState()}requireSubscriber(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=t,this.updateState()}createAndSendPublisherOffer(t){return this.publisher.createAndSendOffer(t)}setPublisherAnswer(t,n){return this.publisher.setRemoteDescription(t,n)}removeTrack(t){return this.publisher.removeTrack(t)}close(){return M(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return M(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(t,n){return M(this,void 0,void 0,function*(){n===Bn.PUBLISHER?yield this.publisher.addIceCandidate(t):yield this.subscriber.addIceCandidate(t)})}createSubscriberAnswerFromOffer(t,n){return M(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type,sdp:t.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(t,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(t,n){this.publisher.setConfiguration(t),this.subscriber.setConfiguration(t),n&&this.triggerIceRestart()}ensurePCTransportConnection(t,n){return M(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,t,n)))}finally{r()}})}negotiate(t){return M(this,void 0,void 0,function*(){return new Promise((n,i)=>M(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};t.signal.addEventListener("abort",s),this.publisher.once(ts.NegotiationStarted,()=>{t.signal.aborted||this.publisher.once(ts.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(t,n){return this.publisher.addTransceiver(t,n)}addPublisherTrack(t){return this.publisher.addTrack(t)}createPublisherDataChannel(t,n){return this.publisher.createDataChannel(t,n)}getConnectedAddress(t){return t===Bn.PUBLISHER?this.publisher.getConnectedAddress():t===Bn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const t=[];return this.isPublisherConnectionRequired&&t.push(this.publisher),this.isSubscriberConnectionRequired&&t.push(this.subscriber),t}ensureTransportConnected(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>M(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Zt.clearTimeout(d),l(new ut("room connection has been cancelled",Ge.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Zt.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(new ut("could not establish pc connection",Ge.InternalError))},o);for(;this.state!==Ct.CONNECTED;)if(yield pn(50),r!=null&&r.signal.aborted){l(new ut("room connection has been cancelled",Ge.Cancelled));return}Zt.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class _t extends Error{constructor(t,n,i){super(n),this.code=t,this.message=Pp(n,_t.MAX_MESSAGE_BYTES),this.data=i?Pp(i,_t.MAX_DATA_BYTES):void 0}static fromProto(t){return new _t(t.code,t.message,t.data)}toProto(){return new Cy({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new _t(_t.ErrorCode[t],_t.ErrorMessage[t],n)}}_t.MAX_MESSAGE_BYTES=256;_t.MAX_DATA_BYTES=15360;_t.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};_t.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 I0=15360;function nh(e){return new TextEncoder().encode(e).length}function Pp(e,t){if(nh(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(e.slice(0,s)).length<=t?n=s:i=s-1}return e.slice(0,n)}const ih=2e3;function mc(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),n===void 0||i===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-i)*8*1e3/(e.timestamp-t.timestamp)}const rh=typeof MediaRecorder<"u";class n_{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const i_=rh?MediaRecorder:n_;class r_ extends i_{constructor(t,n){if(!rh)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([t.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>M(this,void 0,void 0,function*(){const u=yield l.data.arrayBuffer();s()||c.enqueue(new Uint8Array(u))}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function s_(){return rh}const o_=1e3,a_=1e4;class M0 extends B{get sender(){return this._sender}set sender(t){this._sender=t}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(t,n,s),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=eh(()=>M(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>M(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(he.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new dn,this.pauseUpstreamLock=new dn,this.processorLock=new dn,this.restartLock=new dn,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==B.Kind.Video)return;const{width:t,height:n}=this._mediaStreamTrack.getSettings();if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var t,n;return(n=(t=this.processor)===null||t===void 0?void 0:t.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(t,n){return M(this,void 0,void 0,function*(){var i;if(t===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Qr(this._mediaStreamTrack,s)}),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([t]),t&&(t.addEventListener("ended",this.handleEnded),t.addEventListener("mute",this.handleTrackMuteEvent),t.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=t.getConstraints());let r;if(this.processor&&t){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&($r(t,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:t,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??t)),!this.providedByUser&&this._mediaStreamTrack!==t&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=t,t&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{$r(r??t,s)}))})}waitForDimensions(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o_;return function*(){var i;if(t.kind===B.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=kn())===null||i===void 0?void 0:i.os)==="iOS"&&(yield pn(10));const r=Date.now();for(;Date.now()-r<n;){const s=t.dimensions;if(s)return s;yield pn(50)}throw new gi("unable to get track dimensions after timeout")}()})}setDeviceId(t){return M(this,void 0,void 0,function*(){return this._constraints.deviceId===t&&this._mediaStreamTrack.getSettings().deviceId===Bi(t)||(this._constraints.deviceId=t,this.isMuted)?!0:(yield this.restartTrack(),Bi(t)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(t.source===B.Source.ScreenShare)return;const{deviceId:i,groupId:r}=t._mediaStreamTrack.getSettings(),s=t.kind===B.Kind.Audio?"audioinput":"videoinput";return n?Wt.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return M(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return M(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(t,n){return M(this,void 0,void 0,function*(){if(!this.sender)throw new gi("unable to replace an unpublished track");let i,r;return typeof n=="boolean"?i=n:n!==void 0&&(i=n.userProvidedTrack,r=n.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(t),r&&this.processor&&(yield this.stopProcessor()),this})}restart(t){return M(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.restartLock.lock();try{t||(t=this._constraints);const{deviceId:i,facingMode:r}=t,s=VC(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const o={audio:!1,video:!1};this.kind===B.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Qr(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=t,this.emit(he.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),!(this.isMuted===t&&this._mediaStreamTrack.enabled!==t)&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?he.Muted:he.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return M(this,void 0,void 0,function*(){yield t.handleAppVisibilityChanged.call(this),w0()&&(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 t;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(t=this.processor)===null||t===void 0||t.destroy(),this.processor=void 0}pauseUpstream(){return M(this,void 0,void 0,function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(he.UpstreamPaused,this);const i=kn();if((i==null?void 0:i.name)==="Safari"&&br(i.version,"12.0")<0)throw new Kd("pauseUpstream is not supported on Safari < 12.");((t=this.sender.transport)===null||t===void 0?void 0:t.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return M(this,void 0,void 0,function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(he.UpstreamResumed,this),((t=this.sender.transport)===null||t===void 0?void 0:t.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return M(this,void 0,void 0,function*(){var t;return!((t=this.sender)===null||t===void 0)&&t.getStats?yield this.sender.getStats():void 0})}setProcessor(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const o=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if($r(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Qr(i._mediaStreamTrack,l),$r(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(he.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;t.processor&&(t.log.debug("stopping processor",t.logContext),(i=t.processor.processedTrack)===null||i===void 0||i.stop(),yield t.processor.destroy(),t.processor=void 0,n||((r=t.processorElement)===null||r===void 0||r.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(he.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!s_()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(!this.localTrackRecorder)this.localTrackRecorder=new r_(this,{mimeType:"audio/webm;codecs=opus"});else{this.log.warn("preconnect buffer already started");return}this.localTrackRecorder.start(t),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},a_)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var t;return(t=this.localTrackRecorder)===null||t===void 0?void 0:t.byteStream}}class Ua extends M0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(t,B.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>M(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=mc(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(he.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(he.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===B.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{n()}})}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Bi(this._constraints.deviceId);return this.source===B.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this}finally{n()}})}restartTrack(t){return M(this,void 0,void 0,function*(){let n;if(t){const i=Zd({audio:t});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(t){const n=Object.create(null,{restart:{get:()=>super.restart}});return M(this,void 0,void 0,function*(){const i=yield n.restart.call(this,t);return this.checkForSilence(),i})}startMonitor(){hn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ih)))}setProcessor(t){return M(this,void 0,void 0,function*(){var n;const i=yield this.processorLock.lock();try{if(!ni()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(r),this.processor=t,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.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(he.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(t){this.audioContext=t}getSenderStats(){return M(this,void 0,void 0,function*(){var t;if(!(!((t=this.sender)===null||t===void 0)&&t.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return M(this,void 0,void 0,function*(){const t=yield _0(this);return t&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(he.AudioSilenceDetected)),t})}}function c_(e,t,n){switch(e.kind){case"audio":return new Ua(e,t,!1,void 0,n);case"video":return new Ba(e,t,!1,n);default:throw new gi("unsupported track type: ".concat(e.kind))}}const l_=Object.values(io),u_=Object.values(Nu),d_=Object.values(Yd),h_=[io.h180,io.h360],f_=[Nu.h180,Nu.h360],p_=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(n=>{var i,r;return new st(Math.floor(e.width/n.scaleResolutionDownBy),Math.floor(e.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=e.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,e.encoding.priority)}),Vu=["q","h","f"];function $u(e,t,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;e&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!t||!n)return[{}];o||(o=g_(e,t,n,l),qe.debug("using video encoding",o));const u=o.maxFramerate,d=new st(t,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&yi(l)){const g=new O0(c),p=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=kn();if(gr()||ni()||(v==null?void 0:v.name)==="Chrome"&&br(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3,w=vE(v);for(let S=0;S<g.spatial;S+=1)p.push({rid:Vu[2-S],maxBitrate:o.maxBitrate/Math.pow(b,S),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:w?Math.pow(2,S):void 0});p[0].scalabilityMode=c}else p.push({maxBitrate:o.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),qe.debug("using svc encoding",{encodings:p}),p}if(!a)return[o];let h=[];e?h=(r=Ip(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Np(e,d):h=(s=Ip(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Np(e,d);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const p=Math.max(t,n);if(p>=960&&f)return ul(t,n,[g,f,d],u);if(p>=480)return ul(t,n,[g,d],u)}return ul(t,n,[d])}function m_(e,t,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&qe.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=e.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=e.dimensions)===null||o===void 0?void 0:o.height;return e.source===B.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),$u(e.source===B.Source.ScreenShare,c,l,n)}function g_(e,t,n,i){const r=b_(e,t,n);let{encoding:s}=r[0];const o=Math.max(t,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function b_(e,t,n){if(e)return d_;const i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?l_:u_}function Np(e,t){if(e)return p_(t);const{width:n,height:i}=t,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?h_:f_}function ul(e,t,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=Vu.length)return;const a=Math.min(e,t),l={rid:Vu[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(l.maxFramerate=u);const d=as()||o===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),ni()&&C0()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,qe.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),qe.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function Ip(e){if(e)return e.sort((t,n)=>{const{encoding:i}=t,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class O0{constructor(t){const n=t.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var t;return"L".concat(this.spatial,"T").concat(this.temporal).concat((t=this.suffix)!==null&&t!==void 0?t:"")}}function y_(e){return e.source===B.Source.ScreenShare||e.constraints.height&&Bi(e.constraints.height)>=1080?"maintain-resolution":"balanced"}const v_=5e3;class Ba extends M0{get sender(){return this._sender}set sender(t){this._sender=t,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(t,B.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>M(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(s.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,l)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);a+=mc(c,d)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new dn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(t){var n;if(this.signalClient=t,!hn())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ih))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(t=>{t.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const t=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return M(this,void 0,void 0,function*(){var n,i,r,s,o;yield t.pauseUpstream.call(this);try{for(var a=!0,c=mi(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(u){i={error:u}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const t=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return M(this,void 0,void 0,function*(){var n,i,r,s,o;yield t.resumeUpstream.call(this);try{for(var a=!0,c=mi(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const u=s;yield(o=u.sender)===null||o===void 0?void 0:o.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===B.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{n()}})}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===B.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(t){super.setTrackMuted(t);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!t}getSenderStats(){return M(this,void 0,void 0,function*(){var t;if(!(!((t=this.sender)===null||t===void 0)&&t.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(t){const n=[];for(let i=Pn.LOW;i<=Pn.HIGH;i+=1)n.push(new Wd({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(yi(this.codec),n)}restartTrack(t){return M(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(t){const d=Zd({video:t});typeof d.video!="boolean"&&(a=d.video)}yield this.restart(a);try{for(var c=!0,l=mi(this.simulcastCodecs.values()),u;u=yield l.next(),n=u.done,!n;c=!0){s=u.value,c=!1;const d=s;d.sender&&((o=d.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(t){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return M(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,a,c,l,u,d;if(yield n.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=mi(r.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(p){a={error:p}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}}()})}setDegradationPreference(t){return M(this,void 0,void 0,function*(){if(this.degradationPreference=t,this.sender)try{this.log.debug("setting degradationPreference to ".concat(t),this.logContext);const n=this.sender.getParameters();n.degradationPreference=t,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(t,n){if(this.simulcastCodecs.has(t)){this.log.error("".concat(t," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:t,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(t,i),i}setSimulcastTrackSender(t,n){const i=this.simulcastCodecs.get(t);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},v_))}setPublishingCodecs(t){return M(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:t,currentCodec:this.codec})),!this.codec&&t.length>0)return yield this.setPublishingLayers(yi(t[0].codec),t[0].qualities),[];this.subscribedCodecs=t;const l=[];try{for(n=!0,i=mi(t);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(yi(u.codec),u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Mp(d.sender,d.encodings,u.qualities,this.senderLock,yi(u.codec),this.log,this.logContext))}}}catch(u){o={error:u}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(t,n){return M(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield Mp(this.sender,this.encodings,n,this.senderLock,t,this.log,this.logContext))})}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return M(this,void 0,void 0,function*(){yield t.handleAppVisibilityChanged.call(this),w0()&&this.isInBackground&&this.source===B.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Mp(e,t,n,i,r,s,o){return M(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{const c=e.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==t.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:t}));return}let u=!1;!1&&l[0].scalabilityMode||(r&&n.some(f=>f.enabled)&&n.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let p=(g=h.rid)!==null&&g!==void 0?g:"";p===""&&(p="q");const v=D0(p),b=n.find(w=>w.quality===v);b&&h.active!==b.enabled&&(u=!0,h.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),o),as()&&(b.enabled?(h.scaleResolutionDownBy=t[f].scaleResolutionDownBy,h.maxBitrate=t[f].maxBitrate,h.maxFrameRate=t[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),u&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield e.setParameters(c))}finally{a()}})}function D0(e){switch(e){case"f":return Pn.HIGH;case"h":return Pn.MEDIUM;case"q":return Pn.LOW;default:return Pn.HIGH}}function Op(e,t,n,i){if(!n)return[new cr({quality:Pn.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new O0(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new cr({quality:Math.min(Pn.HIGH,s.spatial-1)-l,width:Math.ceil(e/Math.pow(a,l)),height:Math.ceil(t/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=D0((o=r.rid)!==null&&o!==void 0?o:"");return new cr({quality:l,width:Math.ceil(e/c),height:Math.ceil(t/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Dp="_lossy",Lp="_reliable",x_=2*1e3,dl="leave-reconnect",k_=3e4;var Ln;(function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"})(Ln||(Ln={}));class S_ extends ii.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=th.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ln.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=qe,this.reliableDataSequence=1,this.reliableMessageBuffer=new Sp,this.reliableReceivedState=new qE(k_),this.handleDataChannel=i=>M(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return function*(){if(o){if(o.label===Lp)s.reliableDCSub=o;else if(o.label===Dp)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>M(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ln.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(fe.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&T_(c,c.value.value),this.emit(fe.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?Be.LOSSY:Be.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(fe.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===dl&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Zt.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ln.Connected&&i();const s=()=>{this.off(fe.Disconnected,o),i()},o=()=>{this.off(fe.Restarted,s),r()};this.once(fe.Restarted,s),this.once(fe.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(fe.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===Be.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===gt.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(_r.RR_SIGNAL_DISCONNECTED))},this.log=xi((n=t.loggerName)!==null&&n!==void 0?n:Hn.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new Jd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new dn,this.dataProcessLock=new dn,this.dcBufferStatus=new Map([[Be.LOSSY,!0],[Be.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(fe.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(fe.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(fe.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(fe.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(fe.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(fe.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(fe.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(fe.SignalRequestResponse,i)}get logContext(){var t,n,i,r,s,o;return{room:(n=(t=this.latestJoinResponse)===null||t===void 0?void 0:t.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(t,n,i,r){return M(this,void 0,void 0,function*(){this.url=t,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(t,n,i,r);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,this.emit(fe.SignalConnected,s),s}catch(s){if(s instanceof ut&&s.reason===Ge.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(t,n,i,r);throw s}})}close(){return M(this,void 0,void 0,function*(){const t=yield this.closingLock.lock();if(this.isClosed){t();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(fe.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}})}cleanupPeerConnections(){return M(this,void 0,void 0,function*(){var t;yield(t=this.pcManager)===null||t===void 0?void 0:t.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Sp,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return M(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new gi("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[t.cid],i(new ut("publication of local track timed out, no response from server",Ge.Timeout))},1e4);this.pendingTrackResolvers[t.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)})}removeTrack(t){if(t.track&&this.pendingTrackResolvers[t.track.id]){const{reject:n}=this.pendingTrackResolvers[t.track.id];n&&n(),delete this.pendingTrackResolvers[t.track.id]}try{return this.pcManager.removeTrack(t),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(t,n){this.client.sendMuteTrack(t,n)}get dataSubscriberReadyState(){var t;return(t=this.reliableDCSub)===null||t===void 0?void 0:t.readyState}getConnectedServerAddress(){return M(this,void 0,void 0,function*(){var t;return(t=this.pcManager)===null||t===void 0?void 0:t.getConnectedAddress()})}setRegionUrlProvider(t){this.regionUrlProvider=t}configure(t){return M(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Ct.NEW)return;this.participantSid=(n=t.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(t);this.pcManager=new t_(r,t.subscriberPrimary,this.loggerOptions),this.emit(fe.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>M(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===Ct.CONNECTED){const u=this.pcState===Ln.New;this.pcState=Ln.Connected,u&&this.emit(fe.Connected,t)}else s===Ct.FAILED&&this.pcState===Ln.Connected&&(this.pcState=Ln.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?_r.RR_SUBSCRIBER_FAILED:_r.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===gt.RECONNECTING,l=[Ct.FAILED,Ct.CLOSING,Ct.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(fe.Offline)}),this.pcManager.onTrack=s=>{this.emit(fe.MediaTrackAdded,s.track,s.streams[0],s.receiver)},w_((i=t.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(t,n)=>M(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type})),yield this.pcManager.setPublisherAnswer(t,n))}),this.client.onTrickle=(t,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:t,target:n})),this.pcManager.addIceCandidate(t,n))},this.client.onOffer=(t,n)=>M(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(t,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=t=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:t.cid,track:(n=t.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[t.cid]){this.log.error("missing track resolver for ".concat(t.cid),Object.assign(Object.assign({},this.logContext),{cid:t.cid}));return}const{resolve:i}=this.pendingTrackResolvers[t.cid];delete this.pendingTrackResolvers[t.cid],i(t.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(fe.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(fe.LocalTrackSubscribed,t)},this.client.onTokenRefresh=t=>{this.token=t},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(fe.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(fe.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var n;this.participantSid=(n=t.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(fe.RoomMoved,t)},this.client.onClose=()=>{this.handleDisconnect("signal",_r.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:t==null?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(t.regions)),t.action){case Xr.DISCONNECT:this.emit(fe.Disconnected,t==null?void 0:t.reason),this.close();break;case Xr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(dl);break;case Xr.RESUME:this.handleDisconnect(dl)}}}makeRTCConfiguration(t){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),t.iceServers&&!i.iceServers){const r=[];t.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return t.clientConfiguration&&t.clientConfiguration.forceRelay===to.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(Dp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Lp,{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(t,n,i){return M(this,void 0,void 0,function*(){if(Iu())return yield this.createTransceiverRTCRtpSender(t,n,i);if(Mu())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(t.mediaStreamTrack);throw new Bt("Required webRTC APIs not supported on this device")})}createSimulcastSender(t,n,i,r){return M(this,void 0,void 0,function*(){if(Iu())return this.createSimulcastTransceiverSender(t,n,i,r);if(Mu())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(t.mediaStreamTrack);throw new Bt("Cannot stream on this device")})}createTransceiverRTCRtpSender(t,n,i){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");const r=[];t.mediaStream&&r.push(t.mediaStream),ps(t)&&(t.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(t,n,i,r){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return t.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(t){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");return this.pcManager.addPublisherTrack(t)})}attemptReconnect(t){return M(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){qe.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===to.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Ct.NEW)===Ct.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof Bt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof Rr||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",_r.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(fe.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(t){try{return this.reconnectPolicy.nextRetryDelayInMs(t)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(t){return M(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new Bt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(fe.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Rr;s=yield this.join(t??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof ut&&o.reason===Ge.NotAllowed?new Bt("could not reconnect, token might be expired"):new Rr}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(fe.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==gt.CONNECTED)throw new Rr("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(fe.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(t){return M(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new Bt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Bt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(fe.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof ut&&r.reason===Ge.NotAllowed?new Bt("could not reconnect, token might be expired"):r instanceof ut&&r.reason===Ge.LeaveRequest?r:new Rr(s)}if(this.emit(fe.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}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!==gt.CONNECTED)throw new Rr("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(fe.Resumed)})}waitForPCInitialConnection(t,n){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,t)})}waitForPCReconnected(){return M(this,void 0,void 0,function*(){this.pcState=Ln.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield pn(x_),!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ln.Connected}catch(t){throw this.pcState=Ln.Disconnected,new ut("could not establish PC connection, ".concat(t.message),Ge.InternalError)}})}publishRpcResponse(t,n,i,r){return M(this,void 0,void 0,function*(){const s=new ln({destinationIdentities:[t],kind:Be.RELIABLE,value:{case:"rpcResponse",value:new Ty({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,Be.RELIABLE)})}publishRpcAck(t,n){return M(this,void 0,void 0,function*(){const i=new ln({destinationIdentities:[t],kind:Be.RELIABLE,value:{case:"rpcAck",value:new wy({requestId:n})}});yield this.sendDataPacket(i,Be.RELIABLE)})}sendDataPacket(t,n){return M(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===Be.RELIABLE&&(t.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=t.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===Be.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:t.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(t){return M(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Be.RELIABLE);const n=this.dataChannelForKind(Be.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(t),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(Be.RELIABLE)})}waitForBufferStatusLow(t){return new Promise((n,i)=>M(this,void 0,void 0,function*(){if(this.isBufferStatusLow(t))n();else{const r=()=>i("Engine closed");for(this.once(fe.Closing,r);!this.dcBufferStatus.get(t);)yield pn(10);this.off(fe.Closing,r),n()}}))}ensureDataTransportConnected(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new Bt("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new ut("".concat(a," connection not set"),Ge.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield pn(50)}throw new ut("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),Ge.InternalError)}()})}ensurePublisherConnected(t){return M(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(t,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ct.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return M(this,void 0,void 0,function*(){return new Promise((t,n)=>M(this,void 0,void 0,function*(){if(!this.pcManager){n(new Au("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(fe.Closing,r),this.pcManager.publisher.once(ts.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();CE(c)&&o.set(a.payload,c)}),this.emit(fe.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),t()}catch(s){s instanceof Au&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",_r.RR_UNKNOWN),n(s)}finally{this.off(fe.Closing,r)}}))})}dataChannelForKind(t,n){if(n){if(t===Be.LOSSY)return this.lossyDCSub;if(t===Be.RELIABLE)return this.reliableDCSub}else{if(t===Be.LOSSY)return this.lossyDC;if(t===Be.RELIABLE)return this.reliableDC}}sendSyncState(t,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;t.forEach(u=>{u.isDesired!==a&&c.push(u.trackSid),u.isEnabled||l.push(u.trackSid)}),this.client.sendSyncState(new Vy({answer:s?ja({sdp:s.sdp,type:s.type}):void 0,offer:o?ja({sdp:o.sdp,type:o.type}):void 0,subscription:new hc({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:OE(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((u,d)=>new $y({publisherSid:d,lastSeq:u}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const t=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&t.push(new zy({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Be.LOSSY),Bn.PUBLISHER),n(this.dataChannelForKind(Be.RELIABLE),Bn.PUBLISHER),n(this.dataChannelForKind(Be.LOSSY,!0),Bn.SUBSCRIBER),n(this.dataChannelForKind(Be.RELIABLE,!0),Bn.SUBSCRIBER),t}clearReconnectTimeout(){this.reconnectTimeout&&Zt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){hn()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){hn()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Rr extends Error{}function w_(e){return e!==void 0&&e>13}function T_(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=e.destinationIdentities.length!==0?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}class zu{constructor(t,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(t),this.token=n}updateToken(t){this.token=t}isCloud(){return Du(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(t){return M(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(t));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),qe.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(t){return M(this,void 0,void 0,function*(){const n=yield fetch("".concat(C_(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:t});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new ut("Could not fetch region settings: ".concat(n.statusText),n.status===401?Ge.NotAllowed:Ge.InternalError,n.status)})}setServerReportedRegions(t){this.regionSettings=t,this.lastUpdateAt=Date.now()}}function C_(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}class L0{get info(){return this._info}constructor(t,n,i){this.reader=n,this.totalByteSize=i,this._info=t,this.bytesReceived=0}}class E_ extends L0{handleChunkReceived(t){var n;this.bytesReceived+=t.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const t=this.reader.getReader();return{next:()=>M(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield t.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return M(this,void 0,void 0,function*(){return t.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return M(this,void 0,void 0,function*(){var t,n,i,r;let s=new Set;try{for(var o=!0,a=mi(this),c;c=yield a.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const l=r;s.add(l)}}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return Array.from(s)})}}class __ extends L0{constructor(t,n,i){super(t,n,i),this.receivedChunks=new Map}handleChunkReceived(t){var n;const i=xa(t.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>t.version)return;this.receivedChunks.set(i,t),this.bytesReceived+=t.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const t=this.reader.getReader(),n=new TextDecoder;return{next:()=>M(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield t.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:n.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return M(this,void 0,void 0,function*(){return t.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return M(this,void 0,void 0,function*(){var t,n,i,r;let s="";try{for(var o=!0,a=mi(this),c;c=yield a.next(),t=c.done,!t;o=!0)r=c.value,o=!1,s+=r}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return s})}}class F0{constructor(t,n,i){this.writableStream=t,this.defaultWriter=t.getWriter(),this.onClose=i,this.info=n}write(t){return this.defaultWriter.write(t)}close(){return M(this,void 0,void 0,function*(){var t;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(t=this.onClose)===null||t===void 0||t.call(this)})}}class R_ extends F0{}class A_ extends F0{}class j0 extends B{constructor(t,n,i,r,s){super(t,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?he.Muted:he.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(he.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return M(this,void 0,void 0,function*(){var t;return!((t=this.receiver)===null||t===void 0)&&t.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(t){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=t: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(),ih)),DE()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>t());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(he.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};t()}}class U0 extends j0{constructor(t,n,i,r,s,o){super(t,n,B.Kind.Audio,i,o),this.monitorReceiver=()=>M(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=mc(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(t){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(t,0,.1):i.volume=t;ni()&&this._mediaStreamTrack._setVolume(t),this.elementVolume=t}getVolume(){if(this.elementVolume)return this.elementVolume;if(ni())return 1;let t=0;return this.attachedElements.forEach(n=>{n.volume>t&&(t=n.volume)}),t}setSinkId(t){return M(this,void 0,void 0,function*(){this.sinkId=t,yield Promise.all(this.attachedElements.map(n=>{if(Ou(n))return n.setSinkId(t)}))})}attach(t){const n=this.attachedElements.length===0;return t?super.attach(t):t=super.attach(),this.sinkId&&Ou(t)&&t.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,t),t.volume=0,t.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),t}detach(t){let n;return t?(n=super.detach(t),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(t){this.audioContext=t,t&&this.attachedElements.length>0?this.connectWebAudio(t,this.attachedElements[0]):t||this.disconnectWebAudio()}setWebAudioPlugins(t){this.webAudioPluginNodes=t,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),t.state!=="running"&&t.resume().then(()=>{t.state!=="running"&&this.emit(he.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(he.AudioPlaybackFailed,r)})}disconnectWebAudio(){var t,n;(t=this.gainNode)===null||t===void 0||t.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return M(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const t=yield this.receiver.getStats();let n;return t.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const hl=100;class P_ extends j0{constructor(t,n,i,r,s){super(t,n,B.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>M(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=mc(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=eh(()=>{this.updateDimensions()},hl),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(t){super.setMuted(t),this.attachedElements.forEach(n=>{t?Qr(this._mediaStreamTrack,n):$r(this._mediaStreamTrack,n)})}attach(t){if(t?super.attach(t):t=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===t)===void 0){const n=new N_(t);this.observeElementInfo(n)}return t}observeElementInfo(t){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===t)===void 0?(t.handleResize=()=>{this.debouncedHandleResize()},t.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(t),t.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(t){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===t);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==t),this.updateVisibility(),this.debouncedHandleResize()}detach(t){let n=[];if(t)return this.stopObservingElement(t),super.detach(t);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var t;return(t=this.prevStats)===null||t===void 0?void 0:t.decoderImplementation}getReceiverStats(){return M(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const t=yield this.receiver.getStats();let n,i="",r=new Map;return t.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(t){const n=this.elementInfos.filter(i=>i.element===t);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return M(this,void 0,void 0,function*(){yield t.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var t,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<hl){Zt.setTimeout(()=>{this.updateVisibility()},hl);return}this.lastVisible=o,this.emit(he.VisibilityChanged,o,this)}}updateDimensions(){var t,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((t=this.lastDimensions)===null||t===void 0?void 0:t.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(he.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var t;const n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pixelDensity;return n==="screen"?gp():n||(gp()>2?2:1)}}class N_{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(t,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=Ps(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ps(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ps(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=t,this.isIntersecting=n??Hu(t),this.isPiP=hn()&&Ps(t),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var t,n,i;this.isIntersecting=Hu(this.element),this.isPiP=Ps(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,yp().observe(this.element),bp().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(t=window.documentPictureInPicture)===null||t===void 0||t.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var t,n,i,r,s;(t=yp())===null||t===void 0||t.unobserve(this.element),(n=bp())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ps(e){var t,n;return document.pictureInPictureElement===e?!0:!((t=window.documentPictureInPicture)===null||t===void 0)&&t.window?Hu(e,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function Hu(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,i+=e.offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class hi extends ii.EventEmitter{constructor(t,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=vn.NONE,this.log=qe,this.handleMuted=()=>{this.emit(he.Muted)},this.handleUnmuted=()=>{this.emit(he.Unmuted)},this.log=xi((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Hn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=B.Source.Unknown}setTrack(t){this.track&&(this.track.off(he.Muted,this.handleMuted),this.track.off(he.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(he.Muted,this.handleMuted),t.on(he.Unmuted,this.handleUnmuted))}get logContext(){var t;return Object.assign(Object.assign({},(t=this.loggerContextCb)===null||t===void 0?void 0:t.call(this)),He(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==vn.NONE}get audioTrack(){if(Qn(this.track))return this.track}get videoTrack(){if(ps(this.track))return this.track}updateInfo(t){this.trackSid=t.sid,this.trackName=t.name,this.source=B.sourceFromProto(t.source),this.mimeType=t.mimeType,this.kind===B.Kind.Video&&t.width>0&&(this.dimensions={width:t.width,height:t.height},this.simulcasted=t.simulcast),this.encryption=t.encryption,this.trackInfo=t,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:t}))}}(function(e){(function(t){t.Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed"})(e.SubscriptionStatus||(e.SubscriptionStatus={})),function(t){t.Allowed="allowed",t.NotAllowed="not_allowed"}(e.PermissionStatus||(e.PermissionStatus={}))})(hi||(hi={}));class Wu extends hi{get isUpstreamPaused(){var t;return(t=this.track)===null||t===void 0?void 0:t.isUpstreamPaused}constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(he.Ended)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&this.track.off(he.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(he.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 M(this,void 0,void 0,function*(){var t;return(t=this.track)===null||t===void 0?void 0:t.mute()})}unmute(){return M(this,void 0,void 0,function*(){var t;return(t=this.track)===null||t===void 0?void 0:t.unmute()})}pauseUpstream(){return M(this,void 0,void 0,function*(){var t;yield(t=this.track)===null||t===void 0?void 0:t.pauseUpstream()})}resumeUpstream(){return M(this,void 0,void 0,function*(){var t;yield(t=this.track)===null||t===void 0?void 0:t.resumeUpstream()})}getTrackFeatures(){var t;if(Qn(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(Ht.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(Ht.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(Ht.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(Ht.TF_STEREO),!((t=this.options)===null||t===void 0)&&t.dtx||i.add(Ht.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ht.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function gc(e,t){return M(this,void 0,void 0,function*(){e??(e={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=R0(e);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),e.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=E0(s,P0,N0),l=Zd(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(Wt.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Wt.userMediaPromiseMap.delete("audioinput"))),s.video&&(Wt.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Wt.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>M(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&Bi(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const w=c_(h,p,t);return w.kind===B.Kind.Video?w.source=B.Source.Camera:w.kind===B.Kind.Audio&&(w.source=B.Source.Microphone),w.mediaStream=d,Qn(w)&&i?yield w.setProcessor(i):ps(w)&&r&&(yield w.setProcessor(r)),w})))}catch(d){if(!n)throw d;return gc(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}})}function I_(e){return M(this,void 0,void 0,function*(){return(yield gc({audio:!1,video:!0}))[0]})}function M_(e){return M(this,void 0,void 0,function*(){return(yield gc({audio:!0,video:!1}))[0]})}var Li;(function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"})(Li||(Li={}));function O_(e){switch(e){case Us.EXCELLENT:return Li.Excellent;case Us.GOOD:return Li.Good;case Us.POOR:return Li.Poor;case Us.LOST:return Li.Lost;default:return Li.Unknown}}class B0 extends ii.EventEmitter{get logContext(){var t,n;return Object.assign({},(n=(t=this.loggerOptions)===null||t===void 0?void 0:t.loggerContextCb)===null||n===void 0?void 0:n.call(t))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(t=>t.isEncrypted)}get isAgent(){var t;return((t=this.permissions)===null||t===void 0?void 0:t.agent)||this.kind===no.AGENT}get isActive(){var t;return((t=this.participantInfo)===null||t===void 0?void 0:t.state)===Zr.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:no.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Li.Unknown,this.log=qe,this.log=xi((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Hn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(t){for(const[,n]of this.trackPublications)if(n.source===t)return n}getTrackPublicationByName(t){for(const[,n]of this.trackPublications)if(n.trackName===t)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new zr,this.once(Q.Active,()=>{var t,n;(n=(t=this.activeFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var t;const n=this.getTrackPublication(B.Source.Camera);return!(!((t=n==null?void 0:n.isMuted)!==null&&t!==void 0)||t)}get isMicrophoneEnabled(){var t;const n=this.getTrackPublication(B.Source.Microphone);return!(!((t=n==null?void 0:n.isMuted)!==null&&t!==void 0)||t)}get isScreenShareEnabled(){return!!this.getTrackPublication(B.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(t){var n;return this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version?!1:(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===Zr.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Zr.ACTIVE&&this.emit(Q.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(Q.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(Q.ParticipantNameChanged,t)}_setAttributes(t){const n=LE(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(Q.AttributesChanged,n)}setPermissions(t){var n,i,r,s,o,a;const c=this.permissions,l=t.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||t.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||t.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||t.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||t.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||t.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=t,l&&this.emit(Q.ParticipantPermissionsChanged,c),l}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(Q.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=O_(t),n!==this._connectionQuality&&this.emit(Q.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var t,n;this.activeFuture&&((n=(t=this.activeFuture).reject)===null||n===void 0||n.call(t,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(t){this.audioContext=t,this.audioTrackPublications.forEach(n=>Qn(n.track)&&n.track.setAudioContext(t))}addTrackPublication(t){t.on(he.Muted,()=>{this.emit(Q.TrackMuted,t)}),t.on(he.Unmuted,()=>{this.emit(Q.TrackUnmuted,t)});const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case B.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case B.Kind.Video:this.videoTrackPublications.set(t.trackSid,t);break}}}function D_(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Uy({participantIdentity:(t=e.participantIdentity)!==null&&t!==void 0?t:"",participantSid:(n=e.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=e.allowAll)!==null&&i!==void 0?i:!1,trackSids:e.allowedTrackSids||[]})}const Fp=15e3;class L_ extends B0{constructor(t,n,i,r,s){super(t,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=vn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new zr)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var o,a,c,l,u,d;this.reconnectFuture&&(this.reconnectFuture.promise.catch(h=>this.log.warn(h.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(c=this.signalConnectedFuture).reject)===null||l===void 0||l.call(c,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(d=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||d===void 0||d.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var a,c;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new zr),(c=(a=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(a)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:c,message:l}=o,u=this.pendingSignalRequests.get(a);u&&(c!==qd.OK&&u.reject(new dp(l,c)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,c=null,l=null;a.value.case==="payload"?c=a.value.value:a.value.case==="error"&&(l=_t.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,c,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},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(o=>D_(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),He(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),He(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),He(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=o=>M(this,void 0,void 0,function*(){var a,c,l,u,d;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const h=this.videoTrackPublications.get(o.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!h.videoTrack)return;const f=yield h.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var g=!0,p=mi(f),v;v=yield p.next(),a=v.done,!a;g=!0){u=v.value,g=!1;const b=u;hE(b)&&(this.log.debug("publish ".concat(b," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),He(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,b,h.options))}}catch(b){c={error:b}}finally{try{!g&&!a&&(l=p.return)&&(yield l.call(p))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>M(this,void 0,void 0,function*(){if(o.source===B.Source.ScreenShare||o.source===B.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),He(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(di(o)||Pi(o))try{if(hn())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===B.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),He(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),He(o))),di(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),He(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,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!==vn.NONE}getTrackPublication(t){const n=super.getTrackPublication(t);if(n)return n}getTrackPublicationByName(t){const n=super.getTrackPublicationByName(t);if(n)return n}setupEngine(t){this.engine=t,this.engine.on(fe.RemoteMute,(n,i)=>{const r=this.trackPublications.get(n);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(fe.Connected,this.handleReconnected).on(fe.SignalConnected,this.handleSignalConnected).on(fe.SignalRestarted,this.handleReconnected).on(fe.SignalResumed,this.handleReconnected).on(fe.Restarting,this.handleReconnecting).on(fe.Resuming,this.handleReconnecting).on(fe.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(fe.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(fe.Disconnected,this.handleDisconnected).on(fe.SignalRequestResponse,this.handleSignalRequestResponse).on(fe.DataPacketReceived,this.handleDataPacket),this.signalConnectedFuture=void 0}setMetadata(t){return M(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:t})})}setName(t){return M(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:t})})}setAttributes(t){return M(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:t})})}requestMetadataUpdate(t){return M(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return function*(){return new Promise((a,c)=>M(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),d=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[p,v]=g;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),a();return}yield pn(50)}c(new dp("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&c(d)}}))}()})}setCameraEnabled(t,n,i){return this.setTrackEnabled(B.Source.Camera,t,n,i)}setMicrophoneEnabled(t,n,i){return this.setTrackEnabled(B.Source.Microphone,t,n,i)}setScreenShareEnabled(t,n,i){return this.setTrackEnabled(B.Source.ScreenShare,t,n,i)}setPermissions(t){const n=this.permissions,i=super.setPermissions(t);return i&&n&&this.emit(Q.ParticipantPermissionsChanged,n),i}setE2EEEnabled(t){return M(this,void 0,void 0,function*(){this.encryptionType=t?vn.GCM:vn.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(t,n,i,r){return M(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(t);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(t)){const l=yield this.waitForPendingPublicationOfSource(t);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(t);try{switch(t){case B.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case B.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case B.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new gi(t)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(Q.MediaDevicesError,l,Uu(t)),this.pendingPublishing.delete(t),l}for(const l of c)t===B.Source.Microphone&&Qn(l)&&(r!=null&&r.preConnectBuffer)&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer());try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),He(d))),l.push(this.publishTrack(d,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}finally{this.pendingPublishing.delete(t)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(t)&&(a=yield this.waitForPendingPublicationOfSource(t),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),a&&a.track)if(t===B.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(B.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return M(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(B.Source.Camera)||this.pendingPublishing.has(B.Source.Microphone))){this.pendingPublishing.add(B.Source.Camera),this.pendingPublishing.add(B.Source.Microphone);try{const t=yield this.createTracks({audio:!0,video:!0});yield Promise.all(t.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(B.Source.Camera),this.pendingPublishing.delete(B.Source.Microphone)}}})}createTracks(t){return M(this,void 0,void 0,function*(){var n,i;t??(t={});const r=E0(t,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield gc(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Qn(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=B.Source.Microphone,this.emit(Q.AudioStreamAcquired)),ps(a)&&(this.cameraError=void 0,a.source=B.Source.Camera),a))}catch(s){throw s instanceof Error&&(t.audio&&(this.microphoneError=s),t.video&&(this.cameraError=s)),s}})}createScreenTracks(t){return M(this,void 0,void 0,function*(){if(t===void 0&&(t={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Kd("getDisplayMedia not supported");t.resolution===void 0&&!yE()&&(t.resolution=Yd.h1080fps30.resolution);const n=ME(t),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new gi("no video track found");const s=new Ba(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=B.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(Q.AudioStreamAcquired);const a=new Ua(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=B.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(t,n){return M(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(t,n)})}publishOrRepublishTrack(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,c,l,u;di(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),es(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case B.Source.Microphone:b="audioinput";break;case B.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Ua(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ba(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new gi("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),He(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),He(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!xE()&&s.roomOptions.e2ee&&(s.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({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,w)=>M(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==gt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:He(i)}));const S=setTimeout(()=>{w(new up("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(S);const k=yield this.publish(i,p,g);b(k)}else try{const S=yield this.publish(i,p,g);b(S)}catch(S){w(S)}}catch(S){w(S)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new zr),this.signalConnectedFuture.promise}hasPermissionsToPublish(t){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),He(t))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>FE(r)).includes(t.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),He(t))),!1)}publish(t,n,i){return M(this,void 0,void 0,function*(){var r,s,o,a,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(t))throw new up("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(N=>es(t)&&N.source===t.source)&&t.source!==B.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),He(t))),n.stopMicTrackOnMute&&Qn(t)&&(t.stopOnMute=!0),t.source===B.Source.ScreenShare&&as()&&(n.simulcast=!1),n.videoCodec==="av1"&&!mE()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!gE()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Bu),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(N=>n.videoCodec===ka(N.mime))||(n.videoCodec=ka(this.enabledPublishVideoCodecs[0].mime)));const p=n.videoCodec;t.on(he.Muted,this.onTrackMuted),t.on(he.Unmuted,this.onTrackUnmuted),t.on(he.Ended,this.handleTrackEnded),t.on(he.UpstreamPaused,this.onTrackUpstreamPaused),t.on(he.UpstreamResumed,this.onTrackUpstreamResumed),t.on(he.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),w=t.getSourceTrackSettings();w.autoGainControl&&v.push(Ht.TF_AUTO_GAIN_CONTROL),w.echoCancellation&&v.push(Ht.TF_ECHO_CANCELLATION),w.noiseSuppression&&v.push(Ht.TF_NOISE_SUPPRESSION),w.channelCount&&w.channelCount>1&&v.push(Ht.TF_STEREO),b&&v.push(Ht.TF_NO_DTX),di(t)&&t.hasPreConnectBuffer&&v.push(Ht.TF_PRECONNECT_BUFFER);const S=new xu({cid:t.mediaStreamTrack.id,name:n.name,type:B.kindToProto(t.kind),muted:t.isMuted,source:B.sourceToProto(t.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:v});let k;if(t.kind===B.Kind.Video){let N={width:0,height:0};try{N=yield t.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:io.h720.resolution;N={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{dims:N}))}S.width=N.width,S.height=N.height,Pi(t)&&(yi(p)&&(t.source===B.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),He(t))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),S.simulcastCodecs=[new vu({codec:p,cid:t.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Bu}),n.backupCodec&&p!==n.backupCodec.codec&&S.encryption===vn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),S.simulcastCodecs.push(new vu({codec:n.backupCodec.codec,cid:""})))),k=$u(t.source===B.Source.ScreenShare,S.width,S.height,n),S.layers=Op(S.width,S.height,k,yi(n.videoCodec))}else t.kind===B.Kind.Audio&&(k=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(d=(u=n.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Bt("cannot publish track when not connected");const x=()=>M(this,void 0,void 0,function*(){var N,y,R;if(!this.engine.pcManager)throw new Bt("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,k),Pi(t)&&((N=n.degradationPreference)!==null&&N!==void 0||(n.degradationPreference=y_(t)),t.setDegradationPreference(n.degradationPreference)),k)if(as()&&t.kind===B.Kind.Audio){let I;for(const L of this.engine.pcManager.publisher.getTransceivers())if(L.sender===t.sender){I=L;break}I&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:I,codec:"opus",maxbr:!((y=k[0])===null||y===void 0)&&y.maxBitrate?k[0].maxBitrate/1e3:0})}else t.codec&&yi(t.codec)&&(!((R=k[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:S.cid,codec:t.codec,maxbr:k[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const P=new Promise((N,y)=>M(this,void 0,void 0,function*(){var R;try{T=yield this.engine.addTrack(S),N(T)}catch(I){t.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch(L=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{error:L}))})),y(I)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([P,x()]))[0];else{T=yield P;let N;if(T.codecs.forEach(y=>{N===void 0&&(N=y.mimeType)}),N&&t.kind===B.Kind.Video){const y=ka(N);y!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{codec:y})),n.videoCodec=y,k=$u(t.source===B.Source.ScreenShare,S.width,S.height,n))}yield x()}const A=new Wu(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(A.options=n,t.sid=T.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:T})),Pi(t)?t.startMonitor(this.engine.client):di(t)&&t.startMonitor(),this.addTrackPublication(A),this.emit(Q.LocalTrackPublished,A),di(t)&&T.audioFeatures.includes(Ht.TF_PRECONNECT_BUFFER)){const N=t.getPreConnectBuffer();this.on(Q.LocalTrackSubscribed,y=>{if(y.trackSid===T.sid){if(!t.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),He(t))),t.stopPreConnectBuffer()}}),N&&new Promise((R,I)=>M(this,void 0,void 0,function*(){var L,U,K,ue,se,z;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),He(t)));const Y=setTimeout(()=>{I(new Error("agent not active within 10 seconds"))},1e4),E=yield this.waitUntilActiveAgentPresent();clearTimeout(Y),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),He(t)));const J=yield this.streamBytes({name:"preconnect-buffer",mimeType:"audio/opus",topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[E.identity],attributes:{trackId:A.trackSid,sampleRate:String((se=w.sampleRate)!==null&&se!==void 0?se:"48000"),channels:String((z=w.channelCount)!==null&&z!==void 0?z:"1")}});try{for(var H=!0,C=mi(N),W;W=yield C.next(),L=W.done,!L;H=!0){ue=W.value,H=!1;const ne=ue;yield J.write(ne)}}catch(ne){U={error:ne}}finally{try{!H&&!L&&(K=C.return)&&(yield K.call(C))}finally{if(U)throw U.error}}yield J.close(),R()}catch(Y){I(Y)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),He(t)))}).catch(R=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{error:R}))})}return A})}get isLocal(){return!0}publishAdditionalCodecForTrack(t,n,i){return M(this,void 0,void 0,function*(){var r;if(this.encryptionType!==vn.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===t&&(s=f)}),!s)throw new gi("track is not published");if(!Pi(t))throw new gi("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=m_(t,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),He(t)));return}const c=t.addSimulcastTrack(n,a);if(!c)return;const l=new xu({cid:c.mediaStreamTrack.id,type:B.kindToProto(t.kind),muted:t.isMuted,source:B.sourceToProto(t.source),sid:t.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Op(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Bt("cannot publish track when not connected");const u=()=>M(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(t,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(n," for track ").concat(t.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(t,n){return M(this,void 0,void 0,function*(){var i,r;if(es(t)){const l=this.pendingPublishPromises.get(t);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),He(t))),yield l)}const s=this.getPublicationForTrack(t),o=s?He(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}t=s.track,t.off(he.Muted,this.onTrackMuted),t.off(he.Unmuted,this.onTrackUnmuted),t.off(he.Ended,this.handleTrackEnded),t.off(he.UpstreamPaused,this.onTrackUpstreamPaused),t.off(he.UpstreamResumed,this.onTrackUpstreamResumed),t.off(he.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ct.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),Pi(t)){for(const[,l]of t.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);t.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case B.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case B.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(Q.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(t){return M(this,void 0,void 0,function*(){return(yield Promise.all(t.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>M(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>M(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==B.Source.ScreenShare&&l.source!==B.Source.ScreenShareAudio&&(di(l)||Pi(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?Be.RELIABLE:Be.LOSSY,o=r.destinationIdentities,a=r.topic,c=new ln({kind:s,value:{case:"user",value:new xy({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(t,n){return M(this,void 0,void 0,function*(){const i=new ln({kind:Be.RELIABLE,value:{case:"sipDtmf",value:new ky({code:t,digit:n})}});yield this.engine.sendDataPacket(i,Be.RELIABLE)})}sendChatMessage(t,n){return M(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new ln({value:{case:"chatMessage",value:new fu(Object.assign(Object.assign({},i),{timestamp:yt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Be.RELIABLE),this.emit(Q.ChatMessage,i),i})}editChatMessage(t,n){return M(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),r=new ln({value:{case:"chatMessage",value:new fu(Object.assign(Object.assign({},i),{timestamp:yt.parse(i.timestamp),editTimestamp:yt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Be.RELIABLE),this.emit(Q.ChatMessage,i),i})}sendText(t,n){return M(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(t).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const g=c.reduce((p,v)=>p+v,0);(f=n==null?void 0:n.onProgress)===null||f===void 0||f.call(n,g)},u=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield u.write(t),l(1,0),yield u.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((d,h)=>M(this,void 0,void 0,function*(){return this._sendFile(a[h],d,{topic:n.topic,mimeType:d.type,onProgress:f=>{l(f,h+1)}})})))),u.info})}streamText(t){return M(this,void 0,void 0,function*(){var n,i;const r=(n=t==null?void 0:t.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=t==null?void 0:t.topic)!==null&&i!==void 0?i:"",size:t==null?void 0:t.totalSize,attributes:t==null?void 0:t.attributes},o=new mu({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:ir(s.timestamp),totalLength:ir(t==null?void 0:t.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Iy({version:t==null?void 0:t.version,attachedStreamIds:t==null?void 0:t.attachedStreamIds,replyToStreamId:t==null?void 0:t.replyToStreamId,operationType:(t==null?void 0:t.type)==="update"?pu.UPDATE:pu.CREATE})}}),a=t==null?void 0:t.destinationIdentities,c=new ln({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Be.RELIABLE);let l=0;const u=this,d=new WritableStream({write(g){return M(this,void 0,void 0,function*(){for(const p of NE(g,Fp)){yield u.engine.waitForBufferStatusLow(Be.RELIABLE);const v=new gu({content:p,streamId:r,chunkIndex:ir(l)}),b=new ln({destinationIdentities:a,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,Be.RELIABLE),l+=1}})},close(){return M(this,void 0,void 0,function*(){const g=new bu({streamId:r}),p=new ln({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield u.engine.sendDataPacket(p,Be.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>M(this,void 0,void 0,function*(){yield f.close()});u.engine.once(fe.Closing,h);const f=new R_(d,s,()=>this.engine.off(fe.Closing,h));return f})}sendFile(t,n){return M(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,t,n),{id:i}})}_sendFile(t,n,i){return M(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:t,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(t){return M(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=t==null?void 0:t.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=t==null?void 0:t.destinationIdentities,l={id:a,mimeType:(i=t==null?void 0:t.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=t==null?void 0:t.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:t==null?void 0:t.attributes,size:t==null?void 0:t.totalSize,name:(s=t==null?void 0:t.name)!==null&&s!==void 0?s:"unknown"},u=new mu({totalLength:ir((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:ir(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new My({name:l.name})}}),d=new ln({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,Be.RELIABLE);let h=0;const f=new dn,g=this.engine,p=this.log,v=new WritableStream({write(w){return M(this,void 0,void 0,function*(){const S=yield f.lock();let k=0;try{for(;k<w.byteLength;){const x=w.slice(k,k+Fp);yield g.waitForBufferStatusLow(Be.RELIABLE);const T=new ln({destinationIdentities:c,value:{case:"streamChunk",value:new gu({content:x,streamId:a,chunkIndex:ir(h)})}});yield g.sendDataPacket(T,Be.RELIABLE),h+=1,k+=x.byteLength}}finally{S()}})},close(){return M(this,void 0,void 0,function*(){const w=new bu({streamId:a}),S=new ln({destinationIdentities:c,value:{case:"streamTrailer",value:w}});yield g.sendDataPacket(S,Be.RELIABLE)})},abort(w){p.error("Sink error:",w)}});return new A_(v,l)})}performRpc(t){return M(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return function*(){return new Promise((l,u)=>M(i,void 0,void 0,function*(){var d,h,f,g;if(nh(o)>I0){u(_t.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||h===void 0)&&h.version&&br((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){u(_t.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,o,a-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),u(_t.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),u(_t.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(p,{resolve:(w,S)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),S?u(S):l(w??"")},participantIdentity:r})}))}()})}registerRpcMethod(t,n){this.rpcHandlers.has(t)&&this.log.warn("you're overriding the RPC handler for method ".concat(t,", in the future this will throw an error")),this.rpcHandlers.set(t,n)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}setTrackSubscriptionPermissions(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=t,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(t){const n=this.pendingAcks.get(t);n?(n.resolve(),this.pendingAcks.delete(t)):console.error("Ack received for unexpected RPC request",t)}handleIncomingRpcResponse(t,n,i){const r=this.pendingResponses.get(t);r?(r.resolve(n,i),this.pendingResponses.delete(t)):console.error("Response received for unexpected RPC request",t)}publishRpcRequest(t,n,i,r,s){return M(this,void 0,void 0,function*(){const o=new ln({destinationIdentities:[t],kind:Be.RELIABLE,value:{case:"rpcRequest",value:new Sy({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,Be.RELIABLE)})}handleParticipantDisconnected(t){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===t&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===t&&(r(null,_t.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(t){this.enabledPublishVideoCodecs=t.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(t){return super.updateInfo(t)?(t.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),He(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(t){var n,i,r,s;this.firstActiveAgent=t,t&&!this.firstActiveAgent&&(this.firstActiveAgent=t),t?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,t):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new zr),this.activeAgentFuture.promise)}getPublicationForTrack(t){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(t instanceof MediaStreamTrack?(di(r)||Pi(r))&&r.mediaStreamTrack===t&&(n=i):t===r&&(n=i))}),n}waitForPendingPublicationOfSource(t){return M(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===t});if(r)return r[1];yield pn(20)}})}}class Va extends hi{constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Pn.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(he.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r=new hc({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Ey({participantSid:"",trackSids:[this.trackSid]})]});this.emit(he.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?hi.SubscriptionStatus.Unsubscribed:super.isSubscribed?hi.SubscriptionStatus.Subscribed:hi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?hi.PermissionStatus.Allowed:hi.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(t){!this.isManualOperationAllowed()||this.disabled===!t||(this.disabled=!t,this.emitTrackUpdate())}setVideoQuality(t){!this.isManualOperationAllowed()||this.currentVideoQuality===t||(this.currentVideoQuality=t,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(t){var n,i;this.isManualOperationAllowed()&&(((n=this.videoDimensions)===null||n===void 0?void 0:n.width)===t.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===t.height||(sl(this.track)&&(this.videoDimensions=t),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(t){this.isManualOperationAllowed()&&sl(this.track)&&this.fps!==t&&(this.fps=t,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(he.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(he.VisibilityChanged,this.handleVisibilityChange),r.off(he.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(he.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(he.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(he.VisibilityChanged,this.handleVisibilityChange),t.on(he.Ended,this.handleEnded),this.emit(he.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=t,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(t){this.emit(he.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?he.Muted:he.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(he.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(he.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===B.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Oy({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=Math.ceil(this.videoDimensions.width),t.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?t.quality=this.currentVideoQuality:t.quality=Pn.HIGH,this.emit(he.UpdateSettings,t)}}class $a extends B0{static fromParticipantInfo(t,n,i){return new $a(t,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(t,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:no.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=t,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(he.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),He(t))),this.signalClient.sendUpdateTrackSettings(n)}),t.on(he.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),t.on(he.SubscriptionPermissionChanged,n=>{this.emit(Q.TrackSubscriptionPermissionChanged,t,n)}),t.on(he.SubscriptionStatusChanged,n=>{this.emit(Q.TrackSubscriptionStatusChanged,t,n)}),t.on(he.Subscribed,n=>{this.emit(Q.TrackSubscribed,n,t)}),t.on(he.Unsubscribed,n=>{this.emit(Q.TrackUnsubscribed,n,t)}),t.on(he.SubscriptionFailed,n=>{this.emit(Q.TrackSubscriptionFailed,t.trackSid,n)})}getTrackPublication(t){const n=super.getTrackPublication(t);if(n)return n}getTrackPublicationByName(t){const n=super.getTrackPublicationByName(t);if(n)return n}setVolume(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:B.Source.Microphone;this.volumeMap.set(n,t);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(t)}getVolume(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:B.Source.Microphone;const n=this.getTrackPublication(t);return n&&n.track?n.track.getVolume():this.volumeMap.get(t)}addSubscribedMediaTrack(t,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(u=>{!a&&t.kind===u.kind.toString()&&(a=u)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(Q.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(t,n,i,r,s,o-1)},150);return}if(t.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),He(a))),this.emit(Q.TrackSubscriptionFailed,n);return}const c=t.kind==="video";let l;return c?l=new P_(t,n,r,s):l=new U0(t,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&Fu(l)&&Qn(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(t){return this.trackPublications.get(t)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=B.kindFromProto(r.type);if(!c)return;a=new Va(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(u=>u.source===(a==null?void 0:a.source));l&&a.source!==B.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:He(l),newTrack:He(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),He(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(Q.TrackPublished,r)}),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case B.Kind.Audio:this.audioTrackPublications.delete(t);break;case B.Kind.Video:this.videoTrackPublications.delete(t);break}n&&this.emit(Q.TrackUnpublished,i)}setAudioOutput(t){return M(this,void 0,void 0,function*(){this.audioOutput=t;const n=[];this.audioTrackPublications.forEach(i=>{var r;Qn(i.track)&&Fu(i.track)&&n.push(i.track.setSinkId((r=t.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:t,args:i})),super.emit(t,...i)}}var $e;(function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"})($e||($e={}));const F_=4*1e3;class vi extends ii.EventEmitter{constructor(t){var n,i,r,s;if(super(),n=this,this.state=$e.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=qe,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=(o,a,c)=>M(this,void 0,void 0,function*(){var l;if(!bE())throw ni()?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 u=yield this.disconnectLock.lock();if(this.state===$e.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState($e.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Du(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new zu(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,g,p)=>M(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,u==null||u();try{yield this.attemptConnection(p??o,a,c,w),this.abortController=void 0,f()}catch(S){if(this.regionUrlProvider&&S instanceof ut&&S.reason!==Ge.Cancelled&&S.reason!==Ge.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(x){if(x instanceof ut&&(x.status===401||x.reason===Ge.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(x);return}}k&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(S.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield d(f,g,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,xp(S)),g(S))}else{let k=Vn.UNKNOWN_REASON;S instanceof ut&&(k=xp(S)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),g(S)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new zr((f,g)=>{d(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,u,d)=>M(this,void 0,void 0,function*(){var h,f,g;const p=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},d.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[w,S]=b;return"".concat(w,": ").concat(S)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(g=p.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new nE("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>M(this,void 0,void 0,function*(){var u,d;this.state===$e.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},th),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(j.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new ut("could not establish signal connection",Ge.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof ut&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ut("Connection attempt aborted",Ge.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}hn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),hn()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState($e.Connected),this.emit(j.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return M(n,[...a],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,g;const p=yield l.disconnectLock.lock();try{if(l.state===$e.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===$e.Connecting||l.state===$e.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(d=l.abortController)===null||d===void 0||d.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new ut("Client initiated disconnect",Ge.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(u,Vn.CLIENT_INITIATED),l.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>M(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>M(this,void 0,void 0,function*(){const o=[],a=kn();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const u=rl();u.enabled=!0;const d=new MediaStream([u]);l.srcObject=d,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(j.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>M(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?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 o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState($e.Reconnecting)&&this.emit(j.Reconnecting)},this.handleSignalRestarted=o=>M(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState($e.Connected),this.emit(j.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===Zr.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),a.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(j.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?a.set(l.sid,u):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(j.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const u=B.streamStateFromProto(a.state);u!==l.track.streamState&&(l.track.streamState=u,c.emit(Q.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(j.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader")this.handleStreamHeader(o.value.value,o.participantIdentity);else if(o.value.case==="streamChunk")this.handleStreamChunk(o.value.value);else if(o.value.case==="streamTrailer")this.handleStreamTrailer(o.value.value);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(j.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(Q.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(j.SipDTMFReceived,a,o),o==null||o.emit(Q.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),u=_E(a,this.transcriptionReceivedTimes);l==null||l.emit(he.TranscriptionReceived,u),c==null||c.emit(Q.TranscriptionReceived,u,l),this.emit(j.TranscriptionReceived,u,c,l)},this.handleChatMessage=(o,a)=>{const c=RE(a);this.emit(j.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(j.MetricsReceived,o,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(j.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(j.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(j.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(j.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>M(this,void 0,void 0,function*(){var o;((o=kn())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(j.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(j.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(j.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(j.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(j.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(j.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(j.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(j.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>M(this,void 0,void 0,function*(){var a,c,l,u,d,h;(a=o.track)===null||a===void 0||a.on(he.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(he.Restarted,this.onLocalTrackRestarted),(d=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(j.LocalTrackPublished,o,this.localParticipant),di(o.track)&&(yield o.track.checkForSilence())&&this.emit(j.LocalAudioSilenceDetected,o);const f=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Uu(o.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(j.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(he.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(he.Restarted,this.onLocalTrackRestarted),this.emit(j.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>M(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Uu(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(j.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(j.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(j.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(j.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(j.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},e_),t),this.log=xi((i=this.options.loggerName)!==null&&i!==void 0?i:Hn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},P0),t==null?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},N0),t==null?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},QE),t==null?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new dn,this.localParticipant=new L_("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Bi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Bi(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Bi(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),hn()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),vi.cleanupRegistry&&vi.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new TypeError('A text stream handler for topic "'.concat(t,'" has already been set.'));this.textStreamHandlers.set(t,n)}unregisterTextStreamHandler(t){this.textStreamHandlers.delete(t)}registerByteStreamHandler(t,n){if(this.byteStreamHandlers.has(t))throw new TypeError('A byte stream handler for topic "'.concat(t,'" has already been set.'));this.byteStreamHandlers.set(t,n)}unregisterByteStreamHandler(t){this.byteStreamHandlers.delete(t)}registerRpcMethod(t,n){if(this.rpcHandlers.has(t))throw Error("RPC handler already registered for method ".concat(t,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(t,n)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}handleIncomingRpcRequest(t,n,i,r,s,o){return M(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(t,n),o!==1){yield this.engine.publishRpcResponse(t,n,null,_t.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(t,n,null,_t.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield a({requestId:n,callerIdentity:t,payload:r,responseTimeout:s});nh(u)>I0?(c=_t.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof _t?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=_t.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(t,n,l,c)})}setE2EEEnabled(t){return M(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(t)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(t,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var t;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new jE(this.options.e2ee),this.e2eeManager.on(Fi.ParticipantEncryptionStatusChanged,(n,i)=>{PE(i)&&(this.isE2EEEnabled=n),this.emit(j.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(Fi.EncryptionError,n=>this.emit(j.EncryptionError,n)),(t=this.e2eeManager)===null||t===void 0||t.setup(this))}get logContext(){var t;return{room:this.name,roomID:(t=this.roomInfo)===null||t===void 0?void 0:t.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return M(this,void 0,void 0,function*(){return this.state===$e.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((t,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(fe.RoomUpdate,i),t(r.sid))};this.engine.on(fe.RoomUpdate,i),this.once(j.Disconnected,()=>{this.engine.off(fe.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.name)!==null&&n!==void 0?n:""}get metadata(){var t;return(t=this.roomInfo)===null||t===void 0?void 0:t.metadata}get numParticipants(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new S_(this.options),this.engine.on(fe.ParticipantUpdate,this.handleParticipantUpdates).on(fe.RoomUpdate,this.handleRoomUpdate).on(fe.SpeakersChanged,this.handleSpeakersChanged).on(fe.StreamStateChanged,this.handleStreamStateUpdate).on(fe.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(fe.SubscriptionError,this.handleSubscriptionError).on(fe.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(fe.MediaTrackAdded,(t,n,i)=>{this.onTrackAdded(t,n,i)}).on(fe.Disconnected,t=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t)}).on(fe.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(fe.DataPacketReceived,this.handleDataPacket).on(fe.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState($e.SignalReconnecting)&&this.emit(j.SignalReconnecting)}).on(fe.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState($e.Connected)&&this.emit(j.Reconnected)}).on(fe.SignalResumed,()=>{this.bufferedEvents=[],(this.state===$e.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(fe.Restarting,this.handleRestarting).on(fe.SignalRestarted,this.handleSignalRestarted).on(fe.Offline,()=>{this.setAndEmitConnectionState($e.Reconnecting)&&this.emit(j.Reconnecting)}).on(fe.DCBufferStatusChanged,(t,n)=>{this.emit(j.DCBufferStatusChanged,t,n)}).on(fe.LocalTrackSubscribed,t=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===t});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(Q.LocalTrackSubscribed,n),this.emitWhenConnected(j.LocalTrackSubscribed,n,this.localParticipant)}).on(fe.RoomMoved,t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(j.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Wt.getInstance().getDevices(t,n)}prepareConnection(t,n){return M(this,void 0,void 0,function*(){if(this.state===$e.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(Du(new URL(t))&&n){this.regionUrlProvider=new zu(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===$e.Disconnected&&(this.regionUrl=i,yield fetch(Lu(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Lu(t),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(t){return this.localParticipant.identity===t?this.localParticipant:this.remoteParticipants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t,n){return M(this,void 0,void 0,function*(){let i=()=>{},r;switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Yn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Yn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Yn({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Yn({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":i=()=>M(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Yn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>M(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Yn({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":r=new Yn({scenario:{case:"switchCandidateProtocol",value:t==="force-tls"?2:1}}),i=()=>M(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new fc({reason:Vn.CLIENT_INITIATED,action:Xr.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Yn({scenario:{case:"subscriberBandwidth",value:ir(n)}});break;case"leave-full-reconnect":r=new Yn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(t){return this.localParticipant.activeDeviceMap.get(t)}switchActiveDevice(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var a,c,l,u,d,h,f;let g=!0,p=!1;const v=o?{exact:r}:r;if(i==="audioinput"){p=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=v;const w=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===B.Source.Microphone);try{g=(yield Promise.all(w.map(k=>{var x;return(x=k.audioTrack)===null||x===void 0?void 0:x.setDeviceId(v)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=b,k}const S=w.some(k=>{var x,T;return(T=(x=k.track)===null||x===void 0?void 0:x.isMuted)!==null&&T!==void 0?T:!1});g&&S&&(p=!0)}else if(i==="videoinput"){p=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=v;const w=Array.from(s.localParticipant.videoTrackPublications.values()).filter(S=>S.source===B.Source.Camera);try{g=(yield Promise.all(w.map(S=>{var k;return(k=S.videoTrack)===null||k===void 0?void 0:k.setDeviceId(v)}))).every(S=>S===!0)}catch(S){throw s.options.videoCaptureDefaults.deviceId=b,S}}else if(i==="audiooutput"){if(p=!0,!Ou()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(l=yield Wt.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(f=s.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const b=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(w=>w.setAudioOutput({deviceId:r})))}catch(w){throw s.options.audioOutput.deviceId=b,w}}return p&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(j.ActiveDeviceChanged,i,r)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(Q.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Q.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Q.AttributesChanged,this.onLocalAttributesChanged).on(Q.TrackMuted,this.onLocalTrackMuted).on(Q.TrackUnmuted,this.onLocalTrackUnmuted).on(Q.LocalTrackPublished,this.onLocalTrackPublished).on(Q.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Q.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Q.MediaDevicesError,this.onMediaDevicesError).on(Q.AudioStreamAcquired,this.startAudio).on(Q.ChatMessage,this.onLocalChatMessageSent).on(Q.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var t;(t=this.engine)===null||t===void 0||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){if(this.state===$e.Connecting||this.state===$e.Reconnecting){const u=()=>{this.onTrackAdded(t,n,i),d()},d=()=>{this.off(j.Reconnected,u),this.off(j.Connected,u),this.off(j.Disconnected,d)};this.once(j.Reconnected,u),this.once(j.Connected,u),this.once(j.Disconnected,d);return}if(this.state===$e.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(t.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=pE(n.id),s=r[0];let o=r[1],a=t.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(t,a,n,i,l)}handleDisconnect(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==$e.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,t),t?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(Q.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Q.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Q.AttributesChanged,this.onLocalAttributesChanged).off(Q.TrackMuted,this.onLocalTrackMuted).off(Q.TrackUnmuted,this.onLocalTrackUnmuted).off(Q.LocalTrackPublished,this.onLocalTrackPublished).off(Q.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Q.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Q.MediaDevicesError,this.onMediaDevicesError).off(Q.AudioStreamAcquired,this.startAudio).off(Q.ChatMessage,this.onLocalChatMessageSent).off(Q.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&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),hn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState($e.Disconnected),this.emit(j.Disconnected,n)}}}handleParticipantDisconnected(t,n){var i;this.remoteParticipants.delete(t),n&&(n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(j.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleStreamHeader(t,n){return M(this,void 0,void 0,function*(){var i;if(t.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(t.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);return}let s;const o={id:t.streamId,name:(i=t.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:xa(t.timestamp),attributes:t.attributes},a=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new E_(o,a,xa(t.totalLength)),{identity:n})}else if(t.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(t.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);return}let s;const o={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes},a=new ReadableStream({start:c=>{s=c,this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new __(o,a,xa(t.totalLength)),{identity:n})}})}handleStreamChunk(t){const n=this.byteStreamControllers.get(t.streamId);n&&t.content.length>0&&n.controller.enqueue(t);const i=this.textStreamControllers.get(t.streamId);i&&t.content.length>0&&i.controller.enqueue(t)}handleStreamTrailer(t){const n=this.textStreamControllers.get(t.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),t.attributes),n.controller.close(),this.textStreamControllers.delete(t.streamId));const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),i.controller.close(),this.byteStreamControllers.delete(t.streamId))}selectDefaultDevices(){return M(this,void 0,void 0,function*(){var t,n,i;const r=Wt.getInstance().previousDevices,s=yield Wt.getInstance().getDevices(void 0,!1),o=kn();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(u=>u.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(j.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=IE(c),u=this.localParticipant.getTrackPublication(l);if(u&&(!((t=u.track)===null||t===void 0)&&t.isUserProvided))continue;const d=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(f=>f.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,d[0].deviceId);continue}c==="audioinput"&&!mp()||c==="videoinput"||d.length>0&&!d.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!mp())&&(yield this.switchActiveDevice(c,d[0].deviceId))}})}acquireAudioContext(){return M(this,void 0,void 0,function*(){var t,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(t=Xd())!==null&&t!==void 0?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),pn(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(j.AudioPlaybackStatusChanged,i))})}createParticipant(t,n){var i;let r;return n?r=$a.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new $a(this.engine.client,"",t,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const r=this.remoteParticipants.get(t);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(j.ParticipantConnected,i),i.on(Q.TrackPublished,r=>{this.emitWhenConnected(j.TrackPublished,r,i)}).on(Q.TrackSubscribed,(r,s)=>{r.kind===B.Kind.Audio?(r.on(he.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(he.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===B.Kind.Video&&(r.on(he.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(he.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(j.TrackSubscribed,r,s,i)}).on(Q.TrackUnpublished,r=>{this.emit(j.TrackUnpublished,r,i)}).on(Q.TrackUnsubscribed,(r,s)=>{this.emit(j.TrackUnsubscribed,r,s,i)}).on(Q.TrackMuted,r=>{this.emitWhenConnected(j.TrackMuted,r,i)}).on(Q.TrackUnmuted,r=>{this.emitWhenConnected(j.TrackUnmuted,r,i)}).on(Q.ParticipantMetadataChanged,r=>{this.emitWhenConnected(j.ParticipantMetadataChanged,r,i)}).on(Q.ParticipantNameChanged,r=>{this.emitWhenConnected(j.ParticipantNameChanged,r,i)}).on(Q.AttributesChanged,r=>{this.emitWhenConnected(j.ParticipantAttributesChanged,r,i)}).on(Q.ConnectionQualityChanged,r=>{this.emitWhenConnected(j.ConnectionQualityChanged,r,i)}).on(Q.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(j.ParticipantPermissionsChanged,r,i)}).on(Q.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(j.TrackSubscriptionStatusChanged,r,s,i)}).on(Q.TrackSubscriptionFailed,(r,s)=>{this.emit(j.TrackSubscriptionFailed,r,i,s)}).on(Q.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(j.TrackSubscriptionPermissionChanged,r,s,i)}).on(Q.Active,()=>{this.emitWhenConnected(j.ParticipantActive,i),i.kind===no.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const t=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(t,n)}updateSubscriptions(){for(const t of this.remoteParticipants.values())for(const n of t.videoTrackPublications.values())n.isSubscribed&&AE(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(t){const n=this.sidToIdentity.get(t);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=Zt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(t++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:t,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vn.STATE_MISMATCH))):t=0},F_)}clearConnectionReconcile(){this.connectionReconcileInterval&&Zt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t===this.state?!1:(this.state=t,this.emit(j.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(t=>{let[n,i]=t;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===$e.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===$e.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return M(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new dc({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:yt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new pr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(j.SignalConnected),this.emit(j.Connected),this.setAndEmitConnectionState($e.Connected),r.video){const o=new Wu(B.Kind.Video,new Vr({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO,name:"video-dummy"}),new Ba(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:vp(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Q.LocalTrackPublished,o)}if(r.audio){const o=new Wu(B.Kind.Audio,new Vr({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO}),new Ua(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rl(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Q.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new pr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Zr.ACTIVE,tracks:[],joinedAt:yt.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=vp(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Vr({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,u]}if(s.audio){const l=rl(),u=new Vr({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,u]}c.updateInfo(a)}})}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(t!==j.ActiveSpeakersChanged&&t!==j.TranscriptionReceived){const s=V0(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:s}))}return super.emit(t,...i)}}vi.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{e()});function V0(e){return e.map(t=>{if(t)return Array.isArray(t)?V0(t):typeof t=="object"?"logContext"in t?t.logContext:void 0:t})}var jn;(function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"})(jn||(jn={}));class Ki extends ii.EventEmitter{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=jn.IDLE,this.logs=[],this.options={},this.url=t,this.token=n,this.name=this.constructor.name,this.room=new vi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return M(this,void 0,void 0,function*(){if(this.status!==jn.IDLE)throw Error("check is running already");this.setStatus(jn.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==jn.SKIPPED&&this.setStatus(this.isSuccess()?jn.SUCCESS:jn.FAILED),t&&t(),this.getInfo()})}isSuccess(){return!this.logs.some(t=>t.level==="error")}connect(t){return M(this,void 0,void 0,function*(){return this.room.state===$e.Connected?this.room:(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions),this.room)})}disconnect(){return M(this,void 0,void 0,function*(){this.room&&this.room.state!==$e.Disconnected&&(yield this.room.disconnect(),yield new Promise(t=>setTimeout(t,500)))})}skip(){this.setStatus(jn.SKIPPED)}switchProtocol(t){return M(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(j.Reconnecting,()=>{n=!0}),this.room.once(j.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(t)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield pn(100)}throw new Error("Could not reconnect using ".concat(t," protocol after 10 seconds"))})}appendMessage(t){this.logs.push({level:"info",message:t}),this.emit("update",this.getInfo())}appendWarning(t){this.logs.push({level:"warning",message:t}),this.emit("update",this.getInfo())}appendError(t){this.logs.push({level:"error",message:t}),this.emit("update",this.getInfo())}setStatus(t){this.status=t,this.emit("update",this.getInfo())}get engine(){var t;return(t=this.room)===null||t===void 0?void 0:t.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class j_ extends Ki{get description(){return"Cloud regions"}perform(){return M(this,void 0,void 0,function*(){const t=new zu(this.url,this.token);if(!t.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield t.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const t=super.getInfo();return t.data=this.bestStats,t}checkCloudRegion(t){return M(this,void 0,void 0,function*(){var n,i;yield this.connect(t),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),u=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const fl=1e4;class U_ extends Ki{get description(){return"Connection via UDP vs TCP"}perform(){return M(this,void 0,void 0,function*(){const t=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=t,t.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(t.packetsLost-n.packetsLost)/t.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(fl/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(fl/1e3)*100).toFixed(2),"%"))})}getInfo(){const t=super.getInfo();return t.data=this.bestStats,t}checkConnectionProtocol(t){return M(this,void 0,void 0,function*(){yield this.connect(),t==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:t,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},d=setInterval(()=>M(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,fl)),clearInterval(d),a.stop(),n.remove(),yield this.disconnect(),u})}}class B_ extends Ki{get description(){return"Can publish audio"}perform(){return M(this,void 0,void 0,function*(){var t;const n=yield this.connect(),i=yield M_();if(yield _0(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(t=i.sender)===null||t===void 0?void 0:t.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class V_ extends Ki{get description(){return"Can publish video"}perform(){return M(this,void 0,void 0,function*(){var t;const n=yield this.connect(),i=yield I_();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(t=i.sender)===null||t===void 0?void 0:t.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(t){return M(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(t.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),u=t.getSettings(),d=(o=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=u.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class $_ extends Ki{get description(){return"Resuming connection after interruption"}perform(){return M(this,void 0,void 0,function*(){var t;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(j.SignalReconnecting,a).on(j.Reconnecting,a).on(j.Reconnected,()=>{r=!0,s(!0)}),(t=n.engine.client.ws)===null||t===void 0||t.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==$e.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class z_ extends Ki{get description(){return"Can connect via TURN"}perform(){return M(this,void 0,void 0,function*(){var t,n;const i=new Jd,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class H_ extends Ki{get description(){return"Establishing WebRTC connection"}perform(){return M(this,void 0,void 0,function*(){let t=!1,n=!1;this.room.on(j.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(W_(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(t=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),qe.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function W_(e){const t=e.split(".");if(t.length===4){if(t[0]==="10")return!0;if(t[0]==="192"&&t[1]==="168")return!0;if(t[0]==="172"){const n=parseInt(t[1],10);if(n>=16&&n<=31)return!0}}return!1}class q_ extends Ki{get description(){return"Connecting to signal connection via WebSocket"}perform(){return M(this,void 0,void 0,function*(){var t,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Jd;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((t=s.serverInfo)===null||t===void 0?void 0:t.edition)===Ry.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class Y4 extends ii.EventEmitter{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=t,this.token=n,this.options=i}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:jn.IDLE,name:"",description:""}),t}updateCheck(t,n){this.checkResults.set(t,n),this.emit("checkUpdate",t,n)}isSuccess(){return Array.from(this.checkResults.values()).every(t=>t.status!==jn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(t){return M(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new t(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(q_)})}checkWebRTC(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(H_)})}checkTURN(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(z_)})}checkReconnect(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck($_)})}checkPublishAudio(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(B_)})}checkPublishVideo(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(V_)})}checkConnectionProtocol(){return M(this,void 0,void 0,function*(){const t=yield this.createAndRunCheck(U_);if(t.data&&"protocol"in t.data){const n=t.data;this.options.protocol=n.protocol}return t})}checkCloudRegion(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(j_)})}}const sh=O.createContext({});function oh(e){const t=O.useRef(null);return t.current===null&&(t.current=e()),t.current}const ah=typeof window<"u",$0=ah?O.useLayoutEffect:O.useEffect,bc=O.createContext(null);function ch(e,t){e.indexOf(t)===-1&&e.push(t)}function lh(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const ki=(e,t,n)=>n>t?t:n<e?e:n;function qu(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let ms=()=>{},Si=()=>{};process.env.NODE_ENV!=="production"&&(ms=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(qu(t,n))},Si=(e,t,n)=>{if(!e)throw new Error(qu(t,n))});const wi={},z0=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function H0(e){return typeof e=="object"&&e!==null}const W0=e=>/^0[^.\s]+$/u.test(e);function uh(e){let t;return()=>(t===void 0&&(t=e()),t)}const Nn=e=>e,G_=(e,t)=>n=>t(e(n)),go=(...e)=>e.reduce(G_),ro=(e,t,n)=>{const i=t-e;return i===0?1:(n-e)/i};class dh{constructor(){this.subscriptions=[]}add(t){return ch(this.subscriptions,t),()=>lh(this.subscriptions,t)}notify(t,n,i){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,i);else for(let s=0;s<r;s++){const o=this.subscriptions[s];o&&o(t,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $n=e=>e*1e3,ei=e=>e/1e3;function q0(e,t){return t?e*(1e3/t):0}const jp=new Set;function hh(e,t,n){e||jp.has(t)||(console.warn(qu(t,n)),jp.add(t))}const G0=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,K_=1e-7,Y_=12;function Z_(e,t,n,i,r){let s,o,a=0;do o=t+(n-t)/2,s=G0(o,i,r)-e,s>0?n=o:t=o;while(Math.abs(s)>K_&&++a<Y_);return o}function bo(e,t,n,i){if(e===t&&n===i)return Nn;const r=s=>Z_(s,0,1,e,n);return s=>s===0||s===1?s:G0(r(s),t,i)}const K0=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Y0=e=>t=>1-e(1-t),Z0=bo(.33,1.53,.69,.99),fh=Y0(Z0),X0=K0(fh),J0=e=>(e*=2)<1?.5*fh(e):.5*(2-Math.pow(2,-10*(e-1))),ph=e=>1-Math.sin(Math.acos(e)),Q0=Y0(ph),ev=K0(ph),X_=bo(.42,0,1,1),J_=bo(0,0,.58,1),tv=bo(.42,0,.58,1),Q_=e=>Array.isArray(e)&&typeof e[0]!="number",nv=e=>Array.isArray(e)&&typeof e[0]=="number",Up={linear:Nn,easeIn:X_,easeInOut:tv,easeOut:J_,circIn:ph,circInOut:ev,circOut:Q0,backIn:fh,backInOut:X0,backOut:Z0,anticipate:J0},e1=e=>typeof e=="string",Bp=e=>{if(nv(e)){Si(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,i,r]=e;return bo(t,n,i,r)}else if(e1(e))return Si(Up[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Up[e];return e},Uo=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function t1(e,t){let n=new Set,i=new Set,r=!1,s=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(u){o.has(u)&&(l.schedule(u),e()),u(a)}const l={schedule:(u,d=!1,h=!1)=>{const g=h&&r?n:i;return d&&o.add(u),g.has(u)||g.add(u),u},cancel:u=>{i.delete(u),o.delete(u)},process:u=>{if(a=u,r){s=!0;return}r=!0,[n,i]=[i,n],n.forEach(c),n.clear(),r=!1,s&&(s=!1,l.process(u))}};return l}const n1=40;function iv(e,t){let n=!1,i=!0;const r={delta:0,timestamp:0,isProcessing:!1},s=()=>n=!0,o=Uo.reduce((S,k)=>(S[k]=t1(s),S),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:h,render:f,postRender:g}=o,p=()=>{const S=wi.useManualTiming?r.timestamp:performance.now();n=!1,wi.useManualTiming||(r.delta=i?1e3/60:Math.max(Math.min(S-r.timestamp,n1),1)),r.timestamp=S,r.isProcessing=!0,a.process(r),c.process(r),l.process(r),u.process(r),d.process(r),h.process(r),f.process(r),g.process(r),r.isProcessing=!1,n&&t&&(i=!1,e(p))},v=()=>{n=!0,i=!0,r.isProcessing||e(p)};return{schedule:Uo.reduce((S,k)=>{const x=o[k];return S[k]=(T,P=!1,A=!1)=>(n||v(),x.schedule(T,P,A)),S},{}),cancel:S=>{for(let k=0;k<Uo.length;k++)o[Uo[k]].cancel(S)},state:r,steps:o}}const{schedule:vt,cancel:$i,state:Yt,steps:pl}=iv(typeof requestAnimationFrame<"u"?requestAnimationFrame:Nn,!0);let Sa;function i1(){Sa=void 0}const fn={now:()=>(Sa===void 0&&fn.set(Yt.isProcessing||wi.useManualTiming?Yt.timestamp:performance.now()),Sa),set:e=>{Sa=e,queueMicrotask(i1)}},rv=e=>t=>typeof t=="string"&&t.startsWith(e),mh=rv("--"),r1=rv("var(--"),gh=e=>r1(e)?s1.test(e.split("/*")[0].trim()):!1,s1=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,gs={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},so={...gs,transform:e=>ki(0,1,e)},Bo={...gs,default:1},Gs=e=>Math.round(e*1e5)/1e5,bh=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function o1(e){return e==null}const a1=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,yh=(e,t)=>n=>!!(typeof n=="string"&&a1.test(n)&&n.startsWith(e)||t&&!o1(n)&&Object.prototype.hasOwnProperty.call(n,t)),sv=(e,t,n)=>i=>{if(typeof i!="string")return i;const[r,s,o,a]=i.match(bh);return{[e]:parseFloat(r),[t]:parseFloat(s),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},c1=e=>ki(0,255,e),ml={...gs,transform:e=>Math.round(c1(e))},sr={test:yh("rgb","red"),parse:sv("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:i=1})=>"rgba("+ml.transform(e)+", "+ml.transform(t)+", "+ml.transform(n)+", "+Gs(so.transform(i))+")"};function l1(e){let t="",n="",i="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),i=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),i=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,i+=i,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const Gu={test:yh("#"),parse:l1,transform:sr.transform},yo=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Di=yo("deg"),ti=yo("%"),Me=yo("px"),u1=yo("vh"),d1=yo("vw"),Vp={...ti,parse:e=>ti.parse(e)/100,transform:e=>ti.transform(e*100)},Hr={test:yh("hsl","hue"),parse:sv("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:i=1})=>"hsla("+Math.round(e)+", "+ti.transform(Gs(t))+", "+ti.transform(Gs(n))+", "+Gs(so.transform(i))+")"},Dt={test:e=>sr.test(e)||Gu.test(e)||Hr.test(e),parse:e=>sr.test(e)?sr.parse(e):Hr.test(e)?Hr.parse(e):Gu.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?sr.transform(e):Hr.transform(e),getAnimatableNone:e=>{const t=Dt.parse(e);return t.alpha=0,Dt.transform(t)}},h1=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function f1(e){var t,n;return isNaN(e)&&typeof e=="string"&&(((t=e.match(bh))==null?void 0:t.length)||0)+(((n=e.match(h1))==null?void 0:n.length)||0)>0}const ov="number",av="color",p1="var",m1="var(",$p="${}",g1=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function oo(e){const t=e.toString(),n=[],i={color:[],number:[],var:[]},r=[];let s=0;const a=t.replace(g1,c=>(Dt.test(c)?(i.color.push(s),r.push(av),n.push(Dt.parse(c))):c.startsWith(m1)?(i.var.push(s),r.push(p1),n.push(c)):(i.number.push(s),r.push(ov),n.push(parseFloat(c))),++s,$p)).split($p);return{values:n,split:a,indexes:i,types:r}}function cv(e){return oo(e).values}function lv(e){const{split:t,types:n}=oo(e),i=t.length;return r=>{let s="";for(let o=0;o<i;o++)if(s+=t[o],r[o]!==void 0){const a=n[o];a===ov?s+=Gs(r[o]):a===av?s+=Dt.transform(r[o]):s+=r[o]}return s}}const b1=e=>typeof e=="number"?0:Dt.test(e)?Dt.getAnimatableNone(e):e;function y1(e){const t=cv(e);return lv(e)(t.map(b1))}const zi={test:f1,parse:cv,createTransformer:lv,getAnimatableNone:y1};function gl(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function v1({hue:e,saturation:t,lightness:n,alpha:i}){e/=360,t/=100,n/=100;let r=0,s=0,o=0;if(!t)r=s=o=n;else{const a=n<.5?n*(1+t):n+t-n*t,c=2*n-a;r=gl(c,a,e+1/3),s=gl(c,a,e),o=gl(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(s*255),blue:Math.round(o*255),alpha:i}}function za(e,t){return n=>n>0?t:e}const St=(e,t,n)=>e+(t-e)*n,bl=(e,t,n)=>{const i=e*e,r=n*(t*t-i)+i;return r<0?0:Math.sqrt(r)},x1=[Gu,sr,Hr],k1=e=>x1.find(t=>t.test(e));function zp(e){const t=k1(e);if(ms(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Hr&&(n=v1(n)),n}const Hp=(e,t)=>{const n=zp(e),i=zp(t);if(!n||!i)return za(e,t);const r={...n};return s=>(r.red=bl(n.red,i.red,s),r.green=bl(n.green,i.green,s),r.blue=bl(n.blue,i.blue,s),r.alpha=St(n.alpha,i.alpha,s),sr.transform(r))},Ku=new Set(["none","hidden"]);function S1(e,t){return Ku.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function w1(e,t){return n=>St(e,t,n)}function vh(e){return typeof e=="number"?w1:typeof e=="string"?gh(e)?za:Dt.test(e)?Hp:E1:Array.isArray(e)?uv:typeof e=="object"?Dt.test(e)?Hp:T1:za}function uv(e,t){const n=[...e],i=n.length,r=e.map((s,o)=>vh(s)(s,t[o]));return s=>{for(let o=0;o<i;o++)n[o]=r[o](s);return n}}function T1(e,t){const n={...e,...t},i={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(i[r]=vh(e[r])(e[r],t[r]));return r=>{for(const s in i)n[s]=i[s](r);return n}}function C1(e,t){const n=[],i={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const s=t.types[r],o=e.indexes[s][i[s]],a=e.values[o]??0;n[r]=a,i[s]++}return n}const E1=(e,t)=>{const n=zi.createTransformer(t),i=oo(e),r=oo(t);return i.indexes.var.length===r.indexes.var.length&&i.indexes.color.length===r.indexes.color.length&&i.indexes.number.length>=r.indexes.number.length?Ku.has(e)&&!r.values.length||Ku.has(t)&&!i.values.length?S1(e,t):go(uv(C1(i,r),r.values),n):(ms(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),za(e,t))};function dv(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?St(e,t,n):vh(e)(e,t)}const _1=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>vt.update(t,n),stop:()=>$i(t),now:()=>Yt.isProcessing?Yt.timestamp:fn.now()}},hv=(e,t,n=10)=>{let i="";const r=Math.max(Math.round(t/n),2);for(let s=0;s<r;s++)i+=Math.round(e(s/(r-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Ha=2e4;function xh(e){let t=0;const n=50;let i=e.next(t);for(;!i.done&&t<Ha;)t+=n,i=e.next(t);return t>=Ha?1/0:t}function R1(e,t=100,n){const i=n({...e,keyframes:[0,t]}),r=Math.min(xh(i),Ha);return{type:"keyframes",ease:s=>i.next(r*s).value/t,duration:ei(r)}}const A1=5;function fv(e,t,n){const i=Math.max(t-A1,0);return q0(n-e(i),t-i)}const xt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},yl=.001;function P1({duration:e=xt.duration,bounce:t=xt.bounce,velocity:n=xt.velocity,mass:i=xt.mass}){let r,s;ms(e<=$n(xt.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let o=1-t;o=ki(xt.minDamping,xt.maxDamping,o),e=ki(xt.minDuration,xt.maxDuration,ei(e)),o<1?(r=l=>{const u=l*o,d=u*e,h=u-n,f=Yu(l,o),g=Math.exp(-d);return yl-h/f*g},s=l=>{const d=l*o*e,h=d*n+n,f=Math.pow(o,2)*Math.pow(l,2)*e,g=Math.exp(-d),p=Yu(Math.pow(l,2),o);return(-r(l)+yl>0?-1:1)*((h-f)*g)/p}):(r=l=>{const u=Math.exp(-l*e),d=(l-n)*e+1;return-yl+u*d},s=l=>{const u=Math.exp(-l*e),d=(n-l)*(e*e);return u*d});const a=5/e,c=I1(r,s,a);if(e=$n(e),isNaN(c))return{stiffness:xt.stiffness,damping:xt.damping,duration:e};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:o*2*Math.sqrt(i*l),duration:e}}}const N1=12;function I1(e,t,n){let i=n;for(let r=1;r<N1;r++)i=i-e(i)/t(i);return i}function Yu(e,t){return e*Math.sqrt(1-t*t)}const M1=["duration","bounce"],O1=["stiffness","damping","mass"];function Wp(e,t){return t.some(n=>e[n]!==void 0)}function D1(e){let t={velocity:xt.velocity,stiffness:xt.stiffness,damping:xt.damping,mass:xt.mass,isResolvedFromDuration:!1,...e};if(!Wp(e,O1)&&Wp(e,M1))if(e.visualDuration){const n=e.visualDuration,i=2*Math.PI/(n*1.2),r=i*i,s=2*ki(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:xt.mass,stiffness:r,damping:s}}else{const n=P1(e);t={...t,...n,mass:xt.mass},t.isResolvedFromDuration=!0}return t}function Wa(e=xt.visualDuration,t=xt.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:i,restDelta:r}=n;const s=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:s},{stiffness:c,damping:l,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=D1({...n,velocity:-ei(n.velocity||0)}),g=h||0,p=l/(2*Math.sqrt(c*u)),v=o-s,b=ei(Math.sqrt(c/u)),w=Math.abs(v)<5;i||(i=w?xt.restSpeed.granular:xt.restSpeed.default),r||(r=w?xt.restDelta.granular:xt.restDelta.default);let S;if(p<1){const x=Yu(b,p);S=T=>{const P=Math.exp(-p*b*T);return o-P*((g+p*b*v)/x*Math.sin(x*T)+v*Math.cos(x*T))}}else if(p===1)S=x=>o-Math.exp(-b*x)*(v+(g+b*v)*x);else{const x=b*Math.sqrt(p*p-1);S=T=>{const P=Math.exp(-p*b*T),A=Math.min(x*T,300);return o-P*((g+p*b*v)*Math.sinh(A)+x*v*Math.cosh(A))/x}}const k={calculatedDuration:f&&d||null,next:x=>{const T=S(x);if(f)a.done=x>=d;else{let P=x===0?g:0;p<1&&(P=x===0?$n(g):fv(S,x,T));const A=Math.abs(P)<=i,N=Math.abs(o-T)<=r;a.done=A&&N}return a.value=a.done?o:T,a},toString:()=>{const x=Math.min(xh(k),Ha),T=hv(P=>k.next(x*P).value,x,30);return x+"ms "+T},toTransition:()=>{}};return k}Wa.applyToOptions=e=>{const t=R1(e,100,Wa);return e.ease=t.ease,e.duration=$n(t.duration),e.type="keyframes",e};function Zu({keyframes:e,velocity:t=0,power:n=.8,timeConstant:i=325,bounceDamping:r=10,bounceStiffness:s=500,modifyTarget:o,min:a,max:c,restDelta:l=.5,restSpeed:u}){const d=e[0],h={done:!1,value:d},f=A=>a!==void 0&&A<a||c!==void 0&&A>c,g=A=>a===void 0?c:c===void 0||Math.abs(a-A)<Math.abs(c-A)?a:c;let p=n*t;const v=d+p,b=o===void 0?v:o(v);b!==v&&(p=b-d);const w=A=>-p*Math.exp(-A/i),S=A=>b+w(A),k=A=>{const N=w(A),y=S(A);h.done=Math.abs(N)<=l,h.value=h.done?b:y};let x,T;const P=A=>{f(h.value)&&(x=A,T=Wa({keyframes:[h.value,g(h.value)],velocity:fv(S,A,h.value),damping:r,stiffness:s,restDelta:l,restSpeed:u}))};return P(0),{calculatedDuration:null,next:A=>{let N=!1;return!T&&x===void 0&&(N=!0,k(A),P(A)),x!==void 0&&A>=x?T.next(A-x):(!N&&k(A),h)}}}function L1(e,t,n){const i=[],r=n||wi.mix||dv,s=e.length-1;for(let o=0;o<s;o++){let a=r(e[o],e[o+1]);if(t){const c=Array.isArray(t)?t[o]||Nn:t;a=go(c,a)}i.push(a)}return i}function F1(e,t,{clamp:n=!0,ease:i,mixer:r}={}){const s=e.length;if(Si(s===t.length,"Both input and output ranges must be the same length","range-length"),s===1)return()=>t[0];if(s===2&&t[0]===t[1])return()=>t[1];const o=e[0]===e[1];e[0]>e[s-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=L1(t,i,r),c=a.length,l=u=>{if(o&&u<e[0])return t[0];let d=0;if(c>1)for(;d<e.length-2&&!(u<e[d+1]);d++);const h=ro(e[d],e[d+1],u);return a[d](h)};return n?u=>l(ki(e[0],e[s-1],u)):l}function j1(e,t){const n=e[e.length-1];for(let i=1;i<=t;i++){const r=ro(0,t,i);e.push(St(n,1,r))}}function U1(e){const t=[0];return j1(t,e.length-1),t}function B1(e,t){return e.map(n=>n*t)}function V1(e,t){return e.map(()=>t||tv).splice(0,e.length-1)}function Wr({duration:e=300,keyframes:t,times:n,ease:i="easeInOut"}){const r=Q_(i)?i.map(Bp):Bp(i),s={done:!1,value:t[0]},o=B1(n&&n.length===t.length?n:U1(t),e),a=F1(o,t,{ease:Array.isArray(r)?r:V1(t,r)});return{calculatedDuration:e,next:c=>(s.value=a(c),s.done=c>=e,s)}}const $1=e=>e!==null;function kh(e,{repeat:t,repeatType:n="loop"},i,r=1){const s=e.filter($1),a=r<0||t&&n!=="loop"&&t%2===1?0:s.length-1;return!a||i===void 0?s[a]:i}const z1={decay:Zu,inertia:Zu,tween:Wr,keyframes:Wr,spring:Wa};function pv(e){typeof e.type=="string"&&(e.type=z1[e.type])}class Sh{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const H1=e=>e/100;class wh extends Sh{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,r;const{motionValue:n}=this.options;n&&n.updatedAt!==fn.now()&&this.tick(fn.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(r=(i=this.options).onStop)==null||r.call(i))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;pv(t);const{type:n=Wr,repeat:i=0,repeatDelay:r=0,repeatType:s,velocity:o=0}=t;let{keyframes:a}=t;const c=n||Wr;process.env.NODE_ENV!=="production"&&c!==Wr&&Si(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Wr&&typeof a[0]!="number"&&(this.mixKeyframes=go(H1,dv(a[0],a[1])),a=[0,100]);const l=c({...t,keyframes:a});s==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-o})),l.calculatedDuration===null&&(l.calculatedDuration=xh(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+r,this.totalDuration=this.resolvedDuration*(i+1)-r,this.generator=l}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:i,totalDuration:r,mixKeyframes:s,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:f,type:g,onUpdate:p,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const b=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?b<0:b>r;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let S=this.currentTime,k=i;if(d){const A=Math.min(this.currentTime,r)/a;let N=Math.floor(A),y=A%1;!y&&A>=1&&(y=1),y===1&&N--,N=Math.min(N,d+1),!!(N%2)&&(h==="reverse"?(y=1-y,f&&(y-=f/a)):h==="mirror"&&(k=o)),S=ki(0,1,y)*a}const x=w?{done:!1,value:u[0]}:k.next(S);s&&(x.value=s(x.value));let{done:T}=x;!w&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return P&&g!==Zu&&(x.value=kh(u,this.options,v,this.speed)),p&&p(x.value),P&&this.finish(),x}then(t,n){return this.finished.then(t,n)}get duration(){return ei(this.calculatedDuration)}get time(){return ei(this.currentTime)}set time(t){var n;t=$n(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(fn.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=ei(this.currentTime))}play(){var r,s;if(this.isStopped)return;const{driver:t=_1,startTime:n}=this.options;this.driver||(this.driver=t(o=>this.tick(o))),(s=(r=this.options).onPlay)==null||s.call(r);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(fn.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(t=this.options).onComplete)==null||n.call(t)}cancel(){var t,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(t=this.options).onCancel)==null||n.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),t.observe(this)}}function W1(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const or=e=>e*180/Math.PI,Xu=e=>{const t=or(Math.atan2(e[1],e[0]));return Ju(t)},q1={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Xu,rotateZ:Xu,skewX:e=>or(Math.atan(e[1])),skewY:e=>or(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ju=e=>(e=e%360,e<0&&(e+=360),e),qp=Xu,Gp=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),Kp=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),G1={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Gp,scaleY:Kp,scale:e=>(Gp(e)+Kp(e))/2,rotateX:e=>Ju(or(Math.atan2(e[6],e[5]))),rotateY:e=>Ju(or(Math.atan2(-e[2],e[0]))),rotateZ:qp,rotate:qp,skewX:e=>or(Math.atan(e[4])),skewY:e=>or(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Qu(e){return e.includes("scale")?1:0}function ed(e,t){if(!e||e==="none")return Qu(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,r;if(n)i=G1,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=q1,r=a}if(!r)return Qu(t);const s=i[t],o=r[1].split(",").map(Y1);return typeof s=="function"?s(o):o[s]}const K1=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return ed(n,t)};function Y1(e){return parseFloat(e.trim())}const bs=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ys=new Set(bs),Yp=e=>e===gs||e===Me,Z1=new Set(["x","y","z"]),X1=bs.filter(e=>!Z1.has(e));function J1(e){const t=[];return X1.forEach(n=>{const i=e.getValue(n);i!==void 0&&(t.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),t}const lr={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>ed(t,"x"),y:(e,{transform:t})=>ed(t,"y")};lr.translateX=lr.x;lr.translateY=lr.y;const ur=new Set;let td=!1,nd=!1,id=!1;function mv(){if(nd){const e=Array.from(ur).filter(i=>i.needsMeasurement),t=new Set(e.map(i=>i.element)),n=new Map;t.forEach(i=>{const r=J1(i);r.length&&(n.set(i,r),i.render())}),e.forEach(i=>i.measureInitialState()),t.forEach(i=>{i.render();const r=n.get(i);r&&r.forEach(([s,o])=>{var a;(a=i.getValue(s))==null||a.set(o)})}),e.forEach(i=>i.measureEndState()),e.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}nd=!1,td=!1,ur.forEach(e=>e.complete(id)),ur.clear()}function gv(){ur.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(nd=!0)})}function Q1(){id=!0,gv(),mv(),id=!1}class Th{constructor(t,n,i,r,s,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=i,this.motionValue=r,this.element=s,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(ur.add(this),td||(td=!0,vt.read(gv),vt.resolveKeyframes(mv))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:i,motionValue:r}=this;if(t[0]===null){const s=r==null?void 0:r.get(),o=t[t.length-1];if(s!==void 0)t[0]=s;else if(i&&n){const a=i.readValue(n,o);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=o),r&&s===void 0&&r.set(t[0])}W1(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),ur.delete(this)}cancel(){this.state==="scheduled"&&(ur.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const eR=e=>e.startsWith("--");function tR(e,t,n){eR(t)?e.style.setProperty(t,n):e.style[t]=n}const nR=uh(()=>window.ScrollTimeline!==void 0),iR={};function rR(e,t){const n=uh(e);return()=>iR[t]??n()}const bv=rR(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Vs=([e,t,n,i])=>`cubic-bezier(${e}, ${t}, ${n}, ${i})`,Zp={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Vs([0,.65,.55,1]),circOut:Vs([.55,0,1,.45]),backIn:Vs([.31,.01,.66,-.59]),backOut:Vs([.33,1.53,.69,.99])};function yv(e,t){if(e)return typeof e=="function"?bv()?hv(e,t):"ease-out":nv(e)?Vs(e):Array.isArray(e)?e.map(n=>yv(n,t)||Zp.easeOut):Zp[e]}function sR(e,t,n,{delay:i=0,duration:r=300,repeat:s=0,repeatType:o="loop",ease:a="easeOut",times:c}={},l=void 0){const u={[t]:n};c&&(u.offset=c);const d=yv(a,r);Array.isArray(d)&&(u.easing=d);const h={delay:i,duration:r,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:s+1,direction:o==="reverse"?"alternate":"normal"};return l&&(h.pseudoElement=l),e.animate(u,h)}function vv(e){return typeof e=="function"&&"applyToOptions"in e}function oR({type:e,...t}){return vv(e)&&bv()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class aR extends Sh{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:i,keyframes:r,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:a,onComplete:c}=t;this.isPseudoElement=!!s,this.allowFlatten=o,this.options=t,Si(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const l=oR(t);this.animation=sR(n,i,r,l,s),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const u=kh(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):tR(n,i,u),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,n;(n=(t=this.animation).finish)==null||n.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var t,n;this.isPseudoElement||(n=(t=this.animation).commitStyles)==null||n.call(t)}get duration(){var n,i;const t=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return ei(Number(t))}get time(){return ei(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=$n(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&nR()?(this.animation.timeline=t,Nn):n(this)}}const xv={anticipate:J0,backInOut:X0,circInOut:ev};function cR(e){return e in xv}function lR(e){typeof e.ease=="string"&&cR(e.ease)&&(e.ease=xv[e.ease])}const Xp=10;class uR extends aR{constructor(t){lR(t),pv(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:i,onComplete:r,element:s,...o}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new wh({...o,autoplay:!1}),c=$n(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Xp).value,a.sample(c).value,Xp),a.stop()}}const Jp=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(zi.test(e)||e==="0")&&!e.startsWith("url("));function dR(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function hR(e,t,n,i){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const s=e[e.length-1],o=Jp(r,t),a=Jp(s,t);return ms(o===a,`You are trying to animate ${t} from "${r}" to "${s}". "${o?s:r}" is not an animatable value.`,"value-not-animatable"),!o||!a?!1:dR(e)||(n==="spring"||vv(n))&&i}function rd(e){e.duration=0,e.type}const fR=new Set(["opacity","clipPath","filter","transform"]),pR=uh(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function mR(e){var u;const{motionValue:t,name:n,repeatDelay:i,repeatType:r,damping:s,type:o}=e;if(!(((u=t==null?void 0:t.owner)==null?void 0:u.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:l}=t.owner.getProps();return pR()&&n&&fR.has(n)&&(n!=="transform"||!l)&&!c&&!i&&r!=="mirror"&&s!==0&&o!=="inertia"}const gR=40;class bR extends Sh{constructor({autoplay:t=!0,delay:n=0,type:i="keyframes",repeat:r=0,repeatDelay:s=0,repeatType:o="loop",keyframes:a,name:c,motionValue:l,element:u,...d}){var g;super(),this.stop=()=>{var p,v;this._animation&&(this._animation.stop(),(p=this.stopTimeline)==null||p.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=fn.now();const h={autoplay:t,delay:n,type:i,repeat:r,repeatDelay:s,repeatType:o,name:c,motionValue:l,element:u,...d},f=(u==null?void 0:u.KeyframeResolver)||Th;this.keyframeResolver=new f(a,(p,v,b)=>this.onKeyframesResolved(p,v,h,!b),c,l,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,i,r){this.keyframeResolver=void 0;const{name:s,type:o,velocity:a,delay:c,isHandoff:l,onUpdate:u}=i;this.resolvedAt=fn.now(),hR(t,s,o,a)||((wi.instantAnimations||!c)&&(u==null||u(kh(t,i,n))),t[0]=t[t.length-1],rd(i),i.repeat=0);const h={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>gR?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:t},f=!l&&mR(h)?new uR({...h,element:h.motionValue.owner.current}):new wh(h);f.finished.then(()=>this.notifyFinished()).catch(Nn),this.pendingTimeline&&(this.stopTimeline=f.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=f}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),Q1()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var t;this._animation&&this.animation.cancel(),(t=this.keyframeResolver)==null||t.cancel()}}const yR=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function vR(e){const t=yR.exec(e);if(!t)return[,];const[,n,i,r]=t;return[`--${n??i}`,r]}const xR=4;function kv(e,t,n=1){Si(n<=xR,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[i,r]=vR(e);if(!i)return;const s=window.getComputedStyle(t).getPropertyValue(i);if(s){const o=s.trim();return z0(o)?parseFloat(o):o}return gh(r)?kv(r,t,n+1):r}function Ch(e,t){return(e==null?void 0:e[t])??(e==null?void 0:e.default)??e}const Sv=new Set(["width","height","top","left","right","bottom",...bs]),kR={test:e=>e==="auto",parse:e=>e},wv=e=>t=>t.test(e),Tv=[gs,Me,ti,Di,d1,u1,kR],Qp=e=>Tv.find(wv(e));function SR(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||W0(e):!0}const wR=new Set(["brightness","contrast","saturate","opacity"]);function TR(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[i]=n.match(bh)||[];if(!i)return e;const r=n.replace(i,"");let s=wR.has(t)?1:0;return i!==n&&(s*=100),t+"("+s+r+")"}const CR=/\b([a-z-]*)\(.*?\)/gu,sd={...zi,getAnimatableNone:e=>{const t=e.match(CR);return t?t.map(TR).join(" "):e}},em={...gs,transform:Math.round},ER={rotate:Di,rotateX:Di,rotateY:Di,rotateZ:Di,scale:Bo,scaleX:Bo,scaleY:Bo,scaleZ:Bo,skew:Di,skewX:Di,skewY:Di,distance:Me,translateX:Me,translateY:Me,translateZ:Me,x:Me,y:Me,z:Me,perspective:Me,transformPerspective:Me,opacity:so,originX:Vp,originY:Vp,originZ:Me},Eh={borderWidth:Me,borderTopWidth:Me,borderRightWidth:Me,borderBottomWidth:Me,borderLeftWidth:Me,borderRadius:Me,radius:Me,borderTopLeftRadius:Me,borderTopRightRadius:Me,borderBottomRightRadius:Me,borderBottomLeftRadius:Me,width:Me,maxWidth:Me,height:Me,maxHeight:Me,top:Me,right:Me,bottom:Me,left:Me,padding:Me,paddingTop:Me,paddingRight:Me,paddingBottom:Me,paddingLeft:Me,margin:Me,marginTop:Me,marginRight:Me,marginBottom:Me,marginLeft:Me,backgroundPositionX:Me,backgroundPositionY:Me,...ER,zIndex:em,fillOpacity:so,strokeOpacity:so,numOctaves:em},_R={...Eh,color:Dt,backgroundColor:Dt,outlineColor:Dt,fill:Dt,stroke:Dt,borderColor:Dt,borderTopColor:Dt,borderRightColor:Dt,borderBottomColor:Dt,borderLeftColor:Dt,filter:sd,WebkitFilter:sd},Cv=e=>_R[e];function Ev(e,t){let n=Cv(e);return n!==sd&&(n=zi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const RR=new Set(["auto","none","0"]);function AR(e,t,n){let i=0,r;for(;i<e.length&&!r;){const s=e[i];typeof s=="string"&&!RR.has(s)&&oo(s).values.length&&(r=e[i]),i++}if(r&&n)for(const s of t)e[s]=Ev(n,r)}class PR extends Th{constructor(t,n,i,r,s){super(t,n,i,r,s,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let l=t[c];if(typeof l=="string"&&(l=l.trim(),gh(l))){const u=kv(l,n.current);u!==void 0&&(t[c]=u),c===t.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!Sv.has(i)||t.length!==2)return;const[r,s]=t,o=Qp(r),a=Qp(s);if(o!==a)if(Yp(o)&&Yp(a))for(let c=0;c<t.length;c++){const l=t[c];typeof l=="string"&&(t[c]=parseFloat(l))}else lr[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,i=[];for(let r=0;r<t.length;r++)(t[r]===null||SR(t[r]))&&i.push(r);i.length&&AR(t,i,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:i}=this;if(!t||!t.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=lr[i](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(i,r).jump(r,!1)}measureEndState(){var a;const{element:t,name:n,unresolvedKeyframes:i}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const s=i.length-1,o=i[s];i[s]=lr[n](t.measureViewportBox(),window.getComputedStyle(t.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([c,l])=>{t.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function NR(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let i=document;const r=(n==null?void 0:n[e])??i.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const _v=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Rv(e){return H0(e)&&"offsetHeight"in e}const tm=30,IR=e=>!isNaN(parseFloat(e));class MR{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{var s;const r=fn.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((s=this.events.change)==null||s.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=fn.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=IR(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&hh(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new dh);const i=this.events[t].add(n);return t==="change"?()=>{i(),vt.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-i}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=fn.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>tm)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,tm);return q0(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,n;(t=this.dependents)==null||t.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function cs(e,t){return new MR(e,t)}const{schedule:_h}=iv(queueMicrotask,!1),Fn={x:!1,y:!1};function Av(){return Fn.x||Fn.y}function OR(e){return e==="x"||e==="y"?Fn[e]?null:(Fn[e]=!0,()=>{Fn[e]=!1}):Fn.x||Fn.y?null:(Fn.x=Fn.y=!0,()=>{Fn.x=Fn.y=!1})}function Pv(e,t){const n=NR(e),i=new AbortController,r={passive:!0,...t,signal:i.signal};return[n,r,()=>i.abort()]}function nm(e){return!(e.pointerType==="touch"||Av())}function DR(e,t,n={}){const[i,r,s]=Pv(e,n),o=a=>{if(!nm(a))return;const{target:c}=a,l=t(c,a);if(typeof l!="function"||!c)return;const u=d=>{nm(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,r)};return i.forEach(a=>{a.addEventListener("pointerenter",o,r)}),s}const Nv=(e,t)=>t?e===t?!0:Nv(e,t.parentElement):!1,Rh=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,LR=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function FR(e){return LR.has(e.tagName)||e.tabIndex!==-1}const wa=new WeakSet;function im(e){return t=>{t.key==="Enter"&&e(t)}}function vl(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const jR=(e,t)=>{const n=e.currentTarget;if(!n)return;const i=im(()=>{if(wa.has(n))return;vl(n,"down");const r=im(()=>{vl(n,"up")}),s=()=>vl(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",s,t)});n.addEventListener("keydown",i,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),t)};function rm(e){return Rh(e)&&!Av()}function UR(e,t,n={}){const[i,r,s]=Pv(e,n),o=a=>{const c=a.currentTarget;if(!rm(a))return;wa.add(c);const l=t(c,a),u=(f,g)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),wa.has(c)&&wa.delete(c),rm(f)&&typeof l=="function"&&l(f,{success:g})},d=f=>{u(f,c===window||c===document||n.useGlobalTarget||Nv(c,f.target))},h=f=>{u(f,!1)};window.addEventListener("pointerup",d,r),window.addEventListener("pointercancel",h,r)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,r),Rv(a)&&(a.addEventListener("focus",l=>jR(l,r)),!FR(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),s}function Iv(e){return H0(e)&&"ownerSVGElement"in e}function BR(e){return Iv(e)&&e.tagName==="svg"}const Jt=e=>!!(e&&e.getVelocity),VR=[...Tv,Dt,zi],$R=e=>VR.find(wv(e)),Ah=O.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class zR extends D.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const i=n.offsetParent,r=Rv(i)&&i.offsetWidth||0,s=this.props.sizeRef.current;s.height=n.offsetHeight||0,s.width=n.offsetWidth||0,s.top=n.offsetTop,s.left=n.offsetLeft,s.right=r-s.width-s.left}return null}componentDidUpdate(){}render(){return this.props.children}}function HR({children:e,isPresent:t,anchorX:n,root:i}){const r=O.useId(),s=O.useRef(null),o=O.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=O.useContext(Ah);return O.useInsertionEffect(()=>{const{width:c,height:l,top:u,left:d,right:h}=o.current;if(t||!s.current||!c||!l)return;const f=n==="left"?`left: ${d}`:`right: ${h}`;s.current.dataset.motionPopId=r;const g=document.createElement("style");a&&(g.nonce=a);const p=i??document.head;return p.appendChild(g),g.sheet&&g.sheet.insertRule(`
|
|
38
|
+
`},ll}var Ep;function YE(){if(Ep)return Dn;Ep=1;var e=GE(),t=KE(),n=Qd();return Dn.grammar=n,Dn.write=t,Dn.parse=e.parse,Dn.parseParams=e.parseParams,Dn.parseFmtpConfig=e.parseFmtpConfig,Dn.parsePayloads=e.parsePayloads,Dn.parseRemoteCandidates=e.parseRemoteCandidates,Dn.parseImageAttributes=e.parseImageAttributes,Dn.parseSimulcastStreamList=e.parseSimulcastStreamList,Dn}var Oi=YE();function eh(e,t,n){var i,r,s;t===void 0&&(t=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,a=(r=n.callback)!=null&&r,c=n.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+t>=c)return c-f}return t}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(p,v){var b=o&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!o){var S=e.apply(g,f);a&&a(S),u.forEach(function(k){return(0,k.resolve)(S)}),u=[]}},d()),b){var w=e.apply(g,f);return a&&a(w),p(w)}u.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(g){return(0,g.reject)(f)}),u=[]},h}const ZE=.7,XE=20,ts={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _p extends ii.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=qe,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=eh(r=>M(this,void 0,void 0,function*(){this.emit(ts.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),XE),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=xi((i=n.loggerName)!==null&&i!==void 0?i:Hn.PCTransport),this.loggerOptions=n,this.config=t,this._pc=this.createPC()}createPC(){const t=new RTCPeerConnection(this.config);return t.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},t.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},t.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,t.iceConnectionState)},t.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,t.signalingState)},t.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,t.connectionState)},t.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},t.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},t}get logContext(){var t,n;return Object.assign({},(n=(t=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(t))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(t){return M(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(t);this.pendingCandidates.push(t)})}setRemoteDescription(t,n){return M(this,void 0,void 0,function*(){var i;if(t.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(t.type==="offer"){let{stereoMids:s,nackMids:o}=JE(t);this.remoteStereoMids=s,this.remoteNackMids=o}else if(t.type==="answer"){const s=Oi.parse((i=t.sdp)!==null&&i!==void 0?i:"");s.media.forEach(o=>{o.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||o.mid!=a.transceiver.mid)return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(c=u.payload,!0):!1),c===0)return!0;let l=!1;for(const u of o.fmtp)if(u.payload===c){u.config=u.config.split(";").filter(d=>!d.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),l=!0;break}return l||a.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),r=Oi.write(s)}return yield this.setMungedSDP(t,r,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):t.type==="answer"&&(this.emit(ts.NegotiationComplete),t.sdp&&Oi.parse(t.sdp).media.forEach(o=>{o.type==="video"&&this.emit(ts.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(t){return M(this,void 0,void 0,function*(){var n;const i=this.latestOfferId+1;if(this.latestOfferId=i,this.onOffer===void 0)return;if(t!=null&&t.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(t!=null&&t.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(t);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const s=Oi.parse((n=r.sdp)!==null&&n!==void 0?n:"");if(s.media.forEach(o=>{Ap(o),o.type==="audio"?Rp(o,[],[]):o.type==="video"&&this.trackBitrates.some(a=>{if(!o.msid||!a.cid||!o.msid.includes(a.cid))return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===a.codec.toUpperCase()?(c=u.payload,!0):!1),c===0||(yi(a.codec)&&this.ensureVideoDDExtensionForSVC(o,s),a.codec!=="av1"))return!0;const l=Math.round(a.maxbr*ZE);for(const u of o.fmtp)if(u.payload===c){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(r,Oi.write(s)),this.onOffer(r,this.latestOfferId)})}createAndSetAnswer(){return M(this,void 0,void 0,function*(){var t;const n=yield this.pc.createAnswer(),i=Oi.parse((t=n.sdp)!==null&&t!==void 0?t:"");return i.media.forEach(r=>{Ap(r),r.type==="audio"&&Rp(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Oi.write(i)),n})}createDataChannel(t,n){return this.pc.createDataChannel(t,n)}addTransceiver(t,n){return this.pc.addTransceiver(t,n)}addTrack(t){if(!this._pc)throw new Bt("PC closed, cannot add track");return this._pc.addTrack(t)}setTrackCodecBitrate(t){this.trackBitrates.push(t)}setConfiguration(t){var n;if(!this._pc)throw new Bt("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(t)}canRemoveTrack(){var t;return!!(!((t=this._pc)===null||t===void 0)&&t.removeTrack)}removeTrack(t){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(t)}getConnectionState(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var t,n;return(n=(t=this._pc)===null||t===void 0?void 0:t.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var t;return(t=this._pc)===null||t===void 0?void 0:t.localDescription}getRemoteDescription(){var t;return(t=this.pc)===null||t===void 0?void 0:t.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return M(this,void 0,void 0,function*(){var t;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":n=a.selectedCandidatePairId;break;case"candidate-pair":n===""&&a.selected&&(n=a.id),i.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),n==="")return;const o=(t=i.get(n))===null||t===void 0?void 0:t.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(t,n,i){return M(this,void 0,void 0,function*(){if(n){const r=t.sdp;t.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t);return}catch(s){this.log.warn("not able to set ".concat(t.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:n})),t.sdp=r}}try{i?yield this.pc.setRemoteDescription(t):yield this.pc.setLocalDescription(t)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const o={error:s,sdp:t.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(t.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Au(s)}})}ensureVideoDDExtensionForSVC(t,n){var i,r;if(!((i=t.ext)===null||i===void 0?void 0:i.some(o=>o.uri===pp))){if(this.ddExtID===0){let o=0;n.media.forEach(a=>{var c;a.type==="video"&&((c=a.ext)===null||c===void 0||c.forEach(l=>{l.value>o&&(o=l.value)}))}),this.ddExtID=o+1}(r=t.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:pp})}}}function Rp(e,t,n){let i=0;e.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(e.mid)&&!e.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&e.rtcpFb.push({payload:i,type:"nack"}),t.includes(e.mid)&&e.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function JE(e){var t;const n=[],i=[],r=Oi.parse((t=e.sdp)!==null&&t!==void 0?t:"");let s=0;return r.media.forEach(o=>{var a;o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((a=o.rtcpFb)===null||a===void 0)&&a.some(c=>c.payload===s&&c.type==="nack")&&i.push(o.mid),o.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&n.push(o.mid),!0):!1))}),{stereoMids:n,nackMids:i}}function Ap(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const Bu="vp8",QE={audioPreset:Pu.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Yd.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Bu,backupCodec:!0,preConnectBuffer:!1},Py={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Ny={deviceId:{ideal:"default"},resolution:io.h720.resolution},e_={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new BC,disconnectOnPageLeave:!0,webAudioMix:!1},th={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ct;(function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"})(Ct||(Ct={}));class t_{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,n,i){var r;this.peerConnectionTimeout=th.peerConnectionTimeout,this.log=qe,this.updateState=()=>{var s;const o=this.state,a=this.requiredTransports.map(c=>c.getConnectionState());a.every(c=>c==="connected")?this.state=Ct.CONNECTED:a.some(c=>c==="failed")?this.state=Ct.FAILED:a.some(c=>c==="connecting")?this.state=Ct.CONNECTING:a.every(c=>c==="closed")?this.state=Ct.CLOSED:a.some(c=>c==="closed")?this.state=Ct.CLOSING:a.every(c=>c==="new")&&(this.state=Ct.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Ct[o]," to ").concat(Ct[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=xi((r=i.loggerName)!==null&&r!==void 0?r:Hn.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new _p(t,i),this.subscriber=new _p(t,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=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,Bn.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,s,Bn.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,s)},this.subscriber.onTrack=s=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,s)},this.publisher.onOffer=(s,o)=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s,o)},this.state=Ct.NEW,this.connectionLock=new dn,this.remoteOfferLock=new dn}get logContext(){var t,n;return Object.assign({},(n=(t=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(t))}requirePublisher(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=t,this.updateState()}requireSubscriber(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=t,this.updateState()}createAndSendPublisherOffer(t){return this.publisher.createAndSendOffer(t)}setPublisherAnswer(t,n){return this.publisher.setRemoteDescription(t,n)}removeTrack(t){return this.publisher.removeTrack(t)}close(){return M(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return M(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(t,n){return M(this,void 0,void 0,function*(){n===Bn.PUBLISHER?yield this.publisher.addIceCandidate(t):yield this.subscriber.addIceCandidate(t)})}createSubscriberAnswerFromOffer(t,n){return M(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type,sdp:t.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(t,n))?yield this.subscriber.createAndSetAnswer():void 0}finally{i()}})}updateConfiguration(t,n){this.publisher.setConfiguration(t),this.subscriber.setConfiguration(t),n&&this.triggerIceRestart()}ensurePCTransportConnection(t,n){return M(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,t,n)))}finally{r()}})}negotiate(t){return M(this,void 0,void 0,function*(){return new Promise((n,i)=>M(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};t.signal.addEventListener("abort",s),this.publisher.once(ts.NegotiationStarted,()=>{t.signal.aborted||this.publisher.once(ts.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(t,n){return this.publisher.addTransceiver(t,n)}addPublisherTrack(t){return this.publisher.addTrack(t)}createPublisherDataChannel(t,n){return this.publisher.createDataChannel(t,n)}getConnectedAddress(t){return t===Bn.PUBLISHER?this.publisher.getConnectedAddress():t===Bn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const t=[];return this.isPublisherConnectionRequired&&t.push(this.publisher),this.isSubscriberConnectionRequired&&t.push(this.subscriber),t}ensureTransportConnected(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>M(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Zt.clearTimeout(d),l(new ut("room connection has been cancelled",Ge.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Zt.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(new ut("could not establish pc connection",Ge.InternalError))},o);for(;this.state!==Ct.CONNECTED;)if(yield pn(50),r!=null&&r.signal.aborted){l(new ut("room connection has been cancelled",Ge.Cancelled));return}Zt.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class _t extends Error{constructor(t,n,i){super(n),this.code=t,this.message=Pp(n,_t.MAX_MESSAGE_BYTES),this.data=i?Pp(i,_t.MAX_DATA_BYTES):void 0}static fromProto(t){return new _t(t.code,t.message,t.data)}toProto(){return new C0({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new _t(_t.ErrorCode[t],_t.ErrorMessage[t],n)}}_t.MAX_MESSAGE_BYTES=256;_t.MAX_DATA_BYTES=15360;_t.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};_t.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 Iy=15360;function nh(e){return new TextEncoder().encode(e).length}function Pp(e,t){if(nh(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(e.slice(0,s)).length<=t?n=s:i=s-1}return e.slice(0,n)}const ih=2e3;function mc(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),n===void 0||i===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-i)*8*1e3/(e.timestamp-t.timestamp)}const rh=typeof MediaRecorder<"u";class n_{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const i_=rh?MediaRecorder:n_;class r_ extends i_{constructor(t,n){if(!rh)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([t.mediaStreamTrack]),n);let i,r;const s=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r==null||r.close(),r=void 0},a=c=>{r==null||r.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",a),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,i=l=>M(this,void 0,void 0,function*(){const u=yield l.data.arrayBuffer();s()||c.enqueue(new Uint8Array(u))}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",a)}}function s_(){return rh}const o_=1e3,a_=1e4;class My extends B{get sender(){return this._sender}set sender(t){this._sender=t}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(t,n,s),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=eh(()=>M(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>M(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(he.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new dn,this.pauseUpstreamLock=new dn,this.processorLock=new dn,this.restartLock=new dn,this.setMediaStreamTrack(t,!0),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==B.Kind.Video)return;const{width:t,height:n}=this._mediaStreamTrack.getSettings();if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var t,n;return(n=(t=this.processor)===null||t===void 0?void 0:t.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(t,n){return M(this,void 0,void 0,function*(){var i;if(t===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Qr(this._mediaStreamTrack,s)}),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([t]),t&&(t.addEventListener("ended",this.handleEnded),t.addEventListener("mute",this.handleTrackMuteEvent),t.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=t.getConstraints());let r;if(this.processor&&t){const s=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&($r(t,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:t,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??t)),!this.providedByUser&&this._mediaStreamTrack!==t&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=t,t&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{$r(r??t,s)}))})}waitForDimensions(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o_;return function*(){var i;if(t.kind===B.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=kn())===null||i===void 0?void 0:i.os)==="iOS"&&(yield pn(10));const r=Date.now();for(;Date.now()-r<n;){const s=t.dimensions;if(s)return s;yield pn(50)}throw new gi("unable to get track dimensions after timeout")}()})}setDeviceId(t){return M(this,void 0,void 0,function*(){return this._constraints.deviceId===t&&this._mediaStreamTrack.getSettings().deviceId===Bi(t)||(this._constraints.deviceId=t,this.isMuted)?!0:(yield this.restartTrack(),Bi(t)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(t.source===B.Source.ScreenShare)return;const{deviceId:i,groupId:r}=t._mediaStreamTrack.getSettings(),s=t.kind===B.Kind.Audio?"audioinput":"videoinput";return n?Wt.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return M(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return M(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(t,n){return M(this,void 0,void 0,function*(){if(!this.sender)throw new gi("unable to replace an unpublished track");let i,r;return typeof n=="boolean"?i=n:n!==void 0&&(i=n.userProvidedTrack,r=n.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(t),r&&this.processor&&(yield this.stopProcessor()),this})}restart(t){return M(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.restartLock.lock();try{t||(t=this._constraints);const{deviceId:i,facingMode:r}=t,s=VC(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const o={audio:!1,video:!1};this.kind===B.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Qr(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=t,this.emit(he.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),!(this.isMuted===t&&this._mediaStreamTrack.enabled!==t)&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?he.Muted:he.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return M(this,void 0,void 0,function*(){yield t.handleAppVisibilityChanged.call(this),wy()&&(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 t;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(t=this.processor)===null||t===void 0||t.destroy(),this.processor=void 0}pauseUpstream(){return M(this,void 0,void 0,function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(he.UpstreamPaused,this);const i=kn();if((i==null?void 0:i.name)==="Safari"&&br(i.version,"12.0")<0)throw new Kd("pauseUpstream is not supported on Safari < 12.");((t=this.sender.transport)===null||t===void 0?void 0:t.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return M(this,void 0,void 0,function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(he.UpstreamResumed,this),((t=this.sender.transport)===null||t===void 0?void 0:t.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return M(this,void 0,void 0,function*(){var t;return!((t=this.sender)===null||t===void 0)&&t.getStats?yield this.sender.getStats():void 0})}setProcessor(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const o=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const a=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:a,audioContext:i.audioContext};if(yield n.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if($r(i._mediaStreamTrack,a),a.muted=!0,a.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=n,i.processorElement=a,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Qr(i._mediaStreamTrack,l),$r(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(he.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return M(this,arguments,void 0,function(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;t.processor&&(t.log.debug("stopping processor",t.logContext),(i=t.processor.processedTrack)===null||i===void 0||i.stop(),yield t.processor.destroy(),t.processor=void 0,n||((r=t.processorElement)===null||r===void 0||r.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(he.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!s_()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(!this.localTrackRecorder)this.localTrackRecorder=new r_(this,{mimeType:"audio/webm;codecs=opus"});else{this.log.warn("preconnect buffer already started");return}this.localTrackRecorder.start(t),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},a_)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var t;return(t=this.localTrackRecorder)===null||t===void 0?void 0:t.byteStream}}class Ua extends My{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(t,B.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>M(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}o&&this.prevStats&&(this._currentBitrate=mc(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(he.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(he.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===B.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{n()}})}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Bi(this._constraints.deviceId);return this.source===B.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this}finally{n()}})}restartTrack(t){return M(this,void 0,void 0,function*(){let n;if(t){const i=Zd({audio:t});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(t){const n=Object.create(null,{restart:{get:()=>super.restart}});return M(this,void 0,void 0,function*(){const i=yield n.restart.call(this,t);return this.checkForSilence(),i})}startMonitor(){hn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ih)))}setProcessor(t){return M(this,void 0,void 0,function*(){var n;const i=yield this.processorLock.lock();try{if(!ni()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(r),this.processor=t,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.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(he.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(t){this.audioContext=t}getSenderStats(){return M(this,void 0,void 0,function*(){var t;if(!(!((t=this.sender)===null||t===void 0)&&t.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return M(this,void 0,void 0,function*(){const t=yield _y(this);return t&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(he.AudioSilenceDetected)),t})}}function c_(e,t,n){switch(e.kind){case"audio":return new Ua(e,t,!1,void 0,n);case"video":return new Ba(e,t,!1,n);default:throw new gi("unsupported track type: ".concat(e.kind))}}const l_=Object.values(io),u_=Object.values(Nu),d_=Object.values(Yd),h_=[io.h180,io.h360],f_=[Nu.h180,Nu.h360],p_=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(n=>{var i,r;return new st(Math.floor(e.width/n.scaleResolutionDownBy),Math.floor(e.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=e.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,e.encoding.priority)}),Vu=["q","h","f"];function $u(e,t,n,i){var r,s;let o=i==null?void 0:i.videoEncoding;e&&(o=i==null?void 0:i.screenShareEncoding);const a=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!o&&!a&&!c||!t||!n)return[{}];o||(o=g_(e,t,n,l),qe.debug("using video encoding",o));const u=o.maxFramerate,d=new st(t,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&yi(l)){const g=new Oy(c),p=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=kn();if(gr()||ni()||(v==null?void 0:v.name)==="Chrome"&&br(v==null?void 0:v.version,"113")<0){const b=g.suffix=="h"?2:3,w=vE(v);for(let S=0;S<g.spatial;S+=1)p.push({rid:Vu[2-S],maxBitrate:o.maxBitrate/Math.pow(b,S),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:w?Math.pow(2,S):void 0});p[0].scalabilityMode=c}else p.push({maxBitrate:o.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),qe.debug("using svc encoding",{encodings:p}),p}if(!a)return[o];let h=[];e?h=(r=Ip(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Np(e,d):h=(s=Ip(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Np(e,d);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const p=Math.max(t,n);if(p>=960&&f)return ul(t,n,[g,f,d],u);if(p>=480)return ul(t,n,[g,d],u)}return ul(t,n,[d])}function m_(e,t,n){var i,r,s,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&qe.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=(i=a.width)!==null&&i!==void 0?i:(r=e.dimensions)===null||r===void 0?void 0:r.width,l=(s=a.height)!==null&&s!==void 0?s:(o=e.dimensions)===null||o===void 0?void 0:o.height;return e.source===B.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),$u(e.source===B.Source.ScreenShare,c,l,n)}function g_(e,t,n,i){const r=b_(e,t,n);let{encoding:s}=r[0];const o=Math.max(t,n);for(let a=0;a<r.length;a+=1){const c=r[a];if(s=c.encoding,c.width>=o)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function b_(e,t,n){if(e)return d_;const i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?l_:u_}function Np(e,t){if(e)return p_(t);const{width:n,height:i}=t,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?h_:f_}function ul(e,t,n,i){const r=[];if(n.forEach((s,o)=>{if(o>=Vu.length)return;const a=Math.min(e,t),l={rid:Vu[o],scaleResolutionDownBy:Math.max(1,a/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(l.maxFramerate=u);const d=as()||o===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),ni()&&Cy()==="ios"){let s;r.forEach(a=>{s?a.maxFramerate&&a.maxFramerate>s&&(s=a.maxFramerate):s=a.maxFramerate});let o=!0;r.forEach(a=>{var c;a.maxFramerate!=s&&(o&&(o=!1,qe.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),qe.info('Setting framerate of encoding "'.concat((c=a.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),a.maxFramerate=s)})}return r}function Ip(e){if(e)return e.sort((t,n)=>{const{encoding:i}=t,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Oy{constructor(t){const n=t.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var t;return"L".concat(this.spatial,"T").concat(this.temporal).concat((t=this.suffix)!==null&&t!==void 0?t:"")}}function y_(e){return e.source===B.Source.ScreenShare||e.constraints.height&&Bi(e.constraints.height)>=1080?"maintain-resolution":"balanced"}const v_=5e3;class Ba extends My{get sender(){return this._sender}set sender(t){this._sender=t,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(t,B.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>M(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(a){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:a}));return}const o=new Map(s.map(a=>[a.rid,a]));if(this.prevStats){let a=0;o.forEach((c,l)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);a+=mc(c,d)}),this._currentBitrate=a}this.prevStats=o}),this.senderLock=new dn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(t){var n;if(this.signalClient=t,!hn())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ih))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(t=>{t.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const t=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return M(this,void 0,void 0,function*(){var n,i,r,s,o;yield t.pauseUpstream.call(this);try{for(var a=!0,c=mi(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0)s=l.value,a=!1,yield(o=s.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(u){i={error:u}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const t=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return M(this,void 0,void 0,function*(){var n,i,r,s,o;yield t.resumeUpstream.call(this);try{for(var a=!0,c=mi(this.simulcastCodecs.values()),l;l=yield c.next(),n=l.done,!n;a=!0){s=l.value,a=!1;const u=s;yield(o=u.sender)===null||o===void 0?void 0:o.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!a&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const t=Object.create(null,{mute:{get:()=>super.mute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===B.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield t.mute.call(this),this)}finally{n()}})}unmute(){const t=Object.create(null,{unmute:{get:()=>super.unmute}});return M(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===B.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield t.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(t){super.setTrackMuted(t);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!t}getSenderStats(){return M(this,void 0,void 0,function*(){var t;if(!(!((t=this.sender)===null||t===void 0)&&t.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},a=i.get(r.remoteId);a&&(o.jitter=a.jitter,o.packetsLost=a.packetsLost,o.roundTripTime=a.roundTripTime),n.push(o)}}),n.sort((r,s)=>{var o,a;return((o=s.frameWidth)!==null&&o!==void 0?o:0)-((a=r.frameWidth)!==null&&a!==void 0?a:0)}),n})}setPublishingQuality(t){const n=[];for(let i=Pn.LOW;i<=Pn.HIGH;i+=1)n.push(new Wd({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(yi(this.codec),n)}restartTrack(t){return M(this,void 0,void 0,function*(){var n,i,r,s,o;let a;if(t){const d=Zd({video:t});typeof d.video!="boolean"&&(a=d.video)}yield this.restart(a);try{for(var c=!0,l=mi(this.simulcastCodecs.values()),u;u=yield l.next(),n=u.done,!n;c=!0){s=u.value,c=!1;const d=s;d.sender&&((o=d.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(t){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return M(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,a,c,l,u,d;if(yield n.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=mi(r.simulcastCodecs.values()),g;g=yield f.next(),o=g.done,!o;h=!0)l=g.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(p){a={error:p}}finally{try{!h&&!o&&(c=f.return)&&(yield c.call(f))}finally{if(a)throw a.error}}}()})}setDegradationPreference(t){return M(this,void 0,void 0,function*(){if(this.degradationPreference=t,this.sender)try{this.log.debug("setting degradationPreference to ".concat(t),this.logContext);const n=this.sender.getParameters();n.degradationPreference=t,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(t,n){if(this.simulcastCodecs.has(t)){this.log.error("".concat(t," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:t,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(t,i),i}setSimulcastTrackSender(t,n){const i=this.simulcastCodecs.get(t);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},v_))}setPublishingCodecs(t){return M(this,void 0,void 0,function*(){var n,i,r,s,o,a,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:t,currentCodec:this.codec})),!this.codec&&t.length>0)return yield this.setPublishingLayers(yi(t[0].codec),t[0].qualities),[];this.subscribedCodecs=t;const l=[];try{for(n=!0,i=mi(t);r=yield i.next(),s=r.done,!s;n=!0){c=r.value,n=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(yi(u.codec),u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Mp(d.sender,d.encodings,u.qualities,this.senderLock,yi(u.codec),this.log,this.logContext))}}}catch(u){o={error:u}}finally{try{!n&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return l})}setPublishingLayers(t,n){return M(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield Mp(this.sender,this.encodings,n,this.senderLock,t,this.log,this.logContext))})}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return M(this,void 0,void 0,function*(){yield t.handleAppVisibilityChanged.call(this),wy()&&this.isInBackground&&this.source===B.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Mp(e,t,n,i,r,s,o){return M(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{const c=e.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==t.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:l,senderEncodings:t}));return}let u=!1;!1&&l[0].scalabilityMode||(r&&n.some(f=>f.enabled)&&n.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let p=(g=h.rid)!==null&&g!==void 0?g:"";p===""&&(p="q");const v=Dy(p),b=n.find(w=>w.quality===v);b&&h.active!==b.enabled&&(u=!0,h.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),o),as()&&(b.enabled?(h.scaleResolutionDownBy=t[f].scaleResolutionDownBy,h.maxBitrate=t[f].maxBitrate,h.maxFrameRate=t[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),u&&(c.encodings=l,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:c.encodings})),yield e.setParameters(c))}finally{a()}})}function Dy(e){switch(e){case"f":return Pn.HIGH;case"h":return Pn.MEDIUM;case"q":return Pn.LOW;default:return Pn.HIGH}}function Op(e,t,n,i){if(!n)return[new cr({quality:Pn.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,s=new Oy(r),o=[],a=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)o.push(new cr({quality:Math.min(Pn.HIGH,s.spatial-1)-l,width:Math.ceil(e/Math.pow(a,l)),height:Math.ceil(t/Math.pow(a,l)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return o}return n.map(r=>{var s,o,a;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Dy((o=r.rid)!==null&&o!==void 0?o:"");return new cr({quality:l,width:Math.ceil(e/c),height:Math.ceil(t/c),bitrate:(a=r.maxBitrate)!==null&&a!==void 0?a:0,ssrc:0})})}const Dp="_lossy",Lp="_reliable",x_=2*1e3,dl="leave-reconnect",k_=3e4;var Ln;(function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"})(Ln||(Ln={}));class S_ extends ii.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=th.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ln.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=qe,this.reliableDataSequence=1,this.reliableMessageBuffer=new Sp,this.reliableReceivedState=new qE(k_),this.handleDataChannel=i=>M(this,[i],void 0,function(r){var s=this;let{channel:o}=r;return function*(){if(o){if(o.label===Lp)s.reliableDCSub=o;else if(o.label===Dp)s.lossyDCSub=o;else return;s.log.debug("on data channel ".concat(o.id,", ").concat(o.label),s.logContext),o.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>M(this,void 0,void 0,function*(){var r,s;const o=yield this.dataProcessLock.lock();try{let a;if(i.data instanceof ArrayBuffer)a=i.data;else if(i.data instanceof Blob)a=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ln.fromBinary(new Uint8Array(a));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(fe.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&T_(c,c.value.value),this.emit(fe.DataPacketReceived,c))}finally{o()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?Be.LOSSY:Be.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(fe.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let a=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(a===null){s(o);return}i===dl&&(a=0),this.log.debug("reconnecting in ".concat(a,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Zt.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),a)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ln.Connected&&i();const s=()=>{this.off(fe.Disconnected,o),i()},o=()=>{this.off(fe.Restarted,s),r()};this.once(fe.Restarted,s),this.once(fe.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(fe.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return i===Be.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount),r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===gt.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(_r.RR_SIGNAL_DISCONNECTED))},this.log=xi((n=t.loggerName)!==null&&n!==void 0?n:Hn.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new Jd(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new dn,this.dataProcessLock=new dn,this.dcBufferStatus=new Map([[Be.LOSSY,!0],[Be.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(fe.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(fe.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(fe.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(fe.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(fe.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(fe.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(fe.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(fe.SignalRequestResponse,i)}get logContext(){var t,n,i,r,s,o;return{room:(n=(t=this.latestJoinResponse)===null||t===void 0?void 0:t.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(t,n,i,r){return M(this,void 0,void 0,function*(){this.url=t,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(t,n,i,r);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,this.emit(fe.SignalConnected,s),s}catch(s){if(s instanceof ut&&s.reason===Ge.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(t,n,i,r);throw s}})}close(){return M(this,void 0,void 0,function*(){const t=yield this.closingLock.lock();if(this.isClosed){t();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(fe.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}})}cleanupPeerConnections(){return M(this,void 0,void 0,function*(){var t;yield(t=this.pcManager)===null||t===void 0?void 0:t.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Sp,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return M(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new gi("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[t.cid],i(new ut("publication of local track timed out, no response from server",Ge.Timeout))},1e4);this.pendingTrackResolvers[t.cid]={resolve:s=>{clearTimeout(r),n(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)})}removeTrack(t){if(t.track&&this.pendingTrackResolvers[t.track.id]){const{reject:n}=this.pendingTrackResolvers[t.track.id];n&&n(),delete this.pendingTrackResolvers[t.track.id]}try{return this.pcManager.removeTrack(t),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(t,n){this.client.sendMuteTrack(t,n)}get dataSubscriberReadyState(){var t;return(t=this.reliableDCSub)===null||t===void 0?void 0:t.readyState}getConnectedServerAddress(){return M(this,void 0,void 0,function*(){var t;return(t=this.pcManager)===null||t===void 0?void 0:t.getConnectedAddress()})}setRegionUrlProvider(t){this.regionUrlProvider=t}configure(t){return M(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Ct.NEW)return;this.participantSid=(n=t.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(t);this.pcManager=new t_(r,t.subscriberPrimary,this.loggerOptions),this.emit(fe.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,o)=>{this.client.sendIceCandidate(s,o)},this.pcManager.onPublisherOffer=(s,o)=>{this.client.sendOffer(s,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,o,a)=>M(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),s===Ct.CONNECTED){const u=this.pcState===Ln.New;this.pcState=Ln.Connected,u&&this.emit(fe.Connected,t)}else s===Ct.FAILED&&this.pcState===Ln.Connected&&(this.pcState=Ln.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?_r.RR_SUBSCRIBER_FAILED:_r.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===gt.RECONNECTING,l=[Ct.FAILED,Ct.CLOSING,Ct.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(fe.Offline)}),this.pcManager.onTrack=s=>{this.emit(fe.MediaTrackAdded,s.track,s.streams[0],s.receiver)},w_((i=t.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(t,n)=>M(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:t.type})),yield this.pcManager.setPublisherAnswer(t,n))}),this.client.onTrickle=(t,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:t,target:n})),this.pcManager.addIceCandidate(t,n))},this.client.onOffer=(t,n)=>M(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(t,n);i&&this.client.sendAnswer(i,n)}),this.client.onLocalTrackPublished=t=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:t.cid,track:(n=t.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[t.cid]){this.log.error("missing track resolver for ".concat(t.cid),Object.assign(Object.assign({},this.logContext),{cid:t.cid}));return}const{resolve:i}=this.pendingTrackResolvers[t.cid];delete this.pendingTrackResolvers[t.cid],i(t.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(fe.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(fe.LocalTrackSubscribed,t)},this.client.onTokenRefresh=t=>{this.token=t},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(fe.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(fe.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var n;this.participantSid=(n=t.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(fe.RoomMoved,t)},this.client.onClose=()=>{this.handleDisconnect("signal",_r.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:t==null?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(t.regions)),t.action){case Xr.DISCONNECT:this.emit(fe.Disconnected,t==null?void 0:t.reason),this.close();break;case Xr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(dl);break;case Xr.RESUME:this.handleDisconnect(dl)}}}makeRTCConfiguration(t){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),t.iceServers&&!i.iceServers){const r=[];t.iceServers.forEach(s=>{const o={urls:s.urls};s.username&&(o.username=s.username),s.credential&&(o.credential=s.credential),r.push(o)}),i.iceServers=r}return t.clientConfiguration&&t.clientConfiguration.forceRelay===to.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(Dp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Lp,{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(t,n,i){return M(this,void 0,void 0,function*(){if(Iu())return yield this.createTransceiverRTCRtpSender(t,n,i);if(Mu())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(t.mediaStreamTrack);throw new Bt("Required webRTC APIs not supported on this device")})}createSimulcastSender(t,n,i,r){return M(this,void 0,void 0,function*(){if(Iu())return this.createSimulcastTransceiverSender(t,n,i,r);if(Mu())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(t.mediaStreamTrack);throw new Bt("Cannot stream on this device")})}createTransceiverRTCRtpSender(t,n,i){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");const r=[];t.mediaStream&&r.push(t.mediaStream),ps(t)&&(t.codec=n.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(t,n,i,r){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,s);if(i.videoCodec)return t.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(t){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");return this.pcManager.addPublisherTrack(t)})}attemptReconnect(t){return M(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){qe.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===to.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Ct.NEW)===Ct.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let o=!0;s instanceof Bt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),o=!1):s instanceof Rr||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",_r.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(fe.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(t){try{return this.reconnectPolicy.nextRetryDelayInMs(t)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(t){return M(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new Bt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(fe.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Rr;s=yield this.join(t??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof ut&&o.reason===Ge.NotAllowed?new Bt("could not reconnect, token might be expired"):new Rr}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(fe.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==gt.CONNECTED)throw new Rr("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(fe.Restarted)}catch(s){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(t){return M(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new Bt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Bt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(fe.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof ut&&r.reason===Ge.NotAllowed?new Bt("could not reconnect, token might be expired"):r instanceof ut&&r.reason===Ge.LeaveRequest?r:new Rr(s)}if(this.emit(fe.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}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!==gt.CONNECTED)throw new Rr("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(fe.Resumed)})}waitForPCInitialConnection(t,n){return M(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,t)})}waitForPCReconnected(){return M(this,void 0,void 0,function*(){this.pcState=Ln.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield pn(x_),!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ln.Connected}catch(t){throw this.pcState=Ln.Disconnected,new ut("could not establish PC connection, ".concat(t.message),Ge.InternalError)}})}publishRpcResponse(t,n,i,r){return M(this,void 0,void 0,function*(){const s=new ln({destinationIdentities:[t],kind:Be.RELIABLE,value:{case:"rpcResponse",value:new T0({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,Be.RELIABLE)})}publishRpcAck(t,n){return M(this,void 0,void 0,function*(){const i=new ln({destinationIdentities:[t],kind:Be.RELIABLE,value:{case:"rpcAck",value:new w0({requestId:n})}});yield this.sendDataPacket(i,Be.RELIABLE)})}sendDataPacket(t,n){return M(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(n),n===Be.RELIABLE&&(t.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=t.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===Be.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:t.sequence}),this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(t){return M(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Be.RELIABLE);const n=this.dataChannelForKind(Be.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(t),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(Be.RELIABLE)})}waitForBufferStatusLow(t){return new Promise((n,i)=>M(this,void 0,void 0,function*(){if(this.isBufferStatusLow(t))n();else{const r=()=>i("Engine closed");for(this.once(fe.Closing,r);!this.dcBufferStatus.get(t);)yield pn(10);this.off(fe.Closing,r),n()}}))}ensureDataTransportConnected(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new Bt("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,a=r?"Subscriber":"Publisher";if(!o)throw new ut("".concat(a," connection not set"),Ge.InternalError);let c=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(n,r);if((l==null?void 0:l.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(o.isICEConnected&&((s=i.dataChannelForKind(n,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield pn(50)}throw new ut("could not establish ".concat(a," connection, state: ").concat(o.getICEConnectionState()),Ge.InternalError)}()})}ensurePublisherConnected(t){return M(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(t,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ct.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return M(this,void 0,void 0,function*(){return new Promise((t,n)=>M(this,void 0,void 0,function*(){if(!this.pcManager){n(new Au("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(fe.Closing,r),this.pcManager.publisher.once(ts.RTPVideoPayloadTypes,s=>{const o=new Map;s.forEach(a=>{const c=a.codec.toLowerCase();CE(c)&&o.set(a.payload,c)}),this.emit(fe.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),t()}catch(s){s instanceof Au&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",_r.RR_UNKNOWN),n(s)}finally{this.off(fe.Closing,r)}}))})}dataChannelForKind(t,n){if(n){if(t===Be.LOSSY)return this.lossyDCSub;if(t===Be.RELIABLE)return this.reliableDCSub}else{if(t===Be.LOSSY)return this.lossyDC;if(t===Be.RELIABLE)return this.reliableDC}}sendSyncState(t,n){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),a=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;t.forEach(u=>{u.isDesired!==a&&c.push(u.trackSid),u.isEnabled||l.push(u.trackSid)}),this.client.sendSyncState(new V0({answer:s?ja({sdp:s.sdp,type:s.type}):void 0,offer:o?ja({sdp:o.sdp,type:o.type}):void 0,subscription:new hc({trackSids:c,subscribe:!a,participantTracks:[]}),publishTracks:OE(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((u,d)=>new $0({publisherSid:d,lastSeq:u}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const t=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&t.push(new z0({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Be.LOSSY),Bn.PUBLISHER),n(this.dataChannelForKind(Be.RELIABLE),Bn.PUBLISHER),n(this.dataChannelForKind(Be.LOSSY,!0),Bn.SUBSCRIBER),n(this.dataChannelForKind(Be.RELIABLE,!0),Bn.SUBSCRIBER),t}clearReconnectTimeout(){this.reconnectTimeout&&Zt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){hn()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){hn()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Rr extends Error{}function w_(e){return e!==void 0&&e>13}function T_(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=e.destinationIdentities.length!==0?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}class zu{constructor(t,n){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(t),this.token=n}updateToken(t){this.token=t}isCloud(){return Du(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(t){return M(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(t));const n=this.regionSettings.regions.filter(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(n.length>0){const i=n[0];return this.attemptedRegions.push(i),qe.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(t){return M(this,void 0,void 0,function*(){const n=yield fetch("".concat(C_(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:t});if(n.ok){const i=yield n.json();return this.lastUpdateAt=Date.now(),i}else throw new ut("Could not fetch region settings: ".concat(n.statusText),n.status===401?Ge.NotAllowed:Ge.InternalError,n.status)})}setServerReportedRegions(t){this.regionSettings=t,this.lastUpdateAt=Date.now()}}function C_(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}class Ly{get info(){return this._info}constructor(t,n,i){this.reader=n,this.totalByteSize=i,this._info=t,this.bytesReceived=0}}class E_ extends Ly{handleChunkReceived(t){var n;this.bytesReceived+=t.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const t=this.reader.getReader();return{next:()=>M(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield t.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return M(this,void 0,void 0,function*(){return t.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return M(this,void 0,void 0,function*(){var t,n,i,r;let s=new Set;try{for(var o=!0,a=mi(this),c;c=yield a.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const l=r;s.add(l)}}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return Array.from(s)})}}class __ extends Ly{constructor(t,n,i){super(t,n,i),this.receivedChunks=new Map}handleChunkReceived(t){var n;const i=xa(t.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>t.version)return;this.receivedChunks.set(i,t),this.bytesReceived+=t.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,s)}[Symbol.asyncIterator](){const t=this.reader.getReader(),n=new TextDecoder;return{next:()=>M(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield t.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:n.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return M(this,void 0,void 0,function*(){return t.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return M(this,void 0,void 0,function*(){var t,n,i,r;let s="";try{for(var o=!0,a=mi(this),c;c=yield a.next(),t=c.done,!t;o=!0)r=c.value,o=!1,s+=r}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}return s})}}class Fy{constructor(t,n,i){this.writableStream=t,this.defaultWriter=t.getWriter(),this.onClose=i,this.info=n}write(t){return this.defaultWriter.write(t)}close(){return M(this,void 0,void 0,function*(){var t;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(t=this.onClose)===null||t===void 0||t.call(this)})}}class R_ extends Fy{}class A_ extends Fy{}class jy extends B{constructor(t,n,i,r,s){super(t,i,s),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?he.Muted:he.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(he.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return M(this,void 0,void 0,function*(){var t;return!((t=this.receiver)===null||t===void 0)&&t.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(t){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=t: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(),ih)),DE()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>t());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(he.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};t()}}class Uy extends jy{constructor(t,n,i,r,s,o){super(t,n,B.Kind.Audio,i,o),this.monitorReceiver=()=>M(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=mc(a,this.prevStats)),this.prevStats=a}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(t){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(t,0,.1):i.volume=t;ni()&&this._mediaStreamTrack._setVolume(t),this.elementVolume=t}getVolume(){if(this.elementVolume)return this.elementVolume;if(ni())return 1;let t=0;return this.attachedElements.forEach(n=>{n.volume>t&&(t=n.volume)}),t}setSinkId(t){return M(this,void 0,void 0,function*(){this.sinkId=t,yield Promise.all(this.attachedElements.map(n=>{if(Ou(n))return n.setSinkId(t)}))})}attach(t){const n=this.attachedElements.length===0;return t?super.attach(t):t=super.attach(),this.sinkId&&Ou(t)&&t.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,t),t.volume=0,t.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),t}detach(t){let n;return t?(n=super.detach(t),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(t){this.audioContext=t,t&&this.attachedElements.length>0?this.connectWebAudio(t,this.attachedElements[0]):t||this.disconnectWebAudio()}setWebAudioPlugins(t){this.webAudioPluginNodes=t,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),t.state!=="running"&&t.resume().then(()=>{t.state!=="running"&&this.emit(he.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(he.AudioPlaybackFailed,r)})}disconnectWebAudio(){var t,n;(t=this.gainNode)===null||t===void 0||t.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return M(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const t=yield this.receiver.getStats();let n;return t.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const hl=100;class P_ extends jy{constructor(t,n,i,r,s){super(t,n,B.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>M(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=mc(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=eh(()=>{this.updateDimensions()},hl),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(t){super.setMuted(t),this.attachedElements.forEach(n=>{t?Qr(this._mediaStreamTrack,n):$r(this._mediaStreamTrack,n)})}attach(t){if(t?super.attach(t):t=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===t)===void 0){const n=new N_(t);this.observeElementInfo(n)}return t}observeElementInfo(t){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===t)===void 0?(t.handleResize=()=>{this.debouncedHandleResize()},t.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(t),t.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(t){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===t);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==t),this.updateVisibility(),this.debouncedHandleResize()}detach(t){let n=[];if(t)return this.stopObservingElement(t),super.detach(t);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var t;return(t=this.prevStats)===null||t===void 0?void 0:t.decoderImplementation}getReceiverStats(){return M(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const t=yield this.receiver.getStats();let n,i="",r=new Map;return t.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,n={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(t){const n=this.elementInfos.filter(i=>i.element===t);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const t=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return M(this,void 0,void 0,function*(){yield t.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var t,n;const i=this.elementInfos.reduce((a,c)=>Math.max(a,c.visibilityChangedAt||0),0),r=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,s=this.elementInfos.some(a=>a.pictureInPicture),o=this.elementInfos.some(a=>a.visible)&&!r||s;if(this.lastVisible!==o){if(!o&&Date.now()-i<hl){Zt.setTimeout(()=>{this.updateVisibility()},hl);return}this.lastVisible=o,this.emit(he.VisibilityChanged,o,this)}}updateDimensions(){var t,n;let i=0,r=0;const s=this.getPixelDensity();for(const o of this.elementInfos){const a=o.width()*s,c=o.height()*s;a+c>i+r&&(i=a,r=c)}((t=this.lastDimensions)===null||t===void 0?void 0:t.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(he.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var t;const n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pixelDensity;return n==="screen"?gp():n||(gp()>2?2:1)}}class N_{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(t,n){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:o}=i;s===this.element&&(this.isIntersecting=o,this.isPiP=Ps(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ps(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Ps(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=t,this.isIntersecting=n??Hu(t),this.isPiP=hn()&&Ps(t),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var t,n,i;this.isIntersecting=Hu(this.element),this.isPiP=Ps(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,yp().observe(this.element),bp().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(t=window.documentPictureInPicture)===null||t===void 0||t.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var t,n,i,r,s;(t=yp())===null||t===void 0||t.unobserve(this.element),(n=bp())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function Ps(e){var t,n;return document.pictureInPictureElement===e?!0:!((t=window.documentPictureInPicture)===null||t===void 0)&&t.window?Hu(e,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function Hu(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,i+=e.offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&c!=="none"}class hi extends ii.EventEmitter{constructor(t,n,i,r){var s;super(),this.metadataMuted=!1,this.encryption=vn.NONE,this.log=qe,this.handleMuted=()=>{this.emit(he.Muted)},this.handleUnmuted=()=>{this.emit(he.Unmuted)},this.log=xi((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Hn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=B.Source.Unknown}setTrack(t){this.track&&(this.track.off(he.Muted,this.handleMuted),this.track.off(he.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(he.Muted,this.handleMuted),t.on(he.Unmuted,this.handleUnmuted))}get logContext(){var t;return Object.assign(Object.assign({},(t=this.loggerContextCb)===null||t===void 0?void 0:t.call(this)),He(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==vn.NONE}get audioTrack(){if(Qn(this.track))return this.track}get videoTrack(){if(ps(this.track))return this.track}updateInfo(t){this.trackSid=t.sid,this.trackName=t.name,this.source=B.sourceFromProto(t.source),this.mimeType=t.mimeType,this.kind===B.Kind.Video&&t.width>0&&(this.dimensions={width:t.width,height:t.height},this.simulcasted=t.simulcast),this.encryption=t.encryption,this.trackInfo=t,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:t}))}}(function(e){(function(t){t.Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed"})(e.SubscriptionStatus||(e.SubscriptionStatus={})),function(t){t.Allowed="allowed",t.NotAllowed="not_allowed"}(e.PermissionStatus||(e.PermissionStatus={}))})(hi||(hi={}));class Wu extends hi{get isUpstreamPaused(){var t;return(t=this.track)===null||t===void 0?void 0:t.isUpstreamPaused}constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(he.Ended)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&this.track.off(he.Ended,this.handleTrackEnded),super.setTrack(t),t&&t.on(he.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 M(this,void 0,void 0,function*(){var t;return(t=this.track)===null||t===void 0?void 0:t.mute()})}unmute(){return M(this,void 0,void 0,function*(){var t;return(t=this.track)===null||t===void 0?void 0:t.unmute()})}pauseUpstream(){return M(this,void 0,void 0,function*(){var t;yield(t=this.track)===null||t===void 0?void 0:t.pauseUpstream()})}resumeUpstream(){return M(this,void 0,void 0,function*(){var t;yield(t=this.track)===null||t===void 0?void 0:t.resumeUpstream()})}getTrackFeatures(){var t;if(Qn(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(Ht.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(Ht.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(Ht.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(Ht.TF_STEREO),!((t=this.options)===null||t===void 0)&&t.dtx||i.add(Ht.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ht.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function gc(e,t){return M(this,void 0,void 0,function*(){e??(e={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=Ry(e);let o=s.audio,a=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),e.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},n=!0,o=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=Ey(s,Py,Ny),l=Zd(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(Wt.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Wt.userMediaPromiseMap.delete("audioinput"))),s.video&&(Wt.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Wt.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>M(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&Bi(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const w=c_(h,p,t);return w.kind===B.Kind.Video?w.source=B.Source.Camera:w.kind===B.Kind.Audio&&(w.source=B.Source.Microphone),w.mediaStream=d,Qn(w)&&i?yield w.setProcessor(i):ps(w)&&r&&(yield w.setProcessor(r)),w})))}catch(d){if(!n)throw d;return gc(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}})}function I_(e){return M(this,void 0,void 0,function*(){return(yield gc({audio:!1,video:!0}))[0]})}function M_(e){return M(this,void 0,void 0,function*(){return(yield gc({audio:!0,video:!1}))[0]})}var Li;(function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"})(Li||(Li={}));function O_(e){switch(e){case Us.EXCELLENT:return Li.Excellent;case Us.GOOD:return Li.Good;case Us.POOR:return Li.Poor;case Us.LOST:return Li.Lost;default:return Li.Unknown}}class By extends ii.EventEmitter{get logContext(){var t,n;return Object.assign({},(n=(t=this.loggerOptions)===null||t===void 0?void 0:t.loggerContextCb)===null||n===void 0?void 0:n.call(t))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(t=>t.isEncrypted)}get isAgent(){var t;return((t=this.permissions)===null||t===void 0?void 0:t.agent)||this.kind===no.AGENT}get isActive(){var t;return((t=this.participantInfo)===null||t===void 0?void 0:t.state)===Zr.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,r,s,o){let a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:no.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Li.Unknown,this.log=qe,this.log=xi((c=o==null?void 0:o.loggerName)!==null&&c!==void 0?c:Hn.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(t){for(const[,n]of this.trackPublications)if(n.source===t)return n}getTrackPublicationByName(t){for(const[,n]of this.trackPublications)if(n.trackName===t)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new zr,this.once(Q.Active,()=>{var t,n;(n=(t=this.activeFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var t;const n=this.getTrackPublication(B.Source.Camera);return!(!((t=n==null?void 0:n.isMuted)!==null&&t!==void 0)||t)}get isMicrophoneEnabled(){var t;const n=this.getTrackPublication(B.Source.Microphone);return!(!((t=n==null?void 0:n.isMuted)!==null&&t!==void 0)||t)}get isScreenShareEnabled(){return!!this.getTrackPublication(B.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(t){var n;return this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version?!1:(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===Zr.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Zr.ACTIVE&&this.emit(Q.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(Q.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(Q.ParticipantNameChanged,t)}_setAttributes(t){const n=LE(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(Q.AttributesChanged,n)}setPermissions(t){var n,i,r,s,o,a;const c=this.permissions,l=t.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||t.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||t.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||t.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||t.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||t.canSubscribeMetrics!==((a=this.permissions)===null||a===void 0?void 0:a.canSubscribeMetrics);return this.permissions=t,l&&this.emit(Q.ParticipantPermissionsChanged,c),l}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(Q.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=O_(t),n!==this._connectionQuality&&this.emit(Q.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var t,n;this.activeFuture&&((n=(t=this.activeFuture).reject)===null||n===void 0||n.call(t,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(t){this.audioContext=t,this.audioTrackPublications.forEach(n=>Qn(n.track)&&n.track.setAudioContext(t))}addTrackPublication(t){t.on(he.Muted,()=>{this.emit(Q.TrackMuted,t)}),t.on(he.Unmuted,()=>{this.emit(Q.TrackUnmuted,t)});const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case B.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case B.Kind.Video:this.videoTrackPublications.set(t.trackSid,t);break}}}function D_(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new U0({participantIdentity:(t=e.participantIdentity)!==null&&t!==void 0?t:"",participantSid:(n=e.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=e.allowAll)!==null&&i!==void 0?i:!1,trackSids:e.allowedTrackSids||[]})}const Fp=15e3;class L_ extends By{constructor(t,n,i,r,s){super(t,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=vn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new zr)},this.handleReconnected=()=>{var o,a;(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||a===void 0||a.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var o,a,c,l,u,d;this.reconnectFuture&&(this.reconnectFuture.promise.catch(h=>this.log.warn(h.message,this.logContext)),(a=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||a===void 0||a.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(c=this.signalConnectedFuture).reject)===null||l===void 0||l.call(c,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(d=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||d===void 0||d.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var a,c;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new zr),(c=(a=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(a)},this.handleSignalRequestResponse=o=>{const{requestId:a,reason:c,message:l}=o,u=this.pendingSignalRequests.get(a);u&&(c!==qd.OK&&u.reject(new dp(l,c)),this.pendingSignalRequests.delete(a))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let a=o.value.value,c=null,l=null;a.value.case==="payload"?c=a.value.value:a.value.case==="error"&&(l=_t.fromProto(a.value.value)),this.handleIncomingRpcResponse(a.requestId,c,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},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(o=>D_(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,a)=>{if(a===void 0&&(a=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),He(o)));return}this.engine.updateMuteStatus(o.sid,a)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),He(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),He(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const a=this.audioTrackPublications.get(o.sid);if(!a){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(a.trackSid,a.getTrackFeatures())},this.handleSubscribedQualityUpdate=o=>M(this,void 0,void 0,function*(){var a,c,l,u,d;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const h=this.videoTrackPublications.get(o.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!h.videoTrack)return;const f=yield h.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var g=!0,p=mi(f),v;v=yield p.next(),a=v.done,!a;g=!0){u=v.value,g=!1;const b=u;hE(b)&&(this.log.debug("publish ".concat(b," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),He(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,b,h.options))}}catch(b){c={error:b}}finally{try{!g&&!a&&(l=p.return)&&(yield l.call(p))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=o=>{const a=this.trackPublications.get(o.trackSid);if(!a){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(a.track)},this.handleTrackEnded=o=>M(this,void 0,void 0,function*(){if(o.source===B.Source.ScreenShare||o.source===B.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),He(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(di(o)||Pi(o))try{if(hn())try{const a=yield navigator==null?void 0:navigator.permissions.query({name:o.source===B.Source.Camera?"camera":"microphone"});if(a&&a.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),He(o))),a.onchange=()=>{a.state!=="denied"&&(o.isMuted||o.restartTrack(),a.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),He(o))),di(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),He(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,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!==vn.NONE}getTrackPublication(t){const n=super.getTrackPublication(t);if(n)return n}getTrackPublicationByName(t){const n=super.getTrackPublicationByName(t);if(n)return n}setupEngine(t){this.engine=t,this.engine.on(fe.RemoteMute,(n,i)=>{const r=this.trackPublications.get(n);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(fe.Connected,this.handleReconnected).on(fe.SignalConnected,this.handleSignalConnected).on(fe.SignalRestarted,this.handleReconnected).on(fe.SignalResumed,this.handleReconnected).on(fe.Restarting,this.handleReconnecting).on(fe.Resuming,this.handleReconnecting).on(fe.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(fe.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(fe.Disconnected,this.handleDisconnected).on(fe.SignalRequestResponse,this.handleSignalRequestResponse).on(fe.DataPacketReceived,this.handleDataPacket),this.signalConnectedFuture=void 0}setMetadata(t){return M(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:t})})}setName(t){return M(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:t})})}setAttributes(t){return M(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:t})})}requestMetadataUpdate(t){return M(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:s,attributes:o}=n;return function*(){return new Promise((a,c)=>M(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",o),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:a,reject:g=>{c(g),d=!0},values:{name:s,metadata:r,attributes:o}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(g=>{let[p,v]=g;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),a();return}yield pn(50)}c(new dp("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&c(d)}}))}()})}setCameraEnabled(t,n,i){return this.setTrackEnabled(B.Source.Camera,t,n,i)}setMicrophoneEnabled(t,n,i){return this.setTrackEnabled(B.Source.Microphone,t,n,i)}setScreenShareEnabled(t,n,i){return this.setTrackEnabled(B.Source.ScreenShare,t,n,i)}setPermissions(t){const n=this.permissions,i=super.setPermissions(t);return i&&n&&this.emit(Q.ParticipantPermissionsChanged,n),i}setE2EEEnabled(t){return M(this,void 0,void 0,function*(){this.encryptionType=t?vn.GCM:vn.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(t,n,i,r){return M(this,void 0,void 0,function*(){var s,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(t);if(n)if(a)yield a.unmute();else{let c;if(this.pendingPublishing.has(t)){const l=yield this.waitForPendingPublicationOfSource(t);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(t);try{switch(t){case B.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case B.Source.Microphone:c=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case B.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new gi(t)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(Q.MediaDevicesError,l,Uu(t)),this.pendingPublishing.delete(t),l}for(const l of c)t===B.Source.Microphone&&Qn(l)&&(r!=null&&r.preConnectBuffer)&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer());try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),He(d))),l.push(this.publishTrack(d,r));[a]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}finally{this.pendingPublishing.delete(t)}}else if(!(a!=null&&a.track)&&this.pendingPublishing.has(t)&&(a=yield this.waitForPendingPublicationOfSource(t),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),a&&a.track)if(t===B.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const c=this.getTrackPublication(B.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield a.mute();return a})}enableCameraAndMicrophone(){return M(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(B.Source.Camera)||this.pendingPublishing.has(B.Source.Microphone))){this.pendingPublishing.add(B.Source.Camera),this.pendingPublishing.add(B.Source.Microphone);try{const t=yield this.createTracks({audio:!0,video:!0});yield Promise.all(t.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(B.Source.Camera),this.pendingPublishing.delete(B.Source.Microphone)}}})}createTracks(t){return M(this,void 0,void 0,function*(){var n,i;t??(t={});const r=Ey(t,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield gc(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(a=>(Qn(a)&&(this.microphoneError=void 0,a.setAudioContext(this.audioContext),a.source=B.Source.Microphone,this.emit(Q.AudioStreamAcquired)),ps(a)&&(this.cameraError=void 0,a.source=B.Source.Camera),a))}catch(s){throw s instanceof Error&&(t.audio&&(this.microphoneError=s),t.video&&(this.cameraError=s)),s}})}createScreenTracks(t){return M(this,void 0,void 0,function*(){if(t===void 0&&(t={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Kd("getDisplayMedia not supported");t.resolution===void 0&&!yE()&&(t.resolution=Yd.h1080fps30.resolution);const n=ME(t),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new gi("no video track found");const s=new Ba(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=B.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const o=[s];if(i.getAudioTracks().length>0){this.emit(Q.AudioStreamAcquired);const a=new Ua(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=B.Source.ScreenShareAudio,o.push(a)}return o})}publishTrack(t,n){return M(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(t,n)})}publishOrRepublishTrack(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var a,c,l,u;di(i)&&i.setAudioContext(s.audioContext),yield(a=s.reconnectFuture)===null||a===void 0?void 0:a.promise,s.republishPromise&&!o&&(yield s.republishPromise),es(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case B.Source.Microphone:b="audioinput";break;case B.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Ua(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new Ba(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new gi("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),He(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,g=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;g&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),He(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!xE()&&s.roomOptions.e2ee&&(s.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({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,w)=>M(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==gt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:He(i)}));const S=setTimeout(()=>{w(new up("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(S);const k=yield this.publish(i,p,g);b(k)}else try{const S=yield this.publish(i,p,g);b(S)}catch(S){w(S)}}catch(S){w(S)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new zr),this.signalConnectedFuture.promise}hasPermissionsToPublish(t){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),He(t))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>FE(r)).includes(t.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),He(t))),!1)}publish(t,n,i){return M(this,void 0,void 0,function*(){var r,s,o,a,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(t))throw new up("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(N=>es(t)&&N.source===t.source)&&t.source!==B.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),He(t))),n.stopMicTrackOnMute&&Qn(t)&&(t.stopOnMute=!0),t.source===B.Source.ScreenShare&&as()&&(n.simulcast=!1),n.videoCodec==="av1"&&!mE()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!gE()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=Bu),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(N=>n.videoCodec===ka(N.mime))||(n.videoCodec=ka(this.enabledPublishVideoCodecs[0].mime)));const p=n.videoCodec;t.on(he.Muted,this.onTrackMuted),t.on(he.Unmuted,this.onTrackUnmuted),t.on(he.Ended,this.handleTrackEnded),t.on(he.UpstreamPaused,this.onTrackUpstreamPaused),t.on(he.UpstreamResumed,this.onTrackUpstreamResumed),t.on(he.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=[],b=!(!((r=n.dtx)!==null&&r!==void 0)||r),w=t.getSourceTrackSettings();w.autoGainControl&&v.push(Ht.TF_AUTO_GAIN_CONTROL),w.echoCancellation&&v.push(Ht.TF_ECHO_CANCELLATION),w.noiseSuppression&&v.push(Ht.TF_NOISE_SUPPRESSION),w.channelCount&&w.channelCount>1&&v.push(Ht.TF_STEREO),b&&v.push(Ht.TF_NO_DTX),di(t)&&t.hasPreConnectBuffer&&v.push(Ht.TF_PRECONNECT_BUFFER);const S=new xu({cid:t.mediaStreamTrack.id,name:n.name,type:B.kindToProto(t.kind),muted:t.isMuted,source:B.sourceToProto(t.source),disableDtx:b,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=n.red)!==null&&s!==void 0)||s),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:v});let k;if(t.kind===B.Kind.Video){let N={width:0,height:0};try{N=yield t.waitForDimensions()}catch{const R=(a=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&a!==void 0?a:io.h720.resolution;N={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{dims:N}))}S.width=N.width,S.height=N.height,Pi(t)&&(yi(p)&&(t.source===B.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),He(t))))),n.scalabilityMode=(c=n.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),S.simulcastCodecs=[new vu({codec:p,cid:t.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:Bu}),n.backupCodec&&p!==n.backupCodec.codec&&S.encryption===vn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),S.simulcastCodecs.push(new vu({codec:n.backupCodec.codec,cid:""})))),k=$u(t.source===B.Source.ScreenShare,S.width,S.height,n),S.layers=Op(S.width,S.height,k,yi(n.videoCodec))}else t.kind===B.Kind.Audio&&(k=[{maxBitrate:(l=n.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(d=(u=n.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Bt("cannot publish track when not connected");const x=()=>M(this,void 0,void 0,function*(){var N,y,R;if(!this.engine.pcManager)throw new Bt("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,k),Pi(t)&&((N=n.degradationPreference)!==null&&N!==void 0||(n.degradationPreference=y_(t)),t.setDegradationPreference(n.degradationPreference)),k)if(as()&&t.kind===B.Kind.Audio){let I;for(const L of this.engine.pcManager.publisher.getTransceivers())if(L.sender===t.sender){I=L;break}I&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:I,codec:"opus",maxbr:!((y=k[0])===null||y===void 0)&&y.maxBitrate?k[0].maxBitrate/1e3:0})}else t.codec&&yi(t.codec)&&(!((R=k[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:S.cid,codec:t.codec,maxbr:k[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const P=new Promise((N,y)=>M(this,void 0,void 0,function*(){var R;try{T=yield this.engine.addTrack(S),N(T)}catch(I){t.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch(L=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{error:L}))})),y(I)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([P,x()]))[0];else{T=yield P;let N;if(T.codecs.forEach(y=>{N===void 0&&(N=y.mimeType)}),N&&t.kind===B.Kind.Video){const y=ka(N);y!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{codec:y})),n.videoCodec=y,k=$u(t.source===B.Source.ScreenShare,S.width,S.height,n))}yield x()}const A=new Wu(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(A.options=n,t.sid=T.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:k,trackInfo:T})),Pi(t)?t.startMonitor(this.engine.client):di(t)&&t.startMonitor(),this.addTrackPublication(A),this.emit(Q.LocalTrackPublished,A),di(t)&&T.audioFeatures.includes(Ht.TF_PRECONNECT_BUFFER)){const N=t.getPreConnectBuffer();this.on(Q.LocalTrackSubscribed,y=>{if(y.trackSid===T.sid){if(!t.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),He(t))),t.stopPreConnectBuffer()}}),N&&new Promise((R,I)=>M(this,void 0,void 0,function*(){var L,U,K,ue,se,z;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),He(t)));const Y=setTimeout(()=>{I(new Error("agent not active within 10 seconds"))},1e4),E=yield this.waitUntilActiveAgentPresent();clearTimeout(Y),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),He(t)));const J=yield this.streamBytes({name:"preconnect-buffer",mimeType:"audio/opus",topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[E.identity],attributes:{trackId:A.trackSid,sampleRate:String((se=w.sampleRate)!==null&&se!==void 0?se:"48000"),channels:String((z=w.channelCount)!==null&&z!==void 0?z:"1")}});try{for(var H=!0,C=mi(N),W;W=yield C.next(),L=W.done,!L;H=!0){ue=W.value,H=!1;const ne=ue;yield J.write(ne)}}catch(ne){U={error:ne}}finally{try{!H&&!L&&(K=C.return)&&(yield K.call(C))}finally{if(U)throw U.error}}yield J.close(),R()}catch(Y){I(Y)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),He(t)))}).catch(R=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),He(t)),{error:R}))})}return A})}get isLocal(){return!0}publishAdditionalCodecForTrack(t,n,i){return M(this,void 0,void 0,function*(){var r;if(this.encryptionType!==vn.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===t&&(s=f)}),!s)throw new gi("track is not published");if(!Pi(t))throw new gi("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),a=m_(t,n,o);if(!a){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),He(t)));return}const c=t.addSimulcastTrack(n,a);if(!c)return;const l=new xu({cid:c.mediaStreamTrack.id,type:B.kindToProto(t.kind),muted:t.isMuted,source:B.sourceToProto(t.source),sid:t.sid,simulcastCodecs:[{codec:o.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Op(l.width,l.height,a),!this.engine||this.engine.isClosed)throw new Bt("cannot publish track when not connected");const u=()=>M(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(t,c,o,a),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(n," for track ").concat(t.sid),Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:h}))})}unpublishTrack(t,n){return M(this,void 0,void 0,function*(){var i,r;if(es(t)){const l=this.pendingPublishPromises.get(t);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),He(t))),yield l)}const s=this.getPublicationForTrack(t),o=s?He(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}t=s.track,t.off(he.Muted,this.onTrackMuted),t.off(he.Unmuted,this.onTrackUnmuted),t.off(he.Ended,this.handleTrackEnded),t.off(he.UpstreamPaused,this.onTrackUpstreamPaused),t.off(he.UpstreamResumed,this.onTrackUpstreamResumed),t.off(he.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ct.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),Pi(t)){for(const[,l]of t.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(a=!0),l.sender=void 0);t.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case B.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case B.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(Q.LocalTrackUnpublished,s),s.setTrack(void 0),a&&(yield this.engine.negotiate()),s})}unpublishTracks(t){return M(this,void 0,void 0,function*(){return(yield Promise.all(t.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,o)=>M(i,void 0,void 0,function*(){try{const a=[];this.trackPublications.forEach(c=>{c.track&&(n&&(c.options=Object.assign(Object.assign({},c.options),n)),a.push(c))}),yield Promise.all(a.map(c=>M(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==B.Source.ScreenShare&&l.source!==B.Source.ScreenShareAudio&&(di(l)||Pi(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(a){o(a)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(t){return M(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?Be.RELIABLE:Be.LOSSY,o=r.destinationIdentities,a=r.topic,c=new ln({kind:s,value:{case:"user",value:new x0({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:a})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(t,n){return M(this,void 0,void 0,function*(){const i=new ln({kind:Be.RELIABLE,value:{case:"sipDtmf",value:new k0({code:t,digit:n})}});yield this.engine.sendDataPacket(i,Be.RELIABLE)})}sendChatMessage(t,n){return M(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new ln({value:{case:"chatMessage",value:new fu(Object.assign(Object.assign({},i),{timestamp:yt.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Be.RELIABLE),this.emit(Q.ChatMessage,i),i})}editChatMessage(t,n){return M(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),r=new ln({value:{case:"chatMessage",value:new fu(Object.assign(Object.assign({},i),{timestamp:yt.parse(i.timestamp),editTimestamp:yt.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Be.RELIABLE),this.emit(Q.ChatMessage,i),i})}sendText(t,n){return M(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(t).byteLength,a=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(a?a.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const g=c.reduce((p,v)=>p+v,0);(f=n==null?void 0:n.onProgress)===null||f===void 0||f.call(n,g)},u=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:a,attributes:n==null?void 0:n.attributes});return yield u.write(t),l(1,0),yield u.close(),n!=null&&n.attachments&&a&&(yield Promise.all(n.attachments.map((d,h)=>M(this,void 0,void 0,function*(){return this._sendFile(a[h],d,{topic:n.topic,mimeType:d.type,onProgress:f=>{l(f,h+1)}})})))),u.info})}streamText(t){return M(this,void 0,void 0,function*(){var n,i;const r=(n=t==null?void 0:t.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=t==null?void 0:t.topic)!==null&&i!==void 0?i:"",size:t==null?void 0:t.totalSize,attributes:t==null?void 0:t.attributes},o=new mu({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:ir(s.timestamp),totalLength:ir(t==null?void 0:t.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new I0({version:t==null?void 0:t.version,attachedStreamIds:t==null?void 0:t.attachedStreamIds,replyToStreamId:t==null?void 0:t.replyToStreamId,operationType:(t==null?void 0:t.type)==="update"?pu.UPDATE:pu.CREATE})}}),a=t==null?void 0:t.destinationIdentities,c=new ln({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Be.RELIABLE);let l=0;const u=this,d=new WritableStream({write(g){return M(this,void 0,void 0,function*(){for(const p of NE(g,Fp)){yield u.engine.waitForBufferStatusLow(Be.RELIABLE);const v=new gu({content:p,streamId:r,chunkIndex:ir(l)}),b=new ln({destinationIdentities:a,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,Be.RELIABLE),l+=1}})},close(){return M(this,void 0,void 0,function*(){const g=new bu({streamId:r}),p=new ln({destinationIdentities:a,value:{case:"streamTrailer",value:g}});yield u.engine.sendDataPacket(p,Be.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>M(this,void 0,void 0,function*(){yield f.close()});u.engine.once(fe.Closing,h);const f=new R_(d,s,()=>this.engine.off(fe.Closing,h));return f})}sendFile(t,n){return M(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,t,n),{id:i}})}_sendFile(t,n,i){return M(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:t,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:a,value:c}=yield o.read();if(a)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(t){return M(this,void 0,void 0,function*(){var n,i,r,s,o;const a=(n=t==null?void 0:t.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=t==null?void 0:t.destinationIdentities,l={id:a,mimeType:(i=t==null?void 0:t.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=t==null?void 0:t.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:t==null?void 0:t.attributes,size:t==null?void 0:t.totalSize,name:(s=t==null?void 0:t.name)!==null&&s!==void 0?s:"unknown"},u=new mu({totalLength:ir((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:a,topic:l.topic,timestamp:ir(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new M0({name:l.name})}}),d=new ln({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,Be.RELIABLE);let h=0;const f=new dn,g=this.engine,p=this.log,v=new WritableStream({write(w){return M(this,void 0,void 0,function*(){const S=yield f.lock();let k=0;try{for(;k<w.byteLength;){const x=w.slice(k,k+Fp);yield g.waitForBufferStatusLow(Be.RELIABLE);const T=new ln({destinationIdentities:c,value:{case:"streamChunk",value:new gu({content:x,streamId:a,chunkIndex:ir(h)})}});yield g.sendDataPacket(T,Be.RELIABLE),h+=1,k+=x.byteLength}}finally{S()}})},close(){return M(this,void 0,void 0,function*(){const w=new bu({streamId:a}),S=new ln({destinationIdentities:c,value:{case:"streamTrailer",value:w}});yield g.sendDataPacket(S,Be.RELIABLE)})},abort(w){p.error("Sink error:",w)}});return new A_(v,l)})}performRpc(t){return M(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:s,payload:o,responseTimeout:a=1e4}=n;return function*(){return new Promise((l,u)=>M(i,void 0,void 0,function*(){var d,h,f,g;if(nh(o)>Iy){u(_t.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||h===void 0)&&h.version&&br((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){u(_t.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,o,a-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),u(_t.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),u(_t.builtIn("RESPONSE_TIMEOUT"))},a);this.pendingResponses.set(p,{resolve:(w,S)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),S?u(S):l(w??"")},participantIdentity:r})}))}()})}registerRpcMethod(t,n){this.rpcHandlers.has(t)&&this.log.warn("you're overriding the RPC handler for method ".concat(t,", in the future this will throw an error")),this.rpcHandlers.set(t,n)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}setTrackSubscriptionPermissions(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=t,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(t){const n=this.pendingAcks.get(t);n?(n.resolve(),this.pendingAcks.delete(t)):console.error("Ack received for unexpected RPC request",t)}handleIncomingRpcResponse(t,n,i){const r=this.pendingResponses.get(t);r?(r.resolve(n,i),this.pendingResponses.delete(t)):console.error("Response received for unexpected RPC request",t)}publishRpcRequest(t,n,i,r,s){return M(this,void 0,void 0,function*(){const o=new ln({destinationIdentities:[t],kind:Be.RELIABLE,value:{case:"rpcRequest",value:new S0({id:n,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,Be.RELIABLE)})}handleParticipantDisconnected(t){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===t&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===t&&(r(null,_t.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(t){this.enabledPublishVideoCodecs=t.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(t){return super.updateInfo(t)?(t.tracks.forEach(n=>{var i,r;const s=this.trackPublications.get(n.sid);if(s){const o=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),He(s)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(t){var n,i,r,s;this.firstActiveAgent=t,t&&!this.firstActiveAgent&&(this.firstActiveAgent=t),t?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,t):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new zr),this.activeAgentFuture.promise)}getPublicationForTrack(t){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(t instanceof MediaStreamTrack?(di(r)||Pi(r))&&r.mediaStreamTrack===t&&(n=i):t===r&&(n=i))}),n}waitForPendingPublicationOfSource(t){return M(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[o]=s;return o.source===t});if(r)return r[1];yield pn(20)}})}}class Va extends hi{constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Pn.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(he.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const r=new hc({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new E0({participantSid:"",trackSids:[this.trackSid]})]});this.emit(he.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?hi.SubscriptionStatus.Unsubscribed:super.isSubscribed?hi.SubscriptionStatus.Subscribed:hi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?hi.PermissionStatus.Allowed:hi.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(t){!this.isManualOperationAllowed()||this.disabled===!t||(this.disabled=!t,this.emitTrackUpdate())}setVideoQuality(t){!this.isManualOperationAllowed()||this.currentVideoQuality===t||(this.currentVideoQuality=t,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(t){var n,i;this.isManualOperationAllowed()&&(((n=this.videoDimensions)===null||n===void 0?void 0:n.width)===t.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===t.height||(sl(this.track)&&(this.videoDimensions=t),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(t){this.isManualOperationAllowed()&&sl(this.track)&&this.fps!==t&&(this.fps=t,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==t&&(r&&(r.off(he.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(he.VisibilityChanged,this.handleVisibilityChange),r.off(he.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(he.Unsubscribed,r)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(he.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(he.VisibilityChanged,this.handleVisibilityChange),t.on(he.Ended,this.handleEnded),this.emit(he.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=t,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(t){this.emit(he.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?he.Muted:he.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(he.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(he.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return this.kind===B.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return sl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new O0({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(t.width=Math.ceil(this.videoDimensions.width),t.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?t.quality=this.currentVideoQuality:t.quality=Pn.HIGH,this.emit(he.UpdateSettings,t)}}class $a extends By{static fromParticipantInfo(t,n,i){return new $a(t,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(t,n,i,r,s,o,a){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:no.STANDARD;super(n,i||"",r,s,o,a,c),this.signalClient=t,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(he.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),He(t))),this.signalClient.sendUpdateTrackSettings(n)}),t.on(he.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),t.on(he.SubscriptionPermissionChanged,n=>{this.emit(Q.TrackSubscriptionPermissionChanged,t,n)}),t.on(he.SubscriptionStatusChanged,n=>{this.emit(Q.TrackSubscriptionStatusChanged,t,n)}),t.on(he.Subscribed,n=>{this.emit(Q.TrackSubscribed,n,t)}),t.on(he.Unsubscribed,n=>{this.emit(Q.TrackUnsubscribed,n,t)}),t.on(he.SubscriptionFailed,n=>{this.emit(Q.TrackSubscriptionFailed,t.trackSid,n)})}getTrackPublication(t){const n=super.getTrackPublication(t);if(n)return n}getTrackPublicationByName(t){const n=super.getTrackPublicationByName(t);if(n)return n}setVolume(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:B.Source.Microphone;this.volumeMap.set(n,t);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(t)}getVolume(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:B.Source.Microphone;const n=this.getTrackPublication(t);return n&&n.track?n.track.getVolume():this.volumeMap.get(t)}addSubscribedMediaTrack(t,n,i,r,s,o){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach(u=>{!a&&t.kind===u.kind.toString()&&(a=u)}),!a){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(Q.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(t,n,i,r,s,o-1)},150);return}if(t.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),He(a))),this.emit(Q.TrackSubscriptionFailed,n);return}const c=t.kind==="video";let l;return c?l=new P_(t,n,r,s):l=new Uy(t,n,r,this.audioContext,this.audioOutput),l.source=a.source,l.isMuted=a.isMuted,l.setMediaStream(i),l.start(),a.setTrack(l),this.volumeMap.has(a.source)&&Fu(l)&&Qn(l)&&l.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(t){return this.trackPublications.get(t)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach(r=>{var s,o;let a=this.getTrackPublicationBySid(r.sid);if(a)a.updateInfo(r);else{const c=B.kindFromProto(r.type);if(!c)return;a=new Va(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),a.updateInfo(r),i.set(r.sid,a);const l=Array.from(this.trackPublications.values()).find(u=>u.source===(a==null?void 0:a.source));l&&a.source!==B.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(a.source),Object.assign(Object.assign({},this.logContext),{oldTrack:He(l),newTrack:He(a)})),this.addTrackPublication(a)}n.set(r.sid,a)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),He(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(Q.TrackPublished,r)}),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case B.Kind.Audio:this.audioTrackPublications.delete(t);break;case B.Kind.Video:this.videoTrackPublications.delete(t);break}n&&this.emit(Q.TrackUnpublished,i)}setAudioOutput(t){return M(this,void 0,void 0,function*(){this.audioOutput=t;const n=[];this.audioTrackPublications.forEach(i=>{var r;Qn(i.track)&&Fu(i.track)&&n.push(i.track.setSinkId((r=t.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:t,args:i})),super.emit(t,...i)}}var $e;(function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"})($e||($e={}));const F_=4*1e3;class vi extends ii.EventEmitter{constructor(t){var n,i,r,s;if(super(),n=this,this.state=$e.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=qe,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=(o,a,c)=>M(this,void 0,void 0,function*(){var l;if(!bE())throw ni()?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 u=yield this.disconnectLock.lock();if(this.state===$e.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState($e.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==o&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Du(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new zu(o,a):this.regionUrlProvider.updateToken(a),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,g,p)=>M(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,u==null||u();try{yield this.attemptConnection(p??o,a,c,w),this.abortController=void 0,f()}catch(S){if(this.regionUrlProvider&&S instanceof ut&&S.reason!==Ge.Cancelled&&S.reason!==Ge.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(x){if(x instanceof ut&&(x.status===401||x.reason===Ge.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(x);return}}k&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(S.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield d(f,g,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,xp(S)),g(S))}else{let k=Vn.UNKNOWN_REASON;S instanceof ut&&(k=xp(S)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),g(S)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new zr((f,g)=>{d(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,a,c,l,u,d)=>M(this,void 0,void 0,function*(){var h,f,g;const p=yield c.join(o,a,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},d.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[w,S]=b;return"".concat(w,": ").concat(S)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(g=p.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new nE("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=o=>{const a=o.participant;if(this.localParticipant.sid=a.sid,this.localParticipant.identity=a.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([a,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,a,c,l)=>M(this,void 0,void 0,function*(){var u,d;this.state===$e.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},th),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,a,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(j.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new ut("could not establish signal connection",Ge.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof ut&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ut("Connection attempt aborted",Ge.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}hn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),hn()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState($e.Connected),this.emit(j.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var o=arguments.length,a=new Array(o),c=0;c<o;c++)a[c]=arguments[c];return M(n,[...a],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,g;const p=yield l.disconnectLock.lock();try{if(l.state===$e.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===$e.Connecting||l.state===$e.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(d=l.abortController)===null||d===void 0||d.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new ut("Client initiated disconnect",Ge.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(u,Vn.CLIENT_INITIATED),l.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>M(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>M(this,void 0,void 0,function*(){const o=[],a=kn();if(a&&a.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const u=rl();u.enabled=!0;const d=new MediaStream([u]);l.srcObject=d,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(j.Disconnected,()=>{l==null||l.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>M(this,void 0,void 0,function*(){const o=[];for(const a of this.remoteParticipants.values())a.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(a=>a.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(a=>{a.name==="NotAllowedError"?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 o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState($e.Reconnecting)&&this.emit(j.Reconnecting)},this.handleSignalRestarted=o=>M(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(a){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:a}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState($e.Connected),this.emit(j.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(a=>{var c;if(a.identity===this.localParticipant.identity){this.localParticipant.updateInfo(a);return}a.identity===""&&(a.identity=(c=this.sidToIdentity.get(a.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(a.identity);a.state===Zr.DISCONNECTED?this.handleParticipantDisconnected(a.identity,l):l=this.getOrCreateParticipant(a.identity,a)})},this.handleActiveSpeakersUpdate=o=>{const a=[],c={};o.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),a.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),a.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=a,this.emitWhenConnected(j.ActiveSpeakersChanged,a)},this.handleSpeakersChanged=o=>{const a=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||a.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?a.set(l.sid,u):a.delete(l.sid))});const c=Array.from(a.values());c.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(j.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(a=>{const c=this.getRemoteParticipantBySid(a.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(a.trackSid);if(!l||!l.track)return;const u=B.streamStateFromProto(a.state);u!==l.track.streamState&&(l.track.streamState=u,c.emit(Q.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(j.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const a=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);c&&c.setSubscriptionError(o.err)},this.handleDataPacket=o=>{const a=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(a,o.value.value,o.kind);else if(o.value.case==="transcription")this.handleTranscription(a,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(a,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(a,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,a);else if(o.value.case==="streamHeader")this.handleStreamHeader(o.value.value,o.participantIdentity);else if(o.value.case==="streamChunk")this.handleStreamChunk(o.value.value);else if(o.value.case==="streamTrailer")this.handleStreamTrailer(o.value.value);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,a,c)=>{this.emit(j.DataReceived,a.payload,o,c,a.topic),o==null||o.emit(Q.DataReceived,a.payload,c)},this.handleSipDtmf=(o,a)=>{this.emit(j.SipDTMFReceived,a,o),o==null||o.emit(Q.SipDTMFReceived,a)},this.bufferedSegments=new Map,this.handleTranscription=(o,a)=>{const c=a.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(a.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(a.trackId),u=_E(a,this.transcriptionReceivedTimes);l==null||l.emit(he.TranscriptionReceived,u),c==null||c.emit(Q.TranscriptionReceived,u,l),this.emit(j.TranscriptionReceived,u,c,l)},this.handleChatMessage=(o,a)=>{const c=RE(a);this.emit(j.ChatMessage,c,o)},this.handleMetrics=(o,a)=>{this.emit(j.MetricsReceived,o,a)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(j.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(j.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(j.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(j.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>M(this,void 0,void 0,function*(){var o;((o=kn())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(j.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const a=this.roomInfo;this.roomInfo=o,a&&a.metadata!==o.metadata&&this.emitWhenConnected(j.RoomMetadataChanged,o.metadata),(a==null?void 0:a.activeRecording)!==o.activeRecording&&this.emitWhenConnected(j.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(a=>{if(a.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(a.quality);return}const c=this.getRemoteParticipantBySid(a.participantSid);c&&c.setConnectionQuality(a.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(j.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(j.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(j.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(j.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(j.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var a;(a=o==null?void 0:o.onPublish)===null||a===void 0||a.call(o,this)},this.onLocalTrackPublished=o=>M(this,void 0,void 0,function*(){var a,c,l,u,d,h;(a=o.track)===null||a===void 0||a.on(he.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.on(he.Restarted,this.onLocalTrackRestarted),(d=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(j.LocalTrackPublished,o,this.localParticipant),di(o.track)&&(yield o.track.checkForSilence())&&this.emit(j.LocalAudioSilenceDetected,o);const f=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Uu(o.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(j.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=o=>{var a,c;(a=o.track)===null||a===void 0||a.off(he.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=o.track)===null||c===void 0||c.off(he.Restarted,this.onLocalTrackRestarted),this.emit(j.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>M(this,void 0,void 0,function*(){const a=yield o.getDeviceId(!1),c=Uu(o.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(a," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,a),this.emit(j.ActiveDeviceChanged,c,a))}),this.onLocalConnectionQualityChanged=o=>{this.emit(j.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,a)=>{this.emit(j.MediaDevicesError,o,a)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(j.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(j.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},e_),t),this.log=xi((i=this.options.loggerName)!==null&&i!==void 0?i:Hn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Py),t==null?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Ny),t==null?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},QE),t==null?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new dn,this.localParticipant=new L_("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Bi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Bi(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Bi(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),hn()){const o=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),vi.cleanupRegistry&&vi.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new TypeError('A text stream handler for topic "'.concat(t,'" has already been set.'));this.textStreamHandlers.set(t,n)}unregisterTextStreamHandler(t){this.textStreamHandlers.delete(t)}registerByteStreamHandler(t,n){if(this.byteStreamHandlers.has(t))throw new TypeError('A byte stream handler for topic "'.concat(t,'" has already been set.'));this.byteStreamHandlers.set(t,n)}unregisterByteStreamHandler(t){this.byteStreamHandlers.delete(t)}registerRpcMethod(t,n){if(this.rpcHandlers.has(t))throw Error("RPC handler already registered for method ".concat(t,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(t,n)}unregisterRpcMethod(t){this.rpcHandlers.delete(t)}handleIncomingRpcRequest(t,n,i,r,s,o){return M(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(t,n),o!==1){yield this.engine.publishRpcResponse(t,n,null,_t.builtIn("UNSUPPORTED_VERSION"));return}const a=this.rpcHandlers.get(i);if(!a){yield this.engine.publishRpcResponse(t,n,null,_t.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield a({requestId:n,callerIdentity:t,payload:r,responseTimeout:s});nh(u)>Iy?(c=_t.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof _t?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=_t.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(t,n,l,c)})}setE2EEEnabled(t){return M(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(t)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(t,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var t;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new jE(this.options.e2ee),this.e2eeManager.on(Fi.ParticipantEncryptionStatusChanged,(n,i)=>{PE(i)&&(this.isE2EEEnabled=n),this.emit(j.ParticipantEncryptionStatusChanged,n,i)}),this.e2eeManager.on(Fi.EncryptionError,n=>this.emit(j.EncryptionError,n)),(t=this.e2eeManager)===null||t===void 0||t.setup(this))}get logContext(){var t;return{room:this.name,roomID:(t=this.roomInfo)===null||t===void 0?void 0:t.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return M(this,void 0,void 0,function*(){return this.state===$e.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((t,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(fe.RoomUpdate,i),t(r.sid))};this.engine.on(fe.RoomUpdate,i),this.once(j.Disconnected,()=>{this.engine.off(fe.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.name)!==null&&n!==void 0?n:""}get metadata(){var t;return(t=this.roomInfo)===null||t===void 0?void 0:t.metadata}get numParticipants(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var t,n;return(n=(t=this.roomInfo)===null||t===void 0?void 0:t.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new S_(this.options),this.engine.on(fe.ParticipantUpdate,this.handleParticipantUpdates).on(fe.RoomUpdate,this.handleRoomUpdate).on(fe.SpeakersChanged,this.handleSpeakersChanged).on(fe.StreamStateChanged,this.handleStreamStateUpdate).on(fe.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(fe.SubscriptionError,this.handleSubscriptionError).on(fe.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(fe.MediaTrackAdded,(t,n,i)=>{this.onTrackAdded(t,n,i)}).on(fe.Disconnected,t=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t)}).on(fe.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(fe.DataPacketReceived,this.handleDataPacket).on(fe.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState($e.SignalReconnecting)&&this.emit(j.SignalReconnecting)}).on(fe.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState($e.Connected)&&this.emit(j.Reconnected)}).on(fe.SignalResumed,()=>{this.bufferedEvents=[],(this.state===$e.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(fe.Restarting,this.handleRestarting).on(fe.SignalRestarted,this.handleSignalRestarted).on(fe.Offline,()=>{this.setAndEmitConnectionState($e.Reconnecting)&&this.emit(j.Reconnecting)}).on(fe.DCBufferStatusChanged,(t,n)=>{this.emit(j.DCBufferStatusChanged,t,n)}).on(fe.LocalTrackSubscribed,t=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===t});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(Q.LocalTrackSubscribed,n),this.emitWhenConnected(j.LocalTrackSubscribed,n,this.localParticipant)}).on(fe.RoomMoved,t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(j.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Wt.getInstance().getDevices(t,n)}prepareConnection(t,n){return M(this,void 0,void 0,function*(){if(this.state===$e.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(Du(new URL(t))&&n){this.regionUrlProvider=new zu(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===$e.Disconnected&&(this.regionUrl=i,yield fetch(Lu(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Lu(t),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(t){return this.localParticipant.identity===t?this.localParticipant:this.remoteParticipants.get(t)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(t,n){return M(this,void 0,void 0,function*(){let i=()=>{},r;switch(t){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Yn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Yn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Yn({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Yn({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":i=()=>M(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Yn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>M(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Yn({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":r=new Yn({scenario:{case:"switchCandidateProtocol",value:t==="force-tls"?2:1}}),i=()=>M(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new fc({reason:Vn.CLIENT_INITIATED,action:Xr.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Yn({scenario:{case:"subscriberBandwidth",value:ir(n)}});break;case"leave-full-reconnect":r=new Yn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(t){return this.localParticipant.activeDeviceMap.get(t)}switchActiveDevice(t,n){return M(this,arguments,void 0,function(i,r){var s=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var a,c,l,u,d,h,f;let g=!0,p=!1;const v=o?{exact:r}:r;if(i==="audioinput"){p=s.localParticipant.audioTrackPublications.size===0;const b=(a=s.getActiveDevice(i))!==null&&a!==void 0?a:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=v;const w=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===B.Source.Microphone);try{g=(yield Promise.all(w.map(k=>{var x;return(x=k.audioTrack)===null||x===void 0?void 0:x.setDeviceId(v)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=b,k}const S=w.some(k=>{var x,T;return(T=(x=k.track)===null||x===void 0?void 0:x.isMuted)!==null&&T!==void 0?T:!1});g&&S&&(p=!0)}else if(i==="videoinput"){p=s.localParticipant.videoTrackPublications.size===0;const b=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=v;const w=Array.from(s.localParticipant.videoTrackPublications.values()).filter(S=>S.source===B.Source.Camera);try{g=(yield Promise.all(w.map(S=>{var k;return(k=S.videoTrack)===null||k===void 0?void 0:k.setDeviceId(v)}))).every(S=>S===!0)}catch(S){throw s.options.videoCaptureDefaults.deviceId=b,S}}else if(i==="audiooutput"){if(p=!0,!Ou()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(l=yield Wt.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(f=s.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const b=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(w=>w.setAudioOutput({deviceId:r})))}catch(w){throw s.options.audioOutput.deviceId=b,w}}return p&&(s.localParticipant.activeDeviceMap.set(i,r),s.emit(j.ActiveDeviceChanged,i,r)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(Q.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Q.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Q.AttributesChanged,this.onLocalAttributesChanged).on(Q.TrackMuted,this.onLocalTrackMuted).on(Q.TrackUnmuted,this.onLocalTrackUnmuted).on(Q.LocalTrackPublished,this.onLocalTrackPublished).on(Q.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Q.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Q.MediaDevicesError,this.onMediaDevicesError).on(Q.AudioStreamAcquired,this.startAudio).on(Q.ChatMessage,this.onLocalChatMessageSent).on(Q.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var t;(t=this.engine)===null||t===void 0||t.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){if(this.state===$e.Connecting||this.state===$e.Reconnecting){const u=()=>{this.onTrackAdded(t,n,i),d()},d=()=>{this.off(j.Reconnected,u),this.off(j.Connected,u),this.off(j.Disconnected,d)};this.once(j.Reconnected,u),this.once(j.Connected,u),this.once(j.Disconnected,d);return}if(this.state===$e.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(t.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=pE(n.id),s=r[0];let o=r[1],a=t.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(t,a,n,i,l)}handleDisconnect(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==$e.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,o,a;r.track&&this.localParticipant.unpublishTrack(r.track,t),t?((s=r.track)===null||s===void 0||s.detach(),(o=r.track)===null||o===void 0||o.stop()):(a=r.track)===null||a===void 0||a.stopMonitor()}),this.localParticipant.off(Q.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Q.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Q.AttributesChanged,this.onLocalAttributesChanged).off(Q.TrackMuted,this.onLocalTrackMuted).off(Q.TrackUnmuted,this.onLocalTrackUnmuted).off(Q.LocalTrackPublished,this.onLocalTrackPublished).off(Q.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Q.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Q.MediaDevicesError,this.onMediaDevicesError).off(Q.AudioStreamAcquired,this.startAudio).off(Q.ChatMessage,this.onLocalChatMessageSent).off(Q.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&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),hn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState($e.Disconnected),this.emit(j.Disconnected,n)}}}handleParticipantDisconnected(t,n){var i;this.remoteParticipants.delete(t),n&&(n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(j.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleStreamHeader(t,n){return M(this,void 0,void 0,function*(){var i;if(t.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(t.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);return}let s;const o={id:t.streamId,name:(i=t.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:xa(t.timestamp),attributes:t.attributes},a=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new E_(o,a,xa(t.totalLength)),{identity:n})}else if(t.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(t.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);return}let s;const o={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes},a=new ReadableStream({start:c=>{s=c,this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now()})}});r(new __(o,a,xa(t.totalLength)),{identity:n})}})}handleStreamChunk(t){const n=this.byteStreamControllers.get(t.streamId);n&&t.content.length>0&&n.controller.enqueue(t);const i=this.textStreamControllers.get(t.streamId);i&&t.content.length>0&&i.controller.enqueue(t)}handleStreamTrailer(t){const n=this.textStreamControllers.get(t.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),t.attributes),n.controller.close(),this.textStreamControllers.delete(t.streamId));const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),i.controller.close(),this.byteStreamControllers.delete(t.streamId))}selectDefaultDevices(){return M(this,void 0,void 0,function*(){var t,n,i;const r=Wt.getInstance().previousDevices,s=yield Wt.getInstance().getDevices(void 0,!1),o=kn();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let c of s){const l=r.find(u=>u.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(j.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let c of a){const l=IE(c),u=this.localParticipant.getTrackPublication(l);if(u&&(!((t=u.track)===null||t===void 0)&&t.isUserProvided))continue;const d=s.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((n=r.filter(f=>f.kind===c)[0])===null||n===void 0?void 0:n.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,d[0].deviceId);continue}c==="audioinput"&&!mp()||c==="videoinput"||d.length>0&&!d.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!mp())&&(yield this.switchActiveDevice(c,d[0].deviceId))}})}acquireAudioContext(){return M(this,void 0,void 0,function*(){var t,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(t=Xd())!==null&&t!==void 0?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),pn(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(j.AudioPlaybackStatusChanged,i))})}createParticipant(t,n){var i;let r;return n?r=$a.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new $a(this.engine.client,"",t,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const r=this.remoteParticipants.get(t);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(j.ParticipantConnected,i),i.on(Q.TrackPublished,r=>{this.emitWhenConnected(j.TrackPublished,r,i)}).on(Q.TrackSubscribed,(r,s)=>{r.kind===B.Kind.Audio?(r.on(he.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(he.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===B.Kind.Video&&(r.on(he.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(he.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(j.TrackSubscribed,r,s,i)}).on(Q.TrackUnpublished,r=>{this.emit(j.TrackUnpublished,r,i)}).on(Q.TrackUnsubscribed,(r,s)=>{this.emit(j.TrackUnsubscribed,r,s,i)}).on(Q.TrackMuted,r=>{this.emitWhenConnected(j.TrackMuted,r,i)}).on(Q.TrackUnmuted,r=>{this.emitWhenConnected(j.TrackUnmuted,r,i)}).on(Q.ParticipantMetadataChanged,r=>{this.emitWhenConnected(j.ParticipantMetadataChanged,r,i)}).on(Q.ParticipantNameChanged,r=>{this.emitWhenConnected(j.ParticipantNameChanged,r,i)}).on(Q.AttributesChanged,r=>{this.emitWhenConnected(j.ParticipantAttributesChanged,r,i)}).on(Q.ConnectionQualityChanged,r=>{this.emitWhenConnected(j.ConnectionQualityChanged,r,i)}).on(Q.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(j.ParticipantPermissionsChanged,r,i)}).on(Q.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(j.TrackSubscriptionStatusChanged,r,s,i)}).on(Q.TrackSubscriptionFailed,(r,s)=>{this.emit(j.TrackSubscriptionFailed,r,i,s)}).on(Q.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(j.TrackSubscriptionPermissionChanged,r,s,i)}).on(Q.Active,()=>{this.emitWhenConnected(j.ParticipantActive,i),i.kind===no.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const t=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(t,n)}updateSubscriptions(){for(const t of this.remoteParticipants.values())for(const n of t.videoTrackPublications.values())n.isSubscribed&&AE(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(t){const n=this.sidToIdentity.get(t);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let t=0;this.connectionReconcileInterval=Zt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(t++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:t,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),t>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vn.STATE_MISMATCH))):t=0},F_)}clearConnectionReconcile(){this.connectionReconcileInterval&&Zt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t===this.state?!1:(this.state=t,this.emit(j.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(t=>{let[n,i]=t;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===$e.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===$e.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return M(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new dc({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:yt.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new pr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(j.SignalConnected),this.emit(j.Connected),this.setAndEmitConnectionState($e.Connected),r.video){const o=new Wu(B.Kind.Video,new Vr({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO,name:"video-dummy"}),new Ba(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:vp(160*((n=s.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Q.LocalTrackPublished,o)}if(r.audio){const o=new Wu(B.Kind.Audio,new Vr({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO}),new Ua(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rl(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(Q.LocalTrackPublished,o)}for(let o=0;o<s.count-1;o+=1){let a=new pr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Zr.ACTIVE,tracks:[],joinedAt:yt.parse(Date.now())});const c=this.getOrCreateParticipant(a.identity,a);if(s.video){const l=vp(160*((i=s.aspectRatios[o%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Vr({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,u]}if(s.audio){const l=rl(),u=new Vr({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Un.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),a.tracks=[...a.tracks,u]}c.updateInfo(a)}})}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(t!==j.ActiveSpeakersChanged&&t!==j.TranscriptionReceived){const s=Vy(i).filter(o=>o!==void 0);this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:s}))}return super.emit(t,...i)}}vi.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(e=>{e()});function Vy(e){return e.map(t=>{if(t)return Array.isArray(t)?Vy(t):typeof t=="object"?"logContext"in t?t.logContext:void 0:t})}var jn;(function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"})(jn||(jn={}));class Ki extends ii.EventEmitter{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=jn.IDLE,this.logs=[],this.options={},this.url=t,this.token=n,this.name=this.constructor.name,this.room=new vi(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return M(this,void 0,void 0,function*(){if(this.status!==jn.IDLE)throw Error("check is running already");this.setStatus(jn.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==jn.SKIPPED&&this.setStatus(this.isSuccess()?jn.SUCCESS:jn.FAILED),t&&t(),this.getInfo()})}isSuccess(){return!this.logs.some(t=>t.level==="error")}connect(t){return M(this,void 0,void 0,function*(){return this.room.state===$e.Connected?this.room:(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions),this.room)})}disconnect(){return M(this,void 0,void 0,function*(){this.room&&this.room.state!==$e.Disconnected&&(yield this.room.disconnect(),yield new Promise(t=>setTimeout(t,500)))})}skip(){this.setStatus(jn.SKIPPED)}switchProtocol(t){return M(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(j.Reconnecting,()=>{n=!0}),this.room.once(j.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(t)),yield new Promise(s=>setTimeout(s,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield pn(100)}throw new Error("Could not reconnect using ".concat(t," protocol after 10 seconds"))})}appendMessage(t){this.logs.push({level:"info",message:t}),this.emit("update",this.getInfo())}appendWarning(t){this.logs.push({level:"warning",message:t}),this.emit("update",this.getInfo())}appendError(t){this.logs.push({level:"error",message:t}),this.emit("update",this.getInfo())}setStatus(t){this.status=t,this.emit("update",this.getInfo())}get engine(){var t;return(t=this.room)===null||t===void 0?void 0:t.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class j_ extends Ki{get description(){return"Cloud regions"}perform(){return M(this,void 0,void 0,function*(){const t=new zu(this.url,this.token);if(!t.isCloud()){this.skip();return}const n=[],i=new Set;for(let s=0;s<3;s++){const o=yield t.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const a=yield this.checkCloudRegion(o);this.appendMessage("".concat(a.region," RTT: ").concat(a.rtt,"ms, duration: ").concat(a.duration,"ms")),n.push(a)}n.sort((s,o)=>(s.duration-o.duration)*.5+(s.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const t=super.getInfo();return t.data=this.bestStats,t}checkCloudRegion(t){return M(this,void 0,void 0,function*(){var n,i;yield this.connect(t),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,c=1e6/o,l="A".repeat(o),u=Date.now();for(let g=0;g<c;g++)yield s.write(l);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const fl=1e4;class U_ extends Ki{get description(){return"Connection via UDP vs TCP"}perform(){return M(this,void 0,void 0,function*(){const t=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=t,t.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(t.packetsLost-n.packetsLost)/t.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(fl/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(fl/1e3)*100).toFixed(2),"%"))})}getInfo(){const t=super.getInfo();return t.data=this.bestStats,t}checkConnectionProtocol(t){return M(this,void 0,void 0,function*(){yield this.connect(),t==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(s)};s();const a=n.captureStream(30).getVideoTracks()[0],l=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:t,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},d=setInterval(()=>M(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,fl)),clearInterval(d),a.stop(),n.remove(),yield this.disconnect(),u})}}class B_ extends Ki{get description(){return"Can publish audio"}perform(){return M(this,void 0,void 0,function*(){var t;const n=yield this.connect(),i=yield M_();if(yield _y(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,3e3));const s=yield(t=i.sender)===null||t===void 0?void 0:t.getStats();if(!s)throw new Error("Could not get RTCStats");let o=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(o=a.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class V_ extends Ki{get description(){return"Can publish video"}perform(){return M(this,void 0,void 0,function*(){var t;const n=yield this.connect(),i=yield I_();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(t=i.sender)===null||t===void 0?void 0:t.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(s+=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(t){return M(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(t.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,o,a,c;const l=document.createElement("canvas"),u=t.getSettings(),d=(o=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&o!==void 0?o:1280,h=(c=(a=u.height)!==null&&a!==void 0?a:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class $_ extends Ki{get description(){return"Resuming connection after interruption"}perform(){return M(this,void 0,void 0,function*(){var t;const n=yield this.connect();let i=!1,r=!1,s;const o=new Promise(l=>{setTimeout(l,5e3),s=l}),a=()=>{i=!0};n.on(j.SignalReconnecting,a).on(j.Reconnecting,a).on(j.Reconnected,()=>{r=!0,s(!0)}),(t=n.engine.client.ws)===null||t===void 0||t.close();const c=n.engine.client.onClose;if(c&&c(""),yield o,i){if(!r||n.state!==$e.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class z_ extends Ki{get description(){return"Can connect via TURN"}perform(){return M(this,void 0,void 0,function*(){var t,n;const i=new Jd,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,a=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(o=!0,a=!0):l.startsWith("turns:")&&(o=!0,a=!0,s=!0),l.startsWith("stun:")&&(a=!0);a?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class H_ extends Ki{get description(){return"Establishing WebRTC connection"}perform(){return M(this,void 0,void 0,function*(){let t=!1,n=!1;this.room.on(j.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const o=new RTCIceCandidate(r);let a="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(W_(o.address)?a+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(t=!0,a+=" (passive)"):o.protocol==="udp"&&(n=!0)),this.appendMessage(a)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),qe.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function W_(e){const t=e.split(".");if(t.length===4){if(t[0]==="10")return!0;if(t[0]==="192"&&t[1]==="168")return!0;if(t[0]==="172"){const n=parseInt(t[1],10);if(n>=16&&n<=31)return!0}}return!1}class q_ extends Ki{get description(){return"Connecting to signal connection via WebSocket"}perform(){return M(this,void 0,void 0,function*(){var t,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Jd;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((t=s.serverInfo)===null||t===void 0?void 0:t.edition)===R0.Cloud&&(!((n=s.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class Y4 extends ii.EventEmitter{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=t,this.token=n,this.options=i}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:jn.IDLE,name:"",description:""}),t}updateCheck(t,n){this.checkResults.set(t,n),this.emit("checkUpdate",t,n)}isSuccess(){return Array.from(this.checkResults.values()).every(t=>t.status!==jn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(t){return M(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new t(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(q_)})}checkWebRTC(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(H_)})}checkTURN(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(z_)})}checkReconnect(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck($_)})}checkPublishAudio(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(B_)})}checkPublishVideo(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(V_)})}checkConnectionProtocol(){return M(this,void 0,void 0,function*(){const t=yield this.createAndRunCheck(U_);if(t.data&&"protocol"in t.data){const n=t.data;this.options.protocol=n.protocol}return t})}checkCloudRegion(){return M(this,void 0,void 0,function*(){return this.createAndRunCheck(j_)})}}const sh=O.createContext({});function oh(e){const t=O.useRef(null);return t.current===null&&(t.current=e()),t.current}const ah=typeof window<"u",$y=ah?O.useLayoutEffect:O.useEffect,bc=O.createContext(null);function ch(e,t){e.indexOf(t)===-1&&e.push(t)}function lh(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const ki=(e,t,n)=>n>t?t:n<e?e:n;function qu(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let ms=()=>{},Si=()=>{};process.env.NODE_ENV!=="production"&&(ms=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(qu(t,n))},Si=(e,t,n)=>{if(!e)throw new Error(qu(t,n))});const wi={},zy=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Hy(e){return typeof e=="object"&&e!==null}const Wy=e=>/^0[^.\s]+$/u.test(e);function uh(e){let t;return()=>(t===void 0&&(t=e()),t)}const Nn=e=>e,G_=(e,t)=>n=>t(e(n)),go=(...e)=>e.reduce(G_),ro=(e,t,n)=>{const i=t-e;return i===0?1:(n-e)/i};class dh{constructor(){this.subscriptions=[]}add(t){return ch(this.subscriptions,t),()=>lh(this.subscriptions,t)}notify(t,n,i){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,i);else for(let s=0;s<r;s++){const o=this.subscriptions[s];o&&o(t,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const $n=e=>e*1e3,ei=e=>e/1e3;function qy(e,t){return t?e*(1e3/t):0}const jp=new Set;function hh(e,t,n){e||jp.has(t)||(console.warn(qu(t,n)),jp.add(t))}const Gy=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,K_=1e-7,Y_=12;function Z_(e,t,n,i,r){let s,o,a=0;do o=t+(n-t)/2,s=Gy(o,i,r)-e,s>0?n=o:t=o;while(Math.abs(s)>K_&&++a<Y_);return o}function bo(e,t,n,i){if(e===t&&n===i)return Nn;const r=s=>Z_(s,0,1,e,n);return s=>s===0||s===1?s:Gy(r(s),t,i)}const Ky=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Yy=e=>t=>1-e(1-t),Zy=bo(.33,1.53,.69,.99),fh=Yy(Zy),Xy=Ky(fh),Jy=e=>(e*=2)<1?.5*fh(e):.5*(2-Math.pow(2,-10*(e-1))),ph=e=>1-Math.sin(Math.acos(e)),Qy=Yy(ph),ev=Ky(ph),X_=bo(.42,0,1,1),J_=bo(0,0,.58,1),tv=bo(.42,0,.58,1),Q_=e=>Array.isArray(e)&&typeof e[0]!="number",nv=e=>Array.isArray(e)&&typeof e[0]=="number",Up={linear:Nn,easeIn:X_,easeInOut:tv,easeOut:J_,circIn:ph,circInOut:ev,circOut:Qy,backIn:fh,backInOut:Xy,backOut:Zy,anticipate:Jy},e1=e=>typeof e=="string",Bp=e=>{if(nv(e)){Si(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,i,r]=e;return bo(t,n,i,r)}else if(e1(e))return Si(Up[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),Up[e];return e},Uo=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function t1(e,t){let n=new Set,i=new Set,r=!1,s=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function c(u){o.has(u)&&(l.schedule(u),e()),u(a)}const l={schedule:(u,d=!1,h=!1)=>{const g=h&&r?n:i;return d&&o.add(u),g.has(u)||g.add(u),u},cancel:u=>{i.delete(u),o.delete(u)},process:u=>{if(a=u,r){s=!0;return}r=!0,[n,i]=[i,n],n.forEach(c),n.clear(),r=!1,s&&(s=!1,l.process(u))}};return l}const n1=40;function iv(e,t){let n=!1,i=!0;const r={delta:0,timestamp:0,isProcessing:!1},s=()=>n=!0,o=Uo.reduce((S,k)=>(S[k]=t1(s),S),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:h,render:f,postRender:g}=o,p=()=>{const S=wi.useManualTiming?r.timestamp:performance.now();n=!1,wi.useManualTiming||(r.delta=i?1e3/60:Math.max(Math.min(S-r.timestamp,n1),1)),r.timestamp=S,r.isProcessing=!0,a.process(r),c.process(r),l.process(r),u.process(r),d.process(r),h.process(r),f.process(r),g.process(r),r.isProcessing=!1,n&&t&&(i=!1,e(p))},v=()=>{n=!0,i=!0,r.isProcessing||e(p)};return{schedule:Uo.reduce((S,k)=>{const x=o[k];return S[k]=(T,P=!1,A=!1)=>(n||v(),x.schedule(T,P,A)),S},{}),cancel:S=>{for(let k=0;k<Uo.length;k++)o[Uo[k]].cancel(S)},state:r,steps:o}}const{schedule:vt,cancel:$i,state:Yt,steps:pl}=iv(typeof requestAnimationFrame<"u"?requestAnimationFrame:Nn,!0);let Sa;function i1(){Sa=void 0}const fn={now:()=>(Sa===void 0&&fn.set(Yt.isProcessing||wi.useManualTiming?Yt.timestamp:performance.now()),Sa),set:e=>{Sa=e,queueMicrotask(i1)}},rv=e=>t=>typeof t=="string"&&t.startsWith(e),mh=rv("--"),r1=rv("var(--"),gh=e=>r1(e)?s1.test(e.split("/*")[0].trim()):!1,s1=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,gs={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},so={...gs,transform:e=>ki(0,1,e)},Bo={...gs,default:1},Gs=e=>Math.round(e*1e5)/1e5,bh=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function o1(e){return e==null}const a1=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,yh=(e,t)=>n=>!!(typeof n=="string"&&a1.test(n)&&n.startsWith(e)||t&&!o1(n)&&Object.prototype.hasOwnProperty.call(n,t)),sv=(e,t,n)=>i=>{if(typeof i!="string")return i;const[r,s,o,a]=i.match(bh);return{[e]:parseFloat(r),[t]:parseFloat(s),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},c1=e=>ki(0,255,e),ml={...gs,transform:e=>Math.round(c1(e))},sr={test:yh("rgb","red"),parse:sv("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:i=1})=>"rgba("+ml.transform(e)+", "+ml.transform(t)+", "+ml.transform(n)+", "+Gs(so.transform(i))+")"};function l1(e){let t="",n="",i="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),i=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),i=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,i+=i,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const Gu={test:yh("#"),parse:l1,transform:sr.transform},yo=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Di=yo("deg"),ti=yo("%"),Me=yo("px"),u1=yo("vh"),d1=yo("vw"),Vp={...ti,parse:e=>ti.parse(e)/100,transform:e=>ti.transform(e*100)},Hr={test:yh("hsl","hue"),parse:sv("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:i=1})=>"hsla("+Math.round(e)+", "+ti.transform(Gs(t))+", "+ti.transform(Gs(n))+", "+Gs(so.transform(i))+")"},Dt={test:e=>sr.test(e)||Gu.test(e)||Hr.test(e),parse:e=>sr.test(e)?sr.parse(e):Hr.test(e)?Hr.parse(e):Gu.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?sr.transform(e):Hr.transform(e),getAnimatableNone:e=>{const t=Dt.parse(e);return t.alpha=0,Dt.transform(t)}},h1=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function f1(e){var t,n;return isNaN(e)&&typeof e=="string"&&(((t=e.match(bh))==null?void 0:t.length)||0)+(((n=e.match(h1))==null?void 0:n.length)||0)>0}const ov="number",av="color",p1="var",m1="var(",$p="${}",g1=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function oo(e){const t=e.toString(),n=[],i={color:[],number:[],var:[]},r=[];let s=0;const a=t.replace(g1,c=>(Dt.test(c)?(i.color.push(s),r.push(av),n.push(Dt.parse(c))):c.startsWith(m1)?(i.var.push(s),r.push(p1),n.push(c)):(i.number.push(s),r.push(ov),n.push(parseFloat(c))),++s,$p)).split($p);return{values:n,split:a,indexes:i,types:r}}function cv(e){return oo(e).values}function lv(e){const{split:t,types:n}=oo(e),i=t.length;return r=>{let s="";for(let o=0;o<i;o++)if(s+=t[o],r[o]!==void 0){const a=n[o];a===ov?s+=Gs(r[o]):a===av?s+=Dt.transform(r[o]):s+=r[o]}return s}}const b1=e=>typeof e=="number"?0:Dt.test(e)?Dt.getAnimatableNone(e):e;function y1(e){const t=cv(e);return lv(e)(t.map(b1))}const zi={test:f1,parse:cv,createTransformer:lv,getAnimatableNone:y1};function gl(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function v1({hue:e,saturation:t,lightness:n,alpha:i}){e/=360,t/=100,n/=100;let r=0,s=0,o=0;if(!t)r=s=o=n;else{const a=n<.5?n*(1+t):n+t-n*t,c=2*n-a;r=gl(c,a,e+1/3),s=gl(c,a,e),o=gl(c,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(s*255),blue:Math.round(o*255),alpha:i}}function za(e,t){return n=>n>0?t:e}const St=(e,t,n)=>e+(t-e)*n,bl=(e,t,n)=>{const i=e*e,r=n*(t*t-i)+i;return r<0?0:Math.sqrt(r)},x1=[Gu,sr,Hr],k1=e=>x1.find(t=>t.test(e));function zp(e){const t=k1(e);if(ms(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Hr&&(n=v1(n)),n}const Hp=(e,t)=>{const n=zp(e),i=zp(t);if(!n||!i)return za(e,t);const r={...n};return s=>(r.red=bl(n.red,i.red,s),r.green=bl(n.green,i.green,s),r.blue=bl(n.blue,i.blue,s),r.alpha=St(n.alpha,i.alpha,s),sr.transform(r))},Ku=new Set(["none","hidden"]);function S1(e,t){return Ku.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function w1(e,t){return n=>St(e,t,n)}function vh(e){return typeof e=="number"?w1:typeof e=="string"?gh(e)?za:Dt.test(e)?Hp:E1:Array.isArray(e)?uv:typeof e=="object"?Dt.test(e)?Hp:T1:za}function uv(e,t){const n=[...e],i=n.length,r=e.map((s,o)=>vh(s)(s,t[o]));return s=>{for(let o=0;o<i;o++)n[o]=r[o](s);return n}}function T1(e,t){const n={...e,...t},i={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(i[r]=vh(e[r])(e[r],t[r]));return r=>{for(const s in i)n[s]=i[s](r);return n}}function C1(e,t){const n=[],i={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const s=t.types[r],o=e.indexes[s][i[s]],a=e.values[o]??0;n[r]=a,i[s]++}return n}const E1=(e,t)=>{const n=zi.createTransformer(t),i=oo(e),r=oo(t);return i.indexes.var.length===r.indexes.var.length&&i.indexes.color.length===r.indexes.color.length&&i.indexes.number.length>=r.indexes.number.length?Ku.has(e)&&!r.values.length||Ku.has(t)&&!i.values.length?S1(e,t):go(uv(C1(i,r),r.values),n):(ms(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),za(e,t))};function dv(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?St(e,t,n):vh(e)(e,t)}const _1=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>vt.update(t,n),stop:()=>$i(t),now:()=>Yt.isProcessing?Yt.timestamp:fn.now()}},hv=(e,t,n=10)=>{let i="";const r=Math.max(Math.round(t/n),2);for(let s=0;s<r;s++)i+=Math.round(e(s/(r-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Ha=2e4;function xh(e){let t=0;const n=50;let i=e.next(t);for(;!i.done&&t<Ha;)t+=n,i=e.next(t);return t>=Ha?1/0:t}function R1(e,t=100,n){const i=n({...e,keyframes:[0,t]}),r=Math.min(xh(i),Ha);return{type:"keyframes",ease:s=>i.next(r*s).value/t,duration:ei(r)}}const A1=5;function fv(e,t,n){const i=Math.max(t-A1,0);return qy(n-e(i),t-i)}const xt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},yl=.001;function P1({duration:e=xt.duration,bounce:t=xt.bounce,velocity:n=xt.velocity,mass:i=xt.mass}){let r,s;ms(e<=$n(xt.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let o=1-t;o=ki(xt.minDamping,xt.maxDamping,o),e=ki(xt.minDuration,xt.maxDuration,ei(e)),o<1?(r=l=>{const u=l*o,d=u*e,h=u-n,f=Yu(l,o),g=Math.exp(-d);return yl-h/f*g},s=l=>{const d=l*o*e,h=d*n+n,f=Math.pow(o,2)*Math.pow(l,2)*e,g=Math.exp(-d),p=Yu(Math.pow(l,2),o);return(-r(l)+yl>0?-1:1)*((h-f)*g)/p}):(r=l=>{const u=Math.exp(-l*e),d=(l-n)*e+1;return-yl+u*d},s=l=>{const u=Math.exp(-l*e),d=(n-l)*(e*e);return u*d});const a=5/e,c=I1(r,s,a);if(e=$n(e),isNaN(c))return{stiffness:xt.stiffness,damping:xt.damping,duration:e};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:o*2*Math.sqrt(i*l),duration:e}}}const N1=12;function I1(e,t,n){let i=n;for(let r=1;r<N1;r++)i=i-e(i)/t(i);return i}function Yu(e,t){return e*Math.sqrt(1-t*t)}const M1=["duration","bounce"],O1=["stiffness","damping","mass"];function Wp(e,t){return t.some(n=>e[n]!==void 0)}function D1(e){let t={velocity:xt.velocity,stiffness:xt.stiffness,damping:xt.damping,mass:xt.mass,isResolvedFromDuration:!1,...e};if(!Wp(e,O1)&&Wp(e,M1))if(e.visualDuration){const n=e.visualDuration,i=2*Math.PI/(n*1.2),r=i*i,s=2*ki(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:xt.mass,stiffness:r,damping:s}}else{const n=P1(e);t={...t,...n,mass:xt.mass},t.isResolvedFromDuration=!0}return t}function Wa(e=xt.visualDuration,t=xt.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:i,restDelta:r}=n;const s=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:s},{stiffness:c,damping:l,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=D1({...n,velocity:-ei(n.velocity||0)}),g=h||0,p=l/(2*Math.sqrt(c*u)),v=o-s,b=ei(Math.sqrt(c/u)),w=Math.abs(v)<5;i||(i=w?xt.restSpeed.granular:xt.restSpeed.default),r||(r=w?xt.restDelta.granular:xt.restDelta.default);let S;if(p<1){const x=Yu(b,p);S=T=>{const P=Math.exp(-p*b*T);return o-P*((g+p*b*v)/x*Math.sin(x*T)+v*Math.cos(x*T))}}else if(p===1)S=x=>o-Math.exp(-b*x)*(v+(g+b*v)*x);else{const x=b*Math.sqrt(p*p-1);S=T=>{const P=Math.exp(-p*b*T),A=Math.min(x*T,300);return o-P*((g+p*b*v)*Math.sinh(A)+x*v*Math.cosh(A))/x}}const k={calculatedDuration:f&&d||null,next:x=>{const T=S(x);if(f)a.done=x>=d;else{let P=x===0?g:0;p<1&&(P=x===0?$n(g):fv(S,x,T));const A=Math.abs(P)<=i,N=Math.abs(o-T)<=r;a.done=A&&N}return a.value=a.done?o:T,a},toString:()=>{const x=Math.min(xh(k),Ha),T=hv(P=>k.next(x*P).value,x,30);return x+"ms "+T},toTransition:()=>{}};return k}Wa.applyToOptions=e=>{const t=R1(e,100,Wa);return e.ease=t.ease,e.duration=$n(t.duration),e.type="keyframes",e};function Zu({keyframes:e,velocity:t=0,power:n=.8,timeConstant:i=325,bounceDamping:r=10,bounceStiffness:s=500,modifyTarget:o,min:a,max:c,restDelta:l=.5,restSpeed:u}){const d=e[0],h={done:!1,value:d},f=A=>a!==void 0&&A<a||c!==void 0&&A>c,g=A=>a===void 0?c:c===void 0||Math.abs(a-A)<Math.abs(c-A)?a:c;let p=n*t;const v=d+p,b=o===void 0?v:o(v);b!==v&&(p=b-d);const w=A=>-p*Math.exp(-A/i),S=A=>b+w(A),k=A=>{const N=w(A),y=S(A);h.done=Math.abs(N)<=l,h.value=h.done?b:y};let x,T;const P=A=>{f(h.value)&&(x=A,T=Wa({keyframes:[h.value,g(h.value)],velocity:fv(S,A,h.value),damping:r,stiffness:s,restDelta:l,restSpeed:u}))};return P(0),{calculatedDuration:null,next:A=>{let N=!1;return!T&&x===void 0&&(N=!0,k(A),P(A)),x!==void 0&&A>=x?T.next(A-x):(!N&&k(A),h)}}}function L1(e,t,n){const i=[],r=n||wi.mix||dv,s=e.length-1;for(let o=0;o<s;o++){let a=r(e[o],e[o+1]);if(t){const c=Array.isArray(t)?t[o]||Nn:t;a=go(c,a)}i.push(a)}return i}function F1(e,t,{clamp:n=!0,ease:i,mixer:r}={}){const s=e.length;if(Si(s===t.length,"Both input and output ranges must be the same length","range-length"),s===1)return()=>t[0];if(s===2&&t[0]===t[1])return()=>t[1];const o=e[0]===e[1];e[0]>e[s-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=L1(t,i,r),c=a.length,l=u=>{if(o&&u<e[0])return t[0];let d=0;if(c>1)for(;d<e.length-2&&!(u<e[d+1]);d++);const h=ro(e[d],e[d+1],u);return a[d](h)};return n?u=>l(ki(e[0],e[s-1],u)):l}function j1(e,t){const n=e[e.length-1];for(let i=1;i<=t;i++){const r=ro(0,t,i);e.push(St(n,1,r))}}function U1(e){const t=[0];return j1(t,e.length-1),t}function B1(e,t){return e.map(n=>n*t)}function V1(e,t){return e.map(()=>t||tv).splice(0,e.length-1)}function Wr({duration:e=300,keyframes:t,times:n,ease:i="easeInOut"}){const r=Q_(i)?i.map(Bp):Bp(i),s={done:!1,value:t[0]},o=B1(n&&n.length===t.length?n:U1(t),e),a=F1(o,t,{ease:Array.isArray(r)?r:V1(t,r)});return{calculatedDuration:e,next:c=>(s.value=a(c),s.done=c>=e,s)}}const $1=e=>e!==null;function kh(e,{repeat:t,repeatType:n="loop"},i,r=1){const s=e.filter($1),a=r<0||t&&n!=="loop"&&t%2===1?0:s.length-1;return!a||i===void 0?s[a]:i}const z1={decay:Zu,inertia:Zu,tween:Wr,keyframes:Wr,spring:Wa};function pv(e){typeof e.type=="string"&&(e.type=z1[e.type])}class Sh{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const H1=e=>e/100;class wh extends Sh{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,r;const{motionValue:n}=this.options;n&&n.updatedAt!==fn.now()&&this.tick(fn.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(r=(i=this.options).onStop)==null||r.call(i))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;pv(t);const{type:n=Wr,repeat:i=0,repeatDelay:r=0,repeatType:s,velocity:o=0}=t;let{keyframes:a}=t;const c=n||Wr;process.env.NODE_ENV!=="production"&&c!==Wr&&Si(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),c!==Wr&&typeof a[0]!="number"&&(this.mixKeyframes=go(H1,dv(a[0],a[1])),a=[0,100]);const l=c({...t,keyframes:a});s==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...a].reverse(),velocity:-o})),l.calculatedDuration===null&&(l.calculatedDuration=xh(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+r,this.totalDuration=this.resolvedDuration*(i+1)-r,this.generator=l}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:i,totalDuration:r,mixKeyframes:s,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:f,type:g,onUpdate:p,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const b=this.currentTime-l*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?b<0:b>r;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let S=this.currentTime,k=i;if(d){const A=Math.min(this.currentTime,r)/a;let N=Math.floor(A),y=A%1;!y&&A>=1&&(y=1),y===1&&N--,N=Math.min(N,d+1),!!(N%2)&&(h==="reverse"?(y=1-y,f&&(y-=f/a)):h==="mirror"&&(k=o)),S=ki(0,1,y)*a}const x=w?{done:!1,value:u[0]}:k.next(S);s&&(x.value=s(x.value));let{done:T}=x;!w&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return P&&g!==Zu&&(x.value=kh(u,this.options,v,this.speed)),p&&p(x.value),P&&this.finish(),x}then(t,n){return this.finished.then(t,n)}get duration(){return ei(this.calculatedDuration)}get time(){return ei(this.currentTime)}set time(t){var n;t=$n(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(fn.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=ei(this.currentTime))}play(){var r,s;if(this.isStopped)return;const{driver:t=_1,startTime:n}=this.options;this.driver||(this.driver=t(o=>this.tick(o))),(s=(r=this.options).onPlay)==null||s.call(r);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(fn.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(t=this.options).onComplete)==null||n.call(t)}cancel(){var t,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(t=this.options).onCancel)==null||n.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),t.observe(this)}}function W1(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const or=e=>e*180/Math.PI,Xu=e=>{const t=or(Math.atan2(e[1],e[0]));return Ju(t)},q1={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Xu,rotateZ:Xu,skewX:e=>or(Math.atan(e[1])),skewY:e=>or(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ju=e=>(e=e%360,e<0&&(e+=360),e),qp=Xu,Gp=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),Kp=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),G1={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Gp,scaleY:Kp,scale:e=>(Gp(e)+Kp(e))/2,rotateX:e=>Ju(or(Math.atan2(e[6],e[5]))),rotateY:e=>Ju(or(Math.atan2(-e[2],e[0]))),rotateZ:qp,rotate:qp,skewX:e=>or(Math.atan(e[4])),skewY:e=>or(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Qu(e){return e.includes("scale")?1:0}function ed(e,t){if(!e||e==="none")return Qu(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,r;if(n)i=G1,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=q1,r=a}if(!r)return Qu(t);const s=i[t],o=r[1].split(",").map(Y1);return typeof s=="function"?s(o):o[s]}const K1=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return ed(n,t)};function Y1(e){return parseFloat(e.trim())}const bs=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ys=new Set(bs),Yp=e=>e===gs||e===Me,Z1=new Set(["x","y","z"]),X1=bs.filter(e=>!Z1.has(e));function J1(e){const t=[];return X1.forEach(n=>{const i=e.getValue(n);i!==void 0&&(t.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),t}const lr={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>ed(t,"x"),y:(e,{transform:t})=>ed(t,"y")};lr.translateX=lr.x;lr.translateY=lr.y;const ur=new Set;let td=!1,nd=!1,id=!1;function mv(){if(nd){const e=Array.from(ur).filter(i=>i.needsMeasurement),t=new Set(e.map(i=>i.element)),n=new Map;t.forEach(i=>{const r=J1(i);r.length&&(n.set(i,r),i.render())}),e.forEach(i=>i.measureInitialState()),t.forEach(i=>{i.render();const r=n.get(i);r&&r.forEach(([s,o])=>{var a;(a=i.getValue(s))==null||a.set(o)})}),e.forEach(i=>i.measureEndState()),e.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}nd=!1,td=!1,ur.forEach(e=>e.complete(id)),ur.clear()}function gv(){ur.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(nd=!0)})}function Q1(){id=!0,gv(),mv(),id=!1}class Th{constructor(t,n,i,r,s,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=i,this.motionValue=r,this.element=s,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(ur.add(this),td||(td=!0,vt.read(gv),vt.resolveKeyframes(mv))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:i,motionValue:r}=this;if(t[0]===null){const s=r==null?void 0:r.get(),o=t[t.length-1];if(s!==void 0)t[0]=s;else if(i&&n){const a=i.readValue(n,o);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=o),r&&s===void 0&&r.set(t[0])}W1(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),ur.delete(this)}cancel(){this.state==="scheduled"&&(ur.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const eR=e=>e.startsWith("--");function tR(e,t,n){eR(t)?e.style.setProperty(t,n):e.style[t]=n}const nR=uh(()=>window.ScrollTimeline!==void 0),iR={};function rR(e,t){const n=uh(e);return()=>iR[t]??n()}const bv=rR(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Vs=([e,t,n,i])=>`cubic-bezier(${e}, ${t}, ${n}, ${i})`,Zp={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Vs([0,.65,.55,1]),circOut:Vs([.55,0,1,.45]),backIn:Vs([.31,.01,.66,-.59]),backOut:Vs([.33,1.53,.69,.99])};function yv(e,t){if(e)return typeof e=="function"?bv()?hv(e,t):"ease-out":nv(e)?Vs(e):Array.isArray(e)?e.map(n=>yv(n,t)||Zp.easeOut):Zp[e]}function sR(e,t,n,{delay:i=0,duration:r=300,repeat:s=0,repeatType:o="loop",ease:a="easeOut",times:c}={},l=void 0){const u={[t]:n};c&&(u.offset=c);const d=yv(a,r);Array.isArray(d)&&(u.easing=d);const h={delay:i,duration:r,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:s+1,direction:o==="reverse"?"alternate":"normal"};return l&&(h.pseudoElement=l),e.animate(u,h)}function vv(e){return typeof e=="function"&&"applyToOptions"in e}function oR({type:e,...t}){return vv(e)&&bv()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class aR extends Sh{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:i,keyframes:r,pseudoElement:s,allowFlatten:o=!1,finalKeyframe:a,onComplete:c}=t;this.isPseudoElement=!!s,this.allowFlatten=o,this.options=t,Si(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const l=oR(t);this.animation=sR(n,i,r,l,s),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const u=kh(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):tR(n,i,u),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,n;(n=(t=this.animation).finish)==null||n.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var t,n;this.isPseudoElement||(n=(t=this.animation).commitStyles)==null||n.call(t)}get duration(){var n,i;const t=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return ei(Number(t))}get time(){return ei(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=$n(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&nR()?(this.animation.timeline=t,Nn):n(this)}}const xv={anticipate:Jy,backInOut:Xy,circInOut:ev};function cR(e){return e in xv}function lR(e){typeof e.ease=="string"&&cR(e.ease)&&(e.ease=xv[e.ease])}const Xp=10;class uR extends aR{constructor(t){lR(t),pv(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:i,onComplete:r,element:s,...o}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new wh({...o,autoplay:!1}),c=$n(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Xp).value,a.sample(c).value,Xp),a.stop()}}const Jp=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(zi.test(e)||e==="0")&&!e.startsWith("url("));function dR(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function hR(e,t,n,i){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const s=e[e.length-1],o=Jp(r,t),a=Jp(s,t);return ms(o===a,`You are trying to animate ${t} from "${r}" to "${s}". "${o?s:r}" is not an animatable value.`,"value-not-animatable"),!o||!a?!1:dR(e)||(n==="spring"||vv(n))&&i}function rd(e){e.duration=0,e.type}const fR=new Set(["opacity","clipPath","filter","transform"]),pR=uh(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function mR(e){var u;const{motionValue:t,name:n,repeatDelay:i,repeatType:r,damping:s,type:o}=e;if(!(((u=t==null?void 0:t.owner)==null?void 0:u.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:l}=t.owner.getProps();return pR()&&n&&fR.has(n)&&(n!=="transform"||!l)&&!c&&!i&&r!=="mirror"&&s!==0&&o!=="inertia"}const gR=40;class bR extends Sh{constructor({autoplay:t=!0,delay:n=0,type:i="keyframes",repeat:r=0,repeatDelay:s=0,repeatType:o="loop",keyframes:a,name:c,motionValue:l,element:u,...d}){var g;super(),this.stop=()=>{var p,v;this._animation&&(this._animation.stop(),(p=this.stopTimeline)==null||p.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=fn.now();const h={autoplay:t,delay:n,type:i,repeat:r,repeatDelay:s,repeatType:o,name:c,motionValue:l,element:u,...d},f=(u==null?void 0:u.KeyframeResolver)||Th;this.keyframeResolver=new f(a,(p,v,b)=>this.onKeyframesResolved(p,v,h,!b),c,l,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,i,r){this.keyframeResolver=void 0;const{name:s,type:o,velocity:a,delay:c,isHandoff:l,onUpdate:u}=i;this.resolvedAt=fn.now(),hR(t,s,o,a)||((wi.instantAnimations||!c)&&(u==null||u(kh(t,i,n))),t[0]=t[t.length-1],rd(i),i.repeat=0);const h={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>gR?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:t},f=!l&&mR(h)?new uR({...h,element:h.motionValue.owner.current}):new wh(h);f.finished.then(()=>this.notifyFinished()).catch(Nn),this.pendingTimeline&&(this.stopTimeline=f.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=f}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),Q1()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var t;this._animation&&this.animation.cancel(),(t=this.keyframeResolver)==null||t.cancel()}}const yR=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function vR(e){const t=yR.exec(e);if(!t)return[,];const[,n,i,r]=t;return[`--${n??i}`,r]}const xR=4;function kv(e,t,n=1){Si(n<=xR,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[i,r]=vR(e);if(!i)return;const s=window.getComputedStyle(t).getPropertyValue(i);if(s){const o=s.trim();return zy(o)?parseFloat(o):o}return gh(r)?kv(r,t,n+1):r}function Ch(e,t){return(e==null?void 0:e[t])??(e==null?void 0:e.default)??e}const Sv=new Set(["width","height","top","left","right","bottom",...bs]),kR={test:e=>e==="auto",parse:e=>e},wv=e=>t=>t.test(e),Tv=[gs,Me,ti,Di,d1,u1,kR],Qp=e=>Tv.find(wv(e));function SR(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Wy(e):!0}const wR=new Set(["brightness","contrast","saturate","opacity"]);function TR(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[i]=n.match(bh)||[];if(!i)return e;const r=n.replace(i,"");let s=wR.has(t)?1:0;return i!==n&&(s*=100),t+"("+s+r+")"}const CR=/\b([a-z-]*)\(.*?\)/gu,sd={...zi,getAnimatableNone:e=>{const t=e.match(CR);return t?t.map(TR).join(" "):e}},em={...gs,transform:Math.round},ER={rotate:Di,rotateX:Di,rotateY:Di,rotateZ:Di,scale:Bo,scaleX:Bo,scaleY:Bo,scaleZ:Bo,skew:Di,skewX:Di,skewY:Di,distance:Me,translateX:Me,translateY:Me,translateZ:Me,x:Me,y:Me,z:Me,perspective:Me,transformPerspective:Me,opacity:so,originX:Vp,originY:Vp,originZ:Me},Eh={borderWidth:Me,borderTopWidth:Me,borderRightWidth:Me,borderBottomWidth:Me,borderLeftWidth:Me,borderRadius:Me,radius:Me,borderTopLeftRadius:Me,borderTopRightRadius:Me,borderBottomRightRadius:Me,borderBottomLeftRadius:Me,width:Me,maxWidth:Me,height:Me,maxHeight:Me,top:Me,right:Me,bottom:Me,left:Me,padding:Me,paddingTop:Me,paddingRight:Me,paddingBottom:Me,paddingLeft:Me,margin:Me,marginTop:Me,marginRight:Me,marginBottom:Me,marginLeft:Me,backgroundPositionX:Me,backgroundPositionY:Me,...ER,zIndex:em,fillOpacity:so,strokeOpacity:so,numOctaves:em},_R={...Eh,color:Dt,backgroundColor:Dt,outlineColor:Dt,fill:Dt,stroke:Dt,borderColor:Dt,borderTopColor:Dt,borderRightColor:Dt,borderBottomColor:Dt,borderLeftColor:Dt,filter:sd,WebkitFilter:sd},Cv=e=>_R[e];function Ev(e,t){let n=Cv(e);return n!==sd&&(n=zi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const RR=new Set(["auto","none","0"]);function AR(e,t,n){let i=0,r;for(;i<e.length&&!r;){const s=e[i];typeof s=="string"&&!RR.has(s)&&oo(s).values.length&&(r=e[i]),i++}if(r&&n)for(const s of t)e[s]=Ev(n,r)}class PR extends Th{constructor(t,n,i,r,s){super(t,n,i,r,s,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let c=0;c<t.length;c++){let l=t[c];if(typeof l=="string"&&(l=l.trim(),gh(l))){const u=kv(l,n.current);u!==void 0&&(t[c]=u),c===t.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!Sv.has(i)||t.length!==2)return;const[r,s]=t,o=Qp(r),a=Qp(s);if(o!==a)if(Yp(o)&&Yp(a))for(let c=0;c<t.length;c++){const l=t[c];typeof l=="string"&&(t[c]=parseFloat(l))}else lr[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,i=[];for(let r=0;r<t.length;r++)(t[r]===null||SR(t[r]))&&i.push(r);i.length&&AR(t,i,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:i}=this;if(!t||!t.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=lr[i](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(i,r).jump(r,!1)}measureEndState(){var a;const{element:t,name:n,unresolvedKeyframes:i}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const s=i.length-1,o=i[s];i[s]=lr[n](t.measureViewportBox(),window.getComputedStyle(t.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([c,l])=>{t.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function NR(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let i=document;const r=(n==null?void 0:n[e])??i.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const _v=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Rv(e){return Hy(e)&&"offsetHeight"in e}const tm=30,IR=e=>!isNaN(parseFloat(e));class MR{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{var s;const r=fn.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((s=this.events.change)==null||s.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=fn.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=IR(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&hh(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new dh);const i=this.events[t].add(n);return t==="change"?()=>{i(),vt.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-i}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=fn.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>tm)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,tm);return qy(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,n;(t=this.dependents)==null||t.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function cs(e,t){return new MR(e,t)}const{schedule:_h}=iv(queueMicrotask,!1),Fn={x:!1,y:!1};function Av(){return Fn.x||Fn.y}function OR(e){return e==="x"||e==="y"?Fn[e]?null:(Fn[e]=!0,()=>{Fn[e]=!1}):Fn.x||Fn.y?null:(Fn.x=Fn.y=!0,()=>{Fn.x=Fn.y=!1})}function Pv(e,t){const n=NR(e),i=new AbortController,r={passive:!0,...t,signal:i.signal};return[n,r,()=>i.abort()]}function nm(e){return!(e.pointerType==="touch"||Av())}function DR(e,t,n={}){const[i,r,s]=Pv(e,n),o=a=>{if(!nm(a))return;const{target:c}=a,l=t(c,a);if(typeof l!="function"||!c)return;const u=d=>{nm(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,r)};return i.forEach(a=>{a.addEventListener("pointerenter",o,r)}),s}const Nv=(e,t)=>t?e===t?!0:Nv(e,t.parentElement):!1,Rh=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,LR=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function FR(e){return LR.has(e.tagName)||e.tabIndex!==-1}const wa=new WeakSet;function im(e){return t=>{t.key==="Enter"&&e(t)}}function vl(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const jR=(e,t)=>{const n=e.currentTarget;if(!n)return;const i=im(()=>{if(wa.has(n))return;vl(n,"down");const r=im(()=>{vl(n,"up")}),s=()=>vl(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",s,t)});n.addEventListener("keydown",i,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),t)};function rm(e){return Rh(e)&&!Av()}function UR(e,t,n={}){const[i,r,s]=Pv(e,n),o=a=>{const c=a.currentTarget;if(!rm(a))return;wa.add(c);const l=t(c,a),u=(f,g)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),wa.has(c)&&wa.delete(c),rm(f)&&typeof l=="function"&&l(f,{success:g})},d=f=>{u(f,c===window||c===document||n.useGlobalTarget||Nv(c,f.target))},h=f=>{u(f,!1)};window.addEventListener("pointerup",d,r),window.addEventListener("pointercancel",h,r)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,r),Rv(a)&&(a.addEventListener("focus",l=>jR(l,r)),!FR(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),s}function Iv(e){return Hy(e)&&"ownerSVGElement"in e}function BR(e){return Iv(e)&&e.tagName==="svg"}const Jt=e=>!!(e&&e.getVelocity),VR=[...Tv,Dt,zi],$R=e=>VR.find(wv(e)),Ah=O.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class zR extends D.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const i=n.offsetParent,r=Rv(i)&&i.offsetWidth||0,s=this.props.sizeRef.current;s.height=n.offsetHeight||0,s.width=n.offsetWidth||0,s.top=n.offsetTop,s.left=n.offsetLeft,s.right=r-s.width-s.left}return null}componentDidUpdate(){}render(){return this.props.children}}function HR({children:e,isPresent:t,anchorX:n,root:i}){const r=O.useId(),s=O.useRef(null),o=O.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=O.useContext(Ah);return O.useInsertionEffect(()=>{const{width:c,height:l,top:u,left:d,right:h}=o.current;if(t||!s.current||!c||!l)return;const f=n==="left"?`left: ${d}`:`right: ${h}`;s.current.dataset.motionPopId=r;const g=document.createElement("style");a&&(g.nonce=a);const p=i??document.head;return p.appendChild(g),g.sheet&&g.sheet.insertRule(`
|
|
39
39
|
[data-motion-pop-id="${r}"] {
|
|
40
40
|
position: absolute !important;
|
|
41
41
|
width: ${c}px !important;
|
|
@@ -43,9 +43,9 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
|
43
43
|
${f}px !important;
|
|
44
44
|
top: ${u}px !important;
|
|
45
45
|
}
|
|
46
|
-
`),()=>{p.contains(g)&&p.removeChild(g)}},[t]),m.jsx(zR,{isPresent:t,childRef:s,sizeRef:o,children:D.cloneElement(e,{ref:s})})}const WR=({children:e,initial:t,isPresent:n,onExitComplete:i,custom:r,presenceAffectsLayout:s,mode:o,anchorX:a,root:c})=>{const l=oh(qR),u=O.useId();let d=!0,h=O.useMemo(()=>(d=!1,{id:u,initial:t,isPresent:n,custom:r,onExitComplete:f=>{l.set(f,!0);for(const g of l.values())if(!g)return;i&&i()},register:f=>(l.set(f,!1),()=>l.delete(f))}),[n,l,i]);return s&&d&&(h={...h}),O.useMemo(()=>{l.forEach((f,g)=>l.set(g,!1))},[n]),D.useEffect(()=>{!n&&!l.size&&i&&i()},[n]),o==="popLayout"&&(e=m.jsx(HR,{isPresent:n,anchorX:a,root:c,children:e})),m.jsx(bc.Provider,{value:h,children:e})};function qR(){return new Map}function Mv(e=!0){const t=O.useContext(bc);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:r}=t,s=O.useId();O.useEffect(()=>{if(e)return r(s)},[e]);const o=O.useCallback(()=>e&&i&&i(s),[s,i,e]);return!n&&i?[!1,o]:[!0]}const Vo=e=>e.key||"";function sm(e){const t=[];return O.Children.forEach(e,n=>{O.isValidElement(n)&&t.push(n)}),t}const ls=({children:e,custom:t,initial:n=!0,onExitComplete:i,presenceAffectsLayout:r=!0,mode:s="sync",propagate:o=!1,anchorX:a="left",root:c})=>{const[l,u]=Mv(o),d=O.useMemo(()=>sm(e),[e]),h=o&&!l?[]:d.map(Vo),f=O.useRef(!0),g=O.useRef(d),p=oh(()=>new Map),[v,b]=O.useState(d),[w,S]=O.useState(d);$0(()=>{f.current=!1,g.current=d;for(let T=0;T<w.length;T++){const P=Vo(w[T]);h.includes(P)?p.delete(P):p.get(P)!==!0&&p.set(P,!1)}},[w,h.length,h.join("-")]);const k=[];if(d!==v){let T=[...d];for(let P=0;P<w.length;P++){const A=w[P],N=Vo(A);h.includes(N)||(T.splice(P,0,A),k.push(A))}return s==="wait"&&k.length&&(T=k),S(sm(T)),b(d),null}process.env.NODE_ENV!=="production"&&s==="wait"&&w.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:x}=O.useContext(sh);return m.jsx(m.Fragment,{children:w.map(T=>{const P=Vo(T),A=o&&!l?!1:d===w||h.includes(P),N=()=>{if(p.has(P))p.set(P,!0);else return;let y=!0;p.forEach(R=>{R||(y=!1)}),y&&(x==null||x(),S(g.current),o&&(u==null||u()),i&&i())};return m.jsx(WR,{isPresent:A,initial:!f.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:s,root:c,onExitComplete:A?void 0:N,anchorX:a,children:T},P)})})},Ov=O.createContext({strict:!1}),om={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},us={};for(const e in om)us[e]={isEnabled:t=>om[e].some(n=>!!t[n])};function GR(e){for(const t in e)us[t]={...us[t],...e[t]}}const KR=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function qa(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||KR.has(e)}let Dv=e=>!qa(e);function YR(e){typeof e=="function"&&(Dv=t=>t.startsWith("on")?!qa(t):e(t))}try{YR(require("@emotion/is-prop-valid").default)}catch{}function ZR(e,t,n){const i={};for(const r in e)r==="values"&&typeof e.values=="object"||(Dv(r)||n===!0&&qa(r)||!t&&!qa(r)||e.draggable&&r.startsWith("onDrag"))&&(i[r]=e[r]);return i}const yc=O.createContext({});function vc(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function ao(e){return typeof e=="string"||Array.isArray(e)}const Ph=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Nh=["initial",...Ph];function xc(e){return vc(e.animate)||Nh.some(t=>ao(e[t]))}function Lv(e){return!!(xc(e)||e.variants)}function XR(e,t){if(xc(e)){const{initial:n,animate:i}=e;return{initial:n===!1||ao(n)?n:void 0,animate:ao(i)?i:void 0}}return e.inherit!==!1?t:{}}function JR(e){const{initial:t,animate:n}=XR(e,O.useContext(yc));return O.useMemo(()=>({initial:t,animate:n}),[am(t),am(n)])}function am(e){return Array.isArray(e)?e.join(" "):e}const co={};function QR(e){for(const t in e)co[t]=e[t],mh(t)&&(co[t].isCSSVariable=!0)}function Fv(e,{layout:t,layoutId:n}){return ys.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!co[e]||e==="opacity")}const eA={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},tA=bs.length;function nA(e,t,n){let i="",r=!0;for(let s=0;s<tA;s++){const o=bs[s],a=e[o];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(o.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const l=_v(a,Eh[o]);if(!c){r=!1;const u=eA[o]||o;i+=`${u}(${l}) `}n&&(t[o]=l)}}return i=i.trim(),n?i=n(t,r?"":i):r&&(i="none"),i}function Ih(e,t,n){const{style:i,vars:r,transformOrigin:s}=e;let o=!1,a=!1;for(const c in t){const l=t[c];if(ys.has(c)){o=!0;continue}else if(mh(c)){r[c]=l;continue}else{const u=_v(l,Eh[c]);c.startsWith("origin")?(a=!0,s[c]=u):i[c]=u}}if(t.transform||(o||n?i.transform=nA(t,e.transform,n):i.transform&&(i.transform="none")),a){const{originX:c="50%",originY:l="50%",originZ:u=0}=s;i.transformOrigin=`${c} ${l} ${u}`}}const Mh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function jv(e,t,n){for(const i in t)!Jt(t[i])&&!Fv(i,n)&&(e[i]=t[i])}function iA({transformTemplate:e},t){return O.useMemo(()=>{const n=Mh();return Ih(n,t,e),Object.assign({},n.vars,n.style)},[t])}function rA(e,t){const n=e.style||{},i={};return jv(i,n,e),Object.assign(i,iA(e,t)),i}function sA(e,t){const n={},i=rA(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=i,n}const oA={offset:"stroke-dashoffset",array:"stroke-dasharray"},aA={offset:"strokeDashoffset",array:"strokeDasharray"};function cA(e,t,n=1,i=0,r=!0){e.pathLength=1;const s=r?oA:aA;e[s.offset]=Me.transform(-i);const o=Me.transform(t),a=Me.transform(n);e[s.array]=`${o} ${a}`}function Uv(e,{attrX:t,attrY:n,attrScale:i,pathLength:r,pathSpacing:s=1,pathOffset:o=0,...a},c,l,u){if(Ih(e,a,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:d,style:h}=e;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),i!==void 0&&(d.scale=i),r!==void 0&&cA(d,r,s,o,!1)}const Bv=()=>({...Mh(),attrs:{}}),Vv=e=>typeof e=="string"&&e.toLowerCase()==="svg";function lA(e,t,n,i){const r=O.useMemo(()=>{const s=Bv();return Uv(s,t,Vv(i),e.transformTemplate,e.style),{...s.attrs,style:{...s.style}}},[t]);if(e.style){const s={};jv(s,e.style,e),r.style={...s,...r.style}}return r}const uA=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Oh(e){return typeof e!="string"||e.includes("-")?!1:!!(uA.indexOf(e)>-1||/[A-Z]/u.test(e))}function dA(e,t,n,{latestValues:i},r,s=!1){const a=(Oh(e)?lA:sA)(t,i,r,e),c=ZR(t,typeof e=="string",s),l=e!==O.Fragment?{...c,...a,ref:n}:{},{children:u}=t,d=O.useMemo(()=>Jt(u)?u.get():u,[u]);return O.createElement(e,{...l,children:d})}function cm(e){const t=[{},{}];return e==null||e.values.forEach((n,i)=>{t[0][i]=n.get(),t[1][i]=n.getVelocity()}),t}function Dh(e,t,n,i){if(typeof t=="function"){const[r,s]=cm(i);t=t(n!==void 0?n:e.custom,r,s)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,s]=cm(i);t=t(n!==void 0?n:e.custom,r,s)}return t}function Ta(e){return Jt(e)?e.get():e}function hA({scrapeMotionValuesFromProps:e,createRenderState:t},n,i,r){return{latestValues:fA(n,i,r,e),renderState:t()}}function fA(e,t,n,i){const r={},s=i(e,{});for(const h in s)r[h]=Ta(s[h]);let{initial:o,animate:a}=e;const c=xc(e),l=Lv(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),a===void 0&&(a=t.animate));let u=n?n.initial===!1:!1;u=u||o===!1;const d=u?a:o;if(d&&typeof d!="boolean"&&!vc(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f<h.length;f++){const g=Dh(e,h[f]);if(g){const{transitionEnd:p,transition:v,...b}=g;for(const w in b){let S=b[w];if(Array.isArray(S)){const k=u?S.length-1:0;S=S[k]}S!==null&&(r[w]=S)}for(const w in p)r[w]=p[w]}}}return r}const $v=e=>(t,n)=>{const i=O.useContext(yc),r=O.useContext(bc),s=()=>hA(e,t,i,r);return n?s():oh(s)};function Lh(e,t,n){var s;const{style:i}=e,r={};for(const o in i)(Jt(i[o])||t.style&&Jt(t.style[o])||Fv(o,e)||((s=n==null?void 0:n.getValue(o))==null?void 0:s.liveStyle)!==void 0)&&(r[o]=i[o]);return r}const pA=$v({scrapeMotionValuesFromProps:Lh,createRenderState:Mh});function zv(e,t,n){const i=Lh(e,t,n);for(const r in e)if(Jt(e[r])||Jt(t[r])){const s=bs.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;i[s]=e[r]}return i}const mA=$v({scrapeMotionValuesFromProps:zv,createRenderState:Bv}),gA=Symbol.for("motionComponentSymbol");function qr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function bA(e,t,n){return O.useCallback(i=>{i&&e.onMount&&e.onMount(i),t&&(i?t.mount(i):t.unmount()),n&&(typeof n=="function"?n(i):qr(n)&&(n.current=i))},[t])}const Fh=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),yA="framerAppearId",Hv="data-"+Fh(yA),Wv=O.createContext({});function vA(e,t,n,i,r){var p,v;const{visualElement:s}=O.useContext(yc),o=O.useContext(Ov),a=O.useContext(bc),c=O.useContext(Ah).reducedMotion,l=O.useRef(null);i=i||o.renderer,!l.current&&i&&(l.current=i(e,{visualState:t,parent:s,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const u=l.current,d=O.useContext(Wv);u&&!u.projection&&r&&(u.type==="html"||u.type==="svg")&&xA(l.current,n,r,d);const h=O.useRef(!1);O.useInsertionEffect(()=>{u&&h.current&&u.update(n,a)});const f=n[Hv],g=O.useRef(!!f&&!((p=window.MotionHandoffIsComplete)!=null&&p.call(window,f))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,f)));return $0(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),u.scheduleRenderMicrotask(),g.current&&u.animationState&&u.animationState.animateChanges())}),O.useEffect(()=>{u&&(!g.current&&u.animationState&&u.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,f)}),g.current=!1),u.enteringChildren=void 0)}),u}function xA(e,t,n,i){const{layoutId:r,layout:s,drag:o,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:qv(e.parent)),e.projection.setOptions({layoutId:r,layout:s,alwaysMeasureLayout:!!o||a&&qr(a),visualElement:e,animationType:typeof s=="string"?s:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function qv(e){if(e)return e.options.allowProjection!==!1?e.projection:qv(e.parent)}function xl(e,{forwardMotionProps:t=!1}={},n,i){n&&GR(n);const r=Oh(e)?mA:pA;function s(a,c){let l;const u={...O.useContext(Ah),...a,layoutId:kA(a)},{isStatic:d}=u,h=JR(a),f=r(a,d);if(!d&&ah){SA(u,n);const g=wA(u);l=g.MeasureLayout,h.visualElement=vA(e,f,u,i,g.ProjectionNode)}return m.jsxs(yc.Provider,{value:h,children:[l&&h.visualElement?m.jsx(l,{visualElement:h.visualElement,...u}):null,dA(e,a,bA(f,h.visualElement,c),f,d,t)]})}s.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const o=O.forwardRef(s);return o[gA]=e,o}function kA({layoutId:e}){const t=O.useContext(sh).id;return t&&e!==void 0?t+"-"+e:e}function SA(e,t){const n=O.useContext(Ov).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const i="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?ms(!1,i,"lazy-strict-mode"):Si(!1,i,"lazy-strict-mode")}}function wA(e){const{drag:t,layout:n}=us;if(!t&&!n)return{};const i={...t,...n};return{MeasureLayout:t!=null&&t.isEnabled(e)||n!=null&&n.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function TA(e,t){if(typeof Proxy>"u")return xl;const n=new Map,i=(s,o)=>xl(s,o,e,t),r=(s,o)=>(process.env.NODE_ENV!=="production"&&hh(!1,"motion() is deprecated. Use motion.create() instead."),i(s,o));return new Proxy(r,{get:(s,o)=>o==="create"?i:(n.has(o)||n.set(o,xl(o,void 0,e,t)),n.get(o))})}function Gv({top:e,left:t,right:n,bottom:i}){return{x:{min:t,max:n},y:{min:e,max:i}}}function CA({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function EA(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),i=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}function kl(e){return e===void 0||e===1}function od({scale:e,scaleX:t,scaleY:n}){return!kl(e)||!kl(t)||!kl(n)}function rr(e){return od(e)||Kv(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Kv(e){return lm(e.x)||lm(e.y)}function lm(e){return e&&e!=="0%"}function Ga(e,t,n){const i=e-n,r=t*i;return n+r}function um(e,t,n,i,r){return r!==void 0&&(e=Ga(e,r,i)),Ga(e,n,i)+t}function ad(e,t=0,n=1,i,r){e.min=um(e.min,t,n,i,r),e.max=um(e.max,t,n,i,r)}function Yv(e,{x:t,y:n}){ad(e.x,t.translate,t.scale,t.originPoint),ad(e.y,n.translate,n.scale,n.originPoint)}const dm=.999999999999,hm=1.0000000000001;function _A(e,t,n,i=!1){const r=n.length;if(!r)return;t.x=t.y=1;let s,o;for(let a=0;a<r;a++){s=n[a],o=s.projectionDelta;const{visualElement:c}=s.options;c&&c.props.style&&c.props.style.display==="contents"||(i&&s.options.layoutScroll&&s.scroll&&s!==s.root&&Kr(e,{x:-s.scroll.offset.x,y:-s.scroll.offset.y}),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Yv(e,o)),i&&rr(s.latestValues)&&Kr(e,s.latestValues))}t.x<hm&&t.x>dm&&(t.x=1),t.y<hm&&t.y>dm&&(t.y=1)}function Gr(e,t){e.min=e.min+t,e.max=e.max+t}function fm(e,t,n,i,r=.5){const s=St(e.min,e.max,r);ad(e,t,n,s,i)}function Kr(e,t){fm(e.x,t.x,t.scaleX,t.scale,t.originX),fm(e.y,t.y,t.scaleY,t.scale,t.originY)}function Zv(e,t){return Gv(EA(e.getBoundingClientRect(),t))}function RA(e,t,n){const i=Zv(e,n),{scroll:r}=t;return r&&(Gr(i.x,r.offset.x),Gr(i.y,r.offset.y)),i}const pm=()=>({translate:0,scale:1,origin:0,originPoint:0}),Yr=()=>({x:pm(),y:pm()}),mm=()=>({min:0,max:0}),Pt=()=>({x:mm(),y:mm()}),cd={current:null},Xv={current:!1};function AA(){if(Xv.current=!0,!!ah)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>cd.current=e.matches;e.addEventListener("change",t),t()}else cd.current=!1}const PA=new WeakMap;function NA(e,t,n){for(const i in t){const r=t[i],s=n[i];if(Jt(r))e.addValue(i,r);else if(Jt(s))e.addValue(i,cs(r,{owner:e}));else if(s!==r)if(e.hasValue(i)){const o=e.getValue(i);o.liveStyle===!0?o.jump(r):o.hasAnimated||o.set(r)}else{const o=e.getStaticValue(i);e.addValue(i,cs(o!==void 0?o:r,{owner:e}))}}for(const i in n)t[i]===void 0&&e.removeValue(i);return t}const gm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class IA{scrapeMotionValuesFromProps(t,n,i){return{}}constructor({parent:t,props:n,presenceContext:i,reducedMotionConfig:r,blockInitialAnimation:s,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Th,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=fn.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,vt.render(this.render,!1,!0))};const{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=l,this.parent=t,this.props=n,this.presenceContext=i,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!s,this.isControllingVariants=xc(n),this.isVariantNode=Lv(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const h in d){const f=d[h];c[h]!==void 0&&Jt(f)&&f.set(c[h])}}mount(t){var n;this.current=t,PA.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,r)=>this.bindToMotionValue(r,i)),Xv.current||AA(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:cd.current,process.env.NODE_ENV!=="production"&&hh(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var t;this.projection&&this.projection.unmount(),$i(this.notifyUpdate),$i(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const i=this.features[n];i&&(i.unmount(),i.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const i=ys.has(t);i&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",o=>{this.latestValues[t]=o,this.props.onUpdate&&vt.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let s;window.MotionCheckAppearSync&&(s=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),s&&s(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in us){const n=us[t];if(!n)continue;const{isEnabled:i,Feature:r}=n;if(!this.features[t]&&r&&i(this.props)&&(this.features[t]=new r(this)),this.features[t]){const s=this.features[t];s.isMounted?s.update():(s.mount(),s.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Pt()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<gm.length;i++){const r=gm[i];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const s="on"+r,o=t[s];o&&(this.propEventSubscriptions[r]=this.on(r,o))}this.prevMotionValues=NA(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const i=this.values.get(t);n!==i&&(i&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let i=this.values.get(t);return i===void 0&&n!==void 0&&(i=cs(n===null?void 0:n,{owner:this}),this.addValue(t,i)),i}readValue(t,n){let i=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return i!=null&&(typeof i=="string"&&(z0(i)||W0(i))?i=parseFloat(i):!$R(i)&&zi.test(n)&&(i=Ev(t,n)),this.setBaseTarget(t,Jt(i)?i.get():i)),Jt(i)?i.get():i}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var s;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const o=Dh(this.props,n,(s=this.presenceContext)==null?void 0:s.custom);o&&(i=o[t])}if(n&&i!==void 0)return i;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Jt(r)?r:this.initialValues[t]!==void 0&&i===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new dh),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){_h.render(this.render)}}class Jv extends IA{constructor(){super(...arguments),this.KeyframeResolver=PR}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:i}){delete n[t],delete i[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Jt(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Qv(e,{style:t,vars:n},i,r){const s=e.style;let o;for(o in t)s[o]=t[o];r==null||r.applyProjectionStyles(s,i);for(o in n)s.setProperty(o,n[o])}function MA(e){return window.getComputedStyle(e)}class OA extends Jv{constructor(){super(...arguments),this.type="html",this.renderInstance=Qv}readValueFromInstance(t,n){var i;if(ys.has(n))return(i=this.projection)!=null&&i.isProjecting?Qu(n):K1(t,n);{const r=MA(t),s=(mh(n)?r.getPropertyValue(n):r[n])||0;return typeof s=="string"?s.trim():s}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Zv(t,n)}build(t,n,i){Ih(t,n,i.transformTemplate)}scrapeMotionValuesFromProps(t,n,i){return Lh(t,n,i)}}const ex=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function DA(e,t,n,i){Qv(e,t,void 0,i);for(const r in t.attrs)e.setAttribute(ex.has(r)?r:Fh(r),t.attrs[r])}class LA extends Jv{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Pt}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(ys.has(n)){const i=Cv(n);return i&&i.default||0}return n=ex.has(n)?n:Fh(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,i){return zv(t,n,i)}build(t,n,i){Uv(t,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(t,n,i,r){DA(t,n,i,r)}mount(t){this.isSVGTag=Vv(t.tagName),super.mount(t)}}const FA=(e,t)=>Oh(e)?new LA(t):new OA(t,{allowProjection:e!==O.Fragment});function ns(e,t,n){const i=e.getProps();return Dh(i,t,n!==void 0?n:i.custom,e)}const ld=e=>Array.isArray(e);function jA(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,cs(n))}function UA(e){return ld(e)?e[e.length-1]||0:e}function BA(e,t){const n=ns(e,t);let{transitionEnd:i={},transition:r={},...s}=n||{};s={...s,...i};for(const o in s){const a=UA(s[o]);jA(e,o,a)}}function VA(e){return!!(Jt(e)&&e.add)}function ud(e,t){const n=e.getValue("willChange");if(VA(n))return n.add(t);if(!n&&wi.WillChange){const i=new wi.WillChange("auto");e.addValue("willChange",i),i.add(t)}}function tx(e){return e.props[Hv]}const $A=e=>e!==null;function zA(e,{repeat:t,repeatType:n="loop"},i){const r=e.filter($A),s=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[s]}const HA={type:"spring",stiffness:500,damping:25,restSpeed:10},WA=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),qA={type:"keyframes",duration:.8},GA={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},KA=(e,{keyframes:t})=>t.length>2?qA:ys.has(e)?e.startsWith("scale")?WA(t[1]):HA:GA;function YA({when:e,delay:t,delayChildren:n,staggerChildren:i,staggerDirection:r,repeat:s,repeatType:o,repeatDelay:a,from:c,elapsed:l,...u}){return!!Object.keys(u).length}const jh=(e,t,n,i={},r,s)=>o=>{const a=Ch(i,e)||{},c=a.delay||i.delay||0;let{elapsed:l=0}=i;l=l-$n(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-l,onUpdate:h=>{t.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:s?void 0:r};YA(a)||Object.assign(u,KA(e,u)),u.duration&&(u.duration=$n(u.duration)),u.repeatDelay&&(u.repeatDelay=$n(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(rd(u),u.delay===0&&(d=!0)),(wi.instantAnimations||wi.skipAnimations)&&(d=!0,rd(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!s&&t.get()!==void 0){const h=zA(u.keyframes,a);if(h!==void 0){vt.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new wh(u):new bR(u)};function ZA({protectedKeys:e,needsAnimating:t},n){const i=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,i}function nx(e,t,{delay:n=0,transitionOverride:i,type:r}={}){let{transition:s=e.getDefaultTransition(),transitionEnd:o,...a}=t;i&&(s=i);const c=[],l=r&&e.animationState&&e.animationState.getState()[r];for(const u in a){const d=e.getValue(u,e.latestValues[u]??null),h=a[u];if(h===void 0||l&&ZA(l,u))continue;const f={delay:n,...Ch(s||{},u)},g=d.get();if(g!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===g&&!f.velocity)continue;let p=!1;if(window.MotionHandoffAnimation){const b=tx(e);if(b){const w=window.MotionHandoffAnimation(b,u,vt);w!==null&&(f.startTime=w,p=!0)}}ud(e,u),d.start(jh(u,d,h,e.shouldReduceMotion&&Sv.has(u)?{type:!1}:f,e,p));const v=d.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{vt.update(()=>{o&&BA(e,o)})}),c}function ix(e,t,n,i=0,r=1){const s=Array.from(e).sort((l,u)=>l.sortNodePosition(u)).indexOf(t),o=e.size,a=(o-1)*i;return typeof n=="function"?n(s,o):r===1?s*i:a-s*i}function dd(e,t,n={}){var c;const i=ns(e,t,n.type==="exit"?(c=e.presenceContext)==null?void 0:c.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(r=n.transitionOverride);const s=i?()=>Promise.all(nx(e,i,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return XA(e,t,l,u,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,u]=a==="beforeChildren"?[s,o]:[o,s];return l().then(()=>u())}else return Promise.all([s(),o(n.delay)])}function XA(e,t,n=0,i=0,r=0,s=1,o){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(dd(c,t,{...o,delay:n+(typeof i=="function"?0:i)+ix(e.variantChildren,c,i,r,s)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function JA(e,t,n={}){e.notify("AnimationStart",t);let i;if(Array.isArray(t)){const r=t.map(s=>dd(e,s,n));i=Promise.all(r)}else if(typeof t=="string")i=dd(e,t,n);else{const r=typeof t=="function"?ns(e,t,n.custom):t;i=Promise.all(nx(e,r,n))}return i.then(()=>{e.notify("AnimationComplete",t)})}function rx(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}const QA=Nh.length;function sx(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?sx(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<QA;n++){const i=Nh[n],r=e.props[i];(ao(r)||r===!1)&&(t[i]=r)}return t}const eP=[...Ph].reverse(),tP=Ph.length;function nP(e){return t=>Promise.all(t.map(({animation:n,options:i})=>JA(e,n,i)))}function iP(e){let t=nP(e),n=bm(),i=!0;const r=c=>(l,u)=>{var h;const d=ns(e,u,c==="exit"?(h=e.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:f,transitionEnd:g,...p}=d;l={...l,...p,...g}}return l};function s(c){t=c(e)}function o(c){const{props:l}=e,u=sx(e.parent)||{},d=[],h=new Set;let f={},g=1/0;for(let v=0;v<tP;v++){const b=eP[v],w=n[b],S=l[b]!==void 0?l[b]:u[b],k=ao(S),x=b===c?w.isActive:null;x===!1&&(g=v);let T=S===u[b]&&S!==l[b]&&k;if(T&&i&&e.manuallyAnimateOnMount&&(T=!1),w.protectedKeys={...f},!w.isActive&&x===null||!S&&!w.prevProp||vc(S)||typeof S=="boolean")continue;const P=rP(w.prevProp,S);let A=P||b===c&&w.isActive&&!T&&k||v>g&&k,N=!1;const y=Array.isArray(S)?S:[S];let R=y.reduce(r(b),{});x===!1&&(R={});const{prevResolvedValues:I={}}=w,L={...I,...R},U=se=>{A=!0,h.has(se)&&(N=!0,h.delete(se)),w.needsAnimating[se]=!0;const z=e.getValue(se);z&&(z.liveStyle=!1)};for(const se in L){const z=R[se],H=I[se];if(f.hasOwnProperty(se))continue;let C=!1;ld(z)&&ld(H)?C=!rx(z,H):C=z!==H,C?z!=null?U(se):h.add(se):z!==void 0&&h.has(se)?U(se):w.protectedKeys[se]=!0}w.prevProp=S,w.prevResolvedValues=R,w.isActive&&(f={...f,...R}),i&&e.blockInitialAnimation&&(A=!1);const K=T&&P;A&&(!K||N)&&d.push(...y.map(se=>{const z={type:b};if(typeof se=="string"&&i&&!K&&e.manuallyAnimateOnMount&&e.parent){const{parent:H}=e,C=ns(H,se);if(H.enteringChildren&&C){const{delayChildren:W}=C.transition||{};z.delay=ix(H.enteringChildren,e,W)}}return{animation:se,options:z}}))}if(h.size){const v={};if(typeof l.initial!="boolean"){const b=ns(e,Array.isArray(l.initial)?l.initial[0]:l.initial);b&&b.transition&&(v.transition=b.transition)}h.forEach(b=>{const w=e.getBaseTarget(b),S=e.getValue(b);S&&(S.liveStyle=!0),v[b]=w??null}),d.push({animation:v})}let p=!!d.length;return i&&(l.initial===!1||l.initial===l.animate)&&!e.manuallyAnimateOnMount&&(p=!1),i=!1,p?t(d):Promise.resolve()}function a(c,l){var d;if(n[c].isActive===l)return Promise.resolve();(d=e.variantChildren)==null||d.forEach(h=>{var f;return(f=h.animationState)==null?void 0:f.setActive(c,l)}),n[c].isActive=l;const u=o(c);for(const h in n)n[h].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:s,getState:()=>n,reset:()=>{n=bm(),i=!0}}}function rP(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!rx(t,e):!1}function er(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function bm(){return{animate:er(!0),whileInView:er(),whileHover:er(),whileTap:er(),whileDrag:er(),whileFocus:er(),exit:er()}}class Yi{constructor(t){this.isMounted=!1,this.node=t}update(){}}class sP extends Yi{constructor(t){super(t),t.animationState||(t.animationState=iP(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();vc(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let oP=0;class aP extends Yi{constructor(){super(...arguments),this.id=oP++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const cP={animation:{Feature:sP},exit:{Feature:aP}};function lo(e,t,n,i={passive:!0}){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n)}function vo(e){return{point:{x:e.pageX,y:e.pageY}}}const lP=e=>t=>Rh(t)&&e(t,vo(t));function Ks(e,t,n,i){return lo(e,t,lP(n),i)}const ox=1e-4,uP=1-ox,dP=1+ox,ax=.01,hP=0-ax,fP=0+ax;function sn(e){return e.max-e.min}function pP(e,t,n){return Math.abs(e-t)<=n}function ym(e,t,n,i=.5){e.origin=i,e.originPoint=St(t.min,t.max,e.origin),e.scale=sn(n)/sn(t),e.translate=St(n.min,n.max,e.origin)-e.originPoint,(e.scale>=uP&&e.scale<=dP||isNaN(e.scale))&&(e.scale=1),(e.translate>=hP&&e.translate<=fP||isNaN(e.translate))&&(e.translate=0)}function Ys(e,t,n,i){ym(e.x,t.x,n.x,i?i.originX:void 0),ym(e.y,t.y,n.y,i?i.originY:void 0)}function vm(e,t,n){e.min=n.min+t.min,e.max=e.min+sn(t)}function mP(e,t,n){vm(e.x,t.x,n.x),vm(e.y,t.y,n.y)}function xm(e,t,n){e.min=t.min-n.min,e.max=e.min+sn(t)}function Zs(e,t,n){xm(e.x,t.x,n.x),xm(e.y,t.y,n.y)}function _n(e){return[e("x"),e("y")]}const cx=({current:e})=>e?e.ownerDocument.defaultView:null,km=(e,t)=>Math.abs(e-t);function gP(e,t){const n=km(e.x,t.x),i=km(e.y,t.y);return Math.sqrt(n**2+i**2)}class lx{constructor(t,n,{transformPagePoint:i,contextWindow:r=window,dragSnapToOrigin:s=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=wl(this.lastMoveEventInfo,this.history),f=this.startEvent!==null,g=gP(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!f&&!g)return;const{point:p}=h,{timestamp:v}=Yt;this.history.push({...p,timestamp:v});const{onStart:b,onMove:w}=this.handlers;f||(b&&b(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,h)},this.handlePointerMove=(h,f)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Sl(f,this.transformPagePoint),vt.update(this.updatePoint,!0)},this.handlePointerUp=(h,f)=>{this.end();const{onEnd:g,onSessionEnd:p,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=wl(h.type==="pointercancel"?this.lastMoveEventInfo:Sl(f,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,b),p&&p(h,b)},!Rh(t))return;this.dragSnapToOrigin=s,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=r||window;const a=vo(t),c=Sl(a,this.transformPagePoint),{point:l}=c,{timestamp:u}=Yt;this.history=[{...l,timestamp:u}];const{onSessionStart:d}=n;d&&d(t,wl(c,this.history)),this.removeListeners=go(Ks(this.contextWindow,"pointermove",this.handlePointerMove),Ks(this.contextWindow,"pointerup",this.handlePointerUp),Ks(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),$i(this.updatePoint)}}function Sl(e,t){return t?{point:t(e.point)}:e}function Sm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function wl({point:e},t){return{point:e,delta:Sm(e,ux(t)),offset:Sm(e,bP(t)),velocity:yP(t,.1)}}function bP(e){return e[0]}function ux(e){return e[e.length-1]}function yP(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,i=null;const r=ux(e);for(;n>=0&&(i=e[n],!(r.timestamp-i.timestamp>$n(t)));)n--;if(!i)return{x:0,y:0};const s=ei(r.timestamp-i.timestamp);if(s===0)return{x:0,y:0};const o={x:(r.x-i.x)/s,y:(r.y-i.y)/s};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function vP(e,{min:t,max:n},i){return t!==void 0&&e<t?e=i?St(t,e,i.min):Math.max(e,t):n!==void 0&&e>n&&(e=i?St(n,e,i.max):Math.min(e,n)),e}function wm(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function xP(e,{top:t,left:n,bottom:i,right:r}){return{x:wm(e.x,n,r),y:wm(e.y,t,i)}}function Tm(e,t){let n=t.min-e.min,i=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,i]=[i,n]),{min:n,max:i}}function kP(e,t){return{x:Tm(e.x,t.x),y:Tm(e.y,t.y)}}function SP(e,t){let n=.5;const i=sn(e),r=sn(t);return r>i?n=ro(t.min,t.max-i,e.min):i>r&&(n=ro(e.min,e.max-r,t.min)),ki(0,1,n)}function wP(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const hd=.35;function TP(e=hd){return e===!1?e=0:e===!0&&(e=hd),{x:Cm(e,"left","right"),y:Cm(e,"top","bottom")}}function Cm(e,t,n){return{min:Em(e,t),max:Em(e,n)}}function Em(e,t){return typeof e=="number"?e:e[t]||0}const CP=new WeakMap;class EP{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Pt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const s=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(vo(d).point)},o=(d,h)=>{const{drag:f,dragPropagation:g,onDragStart:p}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=OR(f),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),_n(b=>{let w=this.getAxisMotionValue(b).get()||0;if(ti.test(w)){const{projection:S}=this.visualElement;if(S&&S.layout){const k=S.layout.layoutBox[b];k&&(w=sn(k)*(parseFloat(w)/100))}}this.originPoint[b]=w}),p&&vt.postRender(()=>p(d,h)),ud(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:p,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:b}=h;if(g&&this.currentDirection===null){this.currentDirection=_P(b),this.currentDirection!==null&&p&&p(this.currentDirection);return}this.updateAxis("x",h.point,b),this.updateAxis("y",h.point,b),this.visualElement.render(),v&&v(d,h)},c=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>_n(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new lx(t,{onSessionStart:s,onStart:o,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:cx(this.visualElement)})}stop(t,n){const i=t||this.latestPointerEvent,r=n||this.latestPanInfo,s=this.isDragging;if(this.cancel(),!s||!r||!i)return;const{velocity:o}=r;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&vt.postRender(()=>a(i,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,i){const{drag:r}=this.getProps();if(!i||!$o(t,r,this.currentDirection))return;const s=this.getAxisMotionValue(t);let o=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(o=vP(o,this.constraints[t],this.elastic[t])),s.set(o)}resolveConstraints(){var s;const{dragConstraints:t,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(s=this.visualElement.projection)==null?void 0:s.layout,r=this.constraints;t&&qr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&i?this.constraints=xP(i.layoutBox,t):this.constraints=!1,this.elastic=TP(n),r!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&_n(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=wP(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!qr(t))return!1;const i=t.current;Si(i!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const s=RA(i,r.root,this.visualElement.getTransformPagePoint());let o=kP(r.layout.layoutBox,s);if(n){const a=n(CA(o));this.hasMutatedConstraints=!!a,a&&(o=Gv(a))}return o}startAnimation(t){const{drag:n,dragMomentum:i,dragElastic:r,dragTransition:s,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},l=_n(u=>{if(!$o(u,n,this.currentDirection))return;let d=c&&c[u]||{};o&&(d={min:0,max:0});const h=r?200:1e6,f=r?40:1e7,g={type:"inertia",velocity:i?t[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...s,...d};return this.startAxisValueAnimation(u,g)});return Promise.all(l).then(a)}startAxisValueAnimation(t,n){const i=this.getAxisMotionValue(t);return ud(this.visualElement,t),i.start(jh(t,i,0,n,this.visualElement,!1))}stopAnimation(){_n(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){_n(t=>{var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps(),r=i[n];return r||this.visualElement.getValue(t,(i.initial?i.initial[t]:void 0)||0)}snapToCursor(t){_n(n=>{const{drag:i}=this.getProps();if(!$o(n,i,this.currentDirection))return;const{projection:r}=this.visualElement,s=this.getAxisMotionValue(n);if(r&&r.layout){const{min:o,max:a}=r.layout.layoutBox[n];s.set(t[n]-St(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!qr(n)||!i||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};_n(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const c=a.get();r[o]=SP({min:c,max:c},this.constraints[o])}});const{transformTemplate:s}=this.visualElement.getProps();this.visualElement.current.style.transform=s?s({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),_n(o=>{if(!$o(o,t,null))return;const a=this.getAxisMotionValue(o),{min:c,max:l}=this.constraints[o];a.set(St(c,l,r[o]))})}addListeners(){if(!this.visualElement.current)return;CP.set(this.visualElement,this);const t=this.visualElement.current,n=Ks(t,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps();l&&u&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();qr(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,s=r.addEventListener("measure",i);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),vt.read(i);const o=lo(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(_n(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[u].translate))}),this.visualElement.render())});return()=>{o(),n(),s(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:r=!1,dragConstraints:s=!1,dragElastic:o=hd,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:i,dragPropagation:r,dragConstraints:s,dragElastic:o,dragMomentum:a}}}function $o(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function _P(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class RP extends Yi{constructor(t){super(t),this.removeGroupControls=Nn,this.removeListeners=Nn,this.controls=new EP(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Nn}unmount(){this.removeGroupControls(),this.removeListeners()}}const _m=e=>(t,n)=>{e&&vt.postRender(()=>e(t,n))};class AP extends Yi{constructor(){super(...arguments),this.removePointerDownListener=Nn}onPointerDown(t){this.session=new lx(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:cx(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:i,onPanEnd:r}=this.node.getProps();return{onSessionStart:_m(t),onStart:_m(n),onMove:i,onEnd:(s,o)=>{delete this.session,r&&vt.postRender(()=>r(s,o))}}}mount(){this.removePointerDownListener=Ks(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Ca={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Rm(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Ns={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(Me.test(e))e=parseFloat(e);else return e;const n=Rm(e,t.target.x),i=Rm(e,t.target.y);return`${n}% ${i}%`}},PP={correct:(e,{treeScale:t,projectionDelta:n})=>{const i=e,r=zi.parse(e);if(r.length>5)return i;const s=zi.createTransformer(e),o=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+o]/=a,r[1+o]/=c;const l=St(a,c,.5);return typeof r[2+o]=="number"&&(r[2+o]/=l),typeof r[3+o]=="number"&&(r[3+o]/=l),s(r)}};let Tl=!1;class NP extends O.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i,layoutId:r}=this.props,{projection:s}=t;QR(IP),s&&(n.group&&n.group.add(s),i&&i.register&&r&&i.register(s),Tl&&s.root.didUpdate(),s.addEventListener("animationComplete",()=>{this.safeToRemove()}),s.setOptions({...s.options,onExitComplete:()=>this.safeToRemove()})),Ca.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:i,drag:r,isPresent:s}=this.props,{projection:o}=i;return o&&(o.isPresent=s,Tl=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==s?o.willUpdate():this.safeToRemove(),t.isPresent!==s&&(s?o.promote():o.relegate()||vt.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),_h.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:r}=t;Tl=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),i&&i.deregister&&i.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function dx(e){const[t,n]=Mv(),i=O.useContext(sh);return m.jsx(NP,{...e,layoutGroup:i,switchLayoutGroup:O.useContext(Wv),isPresent:t,safeToRemove:n})}const IP={borderRadius:{...Ns,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Ns,borderTopRightRadius:Ns,borderBottomLeftRadius:Ns,borderBottomRightRadius:Ns,boxShadow:PP};function MP(e,t,n){const i=Jt(e)?e:cs(e);return i.start(jh("",i,t,n)),i.animation}const OP=(e,t)=>e.depth-t.depth;class DP{constructor(){this.children=[],this.isDirty=!1}add(t){ch(this.children,t),this.isDirty=!0}remove(t){lh(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(OP),this.isDirty=!1,this.children.forEach(t)}}function LP(e,t){const n=fn.now(),i=({timestamp:r})=>{const s=r-n;s>=t&&($i(i),e(s-t))};return vt.setup(i,!0),()=>$i(i)}const hx=["TopLeft","TopRight","BottomLeft","BottomRight"],FP=hx.length,Am=e=>typeof e=="string"?parseFloat(e):e,Pm=e=>typeof e=="number"||Me.test(e);function jP(e,t,n,i,r,s){r?(e.opacity=St(0,n.opacity??1,UP(i)),e.opacityExit=St(t.opacity??1,0,BP(i))):s&&(e.opacity=St(t.opacity??1,n.opacity??1,i));for(let o=0;o<FP;o++){const a=`border${hx[o]}Radius`;let c=Nm(t,a),l=Nm(n,a);if(c===void 0&&l===void 0)continue;c||(c=0),l||(l=0),c===0||l===0||Pm(c)===Pm(l)?(e[a]=Math.max(St(Am(c),Am(l),i),0),(ti.test(l)||ti.test(c))&&(e[a]+="%")):e[a]=l}(t.rotate||n.rotate)&&(e.rotate=St(t.rotate||0,n.rotate||0,i))}function Nm(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const UP=fx(0,.5,Q0),BP=fx(.5,.95,Nn);function fx(e,t,n){return i=>i<e?0:i>t?1:n(ro(e,t,i))}function Im(e,t){e.min=t.min,e.max=t.max}function En(e,t){Im(e.x,t.x),Im(e.y,t.y)}function Mm(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Om(e,t,n,i,r){return e-=t,e=Ga(e,1/n,i),r!==void 0&&(e=Ga(e,1/r,i)),e}function VP(e,t=0,n=1,i=.5,r,s=e,o=e){if(ti.test(t)&&(t=parseFloat(t),t=St(o.min,o.max,t/100)-o.min),typeof t!="number")return;let a=St(s.min,s.max,i);e===s&&(a-=t),e.min=Om(e.min,t,n,a,r),e.max=Om(e.max,t,n,a,r)}function Dm(e,t,[n,i,r],s,o){VP(e,t[n],t[i],t[r],t.scale,s,o)}const $P=["x","scaleX","originX"],zP=["y","scaleY","originY"];function Lm(e,t,n,i){Dm(e.x,t,$P,n?n.x:void 0,i?i.x:void 0),Dm(e.y,t,zP,n?n.y:void 0,i?i.y:void 0)}function Fm(e){return e.translate===0&&e.scale===1}function px(e){return Fm(e.x)&&Fm(e.y)}function jm(e,t){return e.min===t.min&&e.max===t.max}function HP(e,t){return jm(e.x,t.x)&&jm(e.y,t.y)}function Um(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function mx(e,t){return Um(e.x,t.x)&&Um(e.y,t.y)}function Bm(e){return sn(e.x)/sn(e.y)}function Vm(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class WP{constructor(){this.members=[]}add(t){ch(this.members,t),t.scheduleRender()}remove(t){if(lh(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let i;for(let r=n;r>=0;r--){const s=this.members[r];if(s.isPresent!==!1){i=s;break}}return i?(this.promote(i),!0):!1}promote(t,n){const i=this.lead;if(t!==i&&(this.prevLead=i,this.lead=t,t.show(),i)){i.instance&&i.scheduleRender(),t.scheduleRender(),t.resumeFrom=i,n&&(t.resumeFrom.preserveOpacity=!0),i.snapshot&&(t.snapshot=i.snapshot,t.snapshot.latestValues=i.animationValues||i.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:i}=t;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function qP(e,t,n){let i="";const r=e.x.translate/t.x,s=e.y.translate/t.y,o=(n==null?void 0:n.z)||0;if((r||s||o)&&(i=`translate3d(${r}px, ${s}px, ${o}px) `),(t.x!==1||t.y!==1)&&(i+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:l,rotate:u,rotateX:d,rotateY:h,skewX:f,skewY:g}=n;l&&(i=`perspective(${l}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),h&&(i+=`rotateY(${h}deg) `),f&&(i+=`skewX(${f}deg) `),g&&(i+=`skewY(${g}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(i+=`scale(${a}, ${c})`),i||"none"}const Cl=["","X","Y","Z"],GP=1e3;let KP=0;function El(e,t,n,i){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),i&&(i[e]=0))}function gx(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=tx(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:s}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",vt,!(r||s))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&gx(i)}function bx({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:i,resetTransform:r}){return class{constructor(o={},a=t==null?void 0:t()){this.id=KP++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(XP),this.nodes.forEach(tN),this.nodes.forEach(nN),this.nodes.forEach(JP)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new DP)}addEventListener(o,a){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new dh),this.eventHandlers.get(o).add(a)}notifyListeners(o,...a){const c=this.eventHandlers.get(o);c&&c.notify(...a)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=Iv(o)&&!BR(o),this.instance=o;const{layoutId:a,layout:c,visualElement:l}=this.options;if(l&&!l.current&&l.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),e){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;vt.read(()=>{d=window.innerWidth}),e(o,()=>{const f=window.innerWidth;f!==d&&(d=f,this.root.updateBlockedByResize=!0,u&&u(),u=LP(h,250),Ca.hasAnimatedSinceResize&&(Ca.hasAnimatedSinceResize=!1,this.nodes.forEach(Hm)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&l&&(a||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||l.getDefaultTransition()||aN,{onLayoutAnimationStart:p,onLayoutAnimationComplete:v}=l.getProps(),b=!this.targetLayout||!mx(this.targetLayout,f),w=!d&&h;if(this.options.layoutRoot||this.resumeFrom||w||d&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...Ch(g,"layout"),onPlay:p,onComplete:v};(l.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,w)}else d||Hm(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),$i(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(iN),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&gx(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const l=this.getTransformTemplate();this.prevTransformTemplateValue=l?l(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach($m);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(zm);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(eN),this.nodes.forEach(YP),this.nodes.forEach(ZP)):this.nodes.forEach(zm),this.clearAllSnapshots();const a=fn.now();Yt.delta=ki(0,1e3/60,a-Yt.timestamp),Yt.timestamp=a,Yt.isProcessing=!0,pl.update.process(Yt),pl.preRender.process(Yt),pl.render.process(Yt),Yt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,_h.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(QP),this.sharedNodes.forEach(rN)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,vt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){vt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!sn(this.snapshot.measuredBox.x)&&!sn(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Pt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,o?o.layoutBox:void 0)}updateScroll(o="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(a=!1),a&&this.instance){const c=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!r)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!px(this.projectionDelta),c=this.getTransformTemplate(),l=c?c(this.latestValues,""):void 0,u=l!==this.prevTransformTemplateValue;o&&this.instance&&(a||rr(this.latestValues)||u)&&(r(this.instance,l),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return o&&(c=this.removeTransform(c)),cN(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var l;const{visualElement:o}=this.options;if(!o)return Pt();const a=o.measureViewportBox();if(!(((l=this.scroll)==null?void 0:l.wasRoot)||this.path.some(lN))){const{scroll:u}=this.root;u&&(Gr(a.x,u.offset.x),Gr(a.y,u.offset.y))}return a}removeElementScroll(o){var c;const a=Pt();if(En(a,o),(c=this.scroll)!=null&&c.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&En(a,o),Gr(a.x,d.offset.x),Gr(a.y,d.offset.y))}return a}applyTransform(o,a=!1){const c=Pt();En(c,o);for(let l=0;l<this.path.length;l++){const u=this.path[l];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&Kr(c,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),rr(u.latestValues)&&Kr(c,u.latestValues)}return rr(this.latestValues)&&Kr(c,this.latestValues),c}removeTransform(o){const a=Pt();En(a,o);for(let c=0;c<this.path.length;c++){const l=this.path[c];if(!l.instance||!rr(l.latestValues))continue;od(l.latestValues)&&l.updateSnapshot();const u=Pt(),d=l.measurePageBox();En(u,d),Lm(a,l.latestValues,l.snapshot?l.snapshot.layoutBox:void 0,u)}return rr(this.latestValues)&&Lm(a,this.latestValues),a}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Yt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(o||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Yt.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Pt(),this.relativeTargetOrigin=Pt(),Zs(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),En(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Pt(),this.targetWithTransforms=Pt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),mP(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):En(this.target,this.layout.layoutBox),Yv(this.target,this.targetDelta)):En(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const f=this.getClosestProjectingParent();f&&!!f.resumingFrom==!!this.resumingFrom&&!f.options.layoutScroll&&f.target&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Pt(),this.relativeTargetOrigin=Pt(),Zs(this.relativeTargetOrigin,this.target,f.target),En(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||od(this.parent.latestValues)||Kv(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const o=this.getLead(),a=!!this.resumingFrom||this!==o;let c=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Yt.timestamp&&(c=!1),c)return;const{layout:l,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(l||u))return;En(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;_A(this.layoutCorrected,this.treeScale,this.path,a),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=Pt());const{target:f}=o;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Mm(this.prevProjectionDelta.x,this.projectionDelta.x),Mm(this.prevProjectionDelta.y,this.projectionDelta.y)),Ys(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Vm(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vm(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",f))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),o){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Yr(),this.projectionDelta=Yr(),this.projectionDeltaWithTransform=Yr()}setAnimationOrigin(o,a=!1){const c=this.snapshot,l=c?c.latestValues:{},u={...this.latestValues},d=Yr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=Pt(),f=c?c.source:void 0,g=this.layout?this.layout.source:void 0,p=f!==g,v=this.getStack(),b=!v||v.members.length<=1,w=!!(p&&!b&&this.options.crossfade===!0&&!this.path.some(oN));this.animationProgress=0;let S;this.mixTargetDelta=k=>{const x=k/1e3;Wm(d.x,o.x,x),Wm(d.y,o.y,x),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Zs(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),sN(this.relativeTarget,this.relativeTargetOrigin,h,x),S&&HP(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=Pt()),En(S,this.relativeTarget)),p&&(this.animationValues=u,jP(u,l,this.latestValues,x,w,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=x},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var a,c,l;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(l=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||l.stop(),this.pendingAnimation&&($i(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=vt.update(()=>{Ca.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=cs(0)),this.currentAnimation=MP(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),o.onUpdate&&o.onUpdate(u)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(GP),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:c,layout:l,latestValues:u}=o;if(!(!a||!c||!l)){if(this!==o&&this.layout&&l&&yx(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||Pt();const d=sn(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+d;const h=sn(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}En(a,c),Kr(a,u),Ys(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new WP),this.sharedNodes.get(o).add(a);const l=a.options.initialPromotionConfig;a.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.shouldPreserveFollowOpacity(a):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var a;const{layoutId:o}=this.options;return o?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:o}=this.options;return o?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:c}={}){const l=this.getStack();l&&l.promote(this,c),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:c}=o;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const l={};c.z&&El("z",o,l,this.animationValues);for(let u=0;u<Cl.length;u++)El(`rotate${Cl[u]}`,o,l,this.animationValues),El(`skew${Cl[u]}`,o,l,this.animationValues);o.render();for(const u in l)o.setStaticValue(u,l[u]),this.animationValues&&(this.animationValues[u]=l[u]);o.scheduleRender()}applyProjectionStyles(o,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=Ta(a==null?void 0:a.pointerEvents)||"",o.transform=c?c(this.latestValues,""):"none";return}const l=this.getLead();if(!this.projectionDelta||!this.layout||!l.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=Ta(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!rr(this.latestValues)&&(o.transform=c?c({},""):"none",this.hasProjected=!1);return}o.visibility="";const u=l.animationValues||l.latestValues;this.applyTransformsToTarget();let d=qP(this.projectionDeltaWithTransform,this.treeScale,u);c&&(d=c(u,d)),o.transform=d;const{x:h,y:f}=this.projectionDelta;o.transformOrigin=`${h.origin*100}% ${f.origin*100}% 0`,l.animationValues?o.opacity=l===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:o.opacity=l===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in co){if(u[g]===void 0)continue;const{correct:p,applyTo:v,isCSSVariable:b}=co[g],w=d==="none"?u[g]:p(u[g],l);if(v){const S=v.length;for(let k=0;k<S;k++)o[v[k]]=w}else b?this.options.visualElement.renderState.vars[g]=w:o[g]=w}this.options.layoutId&&(o.pointerEvents=l===this?Ta(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var a;return(a=o.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach($m),this.root.sharedNodes.clear()}}}function YP(e){e.updateLayout()}function ZP(e){var n;const t=((n=e.resumeFrom)==null?void 0:n.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:r}=e.layout,{animationType:s}=e.options,o=t.source!==e.layout.source;s==="size"?_n(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],f=sn(h);h.min=i[d].min,h.max=h.min+f}):yx(s,t.layoutBox,i)&&_n(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],f=sn(i[d]);h.max=h.min+f,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+f)});const a=Yr();Ys(a,i,t.layoutBox);const c=Yr();o?Ys(c,e.applyTransform(r,!0),t.measuredBox):Ys(c,i,t.layoutBox);const l=!px(a);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:f}=d;if(h&&f){const g=Pt();Zs(g,t.layoutBox,h.layoutBox);const p=Pt();Zs(p,i,f.layoutBox),mx(g,p)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=p,e.relativeTargetOrigin=g,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:t,delta:c,layoutDelta:a,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function XP(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function JP(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function QP(e){e.clearSnapshot()}function $m(e){e.clearMeasurements()}function zm(e){e.isLayoutDirty=!1}function eN(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Hm(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function tN(e){e.resolveTargetDelta()}function nN(e){e.calcProjection()}function iN(e){e.resetSkewAndRotation()}function rN(e){e.removeLeadSnapshot()}function Wm(e,t,n){e.translate=St(t.translate,0,n),e.scale=St(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function qm(e,t,n,i){e.min=St(t.min,n.min,i),e.max=St(t.max,n.max,i)}function sN(e,t,n,i){qm(e.x,t.x,n.x,i),qm(e.y,t.y,n.y,i)}function oN(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const aN={duration:.45,ease:[.4,0,.1,1]},Gm=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Km=Gm("applewebkit/")&&!Gm("chrome/")?Math.round:Nn;function Ym(e){e.min=Km(e.min),e.max=Km(e.max)}function cN(e){Ym(e.x),Ym(e.y)}function yx(e,t,n){return e==="position"||e==="preserve-aspect"&&!pP(Bm(t),Bm(n),.2)}function lN(e){var t;return e!==e.root&&((t=e.scroll)==null?void 0:t.wasRoot)}const uN=bx({attachResizeListener:(e,t)=>lo(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),_l={current:void 0},vx=bx({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!_l.current){const e=new uN({});e.mount(window),e.setOptions({layoutScroll:!0}),_l.current=e}return _l.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),dN={pan:{Feature:AP},drag:{Feature:RP,ProjectionNode:vx,MeasureLayout:dx}};function Zm(e,t,n){const{props:i}=e;e.animationState&&i.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,s=i[r];s&&vt.postRender(()=>s(t,vo(t)))}class hN extends Yi{mount(){const{current:t}=this.node;t&&(this.unmount=DR(t,(n,i)=>(Zm(this.node,i,"Start"),r=>Zm(this.node,r,"End"))))}unmount(){}}class fN extends Yi{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=go(lo(this.node.current,"focus",()=>this.onFocus()),lo(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Xm(e,t,n){const{props:i}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&i.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),s=i[r];s&&vt.postRender(()=>s(t,vo(t)))}class pN extends Yi{mount(){const{current:t}=this.node;t&&(this.unmount=UR(t,(n,i)=>(Xm(this.node,i,"Start"),(r,{success:s})=>Xm(this.node,r,s?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const fd=new WeakMap,Rl=new WeakMap,mN=e=>{const t=fd.get(e.target);t&&t(e)},gN=e=>{e.forEach(mN)};function bN({root:e,...t}){const n=e||document;Rl.has(n)||Rl.set(n,{});const i=Rl.get(n),r=JSON.stringify(t);return i[r]||(i[r]=new IntersectionObserver(gN,{root:e,...t})),i[r]}function yN(e,t,n){const i=bN(t);return fd.set(e,n),i.observe(e),()=>{fd.delete(e),i.unobserve(e)}}const vN={some:0,all:1};class xN extends Yi{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:i,amount:r="some",once:s}=t,o={root:n?n.current:void 0,rootMargin:i,threshold:typeof r=="number"?r:vN[r]},a=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,s&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=l?u:d;h&&h(c)};return yN(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(kN(t,n))&&this.startObserver()}unmount(){}}function kN({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const SN={inView:{Feature:xN},tap:{Feature:pN},focus:{Feature:fN},hover:{Feature:hN}},wN={layout:{ProjectionNode:vx,MeasureLayout:dx}},TN={...cP,...SN,...dN,...wN},Fe=TA(TN,FA);var zo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function xx(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pd={exports:{}},CN=pd.exports,Jm;function EN(){return Jm||(Jm=1,function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(CN,function(){var t=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(p,v){var b=p[v];if(typeof b.bind=="function")return b.bind(p);try{return Function.prototype.bind.call(b,p)}catch{return function(){return Function.prototype.apply.apply(b,[p,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&i?c:console[p]!==void 0?a(console,p):console.log!==void 0?a(console,"log"):t}function u(){for(var p=this.getLevel(),v=0;v<r.length;v++){var b=r[v];this[b]=v<p?t:this.methodFactory(b,p,this.name)}if(this.log=this.debug,typeof console===n&&p<this.levels.SILENT)return"No console available for logging"}function d(p){return function(){typeof console!==n&&(u.call(this),this[p].apply(this,arguments))}}function h(p,v,b){return l(p)||d.apply(this,arguments)}function f(p,v){var b=this,w,S,k,x="loglevel";typeof p=="string"?x+=":"+p:typeof p=="symbol"&&(x=void 0);function T(R){var I=(r[R]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=I;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+I+";"}catch{}}}function P(){var R;if(!(typeof window===n||!x)){try{R=window.localStorage[x]}catch{}if(typeof R===n)try{var I=window.document.cookie,L=encodeURIComponent(x),U=I.indexOf(L+"=");U!==-1&&(R=/^([^;]+)/.exec(I.slice(U+L.length+1))[1])}catch{}return b.levels[R]===void 0&&(R=void 0),R}}function A(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(R){var I=R;if(typeof I=="string"&&b.levels[I.toUpperCase()]!==void 0&&(I=b.levels[I.toUpperCase()]),typeof I=="number"&&I>=0&&I<=b.levels.SILENT)return I;throw new TypeError("log.setLevel() called with invalid level: "+R)}b.name=p,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=v||h,b.getLevel=function(){return k??S??w},b.setLevel=function(R,I){return k=N(R),I!==!1&&T(k),u.call(b)},b.setDefaultLevel=function(R){S=N(R),P()||b.setLevel(R,!1)},b.resetLevel=function(){k=null,A(),u.call(b)},b.enableAll=function(R){b.setLevel(b.levels.TRACE,R)},b.disableAll=function(R){b.setLevel(b.levels.SILENT,R)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var R in s)s[R].rebuild()},w=N(o?o.getLevel():"WARN");var y=P();y!=null&&(k=N(y)),u.call(b)}o=new f,o.getLogger=function(p){if(typeof p!="symbol"&&typeof p!="string"||p==="")throw new TypeError("You must supply a name when creating a logger.");var v=s[p];return v||(v=s[p]=new f(p,o.methodFactory)),v};var g=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return s},o.default=o,o})}(pd)),pd.exports}var _N=EN();const RN=xx(_N);var md=function(e,t){return md=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},md(e,t)};function Ci(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");md(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function AN(e,t,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(e,[])).next())})}function kx(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(n=0)),n;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,r=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ds(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ka(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,s=[],o;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function Ya(e,t,n){if(arguments.length===2)for(var i=0,r=t.length,s;i<r;i++)(s||!(i in t))&&(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function is(e){return this instanceof is?(this.v=e,this):new is(e)}function PN(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(e,t||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(f){return function(g){return Promise.resolve(g).then(f,d)}}function a(f,g){i[f]&&(r[f]=function(p){return new Promise(function(v,b){s.push([f,p,v,b])>1||c(f,p)})},g&&(r[f]=g(r[f])))}function c(f,g){try{l(i[f](g))}catch(p){h(s[0][3],p)}}function l(f){f.value instanceof is?Promise.resolve(f.value.v).then(u,d):h(s[0][2],f)}function u(f){c("next",f)}function d(f){c("throw",f)}function h(f,g){f(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function NN(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ds=="function"?ds(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Vt(e){return typeof e=="function"}function Uh(e){var t=function(i){Error.call(i),i.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Al=Uh(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
46
|
+
`),()=>{p.contains(g)&&p.removeChild(g)}},[t]),m.jsx(zR,{isPresent:t,childRef:s,sizeRef:o,children:D.cloneElement(e,{ref:s})})}const WR=({children:e,initial:t,isPresent:n,onExitComplete:i,custom:r,presenceAffectsLayout:s,mode:o,anchorX:a,root:c})=>{const l=oh(qR),u=O.useId();let d=!0,h=O.useMemo(()=>(d=!1,{id:u,initial:t,isPresent:n,custom:r,onExitComplete:f=>{l.set(f,!0);for(const g of l.values())if(!g)return;i&&i()},register:f=>(l.set(f,!1),()=>l.delete(f))}),[n,l,i]);return s&&d&&(h={...h}),O.useMemo(()=>{l.forEach((f,g)=>l.set(g,!1))},[n]),D.useEffect(()=>{!n&&!l.size&&i&&i()},[n]),o==="popLayout"&&(e=m.jsx(HR,{isPresent:n,anchorX:a,root:c,children:e})),m.jsx(bc.Provider,{value:h,children:e})};function qR(){return new Map}function Mv(e=!0){const t=O.useContext(bc);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:r}=t,s=O.useId();O.useEffect(()=>{if(e)return r(s)},[e]);const o=O.useCallback(()=>e&&i&&i(s),[s,i,e]);return!n&&i?[!1,o]:[!0]}const Vo=e=>e.key||"";function sm(e){const t=[];return O.Children.forEach(e,n=>{O.isValidElement(n)&&t.push(n)}),t}const ls=({children:e,custom:t,initial:n=!0,onExitComplete:i,presenceAffectsLayout:r=!0,mode:s="sync",propagate:o=!1,anchorX:a="left",root:c})=>{const[l,u]=Mv(o),d=O.useMemo(()=>sm(e),[e]),h=o&&!l?[]:d.map(Vo),f=O.useRef(!0),g=O.useRef(d),p=oh(()=>new Map),[v,b]=O.useState(d),[w,S]=O.useState(d);$y(()=>{f.current=!1,g.current=d;for(let T=0;T<w.length;T++){const P=Vo(w[T]);h.includes(P)?p.delete(P):p.get(P)!==!0&&p.set(P,!1)}},[w,h.length,h.join("-")]);const k=[];if(d!==v){let T=[...d];for(let P=0;P<w.length;P++){const A=w[P],N=Vo(A);h.includes(N)||(T.splice(P,0,A),k.push(A))}return s==="wait"&&k.length&&(T=k),S(sm(T)),b(d),null}process.env.NODE_ENV!=="production"&&s==="wait"&&w.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:x}=O.useContext(sh);return m.jsx(m.Fragment,{children:w.map(T=>{const P=Vo(T),A=o&&!l?!1:d===w||h.includes(P),N=()=>{if(p.has(P))p.set(P,!0);else return;let y=!0;p.forEach(R=>{R||(y=!1)}),y&&(x==null||x(),S(g.current),o&&(u==null||u()),i&&i())};return m.jsx(WR,{isPresent:A,initial:!f.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:s,root:c,onExitComplete:A?void 0:N,anchorX:a,children:T},P)})})},Ov=O.createContext({strict:!1}),om={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},us={};for(const e in om)us[e]={isEnabled:t=>om[e].some(n=>!!t[n])};function GR(e){for(const t in e)us[t]={...us[t],...e[t]}}const KR=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function qa(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||KR.has(e)}let Dv=e=>!qa(e);function YR(e){typeof e=="function"&&(Dv=t=>t.startsWith("on")?!qa(t):e(t))}try{YR(require("@emotion/is-prop-valid").default)}catch{}function ZR(e,t,n){const i={};for(const r in e)r==="values"&&typeof e.values=="object"||(Dv(r)||n===!0&&qa(r)||!t&&!qa(r)||e.draggable&&r.startsWith("onDrag"))&&(i[r]=e[r]);return i}const yc=O.createContext({});function vc(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function ao(e){return typeof e=="string"||Array.isArray(e)}const Ph=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Nh=["initial",...Ph];function xc(e){return vc(e.animate)||Nh.some(t=>ao(e[t]))}function Lv(e){return!!(xc(e)||e.variants)}function XR(e,t){if(xc(e)){const{initial:n,animate:i}=e;return{initial:n===!1||ao(n)?n:void 0,animate:ao(i)?i:void 0}}return e.inherit!==!1?t:{}}function JR(e){const{initial:t,animate:n}=XR(e,O.useContext(yc));return O.useMemo(()=>({initial:t,animate:n}),[am(t),am(n)])}function am(e){return Array.isArray(e)?e.join(" "):e}const co={};function QR(e){for(const t in e)co[t]=e[t],mh(t)&&(co[t].isCSSVariable=!0)}function Fv(e,{layout:t,layoutId:n}){return ys.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!co[e]||e==="opacity")}const eA={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},tA=bs.length;function nA(e,t,n){let i="",r=!0;for(let s=0;s<tA;s++){const o=bs[s],a=e[o];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(o.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const l=_v(a,Eh[o]);if(!c){r=!1;const u=eA[o]||o;i+=`${u}(${l}) `}n&&(t[o]=l)}}return i=i.trim(),n?i=n(t,r?"":i):r&&(i="none"),i}function Ih(e,t,n){const{style:i,vars:r,transformOrigin:s}=e;let o=!1,a=!1;for(const c in t){const l=t[c];if(ys.has(c)){o=!0;continue}else if(mh(c)){r[c]=l;continue}else{const u=_v(l,Eh[c]);c.startsWith("origin")?(a=!0,s[c]=u):i[c]=u}}if(t.transform||(o||n?i.transform=nA(t,e.transform,n):i.transform&&(i.transform="none")),a){const{originX:c="50%",originY:l="50%",originZ:u=0}=s;i.transformOrigin=`${c} ${l} ${u}`}}const Mh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function jv(e,t,n){for(const i in t)!Jt(t[i])&&!Fv(i,n)&&(e[i]=t[i])}function iA({transformTemplate:e},t){return O.useMemo(()=>{const n=Mh();return Ih(n,t,e),Object.assign({},n.vars,n.style)},[t])}function rA(e,t){const n=e.style||{},i={};return jv(i,n,e),Object.assign(i,iA(e,t)),i}function sA(e,t){const n={},i=rA(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=i,n}const oA={offset:"stroke-dashoffset",array:"stroke-dasharray"},aA={offset:"strokeDashoffset",array:"strokeDasharray"};function cA(e,t,n=1,i=0,r=!0){e.pathLength=1;const s=r?oA:aA;e[s.offset]=Me.transform(-i);const o=Me.transform(t),a=Me.transform(n);e[s.array]=`${o} ${a}`}function Uv(e,{attrX:t,attrY:n,attrScale:i,pathLength:r,pathSpacing:s=1,pathOffset:o=0,...a},c,l,u){if(Ih(e,a,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:d,style:h}=e;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),i!==void 0&&(d.scale=i),r!==void 0&&cA(d,r,s,o,!1)}const Bv=()=>({...Mh(),attrs:{}}),Vv=e=>typeof e=="string"&&e.toLowerCase()==="svg";function lA(e,t,n,i){const r=O.useMemo(()=>{const s=Bv();return Uv(s,t,Vv(i),e.transformTemplate,e.style),{...s.attrs,style:{...s.style}}},[t]);if(e.style){const s={};jv(s,e.style,e),r.style={...s,...r.style}}return r}const uA=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Oh(e){return typeof e!="string"||e.includes("-")?!1:!!(uA.indexOf(e)>-1||/[A-Z]/u.test(e))}function dA(e,t,n,{latestValues:i},r,s=!1){const a=(Oh(e)?lA:sA)(t,i,r,e),c=ZR(t,typeof e=="string",s),l=e!==O.Fragment?{...c,...a,ref:n}:{},{children:u}=t,d=O.useMemo(()=>Jt(u)?u.get():u,[u]);return O.createElement(e,{...l,children:d})}function cm(e){const t=[{},{}];return e==null||e.values.forEach((n,i)=>{t[0][i]=n.get(),t[1][i]=n.getVelocity()}),t}function Dh(e,t,n,i){if(typeof t=="function"){const[r,s]=cm(i);t=t(n!==void 0?n:e.custom,r,s)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,s]=cm(i);t=t(n!==void 0?n:e.custom,r,s)}return t}function Ta(e){return Jt(e)?e.get():e}function hA({scrapeMotionValuesFromProps:e,createRenderState:t},n,i,r){return{latestValues:fA(n,i,r,e),renderState:t()}}function fA(e,t,n,i){const r={},s=i(e,{});for(const h in s)r[h]=Ta(s[h]);let{initial:o,animate:a}=e;const c=xc(e),l=Lv(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),a===void 0&&(a=t.animate));let u=n?n.initial===!1:!1;u=u||o===!1;const d=u?a:o;if(d&&typeof d!="boolean"&&!vc(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f<h.length;f++){const g=Dh(e,h[f]);if(g){const{transitionEnd:p,transition:v,...b}=g;for(const w in b){let S=b[w];if(Array.isArray(S)){const k=u?S.length-1:0;S=S[k]}S!==null&&(r[w]=S)}for(const w in p)r[w]=p[w]}}}return r}const $v=e=>(t,n)=>{const i=O.useContext(yc),r=O.useContext(bc),s=()=>hA(e,t,i,r);return n?s():oh(s)};function Lh(e,t,n){var s;const{style:i}=e,r={};for(const o in i)(Jt(i[o])||t.style&&Jt(t.style[o])||Fv(o,e)||((s=n==null?void 0:n.getValue(o))==null?void 0:s.liveStyle)!==void 0)&&(r[o]=i[o]);return r}const pA=$v({scrapeMotionValuesFromProps:Lh,createRenderState:Mh});function zv(e,t,n){const i=Lh(e,t,n);for(const r in e)if(Jt(e[r])||Jt(t[r])){const s=bs.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;i[s]=e[r]}return i}const mA=$v({scrapeMotionValuesFromProps:zv,createRenderState:Bv}),gA=Symbol.for("motionComponentSymbol");function qr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function bA(e,t,n){return O.useCallback(i=>{i&&e.onMount&&e.onMount(i),t&&(i?t.mount(i):t.unmount()),n&&(typeof n=="function"?n(i):qr(n)&&(n.current=i))},[t])}const Fh=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),yA="framerAppearId",Hv="data-"+Fh(yA),Wv=O.createContext({});function vA(e,t,n,i,r){var p,v;const{visualElement:s}=O.useContext(yc),o=O.useContext(Ov),a=O.useContext(bc),c=O.useContext(Ah).reducedMotion,l=O.useRef(null);i=i||o.renderer,!l.current&&i&&(l.current=i(e,{visualState:t,parent:s,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const u=l.current,d=O.useContext(Wv);u&&!u.projection&&r&&(u.type==="html"||u.type==="svg")&&xA(l.current,n,r,d);const h=O.useRef(!1);O.useInsertionEffect(()=>{u&&h.current&&u.update(n,a)});const f=n[Hv],g=O.useRef(!!f&&!((p=window.MotionHandoffIsComplete)!=null&&p.call(window,f))&&((v=window.MotionHasOptimisedAnimation)==null?void 0:v.call(window,f)));return $y(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),u.scheduleRenderMicrotask(),g.current&&u.animationState&&u.animationState.animateChanges())}),O.useEffect(()=>{u&&(!g.current&&u.animationState&&u.animationState.animateChanges(),g.current&&(queueMicrotask(()=>{var b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,f)}),g.current=!1),u.enteringChildren=void 0)}),u}function xA(e,t,n,i){const{layoutId:r,layout:s,drag:o,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:qv(e.parent)),e.projection.setOptions({layoutId:r,layout:s,alwaysMeasureLayout:!!o||a&&qr(a),visualElement:e,animationType:typeof s=="string"?s:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function qv(e){if(e)return e.options.allowProjection!==!1?e.projection:qv(e.parent)}function xl(e,{forwardMotionProps:t=!1}={},n,i){n&&GR(n);const r=Oh(e)?mA:pA;function s(a,c){let l;const u={...O.useContext(Ah),...a,layoutId:kA(a)},{isStatic:d}=u,h=JR(a),f=r(a,d);if(!d&&ah){SA(u,n);const g=wA(u);l=g.MeasureLayout,h.visualElement=vA(e,f,u,i,g.ProjectionNode)}return m.jsxs(yc.Provider,{value:h,children:[l&&h.visualElement?m.jsx(l,{visualElement:h.visualElement,...u}):null,dA(e,a,bA(f,h.visualElement,c),f,d,t)]})}s.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const o=O.forwardRef(s);return o[gA]=e,o}function kA({layoutId:e}){const t=O.useContext(sh).id;return t&&e!==void 0?t+"-"+e:e}function SA(e,t){const n=O.useContext(Ov).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const i="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?ms(!1,i,"lazy-strict-mode"):Si(!1,i,"lazy-strict-mode")}}function wA(e){const{drag:t,layout:n}=us;if(!t&&!n)return{};const i={...t,...n};return{MeasureLayout:t!=null&&t.isEnabled(e)||n!=null&&n.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function TA(e,t){if(typeof Proxy>"u")return xl;const n=new Map,i=(s,o)=>xl(s,o,e,t),r=(s,o)=>(process.env.NODE_ENV!=="production"&&hh(!1,"motion() is deprecated. Use motion.create() instead."),i(s,o));return new Proxy(r,{get:(s,o)=>o==="create"?i:(n.has(o)||n.set(o,xl(o,void 0,e,t)),n.get(o))})}function Gv({top:e,left:t,right:n,bottom:i}){return{x:{min:t,max:n},y:{min:e,max:i}}}function CA({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function EA(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),i=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}function kl(e){return e===void 0||e===1}function od({scale:e,scaleX:t,scaleY:n}){return!kl(e)||!kl(t)||!kl(n)}function rr(e){return od(e)||Kv(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Kv(e){return lm(e.x)||lm(e.y)}function lm(e){return e&&e!=="0%"}function Ga(e,t,n){const i=e-n,r=t*i;return n+r}function um(e,t,n,i,r){return r!==void 0&&(e=Ga(e,r,i)),Ga(e,n,i)+t}function ad(e,t=0,n=1,i,r){e.min=um(e.min,t,n,i,r),e.max=um(e.max,t,n,i,r)}function Yv(e,{x:t,y:n}){ad(e.x,t.translate,t.scale,t.originPoint),ad(e.y,n.translate,n.scale,n.originPoint)}const dm=.999999999999,hm=1.0000000000001;function _A(e,t,n,i=!1){const r=n.length;if(!r)return;t.x=t.y=1;let s,o;for(let a=0;a<r;a++){s=n[a],o=s.projectionDelta;const{visualElement:c}=s.options;c&&c.props.style&&c.props.style.display==="contents"||(i&&s.options.layoutScroll&&s.scroll&&s!==s.root&&Kr(e,{x:-s.scroll.offset.x,y:-s.scroll.offset.y}),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Yv(e,o)),i&&rr(s.latestValues)&&Kr(e,s.latestValues))}t.x<hm&&t.x>dm&&(t.x=1),t.y<hm&&t.y>dm&&(t.y=1)}function Gr(e,t){e.min=e.min+t,e.max=e.max+t}function fm(e,t,n,i,r=.5){const s=St(e.min,e.max,r);ad(e,t,n,s,i)}function Kr(e,t){fm(e.x,t.x,t.scaleX,t.scale,t.originX),fm(e.y,t.y,t.scaleY,t.scale,t.originY)}function Zv(e,t){return Gv(EA(e.getBoundingClientRect(),t))}function RA(e,t,n){const i=Zv(e,n),{scroll:r}=t;return r&&(Gr(i.x,r.offset.x),Gr(i.y,r.offset.y)),i}const pm=()=>({translate:0,scale:1,origin:0,originPoint:0}),Yr=()=>({x:pm(),y:pm()}),mm=()=>({min:0,max:0}),Pt=()=>({x:mm(),y:mm()}),cd={current:null},Xv={current:!1};function AA(){if(Xv.current=!0,!!ah)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>cd.current=e.matches;e.addEventListener("change",t),t()}else cd.current=!1}const PA=new WeakMap;function NA(e,t,n){for(const i in t){const r=t[i],s=n[i];if(Jt(r))e.addValue(i,r);else if(Jt(s))e.addValue(i,cs(r,{owner:e}));else if(s!==r)if(e.hasValue(i)){const o=e.getValue(i);o.liveStyle===!0?o.jump(r):o.hasAnimated||o.set(r)}else{const o=e.getStaticValue(i);e.addValue(i,cs(o!==void 0?o:r,{owner:e}))}}for(const i in n)t[i]===void 0&&e.removeValue(i);return t}const gm=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class IA{scrapeMotionValuesFromProps(t,n,i){return{}}constructor({parent:t,props:n,presenceContext:i,reducedMotionConfig:r,blockInitialAnimation:s,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Th,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=fn.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,vt.render(this.render,!1,!0))};const{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=l,this.parent=t,this.props=n,this.presenceContext=i,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!s,this.isControllingVariants=xc(n),this.isVariantNode=Lv(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const h in d){const f=d[h];c[h]!==void 0&&Jt(f)&&f.set(c[h])}}mount(t){var n;this.current=t,PA.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,r)=>this.bindToMotionValue(r,i)),Xv.current||AA(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:cd.current,process.env.NODE_ENV!=="production"&&hh(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext)}unmount(){var t;this.projection&&this.projection.unmount(),$i(this.notifyUpdate),$i(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const i=this.features[n];i&&(i.unmount(),i.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const i=ys.has(t);i&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",o=>{this.latestValues[t]=o,this.props.onUpdate&&vt.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let s;window.MotionCheckAppearSync&&(s=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),s&&s(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in us){const n=us[t];if(!n)continue;const{isEnabled:i,Feature:r}=n;if(!this.features[t]&&r&&i(this.props)&&(this.features[t]=new r(this)),this.features[t]){const s=this.features[t];s.isMounted?s.update():(s.mount(),s.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Pt()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<gm.length;i++){const r=gm[i];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const s="on"+r,o=t[s];o&&(this.propEventSubscriptions[r]=this.on(r,o))}this.prevMotionValues=NA(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const i=this.values.get(t);n!==i&&(i&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let i=this.values.get(t);return i===void 0&&n!==void 0&&(i=cs(n===null?void 0:n,{owner:this}),this.addValue(t,i)),i}readValue(t,n){let i=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return i!=null&&(typeof i=="string"&&(zy(i)||Wy(i))?i=parseFloat(i):!$R(i)&&zi.test(n)&&(i=Ev(t,n)),this.setBaseTarget(t,Jt(i)?i.get():i)),Jt(i)?i.get():i}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var s;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const o=Dh(this.props,n,(s=this.presenceContext)==null?void 0:s.custom);o&&(i=o[t])}if(n&&i!==void 0)return i;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!Jt(r)?r:this.initialValues[t]!==void 0&&i===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new dh),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){_h.render(this.render)}}class Jv extends IA{constructor(){super(...arguments),this.KeyframeResolver=PR}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:i}){delete n[t],delete i[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Jt(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Qv(e,{style:t,vars:n},i,r){const s=e.style;let o;for(o in t)s[o]=t[o];r==null||r.applyProjectionStyles(s,i);for(o in n)s.setProperty(o,n[o])}function MA(e){return window.getComputedStyle(e)}class OA extends Jv{constructor(){super(...arguments),this.type="html",this.renderInstance=Qv}readValueFromInstance(t,n){var i;if(ys.has(n))return(i=this.projection)!=null&&i.isProjecting?Qu(n):K1(t,n);{const r=MA(t),s=(mh(n)?r.getPropertyValue(n):r[n])||0;return typeof s=="string"?s.trim():s}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Zv(t,n)}build(t,n,i){Ih(t,n,i.transformTemplate)}scrapeMotionValuesFromProps(t,n,i){return Lh(t,n,i)}}const ex=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function DA(e,t,n,i){Qv(e,t,void 0,i);for(const r in t.attrs)e.setAttribute(ex.has(r)?r:Fh(r),t.attrs[r])}class LA extends Jv{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Pt}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(ys.has(n)){const i=Cv(n);return i&&i.default||0}return n=ex.has(n)?n:Fh(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,i){return zv(t,n,i)}build(t,n,i){Uv(t,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(t,n,i,r){DA(t,n,i,r)}mount(t){this.isSVGTag=Vv(t.tagName),super.mount(t)}}const FA=(e,t)=>Oh(e)?new LA(t):new OA(t,{allowProjection:e!==O.Fragment});function ns(e,t,n){const i=e.getProps();return Dh(i,t,n!==void 0?n:i.custom,e)}const ld=e=>Array.isArray(e);function jA(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,cs(n))}function UA(e){return ld(e)?e[e.length-1]||0:e}function BA(e,t){const n=ns(e,t);let{transitionEnd:i={},transition:r={},...s}=n||{};s={...s,...i};for(const o in s){const a=UA(s[o]);jA(e,o,a)}}function VA(e){return!!(Jt(e)&&e.add)}function ud(e,t){const n=e.getValue("willChange");if(VA(n))return n.add(t);if(!n&&wi.WillChange){const i=new wi.WillChange("auto");e.addValue("willChange",i),i.add(t)}}function tx(e){return e.props[Hv]}const $A=e=>e!==null;function zA(e,{repeat:t,repeatType:n="loop"},i){const r=e.filter($A),s=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[s]}const HA={type:"spring",stiffness:500,damping:25,restSpeed:10},WA=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),qA={type:"keyframes",duration:.8},GA={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},KA=(e,{keyframes:t})=>t.length>2?qA:ys.has(e)?e.startsWith("scale")?WA(t[1]):HA:GA;function YA({when:e,delay:t,delayChildren:n,staggerChildren:i,staggerDirection:r,repeat:s,repeatType:o,repeatDelay:a,from:c,elapsed:l,...u}){return!!Object.keys(u).length}const jh=(e,t,n,i={},r,s)=>o=>{const a=Ch(i,e)||{},c=a.delay||i.delay||0;let{elapsed:l=0}=i;l=l-$n(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-l,onUpdate:h=>{t.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:s?void 0:r};YA(a)||Object.assign(u,KA(e,u)),u.duration&&(u.duration=$n(u.duration)),u.repeatDelay&&(u.repeatDelay=$n(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(rd(u),u.delay===0&&(d=!0)),(wi.instantAnimations||wi.skipAnimations)&&(d=!0,rd(u),u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!s&&t.get()!==void 0){const h=zA(u.keyframes,a);if(h!==void 0){vt.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new wh(u):new bR(u)};function ZA({protectedKeys:e,needsAnimating:t},n){const i=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,i}function nx(e,t,{delay:n=0,transitionOverride:i,type:r}={}){let{transition:s=e.getDefaultTransition(),transitionEnd:o,...a}=t;i&&(s=i);const c=[],l=r&&e.animationState&&e.animationState.getState()[r];for(const u in a){const d=e.getValue(u,e.latestValues[u]??null),h=a[u];if(h===void 0||l&&ZA(l,u))continue;const f={delay:n,...Ch(s||{},u)},g=d.get();if(g!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===g&&!f.velocity)continue;let p=!1;if(window.MotionHandoffAnimation){const b=tx(e);if(b){const w=window.MotionHandoffAnimation(b,u,vt);w!==null&&(f.startTime=w,p=!0)}}ud(e,u),d.start(jh(u,d,h,e.shouldReduceMotion&&Sv.has(u)?{type:!1}:f,e,p));const v=d.animation;v&&c.push(v)}return o&&Promise.all(c).then(()=>{vt.update(()=>{o&&BA(e,o)})}),c}function ix(e,t,n,i=0,r=1){const s=Array.from(e).sort((l,u)=>l.sortNodePosition(u)).indexOf(t),o=e.size,a=(o-1)*i;return typeof n=="function"?n(s,o):r===1?s*i:a-s*i}function dd(e,t,n={}){var c;const i=ns(e,t,n.type==="exit"?(c=e.presenceContext)==null?void 0:c.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(r=n.transitionOverride);const s=i?()=>Promise.all(nx(e,i,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=r;return XA(e,t,l,u,d,h,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,u]=a==="beforeChildren"?[s,o]:[o,s];return l().then(()=>u())}else return Promise.all([s(),o(n.delay)])}function XA(e,t,n=0,i=0,r=0,s=1,o){const a=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),a.push(dd(c,t,{...o,delay:n+(typeof i=="function"?0:i)+ix(e.variantChildren,c,i,r,s)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(a)}function JA(e,t,n={}){e.notify("AnimationStart",t);let i;if(Array.isArray(t)){const r=t.map(s=>dd(e,s,n));i=Promise.all(r)}else if(typeof t=="string")i=dd(e,t,n);else{const r=typeof t=="function"?ns(e,t,n.custom):t;i=Promise.all(nx(e,r,n))}return i.then(()=>{e.notify("AnimationComplete",t)})}function rx(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i<n;i++)if(t[i]!==e[i])return!1;return!0}const QA=Nh.length;function sx(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?sx(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<QA;n++){const i=Nh[n],r=e.props[i];(ao(r)||r===!1)&&(t[i]=r)}return t}const eP=[...Ph].reverse(),tP=Ph.length;function nP(e){return t=>Promise.all(t.map(({animation:n,options:i})=>JA(e,n,i)))}function iP(e){let t=nP(e),n=bm(),i=!0;const r=c=>(l,u)=>{var h;const d=ns(e,u,c==="exit"?(h=e.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:f,transitionEnd:g,...p}=d;l={...l,...p,...g}}return l};function s(c){t=c(e)}function o(c){const{props:l}=e,u=sx(e.parent)||{},d=[],h=new Set;let f={},g=1/0;for(let v=0;v<tP;v++){const b=eP[v],w=n[b],S=l[b]!==void 0?l[b]:u[b],k=ao(S),x=b===c?w.isActive:null;x===!1&&(g=v);let T=S===u[b]&&S!==l[b]&&k;if(T&&i&&e.manuallyAnimateOnMount&&(T=!1),w.protectedKeys={...f},!w.isActive&&x===null||!S&&!w.prevProp||vc(S)||typeof S=="boolean")continue;const P=rP(w.prevProp,S);let A=P||b===c&&w.isActive&&!T&&k||v>g&&k,N=!1;const y=Array.isArray(S)?S:[S];let R=y.reduce(r(b),{});x===!1&&(R={});const{prevResolvedValues:I={}}=w,L={...I,...R},U=se=>{A=!0,h.has(se)&&(N=!0,h.delete(se)),w.needsAnimating[se]=!0;const z=e.getValue(se);z&&(z.liveStyle=!1)};for(const se in L){const z=R[se],H=I[se];if(f.hasOwnProperty(se))continue;let C=!1;ld(z)&&ld(H)?C=!rx(z,H):C=z!==H,C?z!=null?U(se):h.add(se):z!==void 0&&h.has(se)?U(se):w.protectedKeys[se]=!0}w.prevProp=S,w.prevResolvedValues=R,w.isActive&&(f={...f,...R}),i&&e.blockInitialAnimation&&(A=!1);const K=T&&P;A&&(!K||N)&&d.push(...y.map(se=>{const z={type:b};if(typeof se=="string"&&i&&!K&&e.manuallyAnimateOnMount&&e.parent){const{parent:H}=e,C=ns(H,se);if(H.enteringChildren&&C){const{delayChildren:W}=C.transition||{};z.delay=ix(H.enteringChildren,e,W)}}return{animation:se,options:z}}))}if(h.size){const v={};if(typeof l.initial!="boolean"){const b=ns(e,Array.isArray(l.initial)?l.initial[0]:l.initial);b&&b.transition&&(v.transition=b.transition)}h.forEach(b=>{const w=e.getBaseTarget(b),S=e.getValue(b);S&&(S.liveStyle=!0),v[b]=w??null}),d.push({animation:v})}let p=!!d.length;return i&&(l.initial===!1||l.initial===l.animate)&&!e.manuallyAnimateOnMount&&(p=!1),i=!1,p?t(d):Promise.resolve()}function a(c,l){var d;if(n[c].isActive===l)return Promise.resolve();(d=e.variantChildren)==null||d.forEach(h=>{var f;return(f=h.animationState)==null?void 0:f.setActive(c,l)}),n[c].isActive=l;const u=o(c);for(const h in n)n[h].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:s,getState:()=>n,reset:()=>{n=bm(),i=!0}}}function rP(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!rx(t,e):!1}function er(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function bm(){return{animate:er(!0),whileInView:er(),whileHover:er(),whileTap:er(),whileDrag:er(),whileFocus:er(),exit:er()}}class Yi{constructor(t){this.isMounted=!1,this.node=t}update(){}}class sP extends Yi{constructor(t){super(t),t.animationState||(t.animationState=iP(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();vc(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let oP=0;class aP extends Yi{constructor(){super(...arguments),this.id=oP++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const cP={animation:{Feature:sP},exit:{Feature:aP}};function lo(e,t,n,i={passive:!0}){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n)}function vo(e){return{point:{x:e.pageX,y:e.pageY}}}const lP=e=>t=>Rh(t)&&e(t,vo(t));function Ks(e,t,n,i){return lo(e,t,lP(n),i)}const ox=1e-4,uP=1-ox,dP=1+ox,ax=.01,hP=0-ax,fP=0+ax;function sn(e){return e.max-e.min}function pP(e,t,n){return Math.abs(e-t)<=n}function ym(e,t,n,i=.5){e.origin=i,e.originPoint=St(t.min,t.max,e.origin),e.scale=sn(n)/sn(t),e.translate=St(n.min,n.max,e.origin)-e.originPoint,(e.scale>=uP&&e.scale<=dP||isNaN(e.scale))&&(e.scale=1),(e.translate>=hP&&e.translate<=fP||isNaN(e.translate))&&(e.translate=0)}function Ys(e,t,n,i){ym(e.x,t.x,n.x,i?i.originX:void 0),ym(e.y,t.y,n.y,i?i.originY:void 0)}function vm(e,t,n){e.min=n.min+t.min,e.max=e.min+sn(t)}function mP(e,t,n){vm(e.x,t.x,n.x),vm(e.y,t.y,n.y)}function xm(e,t,n){e.min=t.min-n.min,e.max=e.min+sn(t)}function Zs(e,t,n){xm(e.x,t.x,n.x),xm(e.y,t.y,n.y)}function _n(e){return[e("x"),e("y")]}const cx=({current:e})=>e?e.ownerDocument.defaultView:null,km=(e,t)=>Math.abs(e-t);function gP(e,t){const n=km(e.x,t.x),i=km(e.y,t.y);return Math.sqrt(n**2+i**2)}class lx{constructor(t,n,{transformPagePoint:i,contextWindow:r=window,dragSnapToOrigin:s=!1,distanceThreshold:o=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=wl(this.lastMoveEventInfo,this.history),f=this.startEvent!==null,g=gP(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!f&&!g)return;const{point:p}=h,{timestamp:v}=Yt;this.history.push({...p,timestamp:v});const{onStart:b,onMove:w}=this.handlers;f||(b&&b(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,h)},this.handlePointerMove=(h,f)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Sl(f,this.transformPagePoint),vt.update(this.updatePoint,!0)},this.handlePointerUp=(h,f)=>{this.end();const{onEnd:g,onSessionEnd:p,resumeAnimation:v}=this.handlers;if(this.dragSnapToOrigin&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=wl(h.type==="pointercancel"?this.lastMoveEventInfo:Sl(f,this.transformPagePoint),this.history);this.startEvent&&g&&g(h,b),p&&p(h,b)},!Rh(t))return;this.dragSnapToOrigin=s,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=r||window;const a=vo(t),c=Sl(a,this.transformPagePoint),{point:l}=c,{timestamp:u}=Yt;this.history=[{...l,timestamp:u}];const{onSessionStart:d}=n;d&&d(t,wl(c,this.history)),this.removeListeners=go(Ks(this.contextWindow,"pointermove",this.handlePointerMove),Ks(this.contextWindow,"pointerup",this.handlePointerUp),Ks(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),$i(this.updatePoint)}}function Sl(e,t){return t?{point:t(e.point)}:e}function Sm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function wl({point:e},t){return{point:e,delta:Sm(e,ux(t)),offset:Sm(e,bP(t)),velocity:yP(t,.1)}}function bP(e){return e[0]}function ux(e){return e[e.length-1]}function yP(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,i=null;const r=ux(e);for(;n>=0&&(i=e[n],!(r.timestamp-i.timestamp>$n(t)));)n--;if(!i)return{x:0,y:0};const s=ei(r.timestamp-i.timestamp);if(s===0)return{x:0,y:0};const o={x:(r.x-i.x)/s,y:(r.y-i.y)/s};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function vP(e,{min:t,max:n},i){return t!==void 0&&e<t?e=i?St(t,e,i.min):Math.max(e,t):n!==void 0&&e>n&&(e=i?St(n,e,i.max):Math.min(e,n)),e}function wm(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function xP(e,{top:t,left:n,bottom:i,right:r}){return{x:wm(e.x,n,r),y:wm(e.y,t,i)}}function Tm(e,t){let n=t.min-e.min,i=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,i]=[i,n]),{min:n,max:i}}function kP(e,t){return{x:Tm(e.x,t.x),y:Tm(e.y,t.y)}}function SP(e,t){let n=.5;const i=sn(e),r=sn(t);return r>i?n=ro(t.min,t.max-i,e.min):i>r&&(n=ro(e.min,e.max-r,t.min)),ki(0,1,n)}function wP(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const hd=.35;function TP(e=hd){return e===!1?e=0:e===!0&&(e=hd),{x:Cm(e,"left","right"),y:Cm(e,"top","bottom")}}function Cm(e,t,n){return{min:Em(e,t),max:Em(e,n)}}function Em(e,t){return typeof e=="number"?e:e[t]||0}const CP=new WeakMap;class EP{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Pt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const s=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(vo(d).point)},o=(d,h)=>{const{drag:f,dragPropagation:g,onDragStart:p}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=OR(f),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),_n(b=>{let w=this.getAxisMotionValue(b).get()||0;if(ti.test(w)){const{projection:S}=this.visualElement;if(S&&S.layout){const k=S.layout.layoutBox[b];k&&(w=sn(k)*(parseFloat(w)/100))}}this.originPoint[b]=w}),p&&vt.postRender(()=>p(d,h)),ud(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:p,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:b}=h;if(g&&this.currentDirection===null){this.currentDirection=_P(b),this.currentDirection!==null&&p&&p(this.currentDirection);return}this.updateAxis("x",h.point,b),this.updateAxis("y",h.point,b),this.visualElement.render(),v&&v(d,h)},c=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>_n(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new lx(t,{onSessionStart:s,onStart:o,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:cx(this.visualElement)})}stop(t,n){const i=t||this.latestPointerEvent,r=n||this.latestPanInfo,s=this.isDragging;if(this.cancel(),!s||!r||!i)return;const{velocity:o}=r;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&vt.postRender(()=>a(i,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,i){const{drag:r}=this.getProps();if(!i||!$o(t,r,this.currentDirection))return;const s=this.getAxisMotionValue(t);let o=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(o=vP(o,this.constraints[t],this.elastic[t])),s.set(o)}resolveConstraints(){var s;const{dragConstraints:t,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(s=this.visualElement.projection)==null?void 0:s.layout,r=this.constraints;t&&qr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&i?this.constraints=xP(i.layoutBox,t):this.constraints=!1,this.elastic=TP(n),r!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&_n(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=wP(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!qr(t))return!1;const i=t.current;Si(i!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const s=RA(i,r.root,this.visualElement.getTransformPagePoint());let o=kP(r.layout.layoutBox,s);if(n){const a=n(CA(o));this.hasMutatedConstraints=!!a,a&&(o=Gv(a))}return o}startAnimation(t){const{drag:n,dragMomentum:i,dragElastic:r,dragTransition:s,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},l=_n(u=>{if(!$o(u,n,this.currentDirection))return;let d=c&&c[u]||{};o&&(d={min:0,max:0});const h=r?200:1e6,f=r?40:1e7,g={type:"inertia",velocity:i?t[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...s,...d};return this.startAxisValueAnimation(u,g)});return Promise.all(l).then(a)}startAxisValueAnimation(t,n){const i=this.getAxisMotionValue(t);return ud(this.visualElement,t),i.start(jh(t,i,0,n,this.visualElement,!1))}stopAnimation(){_n(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){_n(t=>{var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)==null?void 0:n.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps(),r=i[n];return r||this.visualElement.getValue(t,(i.initial?i.initial[t]:void 0)||0)}snapToCursor(t){_n(n=>{const{drag:i}=this.getProps();if(!$o(n,i,this.currentDirection))return;const{projection:r}=this.visualElement,s=this.getAxisMotionValue(n);if(r&&r.layout){const{min:o,max:a}=r.layout.layoutBox[n];s.set(t[n]-St(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!qr(n)||!i||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};_n(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const c=a.get();r[o]=SP({min:c,max:c},this.constraints[o])}});const{transformTemplate:s}=this.visualElement.getProps();this.visualElement.current.style.transform=s?s({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),_n(o=>{if(!$o(o,t,null))return;const a=this.getAxisMotionValue(o),{min:c,max:l}=this.constraints[o];a.set(St(c,l,r[o]))})}addListeners(){if(!this.visualElement.current)return;CP.set(this.visualElement,this);const t=this.visualElement.current,n=Ks(t,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps();l&&u&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();qr(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,s=r.addEventListener("measure",i);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),vt.read(i);const o=lo(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(_n(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[u].translate))}),this.visualElement.render())});return()=>{o(),n(),s(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:r=!1,dragConstraints:s=!1,dragElastic:o=hd,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:i,dragPropagation:r,dragConstraints:s,dragElastic:o,dragMomentum:a}}}function $o(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function _P(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class RP extends Yi{constructor(t){super(t),this.removeGroupControls=Nn,this.removeListeners=Nn,this.controls=new EP(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Nn}unmount(){this.removeGroupControls(),this.removeListeners()}}const _m=e=>(t,n)=>{e&&vt.postRender(()=>e(t,n))};class AP extends Yi{constructor(){super(...arguments),this.removePointerDownListener=Nn}onPointerDown(t){this.session=new lx(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:cx(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:i,onPanEnd:r}=this.node.getProps();return{onSessionStart:_m(t),onStart:_m(n),onMove:i,onEnd:(s,o)=>{delete this.session,r&&vt.postRender(()=>r(s,o))}}}mount(){this.removePointerDownListener=Ks(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Ca={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Rm(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Ns={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(Me.test(e))e=parseFloat(e);else return e;const n=Rm(e,t.target.x),i=Rm(e,t.target.y);return`${n}% ${i}%`}},PP={correct:(e,{treeScale:t,projectionDelta:n})=>{const i=e,r=zi.parse(e);if(r.length>5)return i;const s=zi.createTransformer(e),o=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,c=n.y.scale*t.y;r[0+o]/=a,r[1+o]/=c;const l=St(a,c,.5);return typeof r[2+o]=="number"&&(r[2+o]/=l),typeof r[3+o]=="number"&&(r[3+o]/=l),s(r)}};let Tl=!1;class NP extends O.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i,layoutId:r}=this.props,{projection:s}=t;QR(IP),s&&(n.group&&n.group.add(s),i&&i.register&&r&&i.register(s),Tl&&s.root.didUpdate(),s.addEventListener("animationComplete",()=>{this.safeToRemove()}),s.setOptions({...s.options,onExitComplete:()=>this.safeToRemove()})),Ca.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:i,drag:r,isPresent:s}=this.props,{projection:o}=i;return o&&(o.isPresent=s,Tl=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==s?o.willUpdate():this.safeToRemove(),t.isPresent!==s&&(s?o.promote():o.relegate()||vt.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),_h.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:r}=t;Tl=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),i&&i.deregister&&i.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function dx(e){const[t,n]=Mv(),i=O.useContext(sh);return m.jsx(NP,{...e,layoutGroup:i,switchLayoutGroup:O.useContext(Wv),isPresent:t,safeToRemove:n})}const IP={borderRadius:{...Ns,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Ns,borderTopRightRadius:Ns,borderBottomLeftRadius:Ns,borderBottomRightRadius:Ns,boxShadow:PP};function MP(e,t,n){const i=Jt(e)?e:cs(e);return i.start(jh("",i,t,n)),i.animation}const OP=(e,t)=>e.depth-t.depth;class DP{constructor(){this.children=[],this.isDirty=!1}add(t){ch(this.children,t),this.isDirty=!0}remove(t){lh(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(OP),this.isDirty=!1,this.children.forEach(t)}}function LP(e,t){const n=fn.now(),i=({timestamp:r})=>{const s=r-n;s>=t&&($i(i),e(s-t))};return vt.setup(i,!0),()=>$i(i)}const hx=["TopLeft","TopRight","BottomLeft","BottomRight"],FP=hx.length,Am=e=>typeof e=="string"?parseFloat(e):e,Pm=e=>typeof e=="number"||Me.test(e);function jP(e,t,n,i,r,s){r?(e.opacity=St(0,n.opacity??1,UP(i)),e.opacityExit=St(t.opacity??1,0,BP(i))):s&&(e.opacity=St(t.opacity??1,n.opacity??1,i));for(let o=0;o<FP;o++){const a=`border${hx[o]}Radius`;let c=Nm(t,a),l=Nm(n,a);if(c===void 0&&l===void 0)continue;c||(c=0),l||(l=0),c===0||l===0||Pm(c)===Pm(l)?(e[a]=Math.max(St(Am(c),Am(l),i),0),(ti.test(l)||ti.test(c))&&(e[a]+="%")):e[a]=l}(t.rotate||n.rotate)&&(e.rotate=St(t.rotate||0,n.rotate||0,i))}function Nm(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const UP=fx(0,.5,Qy),BP=fx(.5,.95,Nn);function fx(e,t,n){return i=>i<e?0:i>t?1:n(ro(e,t,i))}function Im(e,t){e.min=t.min,e.max=t.max}function En(e,t){Im(e.x,t.x),Im(e.y,t.y)}function Mm(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function Om(e,t,n,i,r){return e-=t,e=Ga(e,1/n,i),r!==void 0&&(e=Ga(e,1/r,i)),e}function VP(e,t=0,n=1,i=.5,r,s=e,o=e){if(ti.test(t)&&(t=parseFloat(t),t=St(o.min,o.max,t/100)-o.min),typeof t!="number")return;let a=St(s.min,s.max,i);e===s&&(a-=t),e.min=Om(e.min,t,n,a,r),e.max=Om(e.max,t,n,a,r)}function Dm(e,t,[n,i,r],s,o){VP(e,t[n],t[i],t[r],t.scale,s,o)}const $P=["x","scaleX","originX"],zP=["y","scaleY","originY"];function Lm(e,t,n,i){Dm(e.x,t,$P,n?n.x:void 0,i?i.x:void 0),Dm(e.y,t,zP,n?n.y:void 0,i?i.y:void 0)}function Fm(e){return e.translate===0&&e.scale===1}function px(e){return Fm(e.x)&&Fm(e.y)}function jm(e,t){return e.min===t.min&&e.max===t.max}function HP(e,t){return jm(e.x,t.x)&&jm(e.y,t.y)}function Um(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function mx(e,t){return Um(e.x,t.x)&&Um(e.y,t.y)}function Bm(e){return sn(e.x)/sn(e.y)}function Vm(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class WP{constructor(){this.members=[]}add(t){ch(this.members,t),t.scheduleRender()}remove(t){if(lh(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let i;for(let r=n;r>=0;r--){const s=this.members[r];if(s.isPresent!==!1){i=s;break}}return i?(this.promote(i),!0):!1}promote(t,n){const i=this.lead;if(t!==i&&(this.prevLead=i,this.lead=t,t.show(),i)){i.instance&&i.scheduleRender(),t.scheduleRender(),t.resumeFrom=i,n&&(t.resumeFrom.preserveOpacity=!0),i.snapshot&&(t.snapshot=i.snapshot,t.snapshot.latestValues=i.animationValues||i.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:i}=t;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function qP(e,t,n){let i="";const r=e.x.translate/t.x,s=e.y.translate/t.y,o=(n==null?void 0:n.z)||0;if((r||s||o)&&(i=`translate3d(${r}px, ${s}px, ${o}px) `),(t.x!==1||t.y!==1)&&(i+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:l,rotate:u,rotateX:d,rotateY:h,skewX:f,skewY:g}=n;l&&(i=`perspective(${l}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),h&&(i+=`rotateY(${h}deg) `),f&&(i+=`skewX(${f}deg) `),g&&(i+=`skewY(${g}deg) `)}const a=e.x.scale*t.x,c=e.y.scale*t.y;return(a!==1||c!==1)&&(i+=`scale(${a}, ${c})`),i||"none"}const Cl=["","X","Y","Z"],GP=1e3;let KP=0;function El(e,t,n,i){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),i&&(i[e]=0))}function gx(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=tx(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:s}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",vt,!(r||s))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&gx(i)}function bx({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:i,resetTransform:r}){return class{constructor(o={},a=t==null?void 0:t()){this.id=KP++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(XP),this.nodes.forEach(tN),this.nodes.forEach(nN),this.nodes.forEach(JP)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new DP)}addEventListener(o,a){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new dh),this.eventHandlers.get(o).add(a)}notifyListeners(o,...a){const c=this.eventHandlers.get(o);c&&c.notify(...a)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=Iv(o)&&!BR(o),this.instance=o;const{layoutId:a,layout:c,visualElement:l}=this.options;if(l&&!l.current&&l.mount(o),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),e){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;vt.read(()=>{d=window.innerWidth}),e(o,()=>{const f=window.innerWidth;f!==d&&(d=f,this.root.updateBlockedByResize=!0,u&&u(),u=LP(h,250),Ca.hasAnimatedSinceResize&&(Ca.hasAnimatedSinceResize=!1,this.nodes.forEach(Hm)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&l&&(a||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||l.getDefaultTransition()||aN,{onLayoutAnimationStart:p,onLayoutAnimationComplete:v}=l.getProps(),b=!this.targetLayout||!mx(this.targetLayout,f),w=!d&&h;if(this.options.layoutRoot||this.resumeFrom||w||d&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...Ch(g,"layout"),onPlay:p,onComplete:v};(l.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,w)}else d||Hm(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),$i(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(iN),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&gx(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:c}=this.options;if(a===void 0&&!c)return;const l=this.getTransformTemplate();this.prevTransformTemplateValue=l?l(this.latestValues,""):void 0,this.updateSnapshot(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach($m);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(zm);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(eN),this.nodes.forEach(YP),this.nodes.forEach(ZP)):this.nodes.forEach(zm),this.clearAllSnapshots();const a=fn.now();Yt.delta=ki(0,1e3/60,a-Yt.timestamp),Yt.timestamp=a,Yt.isProcessing=!0,pl.update.process(Yt),pl.preRender.process(Yt),pl.render.process(Yt),Yt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,_h.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(QP),this.sharedNodes.forEach(rN)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,vt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){vt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!sn(this.snapshot.measuredBox.x)&&!sn(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c<this.path.length;c++)this.path[c].updateScroll();const o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Pt(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,o?o.layoutBox:void 0)}updateScroll(o="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(a=!1),a&&this.instance){const c=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!r)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!px(this.projectionDelta),c=this.getTransformTemplate(),l=c?c(this.latestValues,""):void 0,u=l!==this.prevTransformTemplateValue;o&&this.instance&&(a||rr(this.latestValues)||u)&&(r(this.instance,l),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return o&&(c=this.removeTransform(c)),cN(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var l;const{visualElement:o}=this.options;if(!o)return Pt();const a=o.measureViewportBox();if(!(((l=this.scroll)==null?void 0:l.wasRoot)||this.path.some(lN))){const{scroll:u}=this.root;u&&(Gr(a.x,u.offset.x),Gr(a.y,u.offset.y))}return a}removeElementScroll(o){var c;const a=Pt();if(En(a,o),(c=this.scroll)!=null&&c.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&En(a,o),Gr(a.x,d.offset.x),Gr(a.y,d.offset.y))}return a}applyTransform(o,a=!1){const c=Pt();En(c,o);for(let l=0;l<this.path.length;l++){const u=this.path[l];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&Kr(c,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),rr(u.latestValues)&&Kr(c,u.latestValues)}return rr(this.latestValues)&&Kr(c,this.latestValues),c}removeTransform(o){const a=Pt();En(a,o);for(let c=0;c<this.path.length;c++){const l=this.path[c];if(!l.instance||!rr(l.latestValues))continue;od(l.latestValues)&&l.updateSnapshot();const u=Pt(),d=l.measurePageBox();En(u,d),Lm(a,l.latestValues,l.snapshot?l.snapshot.layoutBox:void 0,u)}return rr(this.latestValues)&&Lm(a,this.latestValues),a}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Yt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(o=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(o||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Yt.timestamp,!this.targetDelta&&!this.relativeTarget){const f=this.getClosestProjectingParent();f&&f.layout&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Pt(),this.relativeTargetOrigin=Pt(),Zs(this.relativeTargetOrigin,this.layout.layoutBox,f.layout.layoutBox),En(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Pt(),this.targetWithTransforms=Pt()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),mP(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):En(this.target,this.layout.layoutBox),Yv(this.target,this.targetDelta)):En(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const f=this.getClosestProjectingParent();f&&!!f.resumingFrom==!!this.resumingFrom&&!f.options.layoutScroll&&f.target&&this.animationProgress!==1?(this.relativeParent=f,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Pt(),this.relativeTargetOrigin=Pt(),Zs(this.relativeTargetOrigin,this.target,f.target),En(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||od(this.parent.latestValues)||Kv(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var g;const o=this.getLead(),a=!!this.resumingFrom||this!==o;let c=!0;if((this.isProjectionDirty||(g=this.parent)!=null&&g.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Yt.timestamp&&(c=!1),c)return;const{layout:l,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(l||u))return;En(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;_A(this.layoutCorrected,this.treeScale,this.path,a),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=Pt());const{target:f}=o;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Mm(this.prevProjectionDelta.x,this.projectionDelta.x),Mm(this.prevProjectionDelta.y,this.projectionDelta.y)),Ys(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Vm(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vm(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",f))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),o){const c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Yr(),this.projectionDelta=Yr(),this.projectionDeltaWithTransform=Yr()}setAnimationOrigin(o,a=!1){const c=this.snapshot,l=c?c.latestValues:{},u={...this.latestValues},d=Yr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=Pt(),f=c?c.source:void 0,g=this.layout?this.layout.source:void 0,p=f!==g,v=this.getStack(),b=!v||v.members.length<=1,w=!!(p&&!b&&this.options.crossfade===!0&&!this.path.some(oN));this.animationProgress=0;let S;this.mixTargetDelta=k=>{const x=k/1e3;Wm(d.x,o.x,x),Wm(d.y,o.y,x),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Zs(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),sN(this.relativeTarget,this.relativeTargetOrigin,h,x),S&&HP(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=Pt()),En(S,this.relativeTarget)),p&&(this.animationValues=u,jP(u,l,this.latestValues,x,w,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=x},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){var a,c,l;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(l=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||l.stop(),this.pendingAnimation&&($i(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=vt.update(()=>{Ca.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=cs(0)),this.currentAnimation=MP(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),o.onUpdate&&o.onUpdate(u)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(GP),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:c,layout:l,latestValues:u}=o;if(!(!a||!c||!l)){if(this!==o&&this.layout&&l&&yx(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||Pt();const d=sn(this.layout.layoutBox.x);c.x.min=o.target.x.min,c.x.max=c.x.min+d;const h=sn(this.layout.layoutBox.y);c.y.min=o.target.y.min,c.y.max=c.y.min+h}En(a,c),Kr(a,u),Ys(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new WP),this.sharedNodes.get(o).add(a);const l=a.options.initialPromotionConfig;a.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.shouldPreserveFollowOpacity(a):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var a;const{layoutId:o}=this.options;return o?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:o}=this.options;return o?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:c}={}){const l=this.getStack();l&&l.promote(this,c),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:c}=o;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const l={};c.z&&El("z",o,l,this.animationValues);for(let u=0;u<Cl.length;u++)El(`rotate${Cl[u]}`,o,l,this.animationValues),El(`skew${Cl[u]}`,o,l,this.animationValues);o.render();for(const u in l)o.setStaticValue(u,l[u]),this.animationValues&&(this.animationValues[u]=l[u]);o.scheduleRender()}applyProjectionStyles(o,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=Ta(a==null?void 0:a.pointerEvents)||"",o.transform=c?c(this.latestValues,""):"none";return}const l=this.getLead();if(!this.projectionDelta||!this.layout||!l.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=Ta(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!rr(this.latestValues)&&(o.transform=c?c({},""):"none",this.hasProjected=!1);return}o.visibility="";const u=l.animationValues||l.latestValues;this.applyTransformsToTarget();let d=qP(this.projectionDeltaWithTransform,this.treeScale,u);c&&(d=c(u,d)),o.transform=d;const{x:h,y:f}=this.projectionDelta;o.transformOrigin=`${h.origin*100}% ${f.origin*100}% 0`,l.animationValues?o.opacity=l===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:o.opacity=l===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in co){if(u[g]===void 0)continue;const{correct:p,applyTo:v,isCSSVariable:b}=co[g],w=d==="none"?u[g]:p(u[g],l);if(v){const S=v.length;for(let k=0;k<S;k++)o[v[k]]=w}else b?this.options.visualElement.renderState.vars[g]=w:o[g]=w}this.options.layoutId&&(o.pointerEvents=l===this?Ta(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var a;return(a=o.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach($m),this.root.sharedNodes.clear()}}}function YP(e){e.updateLayout()}function ZP(e){var n;const t=((n=e.resumeFrom)==null?void 0:n.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:r}=e.layout,{animationType:s}=e.options,o=t.source!==e.layout.source;s==="size"?_n(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],f=sn(h);h.min=i[d].min,h.max=h.min+f}):yx(s,t.layoutBox,i)&&_n(d=>{const h=o?t.measuredBox[d]:t.layoutBox[d],f=sn(i[d]);h.max=h.min+f,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+f)});const a=Yr();Ys(a,i,t.layoutBox);const c=Yr();o?Ys(c,e.applyTransform(r,!0),t.measuredBox):Ys(c,i,t.layoutBox);const l=!px(a);let u=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:f}=d;if(h&&f){const g=Pt();Zs(g,t.layoutBox,h.layoutBox);const p=Pt();Zs(p,i,f.layoutBox),mx(g,p)||(u=!0),d.options.layoutRoot&&(e.relativeTarget=p,e.relativeTargetOrigin=g,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:t,delta:c,layoutDelta:a,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function XP(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function JP(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function QP(e){e.clearSnapshot()}function $m(e){e.clearMeasurements()}function zm(e){e.isLayoutDirty=!1}function eN(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Hm(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function tN(e){e.resolveTargetDelta()}function nN(e){e.calcProjection()}function iN(e){e.resetSkewAndRotation()}function rN(e){e.removeLeadSnapshot()}function Wm(e,t,n){e.translate=St(t.translate,0,n),e.scale=St(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function qm(e,t,n,i){e.min=St(t.min,n.min,i),e.max=St(t.max,n.max,i)}function sN(e,t,n,i){qm(e.x,t.x,n.x,i),qm(e.y,t.y,n.y,i)}function oN(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const aN={duration:.45,ease:[.4,0,.1,1]},Gm=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Km=Gm("applewebkit/")&&!Gm("chrome/")?Math.round:Nn;function Ym(e){e.min=Km(e.min),e.max=Km(e.max)}function cN(e){Ym(e.x),Ym(e.y)}function yx(e,t,n){return e==="position"||e==="preserve-aspect"&&!pP(Bm(t),Bm(n),.2)}function lN(e){var t;return e!==e.root&&((t=e.scroll)==null?void 0:t.wasRoot)}const uN=bx({attachResizeListener:(e,t)=>lo(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),_l={current:void 0},vx=bx({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!_l.current){const e=new uN({});e.mount(window),e.setOptions({layoutScroll:!0}),_l.current=e}return _l.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),dN={pan:{Feature:AP},drag:{Feature:RP,ProjectionNode:vx,MeasureLayout:dx}};function Zm(e,t,n){const{props:i}=e;e.animationState&&i.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,s=i[r];s&&vt.postRender(()=>s(t,vo(t)))}class hN extends Yi{mount(){const{current:t}=this.node;t&&(this.unmount=DR(t,(n,i)=>(Zm(this.node,i,"Start"),r=>Zm(this.node,r,"End"))))}unmount(){}}class fN extends Yi{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=go(lo(this.node.current,"focus",()=>this.onFocus()),lo(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Xm(e,t,n){const{props:i}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&i.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),s=i[r];s&&vt.postRender(()=>s(t,vo(t)))}class pN extends Yi{mount(){const{current:t}=this.node;t&&(this.unmount=UR(t,(n,i)=>(Xm(this.node,i,"Start"),(r,{success:s})=>Xm(this.node,r,s?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const fd=new WeakMap,Rl=new WeakMap,mN=e=>{const t=fd.get(e.target);t&&t(e)},gN=e=>{e.forEach(mN)};function bN({root:e,...t}){const n=e||document;Rl.has(n)||Rl.set(n,{});const i=Rl.get(n),r=JSON.stringify(t);return i[r]||(i[r]=new IntersectionObserver(gN,{root:e,...t})),i[r]}function yN(e,t,n){const i=bN(t);return fd.set(e,n),i.observe(e),()=>{fd.delete(e),i.unobserve(e)}}const vN={some:0,all:1};class xN extends Yi{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:i,amount:r="some",once:s}=t,o={root:n?n.current:void 0,rootMargin:i,threshold:typeof r=="number"?r:vN[r]},a=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,s&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=l?u:d;h&&h(c)};return yN(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(kN(t,n))&&this.startObserver()}unmount(){}}function kN({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const SN={inView:{Feature:xN},tap:{Feature:pN},focus:{Feature:fN},hover:{Feature:hN}},wN={layout:{ProjectionNode:vx,MeasureLayout:dx}},TN={...cP,...SN,...dN,...wN},Fe=TA(TN,FA);var zo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function xx(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pd={exports:{}},CN=pd.exports,Jm;function EN(){return Jm||(Jm=1,function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(CN,function(){var t=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(p,v){var b=p[v];if(typeof b.bind=="function")return b.bind(p);try{return Function.prototype.bind.call(b,p)}catch{return function(){return Function.prototype.apply.apply(b,[p,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(p){return p==="debug"&&(p="log"),typeof console===n?!1:p==="trace"&&i?c:console[p]!==void 0?a(console,p):console.log!==void 0?a(console,"log"):t}function u(){for(var p=this.getLevel(),v=0;v<r.length;v++){var b=r[v];this[b]=v<p?t:this.methodFactory(b,p,this.name)}if(this.log=this.debug,typeof console===n&&p<this.levels.SILENT)return"No console available for logging"}function d(p){return function(){typeof console!==n&&(u.call(this),this[p].apply(this,arguments))}}function h(p,v,b){return l(p)||d.apply(this,arguments)}function f(p,v){var b=this,w,S,k,x="loglevel";typeof p=="string"?x+=":"+p:typeof p=="symbol"&&(x=void 0);function T(R){var I=(r[R]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=I;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+I+";"}catch{}}}function P(){var R;if(!(typeof window===n||!x)){try{R=window.localStorage[x]}catch{}if(typeof R===n)try{var I=window.document.cookie,L=encodeURIComponent(x),U=I.indexOf(L+"=");U!==-1&&(R=/^([^;]+)/.exec(I.slice(U+L.length+1))[1])}catch{}return b.levels[R]===void 0&&(R=void 0),R}}function A(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(R){var I=R;if(typeof I=="string"&&b.levels[I.toUpperCase()]!==void 0&&(I=b.levels[I.toUpperCase()]),typeof I=="number"&&I>=0&&I<=b.levels.SILENT)return I;throw new TypeError("log.setLevel() called with invalid level: "+R)}b.name=p,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=v||h,b.getLevel=function(){return k??S??w},b.setLevel=function(R,I){return k=N(R),I!==!1&&T(k),u.call(b)},b.setDefaultLevel=function(R){S=N(R),P()||b.setLevel(R,!1)},b.resetLevel=function(){k=null,A(),u.call(b)},b.enableAll=function(R){b.setLevel(b.levels.TRACE,R)},b.disableAll=function(R){b.setLevel(b.levels.SILENT,R)},b.rebuild=function(){if(o!==b&&(w=N(o.getLevel())),u.call(b),o===b)for(var R in s)s[R].rebuild()},w=N(o?o.getLevel():"WARN");var y=P();y!=null&&(k=N(y)),u.call(b)}o=new f,o.getLogger=function(p){if(typeof p!="symbol"&&typeof p!="string"||p==="")throw new TypeError("You must supply a name when creating a logger.");var v=s[p];return v||(v=s[p]=new f(p,o.methodFactory)),v};var g=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=g),o},o.getLoggers=function(){return s},o.default=o,o})}(pd)),pd.exports}var _N=EN();const RN=xx(_N);var md=function(e,t){return md=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(n[r]=i[r])},md(e,t)};function Ci(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");md(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function AN(e,t,n,i){function r(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(e,[])).next())})}function kx(e,t){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(n=0)),n;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,r=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=t.call(e,n)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ds(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ka(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var i=n.call(e),r,s=[],o;try{for(;(t===void 0||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function Ya(e,t,n){if(arguments.length===2)for(var i=0,r=t.length,s;i<r;i++)(s||!(i in t))&&(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function is(e){return this instanceof is?(this.v=e,this):new is(e)}function PN(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(e,t||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(f){return function(g){return Promise.resolve(g).then(f,d)}}function a(f,g){i[f]&&(r[f]=function(p){return new Promise(function(v,b){s.push([f,p,v,b])>1||c(f,p)})},g&&(r[f]=g(r[f])))}function c(f,g){try{l(i[f](g))}catch(p){h(s[0][3],p)}}function l(f){f.value instanceof is?Promise.resolve(f.value.v).then(u,d):h(s[0][2],f)}function u(f){c("next",f)}function d(f){c("throw",f)}function h(f,g){f(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function NN(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ds=="function"?ds(e):e[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(s){n[s]=e[s]&&function(o){return new Promise(function(a,c){o=e[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Vt(e){return typeof e=="function"}function Uh(e){var t=function(i){Error.call(i),i.stack=new Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Al=Uh(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
47
47
|
`+t.map(function(n,i){return i+1+") "+n.toString()}).join(`
|
|
48
|
-
`):"",this.name="UnsubscriptionError",this.errors=t}});function Za(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var xo=function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,i,r,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=ds(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(p){t={error:p}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var u=this.initialTeardown;if(Vt(u))try{u()}catch(p){s=p instanceof Al?p.errors:[p]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var h=ds(d),f=h.next();!f.done;f=h.next()){var g=f.value;try{Qm(g)}catch(p){s=s??[],p instanceof Al?s=Ya(Ya([],Ka(s)),Ka(p.errors)):s.push(p)}}}catch(p){i={error:p}}finally{try{f&&!f.done&&(r=h.return)&&r.call(h)}finally{if(i)throw i.error}}}if(s)throw new Al(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Qm(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&Za(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&Za(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),Sx=xo.EMPTY;function wx(e){return e instanceof xo||e&&"closed"in e&&Vt(e.remove)&&Vt(e.add)&&Vt(e.unsubscribe)}function Qm(e){Vt(e)?e():e.unsubscribe()}var IN={Promise:void 0},MN={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setTimeout.apply(void 0,Ya([e,t],Ka(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function Tx(e){MN.setTimeout(function(){throw e})}function eg(){}function Ea(e){e()}var Bh=function(e){Ci(t,e);function t(n){var i=e.call(this)||this;return i.isStopped=!1,n?(i.destination=n,wx(n)&&n.add(i)):i.destination=LN,i}return t.create=function(n,i,r){return new gd(n,i,r)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(xo),ON=function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(i){Ho(i)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(i){Ho(i)}else Ho(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Ho(n)}},e}(),gd=function(e){Ci(t,e);function t(n,i,r){var s=e.call(this)||this,o;return Vt(n)||!n?o={next:n??void 0,error:i??void 0,complete:r??void 0}:o=n,s.destination=new ON(o),s}return t}(Bh);function Ho(e){Tx(e)}function DN(e){throw e}var LN={closed:!0,next:eg,error:DN,complete:eg},Vh=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Cx(e){return e}function FN(e){return e.length===0?Cx:e.length===1?e[0]:function(t){return e.reduce(function(n,i){return i(n)},t)}}var Tn=function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,i){var r=this,s=UN(t)?t:new gd(t,n,i);return Ea(function(){var o=r,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?r._subscribe(s):r._trySubscribe(s))}),s},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var i=this;return n=tg(n),new n(function(r,s){var o=new gd({next:function(a){try{t(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:r});i.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Vh]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return FN(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=tg(t),new t(function(i,r){var s;n.subscribe(function(o){return s=o},function(o){return r(o)},function(){return i(s)})})},e.create=function(t){return new e(t)},e}();function tg(e){var t;return(t=e??IN.Promise)!==null&&t!==void 0?t:Promise}function jN(e){return e&&Vt(e.next)&&Vt(e.error)&&Vt(e.complete)}function UN(e){return e&&e instanceof Bh||jN(e)&&wx(e)}function BN(e){return Vt(e==null?void 0:e.lift)}function ko(e){return function(t){if(BN(t))return t.lift(function(n){try{return e(n,this)}catch(i){this.error(i)}});throw new TypeError("Unable to lift unknown Observable type")}}function Xa(e,t,n,i,r){return new VN(e,t,n,i,r)}var VN=function(e){Ci(t,e);function t(n,i,r,s,o,a){var c=e.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=i?function(l){try{i(l)}catch(u){n.error(u)}}:e.prototype._next,c._error=s?function(l){try{s(l)}catch(u){n.error(u)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=r?function(){try{r()}catch(l){n.error(l)}finally{this.unsubscribe()}}:e.prototype._complete,c}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t}(Bh),$N=Uh(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ex=function(e){Ci(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var i=new ng(this,this);return i.operator=n,i},t.prototype._throwIfClosed=function(){if(this.closed)throw new $N},t.prototype.next=function(n){var i=this;Ea(function(){var r,s;if(i._throwIfClosed(),!i.isStopped){i.currentObservers||(i.currentObservers=Array.from(i.observers));try{for(var o=ds(i.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(r)throw r.error}}}})},t.prototype.error=function(n){var i=this;Ea(function(){if(i._throwIfClosed(),!i.isStopped){i.hasError=i.isStopped=!0,i.thrownError=n;for(var r=i.observers;r.length;)r.shift().error(n)}})},t.prototype.complete=function(){var n=this;Ea(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var i=n.observers;i.length;)i.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var i=this,r=this,s=r.hasError,o=r.isStopped,a=r.observers;return s||o?Sx:(this.currentObservers=null,a.push(n),new xo(function(){i.currentObservers=null,Za(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var i=this,r=i.hasError,s=i.thrownError,o=i.isStopped;r?n.error(s):o&&n.complete()},t.prototype.asObservable=function(){var n=new Tn;return n.source=this,n},t.create=function(n,i){return new ng(n,i)},t}(Tn),ng=function(e){Ci(t,e);function t(n,i){var r=e.call(this)||this;return r.destination=n,r.source=i,r}return t.prototype.next=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.next)===null||r===void 0||r.call(i,n)},t.prototype.error=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.error)===null||r===void 0||r.call(i,n)},t.prototype.complete=function(){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||i===void 0||i.call(n)},t.prototype._subscribe=function(n){var i,r;return(r=(i=this.source)===null||i===void 0?void 0:i.subscribe(n))!==null&&r!==void 0?r:Sx},t}(Ex);(function(e){Ci(t,e);function t(n){var i=e.call(this)||this;return i._value=n,i}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var i=e.prototype._subscribe.call(this,n);return!i.closed&&n.next(this._value),i},t.prototype.getValue=function(){var n=this,i=n.hasError,r=n.thrownError,s=n._value;if(i)throw r;return this._throwIfClosed(),s},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})(Ex);var zN={now:function(){return Date.now()}},HN=function(e){Ci(t,e);function t(n,i){return e.call(this)||this}return t.prototype.schedule=function(n,i){return this},t}(xo),ig={setInterval:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setInterval.apply(void 0,Ya([e,t],Ka(n)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},WN=function(e){Ci(t,e);function t(n,i){var r=e.call(this,n,i)||this;return r.scheduler=n,r.work=i,r.pending=!1,r}return t.prototype.schedule=function(n,i){var r;if(i===void 0&&(i=0),this.closed)return this;this.state=n;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,i)),this.pending=!0,this.delay=i,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(o,this.id,i),this},t.prototype.requestAsyncId=function(n,i,r){return r===void 0&&(r=0),ig.setInterval(n.flush.bind(n,this),r)},t.prototype.recycleAsyncId=function(n,i,r){if(r===void 0&&(r=0),r!=null&&this.delay===r&&this.pending===!1)return i;i!=null&&ig.clearInterval(i)},t.prototype.execute=function(n,i){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(n,i);if(r)return r;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(n,i){var r=!1,s;try{this.work(n)}catch(o){r=!0,s=o||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),s},t.prototype.unsubscribe=function(){if(!this.closed){var n=this,i=n.id,r=n.scheduler,s=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Za(s,this),i!=null&&(this.id=this.recycleAsyncId(r,i,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(HN),rg=function(){function e(t,n){n===void 0&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(t,n,i){return n===void 0&&(n=0),new this.schedulerActionCtor(this,t).schedule(i,n)},e.now=zN.now,e}(),qN=function(e){Ci(t,e);function t(n,i){i===void 0&&(i=rg.now);var r=e.call(this,n,i)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(n){var i=this.actions;if(this._active){i.push(n);return}var r;this._active=!0;do if(r=n.execute(n.state,n.delay))break;while(n=i.shift());if(this._active=!1,r){for(;n=i.shift();)n.unsubscribe();throw r}},t}(rg);new qN(WN);function GN(e){return e&&Vt(e.schedule)}function KN(e){return e[e.length-1]}function _x(e){return GN(KN(e))?e.pop():void 0}var Rx=function(e){return e&&typeof e.length=="number"&&typeof e!="function"};function Ax(e){return Vt(e==null?void 0:e.then)}function Px(e){return Vt(e[Vh])}function Nx(e){return Symbol.asyncIterator&&Vt(e==null?void 0:e[Symbol.asyncIterator])}function Ix(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function YN(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Mx=YN();function Ox(e){return Vt(e==null?void 0:e[Mx])}function Dx(e){return PN(this,arguments,function(){var t,n,i,r;return kx(this,function(s){switch(s.label){case 0:t=e.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,is(t.read())];case 3:return n=s.sent(),i=n.value,r=n.done,r?[4,is(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,is(i)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Lx(e){return Vt(e==null?void 0:e.getReader)}function So(e){if(e instanceof Tn)return e;if(e!=null){if(Px(e))return ZN(e);if(Rx(e))return XN(e);if(Ax(e))return JN(e);if(Nx(e))return Fx(e);if(Ox(e))return QN(e);if(Lx(e))return eI(e)}throw Ix(e)}function ZN(e){return new Tn(function(t){var n=e[Vh]();if(Vt(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function XN(e){return new Tn(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function JN(e){return new Tn(function(t){e.then(function(n){t.closed||(t.next(n),t.complete())},function(n){return t.error(n)}).then(null,Tx)})}function QN(e){return new Tn(function(t){var n,i;try{for(var r=ds(e),s=r.next();!s.done;s=r.next()){var o=s.value;if(t.next(o),t.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}t.complete()})}function Fx(e){return new Tn(function(t){tI(e,t).catch(function(n){return t.error(n)})})}function eI(e){return Fx(Dx(e))}function tI(e,t){var n,i,r,s;return AN(this,void 0,void 0,function(){var o,a;return kx(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=NN(e),c.label=1;case 1:return[4,n.next()];case 2:if(i=c.sent(),!!i.done)return[3,4];if(o=i.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),i&&!i.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function dr(e,t,n,i,r){i===void 0&&(i=0),r===void 0&&(r=!1);var s=t.schedule(function(){n(),r?e.add(this.schedule(null,i)):this.unsubscribe()},i);if(e.add(s),!r)return s}function jx(e,t){return t===void 0&&(t=0),ko(function(n,i){n.subscribe(Xa(i,function(r){return dr(i,e,function(){return i.next(r)},t)},function(){return dr(i,e,function(){return i.complete()},t)},function(r){return dr(i,e,function(){return i.error(r)},t)}))})}function Ux(e,t){return t===void 0&&(t=0),ko(function(n,i){i.add(e.schedule(function(){return n.subscribe(i)},t))})}function nI(e,t){return So(e).pipe(Ux(t),jx(t))}function iI(e,t){return So(e).pipe(Ux(t),jx(t))}function rI(e,t){return new Tn(function(n){var i=0;return t.schedule(function(){i===e.length?n.complete():(n.next(e[i++]),n.closed||this.schedule())})})}function sI(e,t){return new Tn(function(n){var i;return dr(n,t,function(){i=e[Mx](),dr(n,t,function(){var r,s,o;try{r=i.next(),s=r.value,o=r.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return Vt(i==null?void 0:i.return)&&i.return()}})}function Bx(e,t){if(!e)throw new Error("Iterable cannot be null");return new Tn(function(n){dr(n,t,function(){var i=e[Symbol.asyncIterator]();dr(n,t,function(){i.next().then(function(r){r.done?n.complete():n.next(r.value)})},0,!0)})})}function oI(e,t){return Bx(Dx(e),t)}function aI(e,t){if(e!=null){if(Px(e))return nI(e,t);if(Rx(e))return rI(e,t);if(Ax(e))return iI(e,t);if(Nx(e))return Bx(e,t);if(Ox(e))return sI(e,t);if(Lx(e))return oI(e,t)}throw Ix(e)}function cI(e,t){return t?aI(e,t):So(e)}Uh(function(e){return function(t){t===void 0&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function wo(e,t){return ko(function(n,i){var r=0;n.subscribe(Xa(i,function(s){i.next(e.call(t,s,r++))}))})}function lI(e,t,n,i,r,s,o,a){var c=[],l=0,u=0,d=!1,h=function(){d&&!c.length&&!l&&t.complete()},f=function(p){return l<i?g(p):c.push(p)},g=function(p){l++;var v=!1;So(n(p,u++)).subscribe(Xa(t,function(b){t.next(b)},function(){v=!0},void 0,function(){if(v)try{l--;for(var b=function(){var w=c.shift();o||g(w)};c.length&&l<i;)b();h()}catch(w){t.error(w)}}))};return e.subscribe(Xa(t,f,function(){d=!0,h()})),function(){}}function Vx(e,t,n){return n===void 0&&(n=1/0),Vt(t)?Vx(function(i,r){return wo(function(s,o){return t(i,s,r,o)})(So(e(i,r)))},n):(typeof t=="number"&&(n=t),ko(function(i,r){return lI(i,r,e,n)}))}function uI(e){return Vx(Cx,e)}function dI(){return uI(1)}function sg(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dI()(cI(e,_x(e)))}function kc(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=_x(e);return ko(function(i,r){(n?sg(e,i,n):sg(e,i)).subscribe(r)})}var hI=(e,t,n)=>new Promise((i,r)=>{var s=c=>{try{a(n.next(c))}catch(l){r(l)}},o=c=>{try{a(n.throw(c))}catch(l){r(l)}},a=c=>c.done?i(c.value):Promise.resolve(c.value).then(s,o);a((n=n.apply(e,t)).next())}),fI="lk";function $h(e){return typeof e>"u"?!1:pI(e)||mI(e)}function pI(e){var t;return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("track")&&typeof((t=e.publication)==null?void 0:t.track)<"u":!1}function mI(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("publication")&&typeof e.publication<"u":!1}function gI(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&typeof e.publication>"u":!1}function bI(e){if(typeof e=="string"||typeof e=="number")return`${e}`;if(gI(e))return`${e.participant.identity}_${e.source}_placeholder`;if($h(e))return`${e.participant.identity}_${e.publication.source}_${e.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${e}`)}var yI=[j.ConnectionStateChanged,j.RoomMetadataChanged,j.ActiveSpeakersChanged,j.ConnectionQualityChanged,j.ParticipantConnected,j.ParticipantDisconnected,j.ParticipantPermissionsChanged,j.ParticipantMetadataChanged,j.ParticipantNameChanged,j.ParticipantAttributesChanged,j.TrackMuted,j.TrackUnmuted,j.TrackPublished,j.TrackUnpublished,j.TrackStreamStateChanged,j.TrackSubscriptionFailed,j.TrackSubscriptionPermissionChanged,j.TrackSubscriptionStatusChanged],vI=[...yI,j.LocalTrackPublished,j.LocalTrackUnpublished];Q.TrackPublished,Q.TrackUnpublished,Q.TrackMuted,Q.TrackUnmuted,Q.TrackStreamStateChanged,Q.TrackSubscribed,Q.TrackUnsubscribed,Q.TrackSubscriptionPermissionChanged,Q.TrackSubscriptionFailed,Q.LocalTrackPublished,Q.LocalTrackUnpublished;var xI=[Q.ConnectionQualityChanged,Q.IsSpeakingChanged,Q.ParticipantMetadataChanged,Q.ParticipantPermissionsChanged,Q.TrackMuted,Q.TrackUnmuted,Q.TrackPublished,Q.TrackUnpublished,Q.TrackStreamStateChanged,Q.TrackSubscriptionFailed,Q.TrackSubscriptionPermissionChanged,Q.TrackSubscriptionStatusChanged];[...xI,Q.LocalTrackPublished,Q.LocalTrackUnpublished];var Hi=RN.getLogger("lk-components-js");Hi.setDefaultLevel("WARN");function $x(e){return typeof e=="object"}function zx(e){return Array.isArray(e)&&e.filter($x).length>0}function Hx(e){return`${fI}-${e}`}function kI(e){const t=bd(e),n=TI(e.participant).pipe(wo(()=>bd(e)),kc(t));return{className:Hx(e.source===B.Source.Camera||e.source===B.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:n}}function bd(e){if($h(e))return e.publication;{const{source:t,name:n,participant:i}=e;if(t&&n)return i.getTrackPublications().find(r=>r.source===t&&r.trackName===n);if(n)return i.getTrackPublicationByName(n);if(t)return i.getTrackPublication(t);throw new Error("At least one of source and name needs to be defined")}}function Wx(e,...t){return new Tn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(kc(e))}function SI(e){return Wx(e,j.AudioPlaybackStatusChanged).pipe(wo(t=>({canPlayAudio:t.canPlaybackAudio})))}function wI(e,...t){return new Tn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(kc(e))}function TI(e){return wI(e,Q.TrackMuted,Q.TrackUnmuted,Q.ParticipantPermissionsChanged,Q.TrackPublished,Q.TrackUnpublished,Q.LocalTrackPublished,Q.LocalTrackUnpublished,Q.MediaDevicesError,Q.TrackSubscriptionStatusChanged).pipe(wo(t=>{const{isMicrophoneEnabled:n,isCameraEnabled:i,isScreenShareEnabled:r}=t,s=t.getTrackPublication(B.Source.Microphone),o=t.getTrackPublication(B.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:n,isScreenShareEnabled:r,cameraTrack:o,microphoneTrack:s,participant:t}}))}function CI(){const e=t=>hI(this,null,function*(){Hi.info("Start Audio for room: ",t),yield t.startAudio()});return{className:Hx("start-audio-button"),roomAudioPlaybackAllowedObservable:SI,handleStartAudioPlayback:e}}function og(e,t,n=!0){const i=[e.localParticipant,...Array.from(e.remoteParticipants.values())],r=[];return i.forEach(s=>{t.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(c=>c.source===o&&(!n||c.track)).map(c=>({participant:s,publication:c,source:c.source}));r.push(...a)})}),{trackReferences:r,participants:i}}function EI(e,t,n){var i,r;const s=(i=n.additionalRoomEvents)!=null?i:vI,o=(r=n.onlySubscribed)!=null?r:!0,a=Array.from(new Set([j.ParticipantConnected,j.ParticipantDisconnected,j.ConnectionStateChanged,j.LocalTrackPublished,j.LocalTrackUnpublished,j.TrackPublished,j.TrackUnpublished,j.TrackSubscriptionStatusChanged,...s]).values());return Wx(e,...a).pipe(wo(c=>{const l=og(c,t,o);return Hi.debug(`TrackReference[] was updated. (length ${l.trackReferences.length})`,l),l}),kc(og(e,t,o)))}D.createContext(void 0);const _I=D.createContext(void 0);function qx(){return D.useContext(_I)}function Gx(e){const t=qx(),n=e??t;if(!n)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return n}D.createContext(void 0);const Ja=D.createContext(void 0);function Kx(){const e=D.useContext(Ja);if(!e)throw Error("tried to access room context outside of livekit room component");return e}function RI(){return D.useContext(Ja)}function Yx(e){const t=RI(),n=e??t;if(!n)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return n}D.createContext(void 0);function Zx(e){var t,n,i="";if(typeof e=="string"||typeof e=="number")i+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(t=0;t<r;t++)e[t]&&(n=Zx(e[t]))&&(i&&(i+=" "),i+=n)}else for(n in e)e[n]&&(i&&(i+=" "),i+=n);return i}function Xx(){for(var e,t,n=0,i="",r=arguments.length;n<r;n++)(e=arguments[n])&&(t=Zx(e))&&(i&&(i+=" "),i+=t);return i}function AI(...e){return(...t)=>{for(const n of e)if(typeof n=="function")try{n(...t)}catch(i){console.error(i)}}}function Jx(...e){const t={...e[0]};for(let n=1;n<e.length;n++){const i=e[n];for(const r in i){const s=t[r],o=i[r];typeof s=="function"&&typeof o=="function"&&r[0]==="o"&&r[1]==="n"&&r.charCodeAt(2)>=65&&r.charCodeAt(2)<=90?t[r]=AI(s,o):(r==="className"||r==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?t[r]=Xx(s,o):t[r]=o!==void 0?o:s}}return t}function PI(e){return e!==void 0}function Qx(...e){return Jx(...e.filter(PI))}function NI(e,t,n){return D.Children.map(e,i=>D.isValidElement(i)&&D.Children.only(e)?(i.props.className&&(t??(t={}),t.className=Xx(i.props.className,t.className),t.style={...i.props.style,...t.style}),D.cloneElement(i,{...t,key:n})):i)}function II(e,t,n=!0){const[i,r]=D.useState(t);return D.useEffect(()=>{if(n&&r(t),typeof window>"u"||!e)return;const s=e.subscribe(r);return()=>s.unsubscribe()},[e,n]),i}function MI({room:e,props:t}){const n=Yx(e),{className:i,roomAudioPlaybackAllowedObservable:r,handleStartAudioPlayback:s}=D.useMemo(()=>CI(),[]),o=D.useMemo(()=>r(n),[n,r]),{canPlayAudio:a}=II(o,{canPlayAudio:n.canPlaybackAudio});return{mergedProps:D.useMemo(()=>Jx(t,{className:i,onClick:()=>{s(n)},style:{display:a?"none":"block"}}),[t,i,a,s,n]),canPlayAudio:a}}function ek(e=[B.Source.Camera,B.Source.Microphone,B.Source.ScreenShare,B.Source.ScreenShareAudio,B.Source.Unknown],t={}){const n=Yx(t.room),[i,r]=D.useState([]),[s,o]=D.useState([]),a=D.useMemo(()=>e.map(c=>$x(c)?c.source:c),[JSON.stringify(e)]);return D.useEffect(()=>{const c=EI(n,a,{additionalRoomEvents:t.updateOnlyOn,onlySubscribed:t.onlySubscribed}).subscribe(({trackReferences:l,participants:u})=>{Hi.debug("setting track bundles",l,u),r(l),o(u)});return()=>c.unsubscribe()},[n,JSON.stringify(t.onlySubscribed),JSON.stringify(t.updateOnlyOn),JSON.stringify(e)]),D.useMemo(()=>{if(zx(e)){const c=DI(e,s),l=Array.from(i);return s.forEach(u=>{c.has(u.identity)&&(c.get(u.identity)??[]).forEach(d=>{if(i.find(({participant:f,publication:g})=>u.identity===f.identity&&g.source===d))return;Hi.debug(`Add ${d} placeholder for participant ${u.identity}.`);const h={participant:u,source:d};l.push(h)})}),l}else return i},[i,s,e])}function OI(e,t){const n=new Set(e);for(const i of t)n.delete(i);return n}function DI(e,t){const n=new Map;if(zx(e)){const i=e.filter(r=>r.withPlaceholder).map(r=>r.source);t.forEach(r=>{const s=r.getTrackPublications().map(a=>{var c;return(c=a.track)==null?void 0:c.source}).filter(a=>a!==void 0),o=Array.from(OI(new Set(i),new Set(s)));o.length>0&&n.set(r.identity,o)})}return n}const LI=e=>{const t=n=>{let i=1-Math.max(-100,Math.min(-10,n))*-1/100;return i=Math.sqrt(i),i};return e.map(n=>n===-1/0?0:t(n))},FI={bands:5,loPass:100,hiPass:600,updateInterval:32,analyserOptions:{fftSize:2048}};function jI(e,t={}){var n;const i=e instanceof B?e:(n=e==null?void 0:e.publication)==null?void 0:n.track,r={...FI,...t},[s,o]=D.useState(new Array(r.bands).fill(0));return D.useEffect(()=>{if(!i||!(i!=null&&i.mediaStream))return;const{analyser:a,cleanup:c}=TE(i,r.analyserOptions),l=a.frequencyBinCount,u=new Float32Array(l),d=setInterval(()=>{a.getFloatFrequencyData(u);let h=new Float32Array(u.length);for(let v=0;v<u.length;v++)h[v]=u[v];h=h.slice(t.loPass,t.hiPass);const f=LI(h),g=Math.ceil(f.length/r.bands),p=[];for(let v=0;v<r.bands;v++){const b=f.slice(v*g,(v+1)*g).reduce((w,S)=>w+=S,0);p.push(b/g)}o(p)},r.updateInterval);return()=>{c(),clearInterval(d)}},[i,i==null?void 0:i.mediaStream,JSON.stringify(t)]),s}const ag=D.forwardRef(function({label:e="Allow Audio",...t},n){const i=Kx(),{mergedProps:r}=MI({room:i,props:t});return D.createElement("button",{ref:n,...r},e)});function tk(e,t={}){const[n,i]=D.useState(bd(e)),[r,s]=D.useState(n==null?void 0:n.isMuted),[o,a]=D.useState(n==null?void 0:n.isSubscribed),[c,l]=D.useState(n==null?void 0:n.track),[u,d]=D.useState("landscape"),h=D.useRef(),{className:f,trackObserver:g}=D.useMemo(()=>kI(e),[e.participant.sid??e.participant.identity,e.source,$h(e)&&e.publication.trackSid]);return D.useEffect(()=>{const p=g.subscribe(v=>{Hi.debug("update track",v),i(v),s(v==null?void 0:v.isMuted),a(v==null?void 0:v.isSubscribed),l(v==null?void 0:v.track)});return()=>p==null?void 0:p.unsubscribe()},[g]),D.useEffect(()=>{var p,v;return c&&(h.current&&c.detach(h.current),(p=t.element)!=null&&p.current&&!(e.participant.isLocal&&(c==null?void 0:c.kind)==="audio")&&c.attach(t.element.current)),h.current=(v=t.element)==null?void 0:v.current,()=>{h.current&&(c==null||c.detach(h.current))}},[c,t.element]),D.useEffect(()=>{var p,v;if(typeof((p=n==null?void 0:n.dimensions)==null?void 0:p.width)=="number"&&typeof((v=n==null?void 0:n.dimensions)==null?void 0:v.height)=="number"){const b=n.dimensions.width>n.dimensions.height?"landscape":"portrait";d(b)}},[n]),{publication:n,isMuted:r,isSubscribed:o,track:c,elementProps:Qx(t.props,{className:f,"data-lk-local-participant":e.participant.isLocal,"data-lk-source":n==null?void 0:n.source,...(n==null?void 0:n.kind)==="video"&&{"data-lk-orientation":u}})}}var Pl,cg;function UI(){if(cg)return Pl;cg=1;var e="Expected a function",t=NaN,n="[object Symbol]",i=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,o=/^0o[0-7]+$/i,a=parseInt,c=typeof zo=="object"&&zo&&zo.Object===Object&&zo,l=typeof self=="object"&&self&&self.Object===Object&&self,u=c||l||Function("return this")(),d=Object.prototype,h=d.toString,f=Math.max,g=Math.min,p=function(){return u.Date.now()};function v(x,T,P){var A,N,y,R,I,L,U=0,K=!1,ue=!1,se=!0;if(typeof x!="function")throw new TypeError(e);T=k(T)||0,b(P)&&(K=!!P.leading,ue="maxWait"in P,y=ue?f(k(P.maxWait)||0,T):y,se="trailing"in P?!!P.trailing:se);function z(re){var X=A,le=N;return A=N=void 0,U=re,R=x.apply(le,X),R}function H(re){return U=re,I=setTimeout(Y,T),K?z(re):R}function C(re){var X=re-L,le=re-U,Z=T-X;return ue?g(Z,y-le):Z}function W(re){var X=re-L,le=re-U;return L===void 0||X>=T||X<0||ue&&le>=y}function Y(){var re=p();if(W(re))return E(re);I=setTimeout(Y,C(re))}function E(re){return I=void 0,se&&A?z(re):(A=N=void 0,R)}function J(){I!==void 0&&clearTimeout(I),U=0,A=L=N=I=void 0}function ne(){return I===void 0?R:E(p())}function ie(){var re=p(),X=W(re);if(A=arguments,N=this,L=re,X){if(I===void 0)return H(L);if(ue)return I=setTimeout(Y,T),z(L)}return I===void 0&&(I=setTimeout(Y,T)),R}return ie.cancel=J,ie.flush=ne,ie}function b(x){var T=typeof x;return!!x&&(T=="object"||T=="function")}function w(x){return!!x&&typeof x=="object"}function S(x){return typeof x=="symbol"||w(x)&&h.call(x)==n}function k(x){if(typeof x=="number")return x;if(S(x))return t;if(b(x)){var T=typeof x.valueOf=="function"?x.valueOf():x;x=b(T)?T+"":T}if(typeof x!="string")return x===0?x:+x;x=x.replace(i,"");var P=s.test(x);return P||o.test(x)?a(x.slice(2),P?2:8):r.test(x)?t:+x}return Pl=v,Pl}var BI=UI();const lg=xx(BI);function VI(e){const t=O.useRef(e);t.current=e,O.useEffect(()=>()=>{t.current()},[])}function $I(e,t=500,n){const i=O.useRef();VI(()=>{i.current&&i.current.cancel()});const r=O.useMemo(()=>{const s=lg(e,t,n),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!i.current,o.flush=()=>s.flush(),o},[e,t,n]);return O.useEffect(()=>{i.current=lg(e,t,n)},[e,t,n]),r}function zI(e,t,n){const i=(l,u)=>l===u,r=e instanceof Function?e():e,[s,o]=O.useState(r),a=O.useRef(r),c=$I(o,t,n);return i(a.current,r)||(c(r),a.current=r),[s,c]}function HI({threshold:e=0,root:t=null,rootMargin:n="0%",freezeOnceVisible:i=!1,initialIsIntersecting:r=!1,onChange:s}={}){var o;const[a,c]=O.useState(null),[l,u]=O.useState(()=>({isIntersecting:r,entry:void 0})),d=O.useRef();d.current=s;const h=((o=l.entry)==null?void 0:o.isIntersecting)&&i;O.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||h)return;const p=new IntersectionObserver(v=>{const b=Array.isArray(p.thresholds)?p.thresholds:[p.thresholds];v.forEach(w=>{const S=w.isIntersecting&&b.some(k=>w.intersectionRatio>=k);u({isIntersecting:S,entry:w}),d.current&&d.current(S,w)})},{threshold:e,root:t,rootMargin:n});return p.observe(a),()=>{p.disconnect()}},[a,JSON.stringify(e),t,n,h,i]);const f=O.useRef(null);O.useEffect(()=>{var p;!a&&(p=l.entry)!=null&&p.target&&!i&&!h&&f.current!==l.entry.target&&(f.current=l.entry.target,u({isIntersecting:r,entry:void 0}))},[a,l.entry,i,h,r]);const g=[c,!!l.isIntersecting,l.entry];return g.ref=g[0],g.isIntersecting=g[1],g.entry=g[2],g}const Sc=D.forwardRef(function({onTrackClick:e,onClick:t,onSubscriptionStatusChanged:n,trackRef:i,manageSubscription:r,...s},o){const a=Gx(i),c=D.useRef(null);D.useImperativeHandle(o,()=>c.current);const l=HI({root:c.current}),[u]=zI(l,3e3);D.useEffect(()=>{r&&a.publication instanceof Va&&(u==null?void 0:u.isIntersecting)===!1&&(l==null?void 0:l.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[u,a,r]),D.useEffect(()=>{r&&a.publication instanceof Va&&(l==null?void 0:l.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[l,a,r]);const{elementProps:d,publication:h,isSubscribed:f}=tk(a,{element:c,props:s});D.useEffect(()=>{n==null||n(!!f)},[f,n]);const g=p=>{t==null||t(p),e==null||e({participant:a==null?void 0:a.participant,track:h})};return D.createElement("video",{ref:c,...d,muted:!0,onClick:g})}),nk=D.forwardRef(function({trackRef:e,onSubscriptionStatusChanged:t,volume:n,...i},r){const s=Gx(e),o=D.useRef(null);D.useImperativeHandle(r,()=>o.current);const{elementProps:a,isSubscribed:c,track:l,publication:u}=tk(s,{element:o,props:i});return D.useEffect(()=>{t==null||t(!!c)},[c,t]),D.useEffect(()=>{l===void 0||n===void 0||(l instanceof U0?l.setVolume(n):Hi.warn("Volume can only be set on remote audio tracks."))},[n,l]),D.useEffect(()=>{u===void 0||i.muted===void 0||(u instanceof Va?u.setEnabled(!i.muted):Hi.warn("Can only call setEnabled on remote track publications."))},[i.muted,u,l]),D.createElement("audio",{ref:o,...a})});function ug({volume:e,muted:t}){const n=ek([B.Source.Microphone,B.Source.ScreenShareAudio,B.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0}).filter(i=>!i.participant.isLocal&&i.publication.kind===B.Kind.Audio);return D.createElement("div",{style:{display:"none"}},n.map(i=>D.createElement(nk,{key:bI(i),trackRef:i,volume:e,muted:t})))}const WI=e=>{const t=[];for(let n=0;n<e;n++)t.push([n,e-1-n]);return t},dg=e=>[[Math.floor(e/2)],[-1]],qI=(e,t,n)=>{const[i,r]=O.useState(0),[s,o]=O.useState([[]]);O.useEffect(()=>{if(e==="thinking")o(dg(t));else if(e==="connecting"||e==="initializing"){const c=[...WI(t)];o(c)}else o(e==="listening"?dg(t):e===void 0||e==="speaking"?[new Array(t).fill(0).map((c,l)=>l)]:[[]]);r(0)},[e,t]);const a=O.useRef(null);return O.useEffect(()=>{let c=performance.now();const l=u=>{u-c>=n&&(r(d=>d+1),c=u),a.current=requestAnimationFrame(l)};return a.current=requestAnimationFrame(l),()=>{a.current!==null&&cancelAnimationFrame(a.current)}},[n,t,e,s.length]),s[i%s.length]},GI=new Map([["connecting",2e3],["initializing",2e3],["listening",500],["thinking",150]]),KI=(e,t)=>{if(e===void 0)return 1e3;let n=GI.get(e);if(n)switch(e){case"connecting":n/=t;break}return n},ik=D.forwardRef(function({state:e,options:t,barCount:n=15,trackRef:i,children:r,...s},o){const a=Qx(s,{className:"lk-audio-bar-visualizer"});let c=qx();i&&(c=i);const l=jI(c,{bands:n,loPass:100,hiPass:200}),u=(t==null?void 0:t.minHeight)??20,d=(t==null?void 0:t.maxHeight)??100,h=qI(e,n,KI(e,n)??100);return D.createElement("div",{ref:o,...a,"data-lk-va-state":e},l.map((f,g)=>r?NI(r,{"data-lk-highlighted":h.includes(g),"data-lk-bar-index":g,className:"lk-audio-bar",style:{height:`${Math.min(d,Math.max(u,f*100+5))}%`}}):D.createElement("span",{key:g,"data-lk-highlighted":h.includes(g),"data-lk-bar-index":g,className:`lk-audio-bar ${h.includes(g)&&"lk-highlighted"}`,style:{height:`${Math.min(d,Math.max(u,f*100+5))}%`}})))});function YI(e){const[t,n]=O.useState(()=>e.getLocalParticipant()),[i,r]=O.useState(()=>e.getMicrophoneTrack());return O.useEffect(()=>{const s=()=>{const a=e.getLocalParticipant(),c=e.getMicrophoneTrack();console.log("🎤 useVoxketLocalParticipant: Updating state:",{hasParticipant:!!a,hasMicTrack:!!c,isMicEnabled:e.isMicrophoneEnabled,trackPublications:a?a.trackPublications.size:0}),n(a),r(c)};s(),e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("track.muted",s),e.on("track.unmuted",s);const o=e.getRoom();if(o){const a=()=>{console.log("🎤 Track published, updating participant state"),s()},c=()=>{console.log("🎤 Track unpublished, updating participant state"),s()};return o.on("localTrackPublished",a),o.on("localTrackUnpublished",c),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s),o.off("localTrackPublished",a),o.off("localTrackUnpublished",c)}}else return()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s)}},[e]),{localParticipant:t,microphoneTrack:i}}function _a(e,t,n){const[i,r]=O.useState(!1),[s,o]=O.useState(!1);return O.useEffect(()=>{const c=()=>{let l=!1;switch(t){case"microphone":l=e.isMicrophoneEnabled;break;case"camera":l=e.isCameraEnabled;break;case"screenShare":l=e.isScreenShareEnabled;break}console.log(`🎬 useVoxketTrackToggle: ${t} enabled state updated:`,{oldEnabled:i,newEnabled:l,changed:i!==l}),r(l)};return c(),e.on("track.muted",c),e.on("track.unmuted",c),e.on("connection.connected",c),()=>{e.off("track.muted",c),e.off("track.unmuted",c),e.off("connection.connected",c)}},[e,t]),{enabled:i,pending:s,toggle:async c=>{try{o(!0);const l=c!==void 0?c:!i;switch(console.log(`🎬 useVoxketTrackToggle: ${t} toggle called`,{currentEnabled:i,targetEnabled:l,forceEnabled:c}),t){case"microphone":await e.toggleMicrophone(l);break;case"camera":await e.toggleCamera(l);break;case"screenShare":l?(console.log("🎬 useVoxketTrackToggle: Starting screen share"),await e.startScreenShare()):(console.log("🎬 useVoxketTrackToggle: Stopping screen share"),await e.stopScreenShare());break}console.log(`🎬 useVoxketTrackToggle: ${t} toggle completed`)}catch(l){console.error(`🎬 useVoxketTrackToggle: ${t} toggle failed:`,l)}finally{o(!1)}}}}function ZI(e){const[t,n]=O.useState(()=>e.getRoom()),[i,r]=O.useState(()=>e.getConnectionState());return O.useEffect(()=>{const s=()=>{n(e.getRoom()),r(e.getConnectionState())};return e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("connection.connecting",s),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("connection.connecting",s)}},[e]),t}function zh(e){const[t,n]=O.useState(()=>e.getIsAgentConnected()),[i,r]=O.useState(()=>e.getCurrentSession()),[s,o]=O.useState(()=>e.getCurrentAgentInfo()),[a,c]=O.useState(()=>e.getAgentState()),[l,u]=O.useState(()=>e.getAgentAudioTrack()),[d,h]=O.useState(()=>e.getAgentVideoTrack());return O.useEffect(()=>{const f=()=>{const k=e.getIsAgentConnected(),x=e.getCurrentSession(),T=e.getCurrentAgentInfo(),P=e.getAgentState(),A=e.getAgentAudioTrack(),N=e.getAgentVideoTrack();console.log("🤖 useVoxketVoiceAssistant: Updating state:",{isAgentConnected:k,hasSession:!!x,sessionId:x==null?void 0:x.id,sessionState:x==null?void 0:x.state,hasAgentInfo:!!T,agentState:P,hasAudioTrack:!!A,hasVideoTrack:!!N}),n(k),r(x),o(T),c(P),u(A),h(N)};f();const g=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent connected event"),f()},p=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent disconnected event"),f()},v=()=>{console.log("🤖 useVoxketVoiceAssistant: Session changed event"),f()},b=()=>{console.log("🤖 useVoxketVoiceAssistant: Connection changed event"),f()},w=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent state changed event"),f()},S=()=>{console.log("🎵 useVoxketVoiceAssistant: Track subscribed event - updating audio/video tracks"),f()};return e.on("agent.connected",g),e.on("agent.speaking",g),e.on("agent.thinking",g),e.on("agent.state.changed",w),e.on("connection.disconnected",p),e.on("session.created",v),e.on("session.ended",v),e.on("session.state.changed",v),e.on("connection.connected",b),e.on("media.track.subscribed",S),e.on("media.track.unsubscribed",S),()=>{e.off("agent.connected",g),e.off("agent.speaking",g),e.off("agent.thinking",g),e.off("agent.state.changed",w),e.off("connection.disconnected",p),e.off("session.created",v),e.off("session.ended",v),e.off("session.state.changed",v),e.off("connection.connected",b),e.off("media.track.subscribed",S),e.off("media.track.unsubscribed",S)}},[e]),{agent:{isActive:t,info:s},session:i,state:a,audioTrack:l,videoTrack:d}}function XI(e){const[t,n]=O.useState(()=>e.getVideoTrackRefs()),[i,r]=O.useState(()=>e.getCameraTrackRefs()),[s,o]=O.useState(()=>e.getScreenShareTrackRefs());return O.useEffect(()=>{const a=()=>{const l=e.getVideoTrackRefs(),u=e.getCameraTrackRefs(),d=e.getScreenShareTrackRefs();console.log("📹 useVoxketVideoTracks: Updating tracks:",{videoCount:l.length,cameraCount:u.length,screenShareCount:d.length}),n(l),r(u),o(d)};a(),e.on("connection.connected",a),e.on("connection.disconnected",a),e.on("track.muted",a),e.on("track.unmuted",a),e.on("participant.joined",a),e.on("participant.left",a);const c=e.getRoom();if(c){const l=()=>{console.log("📹 Track event, updating video tracks"),a()};return c.on("localTrackPublished",l),c.on("localTrackUnpublished",l),c.on("trackPublished",l),c.on("trackUnpublished",l),c.on("trackSubscribed",l),c.on("trackUnsubscribed",l),()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a),c.off("localTrackPublished",l),c.off("localTrackUnpublished",l),c.off("trackPublished",l),c.off("trackUnpublished",l),c.off("trackSubscribed",l),c.off("trackUnsubscribed",l)}}else return()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a)}},[e]),{videoTrackRefs:t,cameraTrackRefs:i,screenShareTrackRefs:s}}const Hh="-",JI=e=>{const t=eM(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:i}=e;return{getClassGroupId:o=>{const a=o.split(Hh);return a[0]===""&&a.length!==1&&a.shift(),rk(a,t)||QI(o)},getConflictingClassGroupIds:(o,a)=>{const c=n[o]||[];return a&&i[o]?[...c,...i[o]]:c}}},rk=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],i=t.nextPart.get(n),r=i?rk(e.slice(1),i):void 0;if(r)return r;if(t.validators.length===0)return;const s=e.join(Hh);return(o=t.validators.find(({validator:a})=>a(s)))==null?void 0:o.classGroupId},hg=/^\[(.+)\]$/,QI=e=>{if(hg.test(e)){const t=hg.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},eM=e=>{const{theme:t,classGroups:n}=e,i={nextPart:new Map,validators:[]};for(const r in n)yd(n[r],i,r,t);return i},yd=(e,t,n,i)=>{e.forEach(r=>{if(typeof r=="string"){const s=r===""?t:fg(t,r);s.classGroupId=n;return}if(typeof r=="function"){if(tM(r)){yd(r(i),t,n,i);return}t.validators.push({validator:r,classGroupId:n});return}Object.entries(r).forEach(([s,o])=>{yd(o,fg(t,s),n,i)})})},fg=(e,t)=>{let n=e;return t.split(Hh).forEach(i=>{n.nextPart.has(i)||n.nextPart.set(i,{nextPart:new Map,validators:[]}),n=n.nextPart.get(i)}),n},tM=e=>e.isThemeGetter,nM=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,i=new Map;const r=(s,o)=>{n.set(s,o),t++,t>e&&(t=0,i=n,n=new Map)};return{get(s){let o=n.get(s);if(o!==void 0)return o;if((o=i.get(s))!==void 0)return r(s,o),o},set(s,o){n.has(s)?n.set(s,o):r(s,o)}}},vd="!",xd=":",iM=xd.length,rM=e=>{const{prefix:t,experimentalParseClassName:n}=e;let i=r=>{const s=[];let o=0,a=0,c=0,l;for(let g=0;g<r.length;g++){let p=r[g];if(o===0&&a===0){if(p===xd){s.push(r.slice(c,g)),c=g+iM;continue}if(p==="/"){l=g;continue}}p==="["?o++:p==="]"?o--:p==="("?a++:p===")"&&a--}const u=s.length===0?r:r.substring(c),d=sM(u),h=d!==u,f=l&&l>c?l-c:void 0;return{modifiers:s,hasImportantModifier:h,baseClassName:d,maybePostfixModifierPosition:f}};if(t){const r=t+xd,s=i;i=o=>o.startsWith(r)?s(o.substring(r.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:o,maybePostfixModifierPosition:void 0}}if(n){const r=i;i=s=>n({className:s,parseClassName:r})}return i},sM=e=>e.endsWith(vd)?e.substring(0,e.length-1):e.startsWith(vd)?e.substring(1):e,oM=e=>{const t=Object.fromEntries(e.orderSensitiveModifiers.map(i=>[i,!0]));return i=>{if(i.length<=1)return i;const r=[];let s=[];return i.forEach(o=>{o[0]==="["||t[o]?(r.push(...s.sort(),o),s=[]):s.push(o)}),r.push(...s.sort()),r}},aM=e=>({cache:nM(e.cacheSize),parseClassName:rM(e),sortModifiers:oM(e),...JI(e)}),cM=/\s+/,lM=(e,t)=>{const{parseClassName:n,getClassGroupId:i,getConflictingClassGroupIds:r,sortModifiers:s}=t,o=[],a=e.trim().split(cM);let c="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{isExternal:d,modifiers:h,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:p}=n(u);if(d){c=u+(c.length>0?" "+c:c);continue}let v=!!p,b=i(v?g.substring(0,p):g);if(!b){if(!v){c=u+(c.length>0?" "+c:c);continue}if(b=i(g),!b){c=u+(c.length>0?" "+c:c);continue}v=!1}const w=s(h).join(":"),S=f?w+vd:w,k=S+b;if(o.includes(k))continue;o.push(k);const x=r(b,v);for(let T=0;T<x.length;++T){const P=x[T];o.push(S+P)}c=u+(c.length>0?" "+c:c)}return c};function uM(){let e=0,t,n,i="";for(;e<arguments.length;)(t=arguments[e++])&&(n=sk(t))&&(i&&(i+=" "),i+=n);return i}const sk=e=>{if(typeof e=="string")return e;let t,n="";for(let i=0;i<e.length;i++)e[i]&&(t=sk(e[i]))&&(n&&(n+=" "),n+=t);return n};function dM(e,...t){let n,i,r,s=o;function o(c){const l=t.reduce((u,d)=>d(u),e());return n=aM(l),i=n.cache.get,r=n.cache.set,s=a,a(c)}function a(c){const l=i(c);if(l)return l;const u=lM(c,n);return r(c,u),u}return function(){return s(uM.apply(null,arguments))}}const Ut=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},ok=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,ak=/^\((?:(\w[\w-]*):)?(.+)\)$/i,hM=/^\d+\/\d+$/,fM=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pM=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mM=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,gM=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,bM=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ar=e=>hM.test(e),Ue=e=>!!e&&!Number.isNaN(Number(e)),Ni=e=>!!e&&Number.isInteger(Number(e)),Nl=e=>e.endsWith("%")&&Ue(e.slice(0,-1)),ci=e=>fM.test(e),yM=()=>!0,vM=e=>pM.test(e)&&!mM.test(e),ck=()=>!1,xM=e=>gM.test(e),kM=e=>bM.test(e),SM=e=>!ve(e)&&!xe(e),wM=e=>vs(e,dk,ck),ve=e=>ok.test(e),tr=e=>vs(e,hk,vM),Il=e=>vs(e,RM,Ue),pg=e=>vs(e,lk,ck),TM=e=>vs(e,uk,kM),Wo=e=>vs(e,fk,xM),xe=e=>ak.test(e),Is=e=>xs(e,hk),CM=e=>xs(e,AM),mg=e=>xs(e,lk),EM=e=>xs(e,dk),_M=e=>xs(e,uk),qo=e=>xs(e,fk,!0),vs=(e,t,n)=>{const i=ok.exec(e);return i?i[1]?t(i[1]):n(i[2]):!1},xs=(e,t,n=!1)=>{const i=ak.exec(e);return i?i[1]?t(i[1]):n:!1},lk=e=>e==="position"||e==="percentage",uk=e=>e==="image"||e==="url",dk=e=>e==="length"||e==="size"||e==="bg-size",hk=e=>e==="length",RM=e=>e==="number",AM=e=>e==="family-name",fk=e=>e==="shadow",PM=()=>{const e=Ut("color"),t=Ut("font"),n=Ut("text"),i=Ut("font-weight"),r=Ut("tracking"),s=Ut("leading"),o=Ut("breakpoint"),a=Ut("container"),c=Ut("spacing"),l=Ut("radius"),u=Ut("shadow"),d=Ut("inset-shadow"),h=Ut("text-shadow"),f=Ut("drop-shadow"),g=Ut("blur"),p=Ut("perspective"),v=Ut("aspect"),b=Ut("ease"),w=Ut("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],x=()=>[...k(),xe,ve],T=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],A=()=>[xe,ve,c],N=()=>[Ar,"full","auto",...A()],y=()=>[Ni,"none","subgrid",xe,ve],R=()=>["auto",{span:["full",Ni,xe,ve]},Ni,xe,ve],I=()=>[Ni,"auto",xe,ve],L=()=>["auto","min","max","fr",xe,ve],U=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],K=()=>["start","end","center","stretch","center-safe","end-safe"],ue=()=>["auto",...A()],se=()=>[Ar,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...A()],z=()=>[e,xe,ve],H=()=>[...k(),mg,pg,{position:[xe,ve]}],C=()=>["no-repeat",{repeat:["","x","y","space","round"]}],W=()=>["auto","cover","contain",EM,wM,{size:[xe,ve]}],Y=()=>[Nl,Is,tr],E=()=>["","none","full",l,xe,ve],J=()=>["",Ue,Is,tr],ne=()=>["solid","dashed","dotted","double"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[Ue,Nl,mg,pg],X=()=>["","none",g,xe,ve],le=()=>["none",Ue,xe,ve],Z=()=>["none",Ue,xe,ve],Ae=()=>[Ue,xe,ve],F=()=>[Ar,"full",...A()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ci],breakpoint:[ci],color:[yM],container:[ci],"drop-shadow":[ci],ease:["in","out","in-out"],font:[SM],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ci],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ci],shadow:[ci],spacing:["px",Ue],text:[ci],"text-shadow":[ci],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ar,ve,xe,v]}],container:["container"],columns:[{columns:[Ue,ve,xe,a]}],"break-after":[{"break-after":S()}],"break-before":[{"break-before":S()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:x()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{start:N()}],end:[{end:N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[Ni,"auto",xe,ve]}],basis:[{basis:[Ar,"full","auto",a,...A()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ue,Ar,"auto","initial","none",ve]}],grow:[{grow:["",Ue,xe,ve]}],shrink:[{shrink:["",Ue,xe,ve]}],order:[{order:[Ni,"first","last","none",xe,ve]}],"grid-cols":[{"grid-cols":y()}],"col-start-end":[{col:R()}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":y()}],"row-start-end":[{row:R()}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":L()}],"auto-rows":[{"auto-rows":L()}],gap:[{gap:A()}],"gap-x":[{"gap-x":A()}],"gap-y":[{"gap-y":A()}],"justify-content":[{justify:[...U(),"normal"]}],"justify-items":[{"justify-items":[...K(),"normal"]}],"justify-self":[{"justify-self":["auto",...K()]}],"align-content":[{content:["normal",...U()]}],"align-items":[{items:[...K(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...K(),{baseline:["","last"]}]}],"place-content":[{"place-content":U()}],"place-items":[{"place-items":[...K(),"baseline"]}],"place-self":[{"place-self":["auto",...K()]}],p:[{p:A()}],px:[{px:A()}],py:[{py:A()}],ps:[{ps:A()}],pe:[{pe:A()}],pt:[{pt:A()}],pr:[{pr:A()}],pb:[{pb:A()}],pl:[{pl:A()}],m:[{m:ue()}],mx:[{mx:ue()}],my:[{my:ue()}],ms:[{ms:ue()}],me:[{me:ue()}],mt:[{mt:ue()}],mr:[{mr:ue()}],mb:[{mb:ue()}],ml:[{ml:ue()}],"space-x":[{"space-x":A()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":A()}],"space-y-reverse":["space-y-reverse"],size:[{size:se()}],w:[{w:[a,"screen",...se()]}],"min-w":[{"min-w":[a,"screen","none",...se()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[o]},...se()]}],h:[{h:["screen","lh",...se()]}],"min-h":[{"min-h":["screen","lh","none",...se()]}],"max-h":[{"max-h":["screen","lh",...se()]}],"font-size":[{text:["base",n,Is,tr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,xe,Il]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Nl,ve]}],"font-family":[{font:[CM,ve,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,xe,ve]}],"line-clamp":[{"line-clamp":[Ue,"none",xe,Il]}],leading:[{leading:[s,...A()]}],"list-image":[{"list-image":["none",xe,ve]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",xe,ve]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:z()}],"text-color":[{text:z()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ne(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ue,"from-font","auto",xe,tr]}],"text-decoration-color":[{decoration:z()}],"underline-offset":[{"underline-offset":[Ue,"auto",xe,ve]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:A()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",xe,ve]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",xe,ve]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:H()}],"bg-repeat":[{bg:C()}],"bg-size":[{bg:W()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ni,xe,ve],radial:["",xe,ve],conic:[Ni,xe,ve]},_M,TM]}],"bg-color":[{bg:z()}],"gradient-from-pos":[{from:Y()}],"gradient-via-pos":[{via:Y()}],"gradient-to-pos":[{to:Y()}],"gradient-from":[{from:z()}],"gradient-via":[{via:z()}],"gradient-to":[{to:z()}],rounded:[{rounded:E()}],"rounded-s":[{"rounded-s":E()}],"rounded-e":[{"rounded-e":E()}],"rounded-t":[{"rounded-t":E()}],"rounded-r":[{"rounded-r":E()}],"rounded-b":[{"rounded-b":E()}],"rounded-l":[{"rounded-l":E()}],"rounded-ss":[{"rounded-ss":E()}],"rounded-se":[{"rounded-se":E()}],"rounded-ee":[{"rounded-ee":E()}],"rounded-es":[{"rounded-es":E()}],"rounded-tl":[{"rounded-tl":E()}],"rounded-tr":[{"rounded-tr":E()}],"rounded-br":[{"rounded-br":E()}],"rounded-bl":[{"rounded-bl":E()}],"border-w":[{border:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ne(),"hidden","none"]}],"divide-style":[{divide:[...ne(),"hidden","none"]}],"border-color":[{border:z()}],"border-color-x":[{"border-x":z()}],"border-color-y":[{"border-y":z()}],"border-color-s":[{"border-s":z()}],"border-color-e":[{"border-e":z()}],"border-color-t":[{"border-t":z()}],"border-color-r":[{"border-r":z()}],"border-color-b":[{"border-b":z()}],"border-color-l":[{"border-l":z()}],"divide-color":[{divide:z()}],"outline-style":[{outline:[...ne(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ue,xe,ve]}],"outline-w":[{outline:["",Ue,Is,tr]}],"outline-color":[{outline:z()}],shadow:[{shadow:["","none",u,qo,Wo]}],"shadow-color":[{shadow:z()}],"inset-shadow":[{"inset-shadow":["none",d,qo,Wo]}],"inset-shadow-color":[{"inset-shadow":z()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:z()}],"ring-offset-w":[{"ring-offset":[Ue,tr]}],"ring-offset-color":[{"ring-offset":z()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":z()}],"text-shadow":[{"text-shadow":["none",h,qo,Wo]}],"text-shadow-color":[{"text-shadow":z()}],opacity:[{opacity:[Ue,xe,ve]}],"mix-blend":[{"mix-blend":[...ie(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ie()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ue]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":z()}],"mask-image-linear-to-color":[{"mask-linear-to":z()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":z()}],"mask-image-t-to-color":[{"mask-t-to":z()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":z()}],"mask-image-r-to-color":[{"mask-r-to":z()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":z()}],"mask-image-b-to-color":[{"mask-b-to":z()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":z()}],"mask-image-l-to-color":[{"mask-l-to":z()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":z()}],"mask-image-x-to-color":[{"mask-x-to":z()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":z()}],"mask-image-y-to-color":[{"mask-y-to":z()}],"mask-image-radial":[{"mask-radial":[xe,ve]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":z()}],"mask-image-radial-to-color":[{"mask-radial-to":z()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":z()}],"mask-image-conic-to-color":[{"mask-conic-to":z()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:H()}],"mask-repeat":[{mask:C()}],"mask-size":[{mask:W()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",xe,ve]}],filter:[{filter:["","none",xe,ve]}],blur:[{blur:X()}],brightness:[{brightness:[Ue,xe,ve]}],contrast:[{contrast:[Ue,xe,ve]}],"drop-shadow":[{"drop-shadow":["","none",f,qo,Wo]}],"drop-shadow-color":[{"drop-shadow":z()}],grayscale:[{grayscale:["",Ue,xe,ve]}],"hue-rotate":[{"hue-rotate":[Ue,xe,ve]}],invert:[{invert:["",Ue,xe,ve]}],saturate:[{saturate:[Ue,xe,ve]}],sepia:[{sepia:["",Ue,xe,ve]}],"backdrop-filter":[{"backdrop-filter":["","none",xe,ve]}],"backdrop-blur":[{"backdrop-blur":X()}],"backdrop-brightness":[{"backdrop-brightness":[Ue,xe,ve]}],"backdrop-contrast":[{"backdrop-contrast":[Ue,xe,ve]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ue,xe,ve]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ue,xe,ve]}],"backdrop-invert":[{"backdrop-invert":["",Ue,xe,ve]}],"backdrop-opacity":[{"backdrop-opacity":[Ue,xe,ve]}],"backdrop-saturate":[{"backdrop-saturate":[Ue,xe,ve]}],"backdrop-sepia":[{"backdrop-sepia":["",Ue,xe,ve]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":A()}],"border-spacing-x":[{"border-spacing-x":A()}],"border-spacing-y":[{"border-spacing-y":A()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",xe,ve]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ue,"initial",xe,ve]}],ease:[{ease:["linear","initial",b,xe,ve]}],delay:[{delay:[Ue,xe,ve]}],animate:[{animate:["none",w,xe,ve]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,xe,ve]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:Z()}],"scale-x":[{"scale-x":Z()}],"scale-y":[{"scale-y":Z()}],"scale-z":[{"scale-z":Z()}],"scale-3d":["scale-3d"],skew:[{skew:Ae()}],"skew-x":[{"skew-x":Ae()}],"skew-y":[{"skew-y":Ae()}],transform:[{transform:[xe,ve,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:F()}],"translate-x":[{"translate-x":F()}],"translate-y":[{"translate-y":F()}],"translate-z":[{"translate-z":F()}],"translate-none":["translate-none"],accent:[{accent:z()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:z()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",xe,ve]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",xe,ve]}],fill:[{fill:["none",...z()]}],"stroke-w":[{stroke:[Ue,Is,tr,Il]}],stroke:[{stroke:["none",...z()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},NM=dM(PM);function Xe(...e){return NM(jd.clsx(e))}function wc(e){var r;if(!e)return{sessionSettings:{},capabilities:{},modality:"voice"};const t={session_timer:((r=e.session_settings)==null?void 0:r.session_timer)||null},n=e.capabilities||{},i=e.modality||"voice";return{sessionSettings:t,capabilities:n,modality:i}}function IM(e,t){return e.capabilities[t]===!0}function Tc(e){return e.sessionSettings.session_timer||null}function pk(e){const t=e.capabilities;return{userVideoEnabled:t.user_video_enabled!==!1,agentAvatarEnabled:t.agent_avatar_enabled!==!1,screenshareEnabled:t.screenshare_session_enabled!==!1}}function mk(e){const t=e.capabilities;return{suggestedReplyEnabled:t.suggested_reply_enabled!==!1,attachmentsEnabled:t.support_in_chat_attachments!==!1}}function gk(e){return{...e.capabilities}}function bk(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}const yk=O.forwardRef(({state:e,audioTrack:t,className:n,theme:i="vox"},r)=>{var l,u,d,h,f;const s=O.useRef(null),[o,a]=O.useState(!1);O.useEffect(()=>{s.current&&(console.log("🔊 AgentTile: Audio element created:",{autoplay:s.current.autoplay,muted:s.current.muted,volume:s.current.volume,readyState:s.current.readyState,paused:s.current.paused}),a(!0))},[t]),O.useEffect(()=>{const g=s.current;if(!g)return;const p=()=>console.log("▶️ AgentTile: Audio started playing"),v=()=>console.log("⏸️ AgentTile: Audio paused"),b=()=>console.log("⏹️ AgentTile: Audio ended"),w=x=>console.error("❌ AgentTile: Audio error:",x),S=()=>console.log("⏳ AgentTile: Audio load started"),k=()=>console.log("✅ AgentTile: Audio can play");return g.addEventListener("play",p),g.addEventListener("pause",v),g.addEventListener("ended",b),g.addEventListener("error",w),g.addEventListener("loadstart",S),g.addEventListener("canplay",k),()=>{g.removeEventListener("play",p),g.removeEventListener("pause",v),g.removeEventListener("ended",b),g.removeEventListener("error",w),g.removeEventListener("loadstart",S),g.removeEventListener("canplay",k)}},[o]),console.log("🎤 AgentTile render:",{state:e,hasAudioTrack:!!t,trackSource:t==null?void 0:t.source,participantId:(l=t==null?void 0:t.participant)==null?void 0:l.identity,publicationMuted:(u=t==null?void 0:t.publication)==null?void 0:u.isMuted,audioElementReady:o,trackMediaStreamTrack:(f=(h=(d=t==null?void 0:t.publication)==null?void 0:d.track)==null?void 0:h.mediaStreamTrack)==null?void 0:f.readyState});const c=O.useMemo(()=>i==="light"?{base:"bg-black/90",highlighted:"bg-black",muted:"bg-black/30"}:{base:"bg-white/90",highlighted:"bg-white",muted:"bg-white/30"},[i]);return m.jsxs("div",{ref:r,className:Xe("",n),children:[t&&m.jsxs(m.Fragment,{children:[m.jsx(nk,{ref:s,trackRef:t,volume:1}),m.jsx(ik,{barCount:5,state:e,options:{minHeight:5},trackRef:t,className:Xe("flex aspect-video w-40 items-center justify-center gap-1.5"),children:m.jsx("span",{className:Xe([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",`data-[lk-highlighted=true]:${c.highlighted}`,`data-[lk-muted=true]:${c.muted}`])})})]}),!t&&m.jsx("div",{className:Xe("flex aspect-video w-40 items-center justify-center"),children:m.jsx("div",{className:"flex flex-col items-center justify-center",children:m.jsx("div",{className:"flex gap-1.5",children:Array.from({length:5}).map((g,p)=>m.jsx("span",{className:Xe([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",e==="speaking"&&`animate-pulse ${c.highlighted}`,e==="thinking"&&`animate-pulse ${c.muted}`])},p))})})})]})});yk.displayName="AgentTile";const MM=({videoTrack:e,className:t,ref:n})=>{var i,r;return!e||!e.publication||!e.participant?m.jsx("div",{ref:n,className:Xe(t),children:m.jsx("div",{className:"w-full h-full bg-gray-200 rounded-md flex items-center justify-center",children:m.jsx("span",{className:"text-gray-500",children:"No video available"})})}):m.jsx("div",{ref:n,className:Xe(t),children:m.jsx(Sc,{trackRef:e,width:((i=e.publication.dimensions)==null?void 0:i.width)??0,height:((r=e.publication.dimensions)==null?void 0:r.height)??0,className:"rounded-md"})})},OM=D.forwardRef(function({trackRef:t,className:n,...i},r){var s,o;return m.jsx("div",{ref:r,className:Xe("bg-muted overflow-hidden rounded-md",n),children:m.jsx(Sc,{trackRef:t,width:((s=t==null?void 0:t.publication.dimensions)==null?void 0:s.width)??0,height:((o=t==null?void 0:t.publication.dimensions)==null?void 0:o.height)??0,className:Xe("h-full w-auto"),...i})})}),gg=Fe.create(OM),DM=Fe.create(yk),LM=Fe.create(MM),li={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},Pr={grid:["h-full w-full","grid gap-x-2 place-content-center","grid-cols-[1fr_1fr] grid-rows-[90px_1fr_90px]"],agentChatOpenWithSecondTile:["col-start-1 row-start-1","self-center justify-self-end"],agentChatOpenWithoutSecondTile:["col-start-1 row-start-1","col-span-2","place-content-center"],agentChatClosed:["col-start-1 row-start-1","col-span-2","place-content-center"],secondTileChatOpen:["col-start-2 row-start-1","self-center justify-self-start"],secondTileChatClosed:["col-start-2 row-start-3","place-content-end"]};function FM(e,t){const{localParticipant:n}=YI(t),i=n==null?void 0:n.getTrackPublication(e);return O.useMemo(()=>i&&n?{source:e,participant:n,publication:i}:void 0,[e,i,n])}function jM({chatOpen:e,client:t,theme:n="vox"}){const{agent:{isActive:i=!1}={},session:r,state:s="idle",audioTrack:o,videoTrack:a}=t?zh(t):{agent:{isActive:!1},session:null,state:"idle",audioTrack:null,videoTrack:null};console.log("🎨 MediaTiles render:",{chatOpen:e,isAgentActive:i,hasSession:!!r,sessionState:r==null?void 0:r.state,agentState:s,hasAudioTrack:!!o,hasVideoTrack:!!a});const[c]=ek([B.Source.ScreenShare]),l=FM(B.Source.Camera,t),u=l&&!l.publication.isMuted,d=c&&!c.publication.isMuted,h=u||d,f=i||r&&r.state==="active",g={...li.transition,delay:e?0:.15},p={...li.animate,scale:e?1:3,transition:g},v={...li.animate,transition:g},b=g,w=g,S=a&&a.publication&&a.participant;return m.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:m.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:m.jsxs("div",{className:Xe(Pr.grid),children:[f&&m.jsx("div",{className:Xe(["grid",!e&&Pr.agentChatClosed,e&&h&&Pr.agentChatOpenWithSecondTile,e&&!h&&Pr.agentChatOpenWithoutSecondTile]),children:m.jsxs("div",{className:"h-full flex items-center justify-center",children:[!S&&m.jsx(DM,{layoutId:"agent",...li,animate:p,transition:b,state:s,audioTrack:o||void 0,theme:n,className:Xe(e?"h-[90px]":"h-auto w-full")},"agent"),S&&a&&m.jsx(LM,{layoutId:"avatar",...li,animate:v,transition:w,videoTrack:a,className:Xe(e?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),m.jsx("div",{className:Xe(["grid",e&&Pr.secondTileChatOpen,!e&&Pr.secondTileChatClosed]),children:m.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[l&&u&&m.jsx(gg,{layout:"position",layoutId:"camera",...li,trackRef:l,transition:{...li.transition,delay:e?0:.15},className:"h-[60px] order-1"},"camera"),d&&m.jsx(gg,{layout:"position",layoutId:"screen",...li,trackRef:c,transition:{...li.transition,delay:e?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}const UM={card:"text-gray-100 bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] border border-gray-800/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-black/90 via-black/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(75,85,99,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-gray-500/[0.12] via-gray-600/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-gray-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-100 font-semibold",secondary:"text-gray-200",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-300 via-gray-200 to-gray-300"},micButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 text-gray-100 font-bold hover:bg-gray-900 hover:border-gray-600 hover:scale-[1.02] hover:shadow-2xl hover:shadow-gray-600/30 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-gray-900/60 backdrop-blur-xl rounded-2xl text-center text-gray-200 text-sm font-medium transition-all duration-700 ease-in-out border border-gray-700/50 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-gray-400 rounded-full animate-pulse shadow-lg shadow-gray-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-gray-800/50 rounded-3xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-black/90 backdrop-blur-xl border-gray-800/50 shadow-xl",textarea:"bg-black/80 border border-gray-800/50 rounded-xl text-gray-100 placeholder-gray-500 font-medium px-4 py-3",sendButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 disabled:border-gray-800 disabled:opacity-40 text-gray-100 font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-gray-600/30",attachButton:"text-gray-400 hover:text-gray-200 hover:bg-gray-700/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/40 hover:border-red-500/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-gray-800/70 text-gray-100 backdrop-blur-md shadow-lg border border-gray-700/50",other:"bg-gray-900/60 text-gray-100 border border-gray-700/50 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-gray-900/80 border-gray-700/50 backdrop-blur-xl shadow-xl",backButton:"text-gray-300 hover:text-gray-100 hover:bg-gray-700/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-gray-400 mb-2",suggestedResponse:{container:"bg-gray-900/70 text-gray-200 border-gray-700/50 backdrop-blur-md hover:bg-gray-800/80 hover:border-gray-600 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] text-gray-100",header:"border-gray-700/50 bg-gray-900/80 backdrop-blur-xl shadow-xl",headerButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-gray-900 via-gray-900/90 to-gray-900/60 backdrop-blur-xl border-t border-gray-700/50 shadow-2xl",controlEnabled:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 hover:shadow-xl hover:shadow-gray-600/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-900/50 hover:bg-gray-900/60 text-gray-500 border border-gray-800 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/50 hover:border-red-500/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-gray-900/70 border border-gray-700/50 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-900/60 text-gray-300",avatar:"bg-gray-800/80 text-gray-300 border-2 border-gray-700/50",nameOverlay:"bg-gradient-to-t from-gray-900 via-gray-900/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},BM={card:"text-gray-900 bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] border-[3px] border-indigo-200/60 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl shadow-indigo-200/30",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#FFFFFF]/90 via-[#FFFFFF]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(129,140,248,0.12),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 right-0 w-64 h-64 bg-gradient-to-br from-indigo-300/40 via-purple-300/25 to-transparent rounded-full blur-3xl animate-pulse-slow",cardPinkBlur:"absolute bottom-0 left-0 w-56 h-56 bg-gradient-to-tr from-blue-300/35 via-purple-200/20 to-transparent rounded-full blur-3xl",cardPulse1:"absolute top-4 right-4 w-8 h-8 bg-gradient-to-br from-indigo-400/30 to-purple-400/30 rounded-full blur-md opacity-60 animate-pulse",cardPulse2:"absolute bottom-6 left-6 w-6 h-6 bg-gradient-to-br from-blue-400/25 to-purple-400/25 rounded-full blur-md opacity-50 animate-pulse",main:"w-full flex flex-col items-center justify-center bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-900 font-semibold",secondary:"text-gray-700",muted:"text-gray-500",accent:"text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600"},micButton:"relative w-20 h-20 backdrop-blur-xl border-2 border-indigo-400/40 rounded-3xl flex items-center justify-center hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-indigo-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",chatButton:"relative w-20 h-20 bg-gradient-to-br from-blue-600 to-cyan-600 backdrop-blur-xl border-2 border-blue-400/40 rounded-3xl flex items-center justify-center hover:from-blue-700 hover:to-cyan-700 hover:border-blue-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-blue-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",videoButton:"relative w-20 h-20 bg-gradient-to-br from-purple-600 to-pink-600 backdrop-blur-xl border-2 border-purple-400/40 rounded-3xl flex items-center justify-center hover:from-purple-700 hover:to-pink-700 hover:border-purple-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-purple-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",popupTrigger:"bg-gradient-to-r from-indigo-600 to-purple-600 backdrop-blur-xl border-2 border-indigo-400/40 text-white font-bold hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-[1.02] hover:shadow-2xl hover:shadow-indigo-500/40 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-white transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/80 backdrop-blur-xl rounded-2xl text-center text-gray-700 text-sm font-medium transition-all duration-700 ease-in-out border border-indigo-100 shadow-lg shadow-indigo-100/20",statusIndicator:"w-2.5 h-2.5 bg-emerald-500 rounded-full animate-pulse shadow-lg shadow-emerald-500/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-indigo-100 rounded-3xl py-4 flex flex-col justify-end h-full bg-white/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-white/80 backdrop-blur-xl border-indigo-100 shadow-xl",textarea:"bg-white/90 border border-indigo-100 rounded-xl text-gray-900 placeholder-gray-400 font-medium px-4 py-3 focus:border-indigo-300 focus:ring-2 focus:ring-indigo-200",sendButton:"bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 border-2 border-transparent disabled:from-gray-300 disabled:to-gray-300 disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-indigo-500/40",attachButton:"text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-indigo-100/70 text-gray-900 backdrop-blur-md shadow-lg border border-indigo-200/50",other:"bg-white/80 text-gray-900 border border-gray-200 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-white/80 border-indigo-100 backdrop-blur-xl shadow-xl",backButton:"text-gray-600 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-indigo-600 mb-2",suggestedResponse:{container:"bg-white/80 text-indigo-700 border-indigo-100 backdrop-blur-md hover:bg-indigo-50 hover:border-indigo-200 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] text-gray-900",header:"border-indigo-100 bg-white/80 backdrop-blur-xl shadow-xl",headerButton:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-500 animate-pulse shadow-lg shadow-emerald-500/60",controlsBackground:"bg-gradient-to-t from-white via-white/90 to-white/60 backdrop-blur-xl border-t border-indigo-100 shadow-2xl",controlEnabled:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 hover:shadow-xl hover:shadow-indigo-200/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-100/50 hover:bg-gray-100/60 text-gray-400 border border-gray-200 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-white/80 border border-indigo-100 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-50 text-gray-600",avatar:"bg-indigo-100/80 text-indigo-700 border-2 border-indigo-200",nameOverlay:"bg-gradient-to-t from-white via-white/80 to-transparent text-gray-900 backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},VM={card:"text-white bg-gradient-to-b from-[#0a0a0a] via-[#000000] to-[#0a0a0a] border border-gray-800/30 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-[0_8px_32px_rgba(0,0,0,0.9),0_0_0_1px_rgba(255,255,255,0.08)_inset]",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-32 z-10 bg-gradient-to-b from-black/95 via-black/30 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_rgba(255,255,255,0.03),transparent_60%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[400px] h-[200px] bg-gradient-to-b from-white/[0.03] via-white/[0.015] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[300px] h-[150px] bg-gradient-to-t from-white/[0.02] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-black p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-200 via-white to-gray-200"},micButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",popupTrigger:"bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] text-white font-bold hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.02] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] focus:outline-none focus:ring-2 focus:ring-white/30 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/[0.06] backdrop-blur-md rounded-xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-white/[0.12] ",statusIndicator:"w-2 h-2 bg-emerald-400 rounded-full animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-white/[0.12] rounded-2xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-md shadow-[0_4px_24px_rgba(0,0,0,0.6)]",chatInput:{container:"bg-black/90 backdrop-blur-md border-white/[0.12] shadow-[0_4px_16px_rgba(0,0,0,0.4)]",textarea:"bg-white/[0.08] border border-white/[0.12] rounded-xl text-white placeholder-gray-500 font-medium px-4 py-3 focus:border-white/[0.2] focus:ring-1 focus:ring-white/[0.15] transition-all",sendButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] disabled:border-white/[0.08] disabled:opacity-40 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(255,255,255,0.12)]",attachButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg",endButton:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(239,68,68,0.3)]"},chatMessage:{own:"bg-white/[0.10] text-white backdrop-blur-sm shadow-md border border-white/[0.15]",other:"bg-white/[0.06] text-white border border-white/[0.10] backdrop-blur-sm shadow-md"},chatHeader:{container:"bg-black/90 border-white/[0.12] backdrop-blur-md shadow-lg",backButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg"},spinner:"w-10 h-10 animate-spin text-white mb-2",suggestedResponse:{container:"bg-white/[0.08] text-white border-white/[0.15] backdrop-blur-sm hover:bg-white/[0.12] hover:border-white/[0.25] transition-all duration-300 shadow-md"},video:{container:"bg-black text-white",header:"border-white/[0.12] bg-black/90 backdrop-blur-md shadow-lg",headerButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] transition-all duration-300 rounded-lg shadow-md",statusDot:"bg-emerald-400 animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",controlsBackground:"bg-gradient-to-t from-black via-black/95 to-black/70 backdrop-blur-md border-t border-white/[0.12] shadow-[0_-4px_24px_rgba(0,0,0,0.6)]",controlEnabled:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] hover:shadow-md hover:shadow-white/10 transition-all duration-300 font-semibold",controlDisabled:"bg-white/[0.04] hover:bg-white/[0.06] text-gray-500 border border-white/[0.08] transition-all duration-300",endCall:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-red-500/30",tile:"bg-white/[0.08] border border-white/[0.12] shadow-lg backdrop-blur-sm rounded-xl",placeholder:"bg-white/[0.06] text-gray-400",avatar:"bg-white/[0.10] text-gray-300 border border-white/[0.12]",nameOverlay:"bg-gradient-to-t from-black via-black/85 to-transparent text-white backdrop-blur-sm font-semibold",mutedIndicator:"bg-red-500 text-white shadow-md shadow-red-500/30 font-semibold"}},$M={card:"text-white bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] border border-[#2a3142]/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#0b1220]/90 via-[#0b1220]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(34,211,238,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-cyan-500/[0.12] via-sky-500/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-cyan-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"text-transparent bg-clip-text bg-gradient-to-r from-cyan-300 via-sky-300 to-cyan-300"},micButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-sky-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-sky-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-sky-500/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 text-white font-bold hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-[1.02] hover:shadow-2xl hover:shadow-cyan-500/30 focus:outline-none focus:ring-2 focus:ring-cyan-400/50 focus:ring-offset-2 focus:ring-offset-[#161a25] transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-[#1c2230]/60 backdrop-blur-xl rounded-2xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-[#2a3142]/80 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-emerald-400 rounded-full animate-pulse shadow-lg shadow-emerald-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-[#2a3142]/80 rounded-3xl py-4 flex flex-col justify-end h-full bg-[#161a25]/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-[#1c2230]/80 backdrop-blur-xl border-[#2a3142]/80 shadow-xl",textarea:"bg-[#1c2230]/60 border border-[#2a3142]/50 rounded-xl text-white placeholder-gray-400 font-medium px-4 py-3",sendButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 disabled:border-[#2a3142] disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-cyan-500/30",attachButton:"text-gray-400 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-[#243049]/70 text-white backdrop-blur-md shadow-lg border border-[#2a3142]/80",other:"bg-[#1c2230]/60 text-white border border-[#2a3142]/80 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-[#1c2230]/80 border-[#2a3142]/80 backdrop-blur-xl shadow-xl",backButton:"text-white/80 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-cyan-400 mb-2",suggestedResponse:{container:"bg-[#1c2230]/70 text-white border-[#2a3142]/80 backdrop-blur-md hover:bg-[#1c2230]/80 hover:border-cyan-400/30 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] text-white",header:"border-[#2a3142]/80 bg-[#1c2230]/80 backdrop-blur-xl shadow-xl",headerButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-[#161a25] via-[#161a25]/90 to-[#161a25]/60 backdrop-blur-xl border-t border-[#2a3142]/80 shadow-2xl",controlEnabled:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 hover:shadow-xl hover:shadow-cyan-500/30 transition-all duration-300 font-semibold",controlDisabled:"bg-[#1c2230]/50 hover:bg-[#1c2230]/60 text-white/40 border border-[#2a3142] transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-[#1c2230]/70 border border-[#2a3142]/80 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-[#1c2230]/60 text-white/80",avatar:"bg-[#171b26]/80 text-white border-2 border-[#2a3142]/80",nameOverlay:"bg-gradient-to-t from-[#161a25] via-[#161a25]/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},zM={card:" text-white bg-gradient-to-br from-[#171727] to-[#12121F] border border-gray-800 w-full h-full flex flex-col justify-between overflow-hidden relative",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-[#171727]/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#3B82F6]/15 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#8B5CF6]/25 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-[#EC4899]/20 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full blur-sm opacity-50 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-[#EC4899] to-[#8B5CF6] rounded-full blur-sm opacity-40 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-[#171727] to-[#12121F] rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"bg-clip-text text-transparent bg-gradient-to-r from-[#3B82F6] via-[#8B5CF6] to-[#EC4899]"},micButton:"relative w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"relative w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"relative w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 shadow-xl",promptSlider:"absolute w-full py-3 px-2 bg-[#1E1E2E] rounded-xl text-center text-gray-200 text-sm transition-opacity duration-700 ease-in-out border border-gray-700",statusIndicator:"w-2 h-2 bg-[#10B981] rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-[#3B82F6]/40 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-[#8B5CF6]/30 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-[#EC4899]/20 pulse-ring"},controlBar:"border border-border rounded-3xl py-4 flex flex-col justify-end h-full bg-[#1E1E2E] shadow-2xl",chatInput:{container:"bg-[#1E1E2E] border-gray-700",textarea:"bg-[#1E1E2E] border-none text-white placeholder-gray-400",sendButton:"bg-[#3B82F6] hover:bg-[#2563EB] disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-[#1E1E2E]/80 text-white",other:"bg-[#1E1E2E] text-white border border-gray-700"},chatHeader:{container:"bg-[#1E1E2E] border-gray-700",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-blue-400 mb-2",suggestedResponse:{container:"bg-[#221f3f] text-white border-none"},video:{container:"bg-gradient-to-br from-[#171727] to-[#12121F] text-white",header:"border-gray-700 bg-[#1E1E2E]/80",headerButton:"bg-[#1E1E2E] hover:bg-gray-700 text-gray-300",statusDot:"bg-[#10B981] animate-pulse",controlsBackground:"bg-[#1E1E2E]/90 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-[#3B82F6] hover:bg-[#2563EB] text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-[#1E1E2E] border border-gray-700 shadow-xl",placeholder:"bg-[#1E1E2E] text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},bg={dark:UM,light:BM,vox:VM,midnight:$M,levish:zM};function on(e){return bg[e]||bg.vox}function yg({timeout:e}){const[t,n]=O.useState(100),i=O.useRef(null),r=O.useRef(null);return O.useEffect(()=>{if(!e||e<=0)return;n(100),r.current=Date.now();const s=()=>{if(!e||r.current===null)return;const o=Date.now()-r.current,a=Math.max(0,100-o/e*100);n(a),a>0&&(i.current=requestAnimationFrame(s))};return i.current=requestAnimationFrame(s),()=>{i.current&&cancelAnimationFrame(i.current)}},[e]),!e||e<=0?null:m.jsx("div",{className:"w-full h-1 relative top-1 rounded-t-4xl bg-gray-700 overflow-hidden",children:m.jsx(Fe.div,{className:"h-1 rounded-t-4xl dark:bg-white bg-blue-200 ",initial:{width:"100%"},animate:{width:`${Math.max(t,2)}%`},transition:{duration:.1,ease:"linear"},style:{minWidth:"2%"}})})}function uo({interaction:e,theme:t,onDismiss:n,client:i,addLocalMessage:r}){var a;if(!e||!e.isVisible||!e.component)return null;const[s]=D.useState(()=>Date.now()),o=()=>e.component?D.createElement(e.component,{handler:e.handler||void 0,timeout:e.timeout,loadData:async l=>{console.log("InteractiveComponent: Loading data:",l)},presentationMode:e.presentationMode,data:e.data,client:i,addLocalMessage:r}):m.jsx("div",{className:"p-4 text-red-500",children:"Component not found"});switch(e.presentationMode){case"fullscreen":return m.jsx(ls,{children:m.jsxs(Fe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] bg-black",children:[m.jsxs("div",{className:"flex flex-col",children:[m.jsx(yg,{timeout:e.timeout}),m.jsxs("div",{className:"flex items-center justify-between p-4 bg-black/80 text-white border-b border-gray-700",children:[m.jsx("h3",{className:"text-lg font-semibold",children:e.methodName.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase())}),m.jsx("button",{onClick:n||((a=e.handler)==null?void 0:a.dismissView),className:"p-2 rounded-full bg-white/20 hover:bg-white/30 text-white transition-colors",children:m.jsx(kt.X,{className:"w-5 h-5"})})]})]}),m.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:o()})]})});case"embedded":default:return m.jsx(ls,{children:m.jsx(Fe.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-fit rounded-lg ",children:m.jsxs("div",{children:[m.jsx(yg,{timeout:e.timeout}),o()]})})})}}function ho({duration:e,theme:t="vox",onTimerExpired:n,className:i="",showIcon:r=!0}){const[s,o]=O.useState(e),[a,c]=O.useState(!1);O.useEffect(()=>{if(s<=0){c(!0),n==null||n();return}const u=setInterval(()=>{o(d=>{const h=d-1;return h<=0?(c(!0),n==null||n(),0):h})},1e3);return()=>clearInterval(u)},[s,n]),O.useEffect(()=>{o(e),c(!1)},[e]);const l=()=>a?"text-red-500":s<=60?"text-orange-500":s<=300?"text-yellow-500":t==="dark"?"text-gray-300":"text-gray-600";return m.jsxs("div",{className:`flex items-center gap-1 text-sm ${l()} ${i}`,children:[r&&m.jsx(kt.Clock,{className:"w-4 h-4"}),m.jsx("span",{className:"font-mono",children:bk(s)}),a&&m.jsx("span",{className:"text-xs ml-1 text-red-500",children:"(Expired)"})]})}function Cc({modality:e,theme:t,disabled:n=!1,showMicrophone:i=!1,microphoneEnabled:r=!0,microphoneLoading:s=!1,onToggleMicrophone:o,showCamera:a=!1,cameraEnabled:c=!0,cameraLoading:l=!1,onToggleCamera:u,showScreenShare:d=!1,screenShareEnabled:h=!1,screenShareLoading:f=!1,onToggleScreenShare:g,showChatToggle:p=!1,chatOpen:v=!1,onToggleChat:b,showTextInput:w=!1,textInputPlaceholder:S="Type a message...",onSendText:k,onSendAttachments:x,supportsAttachments:T=!1,showEndCall:P=!0,onEndCall:A}){var H;const N=on(t),[y,R]=O.useState(""),I=O.useRef(null),L=()=>{const C=y.trim();C&&k&&(k(C),R(""))},U=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),L())},K=C=>{const W=Array.from(C.target.files||[]);W.length>0&&x&&x(W),I.current&&(I.current.value="")},ue=Xe("flex items-center gap-3 px-2 sm:px-3 py-2 w-full backdrop-blur-xl overflow-hidden",w?"justify-between":"justify-center",t==="light"?"bg-white/95 border-gray-200":""),se=(C,W)=>{var Y,E,J;return W==="end-call"?Xe("p-3 rounded-full transition-all duration-200",((Y=N.video)==null?void 0:Y.endCall)||"bg-red-500 text-white hover:bg-red-600",n?"opacity-50 cursor-not-allowed":"hover:scale-105"):Xe("p-3 rounded-full transition-all duration-200",C?((E=N.video)==null?void 0:E.controlEnabled)||"bg-green-500 text-white":((J=N.video)==null?void 0:J.controlDisabled)||"bg-gray-500 text-white",n?"opacity-50 cursor-not-allowed":"hover:scale-105")},z=()=>m.jsx("div",{className:"w-5 h-5 animate-spin rounded-full border-2 border-current border-t-transparent"});return m.jsxs("div",{className:ue,children:[w&&m.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[T&&x&&m.jsxs(m.Fragment,{children:[m.jsx("button",{onClick:()=>{var C;return(C=I.current)==null?void 0:C.click()},disabled:n,className:Xe("p-2 rounded-full transition-all duration-200",t==="light"?"hover:bg-gray-100":"hover:bg-gray-800",n&&"opacity-50 cursor-not-allowed"),title:"Attach files",children:m.jsx(kt.Paperclip,{className:"w-5 h-5"})}),m.jsx("input",{ref:I,type:"file",multiple:!0,accept:"image/*",onChange:K,className:"hidden"})]}),m.jsx("input",{type:"text",value:y,onChange:C=>R(C.target.value),onKeyDown:U,disabled:n,placeholder:S,className:Xe("flex-1 min-w-0 px-4 py-2 rounded-full border outline-none transition-all",t==="light"?"bg-gray-100 border-gray-300 focus:border-blue-500 text-gray-900":"bg-gray-800 border-gray-700 focus:border-blue-400 text-white",n&&"opacity-50 cursor-not-allowed")}),m.jsx("button",{onClick:L,disabled:n||!y.trim(),className:Xe("p-2 rounded-full transition-all duration-200",y.trim()?((H=N.video)==null?void 0:H.controlEnabled)||"bg-blue-500 text-white hover:bg-blue-600":t==="light"?"bg-gray-200 text-gray-400":"bg-gray-700 text-gray-500",n&&"opacity-50 cursor-not-allowed",y.trim()&&!n&&"hover:scale-105"),title:"Send message",children:m.jsx(kt.SendHorizontal,{className:"w-5 h-5"})})]}),!w&&m.jsxs(m.Fragment,{children:[i&&o&&m.jsx("button",{onClick:o,disabled:n||s,className:se(r),title:r?"Mute microphone":"Unmute microphone",children:s?m.jsx(z,{}):r?m.jsx(kt.Mic,{className:"w-5 h-5"}):m.jsx(kt.MicOff,{className:"w-5 h-5"})}),a&&u&&m.jsx("button",{onClick:u,disabled:n||l,className:se(c),title:c?"Turn off camera":"Turn on camera",children:l?m.jsx(z,{}):c?m.jsx(kt.Camera,{className:"w-5 h-5"}):m.jsx(kt.CameraOff,{className:"w-5 h-5"})}),d&&g&&m.jsx("button",{onClick:g,disabled:n||f,className:se(h),title:h?"Stop screen share":"Share screen",children:f?m.jsx(z,{}):m.jsx(kt.Monitor,{className:"w-5 h-5"})}),p&&b&&m.jsx("button",{onClick:b,disabled:n,className:se(v),title:e==="voice"?v?"Hide transcription":"Show transcription":v?"Hide chat":"Show chat",children:m.jsx(kt.MessageCircle,{className:"w-5 h-5"})})]}),P&&A&&m.jsx("button",{onClick:A,disabled:n,className:se(!1,"end-call"),title:"End call",children:m.jsx(kt.PhoneOff,{className:"w-5 h-5"})})]})}Cc.displayName="UnifiedControlBar";const HM=({logLevel:e}={})=>{const t=Kx();D.useEffect(()=>(FC(e??"debug"),window.__lk_room=t,()=>{window.__lk_room=void 0}),[t,e])},vk=D.forwardRef((e,t)=>{const{alt:n,color:i="currentColor",size:r="1em",weight:s="regular",mirrored:o=!1,children:a,weights:c,...l}=e;return D.createElement("svg",{ref:t,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,fill:i,viewBox:"0 0 256 256",transform:o?"scale(-1, 1)":void 0,...l},!!n&&D.createElement("title",null,n),a,c.get(s))});vk.displayName="SSRBase";const WM=new Map([["bold",D.createElement(D.Fragment,null,D.createElement("path",{d:"M140,32V64a12,12,0,0,1-24,0V32a12,12,0,0,1,24,0Zm33.25,62.75a12,12,0,0,0,8.49-3.52L204.37,68.6a12,12,0,0,0-17-17L164.77,74.26a12,12,0,0,0,8.48,20.49ZM224,116H192a12,12,0,0,0,0,24h32a12,12,0,0,0,0-24Zm-42.26,48.77a12,12,0,1,0-17,17l22.63,22.63a12,12,0,0,0,17-17ZM128,180a12,12,0,0,0-12,12v32a12,12,0,0,0,24,0V192A12,12,0,0,0,128,180ZM74.26,164.77,51.63,187.4a12,12,0,0,0,17,17l22.63-22.63a12,12,0,1,0-17-17ZM76,128a12,12,0,0,0-12-12H32a12,12,0,0,0,0,24H64A12,12,0,0,0,76,128ZM68.6,51.63a12,12,0,1,0-17,17L74.26,91.23a12,12,0,0,0,17-17Z"}))],["duotone",D.createElement(D.Fragment,null,D.createElement("path",{d:"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z",opacity:"0.2"}),D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["fill",D.createElement(D.Fragment,null,D.createElement("path",{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm33.94,58.75,17-17a8,8,0,0,1,11.32,11.32l-17,17a8,8,0,0,1-11.31-11.31ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z"}))],["light",D.createElement(D.Fragment,null,D.createElement("path",{d:"M134,32V64a6,6,0,0,1-12,0V32a6,6,0,0,1,12,0Zm39.25,56.75A6,6,0,0,0,177.5,87l22.62-22.63a6,6,0,0,0-8.48-8.48L169,78.5a6,6,0,0,0,4.24,10.25ZM224,122H192a6,6,0,0,0,0,12h32a6,6,0,0,0,0-12Zm-46.5,47A6,6,0,0,0,169,177.5l22.63,22.62a6,6,0,0,0,8.48-8.48ZM128,186a6,6,0,0,0-6,6v32a6,6,0,0,0,12,0V192A6,6,0,0,0,128,186ZM78.5,169,55.88,191.64a6,6,0,1,0,8.48,8.48L87,177.5A6,6,0,1,0,78.5,169ZM70,128a6,6,0,0,0-6-6H32a6,6,0,0,0,0,12H64A6,6,0,0,0,70,128ZM64.36,55.88a6,6,0,0,0-8.48,8.48L78.5,87A6,6,0,1,0,87,78.5Z"}))],["regular",D.createElement(D.Fragment,null,D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["thin",D.createElement(D.Fragment,null,D.createElement("path",{d:"M132,32V64a4,4,0,0,1-8,0V32a4,4,0,0,1,8,0Zm41.25,54.75a4,4,0,0,0,2.83-1.18L198.71,63a4,4,0,0,0-5.66-5.66L170.43,79.92a4,4,0,0,0,2.82,6.83ZM224,124H192a4,4,0,0,0,0,8h32a4,4,0,0,0,0-8Zm-47.92,46.43a4,4,0,1,0-5.65,5.65l22.62,22.63a4,4,0,0,0,5.66-5.66ZM128,188a4,4,0,0,0-4,4v32a4,4,0,0,0,8,0V192A4,4,0,0,0,128,188ZM79.92,170.43,57.29,193.05A4,4,0,0,0,63,198.71l22.62-22.63a4,4,0,1,0-5.65-5.65ZM68,128a4,4,0,0,0-4-4H32a4,4,0,0,0,0,8H64A4,4,0,0,0,68,128ZM63,57.29A4,4,0,0,0,57.29,63L79.92,85.57a4,4,0,1,0,5.65-5.65Z"}))]]),Qa=D.forwardRef((e,t)=>D.createElement(vk,{ref:t,...e,weights:WM}));Qa.displayName="SpinnerIcon";function qM({text:e,isComplete:t,isRealTimeStream:n=!1,speed:i=50}){const[r,s]=D.useState(""),[o,a]=D.useState(0);return D.useEffect(()=>{if(n){s(e);return}if(t){s(e);return}if(o<e.length){const c=setTimeout(()=>{s(e.slice(0,o+1)),a(o+1)},i);return()=>clearTimeout(c)}},[e,o,t,i,n]),D.useEffect(()=>{n||(a(0),s(""))},[e,n]),m.jsxs("span",{className:"relative",children:[m.jsx("span",{className:"inline-block",children:r}),!t&&m.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(c=>m.jsx(Fe.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:c*.2,ease:"easeInOut"}},c))})]})}function GM(e,t){return e.startsWith("image/")?kt.Image:e.startsWith("video/")?kt.Video:e.startsWith("audio/")?kt.Music:e.includes("zip")||e.includes("rar")||e.includes("archive")?kt.Archive:kt.FileText}function KM(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,i)).toFixed(2))+" "+n[i]}function YM({message:e,theme:t,isOwn:n}){const i=on(t),r=e.metadata,s=(r==null?void 0:r.fileName)||"Unknown file",o=(r==null?void 0:r.fileSize)||0,a=(r==null?void 0:r.mimeType)||"application/octet-stream",c=r==null?void 0:r.downloading,l=r==null?void 0:r.uploading,u=(r==null?void 0:r.downloadProgress)||0,d=(r==null?void 0:r.uploadProgress)||0,h=r==null?void 0:r.downloadUrl,f=r==null?void 0:r.file,g=GM(a),p=c||l,v=c?u:d,b=c?"Downloading...":l?"Uploading...":"Complete",[w,S]=D.useState(null);D.useEffect(()=>{if(h)S(h);else if(f&&a.startsWith("image/")){const P=URL.createObjectURL(f);return S(P),()=>URL.revokeObjectURL(P)}else S(null)},[h,f,a]);const k=()=>{if(h){const P=document.createElement("a");P.href=h,P.download=s,P.click()}},T=a.startsWith("image/")&&w;return m.jsxs("div",{className:"flex flex-col gap-2 max-w-full sm:max-w-sm",children:[T&&m.jsxs("div",{className:"relative rounded-lg overflow-hidden",children:[m.jsx("img",{src:w,alt:s,className:"max-w-full h-auto max-h-48 object-cover rounded-lg cursor-pointer",onClick:k}),m.jsx("div",{className:"absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors duration-200 cursor-pointer"})]}),m.jsxs("div",{className:`
|
|
48
|
+
`):"",this.name="UnsubscriptionError",this.errors=t}});function Za(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var xo=function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,n,i,r,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var a=ds(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(p){t={error:p}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}else o.remove(this);var u=this.initialTeardown;if(Vt(u))try{u()}catch(p){s=p instanceof Al?p.errors:[p]}var d=this._finalizers;if(d){this._finalizers=null;try{for(var h=ds(d),f=h.next();!f.done;f=h.next()){var g=f.value;try{Qm(g)}catch(p){s=s??[],p instanceof Al?s=Ya(Ya([],Ka(s)),Ka(p.errors)):s.push(p)}}}catch(p){i={error:p}}finally{try{f&&!f.done&&(r=h.return)&&r.call(h)}finally{if(i)throw i.error}}}if(s)throw new Al(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Qm(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(t)}},e.prototype._hasParent=function(t){var n=this._parentage;return n===t||Array.isArray(n)&&n.includes(t)},e.prototype._addParent=function(t){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(t),n):n?[n,t]:t},e.prototype._removeParent=function(t){var n=this._parentage;n===t?this._parentage=null:Array.isArray(n)&&Za(n,t)},e.prototype.remove=function(t){var n=this._finalizers;n&&Za(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}(),Sx=xo.EMPTY;function wx(e){return e instanceof xo||e&&"closed"in e&&Vt(e.remove)&&Vt(e.add)&&Vt(e.unsubscribe)}function Qm(e){Vt(e)?e():e.unsubscribe()}var IN={Promise:void 0},MN={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setTimeout.apply(void 0,Ya([e,t],Ka(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function Tx(e){MN.setTimeout(function(){throw e})}function eg(){}function Ea(e){e()}var Bh=function(e){Ci(t,e);function t(n){var i=e.call(this)||this;return i.isStopped=!1,n?(i.destination=n,wx(n)&&n.add(i)):i.destination=LN,i}return t.create=function(n,i,r){return new gd(n,i,r)},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(xo),ON=function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var n=this.partialObserver;if(n.next)try{n.next(t)}catch(i){Ho(i)}},e.prototype.error=function(t){var n=this.partialObserver;if(n.error)try{n.error(t)}catch(i){Ho(i)}else Ho(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(n){Ho(n)}},e}(),gd=function(e){Ci(t,e);function t(n,i,r){var s=e.call(this)||this,o;return Vt(n)||!n?o={next:n??void 0,error:i??void 0,complete:r??void 0}:o=n,s.destination=new ON(o),s}return t}(Bh);function Ho(e){Tx(e)}function DN(e){throw e}var LN={closed:!0,next:eg,error:DN,complete:eg},Vh=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Cx(e){return e}function FN(e){return e.length===0?Cx:e.length===1?e[0]:function(t){return e.reduce(function(n,i){return i(n)},t)}}var Tn=function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(t,n,i){var r=this,s=UN(t)?t:new gd(t,n,i);return Ea(function(){var o=r,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?r._subscribe(s):r._trySubscribe(s))}),s},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(n){t.error(n)}},e.prototype.forEach=function(t,n){var i=this;return n=tg(n),new n(function(r,s){var o=new gd({next:function(a){try{t(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:r});i.subscribe(o)})},e.prototype._subscribe=function(t){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(t)},e.prototype[Vh]=function(){return this},e.prototype.pipe=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return FN(t)(this)},e.prototype.toPromise=function(t){var n=this;return t=tg(t),new t(function(i,r){var s;n.subscribe(function(o){return s=o},function(o){return r(o)},function(){return i(s)})})},e.create=function(t){return new e(t)},e}();function tg(e){var t;return(t=e??IN.Promise)!==null&&t!==void 0?t:Promise}function jN(e){return e&&Vt(e.next)&&Vt(e.error)&&Vt(e.complete)}function UN(e){return e&&e instanceof Bh||jN(e)&&wx(e)}function BN(e){return Vt(e==null?void 0:e.lift)}function ko(e){return function(t){if(BN(t))return t.lift(function(n){try{return e(n,this)}catch(i){this.error(i)}});throw new TypeError("Unable to lift unknown Observable type")}}function Xa(e,t,n,i,r){return new VN(e,t,n,i,r)}var VN=function(e){Ci(t,e);function t(n,i,r,s,o,a){var c=e.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=i?function(l){try{i(l)}catch(u){n.error(u)}}:e.prototype._next,c._error=s?function(l){try{s(l)}catch(u){n.error(u)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=r?function(){try{r()}catch(l){n.error(l)}finally{this.unsubscribe()}}:e.prototype._complete,c}return t.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},t}(Bh),$N=Uh(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Ex=function(e){Ci(t,e);function t(){var n=e.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return t.prototype.lift=function(n){var i=new ng(this,this);return i.operator=n,i},t.prototype._throwIfClosed=function(){if(this.closed)throw new $N},t.prototype.next=function(n){var i=this;Ea(function(){var r,s;if(i._throwIfClosed(),!i.isStopped){i.currentObservers||(i.currentObservers=Array.from(i.observers));try{for(var o=ds(i.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){r={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(r)throw r.error}}}})},t.prototype.error=function(n){var i=this;Ea(function(){if(i._throwIfClosed(),!i.isStopped){i.hasError=i.isStopped=!0,i.thrownError=n;for(var r=i.observers;r.length;)r.shift().error(n)}})},t.prototype.complete=function(){var n=this;Ea(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var i=n.observers;i.length;)i.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(n){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,n)},t.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},t.prototype._innerSubscribe=function(n){var i=this,r=this,s=r.hasError,o=r.isStopped,a=r.observers;return s||o?Sx:(this.currentObservers=null,a.push(n),new xo(function(){i.currentObservers=null,Za(a,n)}))},t.prototype._checkFinalizedStatuses=function(n){var i=this,r=i.hasError,s=i.thrownError,o=i.isStopped;r?n.error(s):o&&n.complete()},t.prototype.asObservable=function(){var n=new Tn;return n.source=this,n},t.create=function(n,i){return new ng(n,i)},t}(Tn),ng=function(e){Ci(t,e);function t(n,i){var r=e.call(this)||this;return r.destination=n,r.source=i,r}return t.prototype.next=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.next)===null||r===void 0||r.call(i,n)},t.prototype.error=function(n){var i,r;(r=(i=this.destination)===null||i===void 0?void 0:i.error)===null||r===void 0||r.call(i,n)},t.prototype.complete=function(){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||i===void 0||i.call(n)},t.prototype._subscribe=function(n){var i,r;return(r=(i=this.source)===null||i===void 0?void 0:i.subscribe(n))!==null&&r!==void 0?r:Sx},t}(Ex);(function(e){Ci(t,e);function t(n){var i=e.call(this)||this;return i._value=n,i}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(n){var i=e.prototype._subscribe.call(this,n);return!i.closed&&n.next(this._value),i},t.prototype.getValue=function(){var n=this,i=n.hasError,r=n.thrownError,s=n._value;if(i)throw r;return this._throwIfClosed(),s},t.prototype.next=function(n){e.prototype.next.call(this,this._value=n)},t})(Ex);var zN={now:function(){return Date.now()}},HN=function(e){Ci(t,e);function t(n,i){return e.call(this)||this}return t.prototype.schedule=function(n,i){return this},t}(xo),ig={setInterval:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];return setInterval.apply(void 0,Ya([e,t],Ka(n)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},WN=function(e){Ci(t,e);function t(n,i){var r=e.call(this,n,i)||this;return r.scheduler=n,r.work=i,r.pending=!1,r}return t.prototype.schedule=function(n,i){var r;if(i===void 0&&(i=0),this.closed)return this;this.state=n;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,i)),this.pending=!0,this.delay=i,this.id=(r=this.id)!==null&&r!==void 0?r:this.requestAsyncId(o,this.id,i),this},t.prototype.requestAsyncId=function(n,i,r){return r===void 0&&(r=0),ig.setInterval(n.flush.bind(n,this),r)},t.prototype.recycleAsyncId=function(n,i,r){if(r===void 0&&(r=0),r!=null&&this.delay===r&&this.pending===!1)return i;i!=null&&ig.clearInterval(i)},t.prototype.execute=function(n,i){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(n,i);if(r)return r;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(n,i){var r=!1,s;try{this.work(n)}catch(o){r=!0,s=o||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),s},t.prototype.unsubscribe=function(){if(!this.closed){var n=this,i=n.id,r=n.scheduler,s=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Za(s,this),i!=null&&(this.id=this.recycleAsyncId(r,i,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(HN),rg=function(){function e(t,n){n===void 0&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(t,n,i){return n===void 0&&(n=0),new this.schedulerActionCtor(this,t).schedule(i,n)},e.now=zN.now,e}(),qN=function(e){Ci(t,e);function t(n,i){i===void 0&&(i=rg.now);var r=e.call(this,n,i)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(n){var i=this.actions;if(this._active){i.push(n);return}var r;this._active=!0;do if(r=n.execute(n.state,n.delay))break;while(n=i.shift());if(this._active=!1,r){for(;n=i.shift();)n.unsubscribe();throw r}},t}(rg);new qN(WN);function GN(e){return e&&Vt(e.schedule)}function KN(e){return e[e.length-1]}function _x(e){return GN(KN(e))?e.pop():void 0}var Rx=function(e){return e&&typeof e.length=="number"&&typeof e!="function"};function Ax(e){return Vt(e==null?void 0:e.then)}function Px(e){return Vt(e[Vh])}function Nx(e){return Symbol.asyncIterator&&Vt(e==null?void 0:e[Symbol.asyncIterator])}function Ix(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function YN(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Mx=YN();function Ox(e){return Vt(e==null?void 0:e[Mx])}function Dx(e){return PN(this,arguments,function(){var t,n,i,r;return kx(this,function(s){switch(s.label){case 0:t=e.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,is(t.read())];case 3:return n=s.sent(),i=n.value,r=n.done,r?[4,is(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,is(i)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Lx(e){return Vt(e==null?void 0:e.getReader)}function So(e){if(e instanceof Tn)return e;if(e!=null){if(Px(e))return ZN(e);if(Rx(e))return XN(e);if(Ax(e))return JN(e);if(Nx(e))return Fx(e);if(Ox(e))return QN(e);if(Lx(e))return eI(e)}throw Ix(e)}function ZN(e){return new Tn(function(t){var n=e[Vh]();if(Vt(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function XN(e){return new Tn(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function JN(e){return new Tn(function(t){e.then(function(n){t.closed||(t.next(n),t.complete())},function(n){return t.error(n)}).then(null,Tx)})}function QN(e){return new Tn(function(t){var n,i;try{for(var r=ds(e),s=r.next();!s.done;s=r.next()){var o=s.value;if(t.next(o),t.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}t.complete()})}function Fx(e){return new Tn(function(t){tI(e,t).catch(function(n){return t.error(n)})})}function eI(e){return Fx(Dx(e))}function tI(e,t){var n,i,r,s;return AN(this,void 0,void 0,function(){var o,a;return kx(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=NN(e),c.label=1;case 1:return[4,n.next()];case 2:if(i=c.sent(),!!i.done)return[3,4];if(o=i.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),r={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),i&&!i.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function dr(e,t,n,i,r){i===void 0&&(i=0),r===void 0&&(r=!1);var s=t.schedule(function(){n(),r?e.add(this.schedule(null,i)):this.unsubscribe()},i);if(e.add(s),!r)return s}function jx(e,t){return t===void 0&&(t=0),ko(function(n,i){n.subscribe(Xa(i,function(r){return dr(i,e,function(){return i.next(r)},t)},function(){return dr(i,e,function(){return i.complete()},t)},function(r){return dr(i,e,function(){return i.error(r)},t)}))})}function Ux(e,t){return t===void 0&&(t=0),ko(function(n,i){i.add(e.schedule(function(){return n.subscribe(i)},t))})}function nI(e,t){return So(e).pipe(Ux(t),jx(t))}function iI(e,t){return So(e).pipe(Ux(t),jx(t))}function rI(e,t){return new Tn(function(n){var i=0;return t.schedule(function(){i===e.length?n.complete():(n.next(e[i++]),n.closed||this.schedule())})})}function sI(e,t){return new Tn(function(n){var i;return dr(n,t,function(){i=e[Mx](),dr(n,t,function(){var r,s,o;try{r=i.next(),s=r.value,o=r.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return Vt(i==null?void 0:i.return)&&i.return()}})}function Bx(e,t){if(!e)throw new Error("Iterable cannot be null");return new Tn(function(n){dr(n,t,function(){var i=e[Symbol.asyncIterator]();dr(n,t,function(){i.next().then(function(r){r.done?n.complete():n.next(r.value)})},0,!0)})})}function oI(e,t){return Bx(Dx(e),t)}function aI(e,t){if(e!=null){if(Px(e))return nI(e,t);if(Rx(e))return rI(e,t);if(Ax(e))return iI(e,t);if(Nx(e))return Bx(e,t);if(Ox(e))return sI(e,t);if(Lx(e))return oI(e,t)}throw Ix(e)}function cI(e,t){return t?aI(e,t):So(e)}Uh(function(e){return function(t){t===void 0&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function wo(e,t){return ko(function(n,i){var r=0;n.subscribe(Xa(i,function(s){i.next(e.call(t,s,r++))}))})}function lI(e,t,n,i,r,s,o,a){var c=[],l=0,u=0,d=!1,h=function(){d&&!c.length&&!l&&t.complete()},f=function(p){return l<i?g(p):c.push(p)},g=function(p){l++;var v=!1;So(n(p,u++)).subscribe(Xa(t,function(b){t.next(b)},function(){v=!0},void 0,function(){if(v)try{l--;for(var b=function(){var w=c.shift();o||g(w)};c.length&&l<i;)b();h()}catch(w){t.error(w)}}))};return e.subscribe(Xa(t,f,function(){d=!0,h()})),function(){}}function Vx(e,t,n){return n===void 0&&(n=1/0),Vt(t)?Vx(function(i,r){return wo(function(s,o){return t(i,s,r,o)})(So(e(i,r)))},n):(typeof t=="number"&&(n=t),ko(function(i,r){return lI(i,r,e,n)}))}function uI(e){return Vx(Cx,e)}function dI(){return uI(1)}function sg(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dI()(cI(e,_x(e)))}function kc(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=_x(e);return ko(function(i,r){(n?sg(e,i,n):sg(e,i)).subscribe(r)})}var hI=(e,t,n)=>new Promise((i,r)=>{var s=c=>{try{a(n.next(c))}catch(l){r(l)}},o=c=>{try{a(n.throw(c))}catch(l){r(l)}},a=c=>c.done?i(c.value):Promise.resolve(c.value).then(s,o);a((n=n.apply(e,t)).next())}),fI="lk";function $h(e){return typeof e>"u"?!1:pI(e)||mI(e)}function pI(e){var t;return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("track")&&typeof((t=e.publication)==null?void 0:t.track)<"u":!1}function mI(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("publication")&&typeof e.publication<"u":!1}function gI(e){return e?e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&typeof e.publication>"u":!1}function bI(e){if(typeof e=="string"||typeof e=="number")return`${e}`;if(gI(e))return`${e.participant.identity}_${e.source}_placeholder`;if($h(e))return`${e.participant.identity}_${e.publication.source}_${e.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${e}`)}var yI=[j.ConnectionStateChanged,j.RoomMetadataChanged,j.ActiveSpeakersChanged,j.ConnectionQualityChanged,j.ParticipantConnected,j.ParticipantDisconnected,j.ParticipantPermissionsChanged,j.ParticipantMetadataChanged,j.ParticipantNameChanged,j.ParticipantAttributesChanged,j.TrackMuted,j.TrackUnmuted,j.TrackPublished,j.TrackUnpublished,j.TrackStreamStateChanged,j.TrackSubscriptionFailed,j.TrackSubscriptionPermissionChanged,j.TrackSubscriptionStatusChanged],vI=[...yI,j.LocalTrackPublished,j.LocalTrackUnpublished];Q.TrackPublished,Q.TrackUnpublished,Q.TrackMuted,Q.TrackUnmuted,Q.TrackStreamStateChanged,Q.TrackSubscribed,Q.TrackUnsubscribed,Q.TrackSubscriptionPermissionChanged,Q.TrackSubscriptionFailed,Q.LocalTrackPublished,Q.LocalTrackUnpublished;var xI=[Q.ConnectionQualityChanged,Q.IsSpeakingChanged,Q.ParticipantMetadataChanged,Q.ParticipantPermissionsChanged,Q.TrackMuted,Q.TrackUnmuted,Q.TrackPublished,Q.TrackUnpublished,Q.TrackStreamStateChanged,Q.TrackSubscriptionFailed,Q.TrackSubscriptionPermissionChanged,Q.TrackSubscriptionStatusChanged];[...xI,Q.LocalTrackPublished,Q.LocalTrackUnpublished];var Hi=RN.getLogger("lk-components-js");Hi.setDefaultLevel("WARN");function $x(e){return typeof e=="object"}function zx(e){return Array.isArray(e)&&e.filter($x).length>0}function Hx(e){return`${fI}-${e}`}function kI(e){const t=bd(e),n=TI(e.participant).pipe(wo(()=>bd(e)),kc(t));return{className:Hx(e.source===B.Source.Camera||e.source===B.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:n}}function bd(e){if($h(e))return e.publication;{const{source:t,name:n,participant:i}=e;if(t&&n)return i.getTrackPublications().find(r=>r.source===t&&r.trackName===n);if(n)return i.getTrackPublicationByName(n);if(t)return i.getTrackPublication(t);throw new Error("At least one of source and name needs to be defined")}}function Wx(e,...t){return new Tn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(kc(e))}function SI(e){return Wx(e,j.AudioPlaybackStatusChanged).pipe(wo(t=>({canPlayAudio:t.canPlaybackAudio})))}function wI(e,...t){return new Tn(n=>{const i=()=>{n.next(e)};return t.forEach(r=>{e.on(r,i)}),()=>{t.forEach(r=>{e.off(r,i)})}}).pipe(kc(e))}function TI(e){return wI(e,Q.TrackMuted,Q.TrackUnmuted,Q.ParticipantPermissionsChanged,Q.TrackPublished,Q.TrackUnpublished,Q.LocalTrackPublished,Q.LocalTrackUnpublished,Q.MediaDevicesError,Q.TrackSubscriptionStatusChanged).pipe(wo(t=>{const{isMicrophoneEnabled:n,isCameraEnabled:i,isScreenShareEnabled:r}=t,s=t.getTrackPublication(B.Source.Microphone),o=t.getTrackPublication(B.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:n,isScreenShareEnabled:r,cameraTrack:o,microphoneTrack:s,participant:t}}))}function CI(){const e=t=>hI(this,null,function*(){Hi.info("Start Audio for room: ",t),yield t.startAudio()});return{className:Hx("start-audio-button"),roomAudioPlaybackAllowedObservable:SI,handleStartAudioPlayback:e}}function og(e,t,n=!0){const i=[e.localParticipant,...Array.from(e.remoteParticipants.values())],r=[];return i.forEach(s=>{t.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(c=>c.source===o&&(!n||c.track)).map(c=>({participant:s,publication:c,source:c.source}));r.push(...a)})}),{trackReferences:r,participants:i}}function EI(e,t,n){var i,r;const s=(i=n.additionalRoomEvents)!=null?i:vI,o=(r=n.onlySubscribed)!=null?r:!0,a=Array.from(new Set([j.ParticipantConnected,j.ParticipantDisconnected,j.ConnectionStateChanged,j.LocalTrackPublished,j.LocalTrackUnpublished,j.TrackPublished,j.TrackUnpublished,j.TrackSubscriptionStatusChanged,...s]).values());return Wx(e,...a).pipe(wo(c=>{const l=og(c,t,o);return Hi.debug(`TrackReference[] was updated. (length ${l.trackReferences.length})`,l),l}),kc(og(e,t,o)))}D.createContext(void 0);const _I=D.createContext(void 0);function qx(){return D.useContext(_I)}function Gx(e){const t=qx(),n=e??t;if(!n)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return n}D.createContext(void 0);const Ja=D.createContext(void 0);function Kx(){const e=D.useContext(Ja);if(!e)throw Error("tried to access room context outside of livekit room component");return e}function RI(){return D.useContext(Ja)}function Yx(e){const t=RI(),n=e??t;if(!n)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return n}D.createContext(void 0);function Zx(e){var t,n,i="";if(typeof e=="string"||typeof e=="number")i+=e;else if(typeof e=="object")if(Array.isArray(e)){var r=e.length;for(t=0;t<r;t++)e[t]&&(n=Zx(e[t]))&&(i&&(i+=" "),i+=n)}else for(n in e)e[n]&&(i&&(i+=" "),i+=n);return i}function Xx(){for(var e,t,n=0,i="",r=arguments.length;n<r;n++)(e=arguments[n])&&(t=Zx(e))&&(i&&(i+=" "),i+=t);return i}function AI(...e){return(...t)=>{for(const n of e)if(typeof n=="function")try{n(...t)}catch(i){console.error(i)}}}function Jx(...e){const t={...e[0]};for(let n=1;n<e.length;n++){const i=e[n];for(const r in i){const s=t[r],o=i[r];typeof s=="function"&&typeof o=="function"&&r[0]==="o"&&r[1]==="n"&&r.charCodeAt(2)>=65&&r.charCodeAt(2)<=90?t[r]=AI(s,o):(r==="className"||r==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?t[r]=Xx(s,o):t[r]=o!==void 0?o:s}}return t}function PI(e){return e!==void 0}function Qx(...e){return Jx(...e.filter(PI))}function NI(e,t,n){return D.Children.map(e,i=>D.isValidElement(i)&&D.Children.only(e)?(i.props.className&&(t??(t={}),t.className=Xx(i.props.className,t.className),t.style={...i.props.style,...t.style}),D.cloneElement(i,{...t,key:n})):i)}function II(e,t,n=!0){const[i,r]=D.useState(t);return D.useEffect(()=>{if(n&&r(t),typeof window>"u"||!e)return;const s=e.subscribe(r);return()=>s.unsubscribe()},[e,n]),i}function MI({room:e,props:t}){const n=Yx(e),{className:i,roomAudioPlaybackAllowedObservable:r,handleStartAudioPlayback:s}=D.useMemo(()=>CI(),[]),o=D.useMemo(()=>r(n),[n,r]),{canPlayAudio:a}=II(o,{canPlayAudio:n.canPlaybackAudio});return{mergedProps:D.useMemo(()=>Jx(t,{className:i,onClick:()=>{s(n)},style:{display:a?"none":"block"}}),[t,i,a,s,n]),canPlayAudio:a}}function ek(e=[B.Source.Camera,B.Source.Microphone,B.Source.ScreenShare,B.Source.ScreenShareAudio,B.Source.Unknown],t={}){const n=Yx(t.room),[i,r]=D.useState([]),[s,o]=D.useState([]),a=D.useMemo(()=>e.map(c=>$x(c)?c.source:c),[JSON.stringify(e)]);return D.useEffect(()=>{const c=EI(n,a,{additionalRoomEvents:t.updateOnlyOn,onlySubscribed:t.onlySubscribed}).subscribe(({trackReferences:l,participants:u})=>{Hi.debug("setting track bundles",l,u),r(l),o(u)});return()=>c.unsubscribe()},[n,JSON.stringify(t.onlySubscribed),JSON.stringify(t.updateOnlyOn),JSON.stringify(e)]),D.useMemo(()=>{if(zx(e)){const c=DI(e,s),l=Array.from(i);return s.forEach(u=>{c.has(u.identity)&&(c.get(u.identity)??[]).forEach(d=>{if(i.find(({participant:f,publication:g})=>u.identity===f.identity&&g.source===d))return;Hi.debug(`Add ${d} placeholder for participant ${u.identity}.`);const h={participant:u,source:d};l.push(h)})}),l}else return i},[i,s,e])}function OI(e,t){const n=new Set(e);for(const i of t)n.delete(i);return n}function DI(e,t){const n=new Map;if(zx(e)){const i=e.filter(r=>r.withPlaceholder).map(r=>r.source);t.forEach(r=>{const s=r.getTrackPublications().map(a=>{var c;return(c=a.track)==null?void 0:c.source}).filter(a=>a!==void 0),o=Array.from(OI(new Set(i),new Set(s)));o.length>0&&n.set(r.identity,o)})}return n}const LI=e=>{const t=n=>{let i=1-Math.max(-100,Math.min(-10,n))*-1/100;return i=Math.sqrt(i),i};return e.map(n=>n===-1/0?0:t(n))},FI={bands:5,loPass:100,hiPass:600,updateInterval:32,analyserOptions:{fftSize:2048}};function jI(e,t={}){var n;const i=e instanceof B?e:(n=e==null?void 0:e.publication)==null?void 0:n.track,r={...FI,...t},[s,o]=D.useState(new Array(r.bands).fill(0));return D.useEffect(()=>{if(!i||!(i!=null&&i.mediaStream))return;const{analyser:a,cleanup:c}=TE(i,r.analyserOptions),l=a.frequencyBinCount,u=new Float32Array(l),d=setInterval(()=>{a.getFloatFrequencyData(u);let h=new Float32Array(u.length);for(let v=0;v<u.length;v++)h[v]=u[v];h=h.slice(t.loPass,t.hiPass);const f=LI(h),g=Math.ceil(f.length/r.bands),p=[];for(let v=0;v<r.bands;v++){const b=f.slice(v*g,(v+1)*g).reduce((w,S)=>w+=S,0);p.push(b/g)}o(p)},r.updateInterval);return()=>{c(),clearInterval(d)}},[i,i==null?void 0:i.mediaStream,JSON.stringify(t)]),s}const ag=D.forwardRef(function({label:e="Allow Audio",...t},n){const i=Kx(),{mergedProps:r}=MI({room:i,props:t});return D.createElement("button",{ref:n,...r},e)});function tk(e,t={}){const[n,i]=D.useState(bd(e)),[r,s]=D.useState(n==null?void 0:n.isMuted),[o,a]=D.useState(n==null?void 0:n.isSubscribed),[c,l]=D.useState(n==null?void 0:n.track),[u,d]=D.useState("landscape"),h=D.useRef(),{className:f,trackObserver:g}=D.useMemo(()=>kI(e),[e.participant.sid??e.participant.identity,e.source,$h(e)&&e.publication.trackSid]);return D.useEffect(()=>{const p=g.subscribe(v=>{Hi.debug("update track",v),i(v),s(v==null?void 0:v.isMuted),a(v==null?void 0:v.isSubscribed),l(v==null?void 0:v.track)});return()=>p==null?void 0:p.unsubscribe()},[g]),D.useEffect(()=>{var p,v;return c&&(h.current&&c.detach(h.current),(p=t.element)!=null&&p.current&&!(e.participant.isLocal&&(c==null?void 0:c.kind)==="audio")&&c.attach(t.element.current)),h.current=(v=t.element)==null?void 0:v.current,()=>{h.current&&(c==null||c.detach(h.current))}},[c,t.element]),D.useEffect(()=>{var p,v;if(typeof((p=n==null?void 0:n.dimensions)==null?void 0:p.width)=="number"&&typeof((v=n==null?void 0:n.dimensions)==null?void 0:v.height)=="number"){const b=n.dimensions.width>n.dimensions.height?"landscape":"portrait";d(b)}},[n]),{publication:n,isMuted:r,isSubscribed:o,track:c,elementProps:Qx(t.props,{className:f,"data-lk-local-participant":e.participant.isLocal,"data-lk-source":n==null?void 0:n.source,...(n==null?void 0:n.kind)==="video"&&{"data-lk-orientation":u}})}}var Pl,cg;function UI(){if(cg)return Pl;cg=1;var e="Expected a function",t=NaN,n="[object Symbol]",i=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,o=/^0o[0-7]+$/i,a=parseInt,c=typeof zo=="object"&&zo&&zo.Object===Object&&zo,l=typeof self=="object"&&self&&self.Object===Object&&self,u=c||l||Function("return this")(),d=Object.prototype,h=d.toString,f=Math.max,g=Math.min,p=function(){return u.Date.now()};function v(x,T,P){var A,N,y,R,I,L,U=0,K=!1,ue=!1,se=!0;if(typeof x!="function")throw new TypeError(e);T=k(T)||0,b(P)&&(K=!!P.leading,ue="maxWait"in P,y=ue?f(k(P.maxWait)||0,T):y,se="trailing"in P?!!P.trailing:se);function z(re){var X=A,le=N;return A=N=void 0,U=re,R=x.apply(le,X),R}function H(re){return U=re,I=setTimeout(Y,T),K?z(re):R}function C(re){var X=re-L,le=re-U,Z=T-X;return ue?g(Z,y-le):Z}function W(re){var X=re-L,le=re-U;return L===void 0||X>=T||X<0||ue&&le>=y}function Y(){var re=p();if(W(re))return E(re);I=setTimeout(Y,C(re))}function E(re){return I=void 0,se&&A?z(re):(A=N=void 0,R)}function J(){I!==void 0&&clearTimeout(I),U=0,A=L=N=I=void 0}function ne(){return I===void 0?R:E(p())}function ie(){var re=p(),X=W(re);if(A=arguments,N=this,L=re,X){if(I===void 0)return H(L);if(ue)return I=setTimeout(Y,T),z(L)}return I===void 0&&(I=setTimeout(Y,T)),R}return ie.cancel=J,ie.flush=ne,ie}function b(x){var T=typeof x;return!!x&&(T=="object"||T=="function")}function w(x){return!!x&&typeof x=="object"}function S(x){return typeof x=="symbol"||w(x)&&h.call(x)==n}function k(x){if(typeof x=="number")return x;if(S(x))return t;if(b(x)){var T=typeof x.valueOf=="function"?x.valueOf():x;x=b(T)?T+"":T}if(typeof x!="string")return x===0?x:+x;x=x.replace(i,"");var P=s.test(x);return P||o.test(x)?a(x.slice(2),P?2:8):r.test(x)?t:+x}return Pl=v,Pl}var BI=UI();const lg=xx(BI);function VI(e){const t=O.useRef(e);t.current=e,O.useEffect(()=>()=>{t.current()},[])}function $I(e,t=500,n){const i=O.useRef();VI(()=>{i.current&&i.current.cancel()});const r=O.useMemo(()=>{const s=lg(e,t,n),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!i.current,o.flush=()=>s.flush(),o},[e,t,n]);return O.useEffect(()=>{i.current=lg(e,t,n)},[e,t,n]),r}function zI(e,t,n){const i=(l,u)=>l===u,r=e instanceof Function?e():e,[s,o]=O.useState(r),a=O.useRef(r),c=$I(o,t,n);return i(a.current,r)||(c(r),a.current=r),[s,c]}function HI({threshold:e=0,root:t=null,rootMargin:n="0%",freezeOnceVisible:i=!1,initialIsIntersecting:r=!1,onChange:s}={}){var o;const[a,c]=O.useState(null),[l,u]=O.useState(()=>({isIntersecting:r,entry:void 0})),d=O.useRef();d.current=s;const h=((o=l.entry)==null?void 0:o.isIntersecting)&&i;O.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||h)return;const p=new IntersectionObserver(v=>{const b=Array.isArray(p.thresholds)?p.thresholds:[p.thresholds];v.forEach(w=>{const S=w.isIntersecting&&b.some(k=>w.intersectionRatio>=k);u({isIntersecting:S,entry:w}),d.current&&d.current(S,w)})},{threshold:e,root:t,rootMargin:n});return p.observe(a),()=>{p.disconnect()}},[a,JSON.stringify(e),t,n,h,i]);const f=O.useRef(null);O.useEffect(()=>{var p;!a&&(p=l.entry)!=null&&p.target&&!i&&!h&&f.current!==l.entry.target&&(f.current=l.entry.target,u({isIntersecting:r,entry:void 0}))},[a,l.entry,i,h,r]);const g=[c,!!l.isIntersecting,l.entry];return g.ref=g[0],g.isIntersecting=g[1],g.entry=g[2],g}const Sc=D.forwardRef(function({onTrackClick:e,onClick:t,onSubscriptionStatusChanged:n,trackRef:i,manageSubscription:r,...s},o){const a=Gx(i),c=D.useRef(null);D.useImperativeHandle(o,()=>c.current);const l=HI({root:c.current}),[u]=zI(l,3e3);D.useEffect(()=>{r&&a.publication instanceof Va&&(u==null?void 0:u.isIntersecting)===!1&&(l==null?void 0:l.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[u,a,r]),D.useEffect(()=>{r&&a.publication instanceof Va&&(l==null?void 0:l.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[l,a,r]);const{elementProps:d,publication:h,isSubscribed:f}=tk(a,{element:c,props:s});D.useEffect(()=>{n==null||n(!!f)},[f,n]);const g=p=>{t==null||t(p),e==null||e({participant:a==null?void 0:a.participant,track:h})};return D.createElement("video",{ref:c,...d,muted:!0,onClick:g})}),nk=D.forwardRef(function({trackRef:e,onSubscriptionStatusChanged:t,volume:n,...i},r){const s=Gx(e),o=D.useRef(null);D.useImperativeHandle(r,()=>o.current);const{elementProps:a,isSubscribed:c,track:l,publication:u}=tk(s,{element:o,props:i});return D.useEffect(()=>{t==null||t(!!c)},[c,t]),D.useEffect(()=>{l===void 0||n===void 0||(l instanceof Uy?l.setVolume(n):Hi.warn("Volume can only be set on remote audio tracks."))},[n,l]),D.useEffect(()=>{u===void 0||i.muted===void 0||(u instanceof Va?u.setEnabled(!i.muted):Hi.warn("Can only call setEnabled on remote track publications."))},[i.muted,u,l]),D.createElement("audio",{ref:o,...a})});function ug({volume:e,muted:t}){const n=ek([B.Source.Microphone,B.Source.ScreenShareAudio,B.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0}).filter(i=>!i.participant.isLocal&&i.publication.kind===B.Kind.Audio);return D.createElement("div",{style:{display:"none"}},n.map(i=>D.createElement(nk,{key:bI(i),trackRef:i,volume:e,muted:t})))}const WI=e=>{const t=[];for(let n=0;n<e;n++)t.push([n,e-1-n]);return t},dg=e=>[[Math.floor(e/2)],[-1]],qI=(e,t,n)=>{const[i,r]=O.useState(0),[s,o]=O.useState([[]]);O.useEffect(()=>{if(e==="thinking")o(dg(t));else if(e==="connecting"||e==="initializing"){const c=[...WI(t)];o(c)}else o(e==="listening"?dg(t):e===void 0||e==="speaking"?[new Array(t).fill(0).map((c,l)=>l)]:[[]]);r(0)},[e,t]);const a=O.useRef(null);return O.useEffect(()=>{let c=performance.now();const l=u=>{u-c>=n&&(r(d=>d+1),c=u),a.current=requestAnimationFrame(l)};return a.current=requestAnimationFrame(l),()=>{a.current!==null&&cancelAnimationFrame(a.current)}},[n,t,e,s.length]),s[i%s.length]},GI=new Map([["connecting",2e3],["initializing",2e3],["listening",500],["thinking",150]]),KI=(e,t)=>{if(e===void 0)return 1e3;let n=GI.get(e);if(n)switch(e){case"connecting":n/=t;break}return n},ik=D.forwardRef(function({state:e,options:t,barCount:n=15,trackRef:i,children:r,...s},o){const a=Qx(s,{className:"lk-audio-bar-visualizer"});let c=qx();i&&(c=i);const l=jI(c,{bands:n,loPass:100,hiPass:200}),u=(t==null?void 0:t.minHeight)??20,d=(t==null?void 0:t.maxHeight)??100,h=qI(e,n,KI(e,n)??100);return D.createElement("div",{ref:o,...a,"data-lk-va-state":e},l.map((f,g)=>r?NI(r,{"data-lk-highlighted":h.includes(g),"data-lk-bar-index":g,className:"lk-audio-bar",style:{height:`${Math.min(d,Math.max(u,f*100+5))}%`}}):D.createElement("span",{key:g,"data-lk-highlighted":h.includes(g),"data-lk-bar-index":g,className:`lk-audio-bar ${h.includes(g)&&"lk-highlighted"}`,style:{height:`${Math.min(d,Math.max(u,f*100+5))}%`}})))});function YI(e){const[t,n]=O.useState(()=>e.getLocalParticipant()),[i,r]=O.useState(()=>e.getMicrophoneTrack());return O.useEffect(()=>{const s=()=>{const a=e.getLocalParticipant(),c=e.getMicrophoneTrack();console.log("🎤 useVoxketLocalParticipant: Updating state:",{hasParticipant:!!a,hasMicTrack:!!c,isMicEnabled:e.isMicrophoneEnabled,trackPublications:a?a.trackPublications.size:0}),n(a),r(c)};s(),e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("track.muted",s),e.on("track.unmuted",s);const o=e.getRoom();if(o){const a=()=>{console.log("🎤 Track published, updating participant state"),s()},c=()=>{console.log("🎤 Track unpublished, updating participant state"),s()};return o.on("localTrackPublished",a),o.on("localTrackUnpublished",c),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s),o.off("localTrackPublished",a),o.off("localTrackUnpublished",c)}}else return()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("track.muted",s),e.off("track.unmuted",s)}},[e]),{localParticipant:t,microphoneTrack:i}}function _a(e,t,n){const[i,r]=O.useState(!1),[s,o]=O.useState(!1);return O.useEffect(()=>{const c=()=>{let l=!1;switch(t){case"microphone":l=e.isMicrophoneEnabled;break;case"camera":l=e.isCameraEnabled;break;case"screenShare":l=e.isScreenShareEnabled;break}console.log(`🎬 useVoxketTrackToggle: ${t} enabled state updated:`,{oldEnabled:i,newEnabled:l,changed:i!==l}),r(l)};return c(),e.on("track.muted",c),e.on("track.unmuted",c),e.on("connection.connected",c),()=>{e.off("track.muted",c),e.off("track.unmuted",c),e.off("connection.connected",c)}},[e,t]),{enabled:i,pending:s,toggle:async c=>{try{o(!0);const l=c!==void 0?c:!i;switch(console.log(`🎬 useVoxketTrackToggle: ${t} toggle called`,{currentEnabled:i,targetEnabled:l,forceEnabled:c}),t){case"microphone":await e.toggleMicrophone(l);break;case"camera":await e.toggleCamera(l);break;case"screenShare":l?(console.log("🎬 useVoxketTrackToggle: Starting screen share"),await e.startScreenShare()):(console.log("🎬 useVoxketTrackToggle: Stopping screen share"),await e.stopScreenShare());break}console.log(`🎬 useVoxketTrackToggle: ${t} toggle completed`)}catch(l){console.error(`🎬 useVoxketTrackToggle: ${t} toggle failed:`,l)}finally{o(!1)}}}}function ZI(e){const[t,n]=O.useState(()=>e.getRoom()),[i,r]=O.useState(()=>e.getConnectionState());return O.useEffect(()=>{const s=()=>{n(e.getRoom()),r(e.getConnectionState())};return e.on("connection.connected",s),e.on("connection.disconnected",s),e.on("connection.connecting",s),()=>{e.off("connection.connected",s),e.off("connection.disconnected",s),e.off("connection.connecting",s)}},[e]),t}function zh(e){const[t,n]=O.useState(()=>e.getIsAgentConnected()),[i,r]=O.useState(()=>e.getCurrentSession()),[s,o]=O.useState(()=>e.getCurrentAgentInfo()),[a,c]=O.useState(()=>e.getAgentState()),[l,u]=O.useState(()=>e.getAgentAudioTrack()),[d,h]=O.useState(()=>e.getAgentVideoTrack());return O.useEffect(()=>{const f=()=>{const k=e.getIsAgentConnected(),x=e.getCurrentSession(),T=e.getCurrentAgentInfo(),P=e.getAgentState(),A=e.getAgentAudioTrack(),N=e.getAgentVideoTrack();console.log("🤖 useVoxketVoiceAssistant: Updating state:",{isAgentConnected:k,hasSession:!!x,sessionId:x==null?void 0:x.id,sessionState:x==null?void 0:x.state,hasAgentInfo:!!T,agentState:P,hasAudioTrack:!!A,hasVideoTrack:!!N}),n(k),r(x),o(T),c(P),u(A),h(N)};f();const g=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent connected event"),f()},p=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent disconnected event"),f()},v=()=>{console.log("🤖 useVoxketVoiceAssistant: Session changed event"),f()},b=()=>{console.log("🤖 useVoxketVoiceAssistant: Connection changed event"),f()},w=()=>{console.log("🤖 useVoxketVoiceAssistant: Agent state changed event"),f()},S=()=>{console.log("🎵 useVoxketVoiceAssistant: Track subscribed event - updating audio/video tracks"),f()};return e.on("agent.connected",g),e.on("agent.speaking",g),e.on("agent.thinking",g),e.on("agent.state.changed",w),e.on("connection.disconnected",p),e.on("session.created",v),e.on("session.ended",v),e.on("session.state.changed",v),e.on("connection.connected",b),e.on("media.track.subscribed",S),e.on("media.track.unsubscribed",S),()=>{e.off("agent.connected",g),e.off("agent.speaking",g),e.off("agent.thinking",g),e.off("agent.state.changed",w),e.off("connection.disconnected",p),e.off("session.created",v),e.off("session.ended",v),e.off("session.state.changed",v),e.off("connection.connected",b),e.off("media.track.subscribed",S),e.off("media.track.unsubscribed",S)}},[e]),{agent:{isActive:t,info:s},session:i,state:a,audioTrack:l,videoTrack:d}}function XI(e){const[t,n]=O.useState(()=>e.getVideoTrackRefs()),[i,r]=O.useState(()=>e.getCameraTrackRefs()),[s,o]=O.useState(()=>e.getScreenShareTrackRefs());return O.useEffect(()=>{const a=()=>{const l=e.getVideoTrackRefs(),u=e.getCameraTrackRefs(),d=e.getScreenShareTrackRefs();console.log("📹 useVoxketVideoTracks: Updating tracks:",{videoCount:l.length,cameraCount:u.length,screenShareCount:d.length}),n(l),r(u),o(d)};a(),e.on("connection.connected",a),e.on("connection.disconnected",a),e.on("track.muted",a),e.on("track.unmuted",a),e.on("participant.joined",a),e.on("participant.left",a);const c=e.getRoom();if(c){const l=()=>{console.log("📹 Track event, updating video tracks"),a()};return c.on("localTrackPublished",l),c.on("localTrackUnpublished",l),c.on("trackPublished",l),c.on("trackUnpublished",l),c.on("trackSubscribed",l),c.on("trackUnsubscribed",l),()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a),c.off("localTrackPublished",l),c.off("localTrackUnpublished",l),c.off("trackPublished",l),c.off("trackUnpublished",l),c.off("trackSubscribed",l),c.off("trackUnsubscribed",l)}}else return()=>{e.off("connection.connected",a),e.off("connection.disconnected",a),e.off("track.muted",a),e.off("track.unmuted",a),e.off("participant.joined",a),e.off("participant.left",a)}},[e]),{videoTrackRefs:t,cameraTrackRefs:i,screenShareTrackRefs:s}}const Hh="-",JI=e=>{const t=eM(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:i}=e;return{getClassGroupId:o=>{const a=o.split(Hh);return a[0]===""&&a.length!==1&&a.shift(),rk(a,t)||QI(o)},getConflictingClassGroupIds:(o,a)=>{const c=n[o]||[];return a&&i[o]?[...c,...i[o]]:c}}},rk=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],i=t.nextPart.get(n),r=i?rk(e.slice(1),i):void 0;if(r)return r;if(t.validators.length===0)return;const s=e.join(Hh);return(o=t.validators.find(({validator:a})=>a(s)))==null?void 0:o.classGroupId},hg=/^\[(.+)\]$/,QI=e=>{if(hg.test(e)){const t=hg.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},eM=e=>{const{theme:t,classGroups:n}=e,i={nextPart:new Map,validators:[]};for(const r in n)yd(n[r],i,r,t);return i},yd=(e,t,n,i)=>{e.forEach(r=>{if(typeof r=="string"){const s=r===""?t:fg(t,r);s.classGroupId=n;return}if(typeof r=="function"){if(tM(r)){yd(r(i),t,n,i);return}t.validators.push({validator:r,classGroupId:n});return}Object.entries(r).forEach(([s,o])=>{yd(o,fg(t,s),n,i)})})},fg=(e,t)=>{let n=e;return t.split(Hh).forEach(i=>{n.nextPart.has(i)||n.nextPart.set(i,{nextPart:new Map,validators:[]}),n=n.nextPart.get(i)}),n},tM=e=>e.isThemeGetter,nM=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,i=new Map;const r=(s,o)=>{n.set(s,o),t++,t>e&&(t=0,i=n,n=new Map)};return{get(s){let o=n.get(s);if(o!==void 0)return o;if((o=i.get(s))!==void 0)return r(s,o),o},set(s,o){n.has(s)?n.set(s,o):r(s,o)}}},vd="!",xd=":",iM=xd.length,rM=e=>{const{prefix:t,experimentalParseClassName:n}=e;let i=r=>{const s=[];let o=0,a=0,c=0,l;for(let g=0;g<r.length;g++){let p=r[g];if(o===0&&a===0){if(p===xd){s.push(r.slice(c,g)),c=g+iM;continue}if(p==="/"){l=g;continue}}p==="["?o++:p==="]"?o--:p==="("?a++:p===")"&&a--}const u=s.length===0?r:r.substring(c),d=sM(u),h=d!==u,f=l&&l>c?l-c:void 0;return{modifiers:s,hasImportantModifier:h,baseClassName:d,maybePostfixModifierPosition:f}};if(t){const r=t+xd,s=i;i=o=>o.startsWith(r)?s(o.substring(r.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:o,maybePostfixModifierPosition:void 0}}if(n){const r=i;i=s=>n({className:s,parseClassName:r})}return i},sM=e=>e.endsWith(vd)?e.substring(0,e.length-1):e.startsWith(vd)?e.substring(1):e,oM=e=>{const t=Object.fromEntries(e.orderSensitiveModifiers.map(i=>[i,!0]));return i=>{if(i.length<=1)return i;const r=[];let s=[];return i.forEach(o=>{o[0]==="["||t[o]?(r.push(...s.sort(),o),s=[]):s.push(o)}),r.push(...s.sort()),r}},aM=e=>({cache:nM(e.cacheSize),parseClassName:rM(e),sortModifiers:oM(e),...JI(e)}),cM=/\s+/,lM=(e,t)=>{const{parseClassName:n,getClassGroupId:i,getConflictingClassGroupIds:r,sortModifiers:s}=t,o=[],a=e.trim().split(cM);let c="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{isExternal:d,modifiers:h,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:p}=n(u);if(d){c=u+(c.length>0?" "+c:c);continue}let v=!!p,b=i(v?g.substring(0,p):g);if(!b){if(!v){c=u+(c.length>0?" "+c:c);continue}if(b=i(g),!b){c=u+(c.length>0?" "+c:c);continue}v=!1}const w=s(h).join(":"),S=f?w+vd:w,k=S+b;if(o.includes(k))continue;o.push(k);const x=r(b,v);for(let T=0;T<x.length;++T){const P=x[T];o.push(S+P)}c=u+(c.length>0?" "+c:c)}return c};function uM(){let e=0,t,n,i="";for(;e<arguments.length;)(t=arguments[e++])&&(n=sk(t))&&(i&&(i+=" "),i+=n);return i}const sk=e=>{if(typeof e=="string")return e;let t,n="";for(let i=0;i<e.length;i++)e[i]&&(t=sk(e[i]))&&(n&&(n+=" "),n+=t);return n};function dM(e,...t){let n,i,r,s=o;function o(c){const l=t.reduce((u,d)=>d(u),e());return n=aM(l),i=n.cache.get,r=n.cache.set,s=a,a(c)}function a(c){const l=i(c);if(l)return l;const u=lM(c,n);return r(c,u),u}return function(){return s(uM.apply(null,arguments))}}const Ut=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},ok=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,ak=/^\((?:(\w[\w-]*):)?(.+)\)$/i,hM=/^\d+\/\d+$/,fM=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pM=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,mM=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,gM=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,bM=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ar=e=>hM.test(e),Ue=e=>!!e&&!Number.isNaN(Number(e)),Ni=e=>!!e&&Number.isInteger(Number(e)),Nl=e=>e.endsWith("%")&&Ue(e.slice(0,-1)),ci=e=>fM.test(e),yM=()=>!0,vM=e=>pM.test(e)&&!mM.test(e),ck=()=>!1,xM=e=>gM.test(e),kM=e=>bM.test(e),SM=e=>!ve(e)&&!xe(e),wM=e=>vs(e,dk,ck),ve=e=>ok.test(e),tr=e=>vs(e,hk,vM),Il=e=>vs(e,RM,Ue),pg=e=>vs(e,lk,ck),TM=e=>vs(e,uk,kM),Wo=e=>vs(e,fk,xM),xe=e=>ak.test(e),Is=e=>xs(e,hk),CM=e=>xs(e,AM),mg=e=>xs(e,lk),EM=e=>xs(e,dk),_M=e=>xs(e,uk),qo=e=>xs(e,fk,!0),vs=(e,t,n)=>{const i=ok.exec(e);return i?i[1]?t(i[1]):n(i[2]):!1},xs=(e,t,n=!1)=>{const i=ak.exec(e);return i?i[1]?t(i[1]):n:!1},lk=e=>e==="position"||e==="percentage",uk=e=>e==="image"||e==="url",dk=e=>e==="length"||e==="size"||e==="bg-size",hk=e=>e==="length",RM=e=>e==="number",AM=e=>e==="family-name",fk=e=>e==="shadow",PM=()=>{const e=Ut("color"),t=Ut("font"),n=Ut("text"),i=Ut("font-weight"),r=Ut("tracking"),s=Ut("leading"),o=Ut("breakpoint"),a=Ut("container"),c=Ut("spacing"),l=Ut("radius"),u=Ut("shadow"),d=Ut("inset-shadow"),h=Ut("text-shadow"),f=Ut("drop-shadow"),g=Ut("blur"),p=Ut("perspective"),v=Ut("aspect"),b=Ut("ease"),w=Ut("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],x=()=>[...k(),xe,ve],T=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],A=()=>[xe,ve,c],N=()=>[Ar,"full","auto",...A()],y=()=>[Ni,"none","subgrid",xe,ve],R=()=>["auto",{span:["full",Ni,xe,ve]},Ni,xe,ve],I=()=>[Ni,"auto",xe,ve],L=()=>["auto","min","max","fr",xe,ve],U=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],K=()=>["start","end","center","stretch","center-safe","end-safe"],ue=()=>["auto",...A()],se=()=>[Ar,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...A()],z=()=>[e,xe,ve],H=()=>[...k(),mg,pg,{position:[xe,ve]}],C=()=>["no-repeat",{repeat:["","x","y","space","round"]}],W=()=>["auto","cover","contain",EM,wM,{size:[xe,ve]}],Y=()=>[Nl,Is,tr],E=()=>["","none","full",l,xe,ve],J=()=>["",Ue,Is,tr],ne=()=>["solid","dashed","dotted","double"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[Ue,Nl,mg,pg],X=()=>["","none",g,xe,ve],le=()=>["none",Ue,xe,ve],Z=()=>["none",Ue,xe,ve],Ae=()=>[Ue,xe,ve],F=()=>[Ar,"full",...A()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ci],breakpoint:[ci],color:[yM],container:[ci],"drop-shadow":[ci],ease:["in","out","in-out"],font:[SM],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ci],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ci],shadow:[ci],spacing:["px",Ue],text:[ci],"text-shadow":[ci],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ar,ve,xe,v]}],container:["container"],columns:[{columns:[Ue,ve,xe,a]}],"break-after":[{"break-after":S()}],"break-before":[{"break-before":S()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:x()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{start:N()}],end:[{end:N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[Ni,"auto",xe,ve]}],basis:[{basis:[Ar,"full","auto",a,...A()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ue,Ar,"auto","initial","none",ve]}],grow:[{grow:["",Ue,xe,ve]}],shrink:[{shrink:["",Ue,xe,ve]}],order:[{order:[Ni,"first","last","none",xe,ve]}],"grid-cols":[{"grid-cols":y()}],"col-start-end":[{col:R()}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":y()}],"row-start-end":[{row:R()}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":L()}],"auto-rows":[{"auto-rows":L()}],gap:[{gap:A()}],"gap-x":[{"gap-x":A()}],"gap-y":[{"gap-y":A()}],"justify-content":[{justify:[...U(),"normal"]}],"justify-items":[{"justify-items":[...K(),"normal"]}],"justify-self":[{"justify-self":["auto",...K()]}],"align-content":[{content:["normal",...U()]}],"align-items":[{items:[...K(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...K(),{baseline:["","last"]}]}],"place-content":[{"place-content":U()}],"place-items":[{"place-items":[...K(),"baseline"]}],"place-self":[{"place-self":["auto",...K()]}],p:[{p:A()}],px:[{px:A()}],py:[{py:A()}],ps:[{ps:A()}],pe:[{pe:A()}],pt:[{pt:A()}],pr:[{pr:A()}],pb:[{pb:A()}],pl:[{pl:A()}],m:[{m:ue()}],mx:[{mx:ue()}],my:[{my:ue()}],ms:[{ms:ue()}],me:[{me:ue()}],mt:[{mt:ue()}],mr:[{mr:ue()}],mb:[{mb:ue()}],ml:[{ml:ue()}],"space-x":[{"space-x":A()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":A()}],"space-y-reverse":["space-y-reverse"],size:[{size:se()}],w:[{w:[a,"screen",...se()]}],"min-w":[{"min-w":[a,"screen","none",...se()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[o]},...se()]}],h:[{h:["screen","lh",...se()]}],"min-h":[{"min-h":["screen","lh","none",...se()]}],"max-h":[{"max-h":["screen","lh",...se()]}],"font-size":[{text:["base",n,Is,tr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,xe,Il]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Nl,ve]}],"font-family":[{font:[CM,ve,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[r,xe,ve]}],"line-clamp":[{"line-clamp":[Ue,"none",xe,Il]}],leading:[{leading:[s,...A()]}],"list-image":[{"list-image":["none",xe,ve]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",xe,ve]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:z()}],"text-color":[{text:z()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ne(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ue,"from-font","auto",xe,tr]}],"text-decoration-color":[{decoration:z()}],"underline-offset":[{"underline-offset":[Ue,"auto",xe,ve]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:A()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",xe,ve]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",xe,ve]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:H()}],"bg-repeat":[{bg:C()}],"bg-size":[{bg:W()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ni,xe,ve],radial:["",xe,ve],conic:[Ni,xe,ve]},_M,TM]}],"bg-color":[{bg:z()}],"gradient-from-pos":[{from:Y()}],"gradient-via-pos":[{via:Y()}],"gradient-to-pos":[{to:Y()}],"gradient-from":[{from:z()}],"gradient-via":[{via:z()}],"gradient-to":[{to:z()}],rounded:[{rounded:E()}],"rounded-s":[{"rounded-s":E()}],"rounded-e":[{"rounded-e":E()}],"rounded-t":[{"rounded-t":E()}],"rounded-r":[{"rounded-r":E()}],"rounded-b":[{"rounded-b":E()}],"rounded-l":[{"rounded-l":E()}],"rounded-ss":[{"rounded-ss":E()}],"rounded-se":[{"rounded-se":E()}],"rounded-ee":[{"rounded-ee":E()}],"rounded-es":[{"rounded-es":E()}],"rounded-tl":[{"rounded-tl":E()}],"rounded-tr":[{"rounded-tr":E()}],"rounded-br":[{"rounded-br":E()}],"rounded-bl":[{"rounded-bl":E()}],"border-w":[{border:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ne(),"hidden","none"]}],"divide-style":[{divide:[...ne(),"hidden","none"]}],"border-color":[{border:z()}],"border-color-x":[{"border-x":z()}],"border-color-y":[{"border-y":z()}],"border-color-s":[{"border-s":z()}],"border-color-e":[{"border-e":z()}],"border-color-t":[{"border-t":z()}],"border-color-r":[{"border-r":z()}],"border-color-b":[{"border-b":z()}],"border-color-l":[{"border-l":z()}],"divide-color":[{divide:z()}],"outline-style":[{outline:[...ne(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ue,xe,ve]}],"outline-w":[{outline:["",Ue,Is,tr]}],"outline-color":[{outline:z()}],shadow:[{shadow:["","none",u,qo,Wo]}],"shadow-color":[{shadow:z()}],"inset-shadow":[{"inset-shadow":["none",d,qo,Wo]}],"inset-shadow-color":[{"inset-shadow":z()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:z()}],"ring-offset-w":[{"ring-offset":[Ue,tr]}],"ring-offset-color":[{"ring-offset":z()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":z()}],"text-shadow":[{"text-shadow":["none",h,qo,Wo]}],"text-shadow-color":[{"text-shadow":z()}],opacity:[{opacity:[Ue,xe,ve]}],"mix-blend":[{"mix-blend":[...ie(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ie()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ue]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":z()}],"mask-image-linear-to-color":[{"mask-linear-to":z()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":z()}],"mask-image-t-to-color":[{"mask-t-to":z()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":z()}],"mask-image-r-to-color":[{"mask-r-to":z()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":z()}],"mask-image-b-to-color":[{"mask-b-to":z()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":z()}],"mask-image-l-to-color":[{"mask-l-to":z()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":z()}],"mask-image-x-to-color":[{"mask-x-to":z()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":z()}],"mask-image-y-to-color":[{"mask-y-to":z()}],"mask-image-radial":[{"mask-radial":[xe,ve]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":z()}],"mask-image-radial-to-color":[{"mask-radial-to":z()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":z()}],"mask-image-conic-to-color":[{"mask-conic-to":z()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:H()}],"mask-repeat":[{mask:C()}],"mask-size":[{mask:W()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",xe,ve]}],filter:[{filter:["","none",xe,ve]}],blur:[{blur:X()}],brightness:[{brightness:[Ue,xe,ve]}],contrast:[{contrast:[Ue,xe,ve]}],"drop-shadow":[{"drop-shadow":["","none",f,qo,Wo]}],"drop-shadow-color":[{"drop-shadow":z()}],grayscale:[{grayscale:["",Ue,xe,ve]}],"hue-rotate":[{"hue-rotate":[Ue,xe,ve]}],invert:[{invert:["",Ue,xe,ve]}],saturate:[{saturate:[Ue,xe,ve]}],sepia:[{sepia:["",Ue,xe,ve]}],"backdrop-filter":[{"backdrop-filter":["","none",xe,ve]}],"backdrop-blur":[{"backdrop-blur":X()}],"backdrop-brightness":[{"backdrop-brightness":[Ue,xe,ve]}],"backdrop-contrast":[{"backdrop-contrast":[Ue,xe,ve]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ue,xe,ve]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ue,xe,ve]}],"backdrop-invert":[{"backdrop-invert":["",Ue,xe,ve]}],"backdrop-opacity":[{"backdrop-opacity":[Ue,xe,ve]}],"backdrop-saturate":[{"backdrop-saturate":[Ue,xe,ve]}],"backdrop-sepia":[{"backdrop-sepia":["",Ue,xe,ve]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":A()}],"border-spacing-x":[{"border-spacing-x":A()}],"border-spacing-y":[{"border-spacing-y":A()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",xe,ve]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ue,"initial",xe,ve]}],ease:[{ease:["linear","initial",b,xe,ve]}],delay:[{delay:[Ue,xe,ve]}],animate:[{animate:["none",w,xe,ve]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,xe,ve]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:le()}],"rotate-x":[{"rotate-x":le()}],"rotate-y":[{"rotate-y":le()}],"rotate-z":[{"rotate-z":le()}],scale:[{scale:Z()}],"scale-x":[{"scale-x":Z()}],"scale-y":[{"scale-y":Z()}],"scale-z":[{"scale-z":Z()}],"scale-3d":["scale-3d"],skew:[{skew:Ae()}],"skew-x":[{"skew-x":Ae()}],"skew-y":[{"skew-y":Ae()}],transform:[{transform:[xe,ve,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:F()}],"translate-x":[{"translate-x":F()}],"translate-y":[{"translate-y":F()}],"translate-z":[{"translate-z":F()}],"translate-none":["translate-none"],accent:[{accent:z()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:z()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",xe,ve]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",xe,ve]}],fill:[{fill:["none",...z()]}],"stroke-w":[{stroke:[Ue,Is,tr,Il]}],stroke:[{stroke:["none",...z()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},NM=dM(PM);function Xe(...e){return NM(jd.clsx(e))}function wc(e){var r;if(!e)return{sessionSettings:{},capabilities:{},modality:"voice"};const t={session_timer:((r=e.session_settings)==null?void 0:r.session_timer)||null},n=e.capabilities||{},i=e.modality||"voice";return{sessionSettings:t,capabilities:n,modality:i}}function IM(e,t){return e.capabilities[t]===!0}function Tc(e){return e.sessionSettings.session_timer||null}function pk(e){const t=e.capabilities;return{userVideoEnabled:t.user_video_enabled!==!1,agentAvatarEnabled:t.agent_avatar_enabled!==!1,screenshareEnabled:t.screenshare_session_enabled!==!1}}function mk(e){const t=e.capabilities;return{suggestedReplyEnabled:t.suggested_reply_enabled!==!1,attachmentsEnabled:t.support_in_chat_attachments!==!1}}function gk(e){return{...e.capabilities}}function bk(e){const t=Math.floor(e/60),n=e%60;return`${t}:${n.toString().padStart(2,"0")}`}const yk=O.forwardRef(({state:e,audioTrack:t,className:n,theme:i="vox"},r)=>{var l,u,d,h,f;const s=O.useRef(null),[o,a]=O.useState(!1);O.useEffect(()=>{s.current&&(console.log("🔊 AgentTile: Audio element created:",{autoplay:s.current.autoplay,muted:s.current.muted,volume:s.current.volume,readyState:s.current.readyState,paused:s.current.paused}),a(!0))},[t]),O.useEffect(()=>{const g=s.current;if(!g)return;const p=()=>console.log("▶️ AgentTile: Audio started playing"),v=()=>console.log("⏸️ AgentTile: Audio paused"),b=()=>console.log("⏹️ AgentTile: Audio ended"),w=x=>console.error("❌ AgentTile: Audio error:",x),S=()=>console.log("⏳ AgentTile: Audio load started"),k=()=>console.log("✅ AgentTile: Audio can play");return g.addEventListener("play",p),g.addEventListener("pause",v),g.addEventListener("ended",b),g.addEventListener("error",w),g.addEventListener("loadstart",S),g.addEventListener("canplay",k),()=>{g.removeEventListener("play",p),g.removeEventListener("pause",v),g.removeEventListener("ended",b),g.removeEventListener("error",w),g.removeEventListener("loadstart",S),g.removeEventListener("canplay",k)}},[o]),console.log("🎤 AgentTile render:",{state:e,hasAudioTrack:!!t,trackSource:t==null?void 0:t.source,participantId:(l=t==null?void 0:t.participant)==null?void 0:l.identity,publicationMuted:(u=t==null?void 0:t.publication)==null?void 0:u.isMuted,audioElementReady:o,trackMediaStreamTrack:(f=(h=(d=t==null?void 0:t.publication)==null?void 0:d.track)==null?void 0:h.mediaStreamTrack)==null?void 0:f.readyState});const c=O.useMemo(()=>i==="light"?{base:"bg-black/90",highlighted:"bg-black",muted:"bg-black/30"}:{base:"bg-white/90",highlighted:"bg-white",muted:"bg-white/30"},[i]);return m.jsxs("div",{ref:r,className:Xe("",n),children:[t&&m.jsxs(m.Fragment,{children:[m.jsx(nk,{ref:s,trackRef:t,volume:1}),m.jsx(ik,{barCount:5,state:e,options:{minHeight:5},trackRef:t,className:Xe("flex aspect-video w-40 items-center justify-center gap-1.5"),children:m.jsx("span",{className:Xe([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",`data-[lk-highlighted=true]:${c.highlighted}`,`data-[lk-muted=true]:${c.muted}`])})})]}),!t&&m.jsx("div",{className:Xe("flex aspect-video w-40 items-center justify-center"),children:m.jsx("div",{className:"flex flex-col items-center justify-center",children:m.jsx("div",{className:"flex gap-1.5",children:Array.from({length:5}).map((g,p)=>m.jsx("span",{className:Xe([`${c.base} min-h-2 w-2 rounded-full`,"origin-center transition-colors duration-250 ease-linear",e==="speaking"&&`animate-pulse ${c.highlighted}`,e==="thinking"&&`animate-pulse ${c.muted}`])},p))})})})]})});yk.displayName="AgentTile";const MM=({videoTrack:e,className:t,ref:n})=>{var i,r;return!e||!e.publication||!e.participant?m.jsx("div",{ref:n,className:Xe(t),children:m.jsx("div",{className:"w-full h-full bg-gray-200 rounded-md flex items-center justify-center",children:m.jsx("span",{className:"text-gray-500",children:"No video available"})})}):m.jsx("div",{ref:n,className:Xe(t),children:m.jsx(Sc,{trackRef:e,width:((i=e.publication.dimensions)==null?void 0:i.width)??0,height:((r=e.publication.dimensions)==null?void 0:r.height)??0,className:"rounded-md"})})},OM=D.forwardRef(function({trackRef:t,className:n,...i},r){var s,o;return m.jsx("div",{ref:r,className:Xe("bg-muted overflow-hidden rounded-md",n),children:m.jsx(Sc,{trackRef:t,width:((s=t==null?void 0:t.publication.dimensions)==null?void 0:s.width)??0,height:((o=t==null?void 0:t.publication.dimensions)==null?void 0:o.height)??0,className:Xe("h-full w-auto"),...i})})}),gg=Fe.create(OM),DM=Fe.create(yk),LM=Fe.create(MM),li={initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:0},transition:{type:"spring",stiffness:675,damping:75,mass:1}},Pr={grid:["h-full w-full","grid gap-x-2 place-content-center","grid-cols-[1fr_1fr] grid-rows-[90px_1fr_90px]"],agentChatOpenWithSecondTile:["col-start-1 row-start-1","self-center justify-self-end"],agentChatOpenWithoutSecondTile:["col-start-1 row-start-1","col-span-2","place-content-center"],agentChatClosed:["col-start-1 row-start-1","col-span-2","place-content-center"],secondTileChatOpen:["col-start-2 row-start-1","self-center justify-self-start"],secondTileChatClosed:["col-start-2 row-start-3","place-content-end"]};function FM(e,t){const{localParticipant:n}=YI(t),i=n==null?void 0:n.getTrackPublication(e);return O.useMemo(()=>i&&n?{source:e,participant:n,publication:i}:void 0,[e,i,n])}function jM({chatOpen:e,client:t,theme:n="vox"}){const{agent:{isActive:i=!1}={},session:r,state:s="idle",audioTrack:o,videoTrack:a}=t?zh(t):{agent:{isActive:!1},session:null,state:"idle",audioTrack:null,videoTrack:null};console.log("🎨 MediaTiles render:",{chatOpen:e,isAgentActive:i,hasSession:!!r,sessionState:r==null?void 0:r.state,agentState:s,hasAudioTrack:!!o,hasVideoTrack:!!a});const[c]=ek([B.Source.ScreenShare]),l=FM(B.Source.Camera,t),u=l&&!l.publication.isMuted,d=c&&!c.publication.isMuted,h=u||d,f=i||r&&r.state==="active",g={...li.transition,delay:e?0:.15},p={...li.animate,scale:e?1:3,transition:g},v={...li.animate,transition:g},b=g,w=g,S=a&&a.publication&&a.participant;return m.jsx("div",{className:"relative w-full h-full z-10 flex items-center justify-center",children:m.jsx("div",{className:"relative w-full h-full max-w-2xl px-4 md:px-0",children:m.jsxs("div",{className:Xe(Pr.grid),children:[f&&m.jsx("div",{className:Xe(["grid",!e&&Pr.agentChatClosed,e&&h&&Pr.agentChatOpenWithSecondTile,e&&!h&&Pr.agentChatOpenWithoutSecondTile]),children:m.jsxs("div",{className:"h-full flex items-center justify-center",children:[!S&&m.jsx(DM,{layoutId:"agent",...li,animate:p,transition:b,state:s,audioTrack:o||void 0,theme:n,className:Xe(e?"h-[90px]":"h-auto w-full")},"agent"),S&&a&&m.jsx(LM,{layoutId:"avatar",...li,animate:v,transition:w,videoTrack:a,className:Xe(e?"h-[90px] [&>video]:h-[90px] [&>video]:w-auto":"h-auto w-full")},"avatar")]})}),m.jsx("div",{className:Xe(["grid",e&&Pr.secondTileChatOpen,!e&&Pr.secondTileChatClosed]),children:m.jsxs("div",{className:"w-full px-10 flex items-center shadow-2xl justify-between",children:[l&&u&&m.jsx(gg,{layout:"position",layoutId:"camera",...li,trackRef:l,transition:{...li.transition,delay:e?0:.15},className:"h-[60px] order-1"},"camera"),d&&m.jsx(gg,{layout:"position",layoutId:"screen",...li,trackRef:c,transition:{...li.transition,delay:e?0:.15},className:"h-[70px] order-2"},"screen")]})})]})})})}const UM={card:"text-gray-100 bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] border border-gray-800/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-black/90 via-black/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(75,85,99,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-gray-500/[0.12] via-gray-600/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-gray-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-100 font-semibold",secondary:"text-gray-200",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-300 via-gray-200 to-gray-300"},micButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 rounded-3xl flex items-center justify-center hover:bg-gray-900 hover:border-gray-600 hover:scale-105 hover:shadow-2xl hover:shadow-gray-600/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-gray-900/90 backdrop-blur-xl border-2 border-gray-700/50 text-gray-100 font-bold hover:bg-gray-900 hover:border-gray-600 hover:scale-[1.02] hover:shadow-2xl hover:shadow-gray-600/30 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-gray-900/60 backdrop-blur-xl rounded-2xl text-center text-gray-200 text-sm font-medium transition-all duration-700 ease-in-out border border-gray-700/50 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-gray-400 rounded-full animate-pulse shadow-lg shadow-gray-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-gray-800/50 rounded-3xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-black/90 backdrop-blur-xl border-gray-800/50 shadow-xl",textarea:"bg-black/80 border border-gray-800/50 rounded-xl text-gray-100 placeholder-gray-500 font-medium px-4 py-3",sendButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 disabled:border-gray-800 disabled:opacity-40 text-gray-100 font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-gray-600/30",attachButton:"text-gray-400 hover:text-gray-200 hover:bg-gray-700/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/40 hover:border-red-500/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-gray-800/70 text-gray-100 backdrop-blur-md shadow-lg border border-gray-700/50",other:"bg-gray-900/60 text-gray-100 border border-gray-700/50 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-gray-900/80 border-gray-700/50 backdrop-blur-xl shadow-xl",backButton:"text-gray-300 hover:text-gray-100 hover:bg-gray-700/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-gray-400 mb-2",suggestedResponse:{container:"bg-gray-900/70 text-gray-200 border-gray-700/50 backdrop-blur-md hover:bg-gray-800/80 hover:border-gray-600 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0a0a0a] via-[#121212] to-[#0a0a0a] text-gray-100",header:"border-gray-700/50 bg-gray-900/80 backdrop-blur-xl shadow-xl",headerButton:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-gray-900 via-gray-900/90 to-gray-900/60 backdrop-blur-xl border-t border-gray-700/50 shadow-2xl",controlEnabled:"bg-gray-900/90 hover:bg-gray-900 border-2 border-gray-700/50 hover:border-gray-600 text-gray-100 hover:scale-105 hover:shadow-xl hover:shadow-gray-600/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-900/50 hover:bg-gray-900/60 text-gray-500 border border-gray-800 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-500/50 hover:border-red-500/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-gray-900/70 border border-gray-700/50 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-900/60 text-gray-300",avatar:"bg-gray-800/80 text-gray-300 border-2 border-gray-700/50",nameOverlay:"bg-gradient-to-t from-gray-900 via-gray-900/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},BM={card:"text-gray-900 bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] border-[3px] border-indigo-200/60 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl shadow-indigo-200/30",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#FFFFFF]/90 via-[#FFFFFF]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(129,140,248,0.12),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 right-0 w-64 h-64 bg-gradient-to-br from-indigo-300/40 via-purple-300/25 to-transparent rounded-full blur-3xl animate-pulse-slow",cardPinkBlur:"absolute bottom-0 left-0 w-56 h-56 bg-gradient-to-tr from-blue-300/35 via-purple-200/20 to-transparent rounded-full blur-3xl",cardPulse1:"absolute top-4 right-4 w-8 h-8 bg-gradient-to-br from-indigo-400/30 to-purple-400/30 rounded-full blur-md opacity-60 animate-pulse",cardPulse2:"absolute bottom-6 left-6 w-6 h-6 bg-gradient-to-br from-blue-400/25 to-purple-400/25 rounded-full blur-md opacity-50 animate-pulse",main:"w-full flex flex-col items-center justify-center bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-gray-900 font-semibold",secondary:"text-gray-700",muted:"text-gray-500",accent:"text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600"},micButton:"relative w-20 h-20 backdrop-blur-xl border-2 border-indigo-400/40 rounded-3xl flex items-center justify-center hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-indigo-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",chatButton:"relative w-20 h-20 bg-gradient-to-br from-blue-600 to-cyan-600 backdrop-blur-xl border-2 border-blue-400/40 rounded-3xl flex items-center justify-center hover:from-blue-700 hover:to-cyan-700 hover:border-blue-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-blue-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",videoButton:"relative w-20 h-20 bg-gradient-to-br from-purple-600 to-pink-600 backdrop-blur-xl border-2 border-purple-400/40 rounded-3xl flex items-center justify-center hover:from-purple-700 hover:to-pink-700 hover:border-purple-500/60 hover:scale-105 hover:shadow-2xl hover:shadow-purple-500/40 transition-all duration-500 ease-out group overflow-hidden text-white",popupTrigger:"bg-gradient-to-r from-indigo-600 to-purple-600 backdrop-blur-xl border-2 border-indigo-400/40 text-white font-bold hover:from-indigo-700 hover:to-purple-700 hover:border-indigo-500/60 hover:scale-[1.02] hover:shadow-2xl hover:shadow-indigo-500/40 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-white transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/80 backdrop-blur-xl rounded-2xl text-center text-gray-700 text-sm font-medium transition-all duration-700 ease-in-out border border-indigo-100 shadow-lg shadow-indigo-100/20",statusIndicator:"w-2.5 h-2.5 bg-emerald-500 rounded-full animate-pulse shadow-lg shadow-emerald-500/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-indigo-100 rounded-3xl py-4 flex flex-col justify-end h-full bg-white/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-white/80 backdrop-blur-xl border-indigo-100 shadow-xl",textarea:"bg-white/90 border border-indigo-100 rounded-xl text-gray-900 placeholder-gray-400 font-medium px-4 py-3 focus:border-indigo-300 focus:ring-2 focus:ring-indigo-200",sendButton:"bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 border-2 border-transparent disabled:from-gray-300 disabled:to-gray-300 disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-lg hover:shadow-indigo-500/40",attachButton:"text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-indigo-100/70 text-gray-900 backdrop-blur-md shadow-lg border border-indigo-200/50",other:"bg-white/80 text-gray-900 border border-gray-200 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-white/80 border-indigo-100 backdrop-blur-xl shadow-xl",backButton:"text-gray-600 hover:text-indigo-600 hover:bg-indigo-50 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-indigo-600 mb-2",suggestedResponse:{container:"bg-white/80 text-indigo-700 border-indigo-100 backdrop-blur-md hover:bg-indigo-50 hover:border-indigo-200 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#F8F9FC] via-[#FFFFFF] to-[#F8F9FC] text-gray-900",header:"border-indigo-100 bg-white/80 backdrop-blur-xl shadow-xl",headerButton:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-500 animate-pulse shadow-lg shadow-emerald-500/60",controlsBackground:"bg-gradient-to-t from-white via-white/90 to-white/60 backdrop-blur-xl border-t border-indigo-100 shadow-2xl",controlEnabled:"bg-white/90 hover:bg-indigo-50 border-2 border-indigo-100 hover:border-indigo-200 text-gray-900 hover:scale-105 hover:shadow-xl hover:shadow-indigo-200/30 transition-all duration-300 font-semibold",controlDisabled:"bg-gray-100/50 hover:bg-gray-100/60 text-gray-400 border border-gray-200 transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-white/80 border border-indigo-100 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-gray-50 text-gray-600",avatar:"bg-indigo-100/80 text-indigo-700 border-2 border-indigo-200",nameOverlay:"bg-gradient-to-t from-white via-white/80 to-transparent text-gray-900 backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},VM={card:"text-white bg-gradient-to-b from-[#0a0a0a] via-[#000000] to-[#0a0a0a] border border-gray-800/30 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-[0_8px_32px_rgba(0,0,0,0.9),0_0_0_1px_rgba(255,255,255,0.08)_inset]",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-32 z-10 bg-gradient-to-b from-black/95 via-black/30 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,_rgba(255,255,255,0.03),transparent_60%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[400px] h-[200px] bg-gradient-to-b from-white/[0.03] via-white/[0.015] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[300px] h-[150px] bg-gradient-to-t from-white/[0.02] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-black p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-gray-400",accent:"text-transparent bg-clip-text bg-gradient-to-r from-gray-200 via-white to-gray-200"},micButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] rounded-2xl flex items-center justify-center hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.03] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] transition-all duration-300 ease-out group overflow-hidden",popupTrigger:"bg-white/[0.10] backdrop-blur-sm border border-white/[0.2] text-white font-bold hover:bg-white/[0.15] hover:border-white/[0.35] hover:scale-[1.02] hover:shadow-[0_8px_24px_rgba(255,255,255,0.15)] focus:outline-none focus:ring-2 focus:ring-white/30 focus:ring-offset-2 focus:ring-offset-black transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-white/[0.06] backdrop-blur-md rounded-xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-white/[0.12] ",statusIndicator:"w-2 h-2 bg-emerald-400 rounded-full animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-white/[0.12] rounded-2xl py-4 flex flex-col justify-end h-full bg-black/90 backdrop-blur-md shadow-[0_4px_24px_rgba(0,0,0,0.6)]",chatInput:{container:"bg-black/90 backdrop-blur-md border-white/[0.12] shadow-[0_4px_16px_rgba(0,0,0,0.4)]",textarea:"bg-white/[0.08] border border-white/[0.12] rounded-xl text-white placeholder-gray-500 font-medium px-4 py-3 focus:border-white/[0.2] focus:ring-1 focus:ring-white/[0.15] transition-all",sendButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] disabled:border-white/[0.08] disabled:opacity-40 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(255,255,255,0.12)]",attachButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg",endButton:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-[0_4px_16px_rgba(239,68,68,0.3)]"},chatMessage:{own:"bg-white/[0.10] text-white backdrop-blur-sm shadow-md border border-white/[0.15]",other:"bg-white/[0.06] text-white border border-white/[0.10] backdrop-blur-sm shadow-md"},chatHeader:{container:"bg-black/90 border-white/[0.12] backdrop-blur-md shadow-lg",backButton:"text-gray-400 hover:text-white hover:bg-white/[0.08] transition-all duration-300 rounded-lg"},spinner:"w-10 h-10 animate-spin text-white mb-2",suggestedResponse:{container:"bg-white/[0.08] text-white border-white/[0.15] backdrop-blur-sm hover:bg-white/[0.12] hover:border-white/[0.25] transition-all duration-300 shadow-md"},video:{container:"bg-black text-white",header:"border-white/[0.12] bg-black/90 backdrop-blur-md shadow-lg",headerButton:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] transition-all duration-300 rounded-lg shadow-md",statusDot:"bg-emerald-400 animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)]",controlsBackground:"bg-gradient-to-t from-black via-black/95 to-black/70 backdrop-blur-md border-t border-white/[0.12] shadow-[0_-4px_24px_rgba(0,0,0,0.6)]",controlEnabled:"bg-white/[0.12] hover:bg-white/[0.18] border border-white/[0.2] hover:border-white/[0.35] text-white hover:scale-[1.02] hover:shadow-md hover:shadow-white/10 transition-all duration-300 font-semibold",controlDisabled:"bg-white/[0.04] hover:bg-white/[0.06] text-gray-500 border border-white/[0.08] transition-all duration-300",endCall:"bg-red-500/90 hover:bg-red-500 border border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-[1.02] transition-all duration-300 shadow-md hover:shadow-red-500/30",tile:"bg-white/[0.08] border border-white/[0.12] shadow-lg backdrop-blur-sm rounded-xl",placeholder:"bg-white/[0.06] text-gray-400",avatar:"bg-white/[0.10] text-gray-300 border border-white/[0.12]",nameOverlay:"bg-gradient-to-t from-black via-black/85 to-transparent text-white backdrop-blur-sm font-semibold",mutedIndicator:"bg-red-500 text-white shadow-md shadow-red-500/30 font-semibold"}},$M={card:"text-white bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] border border-[#2a3142]/50 w-full h-full flex flex-col justify-between overflow-hidden relative shadow-2xl",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-40 z-10 bg-gradient-to-b from-[#0b1220]/90 via-[#0b1220]/40 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(circle_at_50%_-20%,_rgba(34,211,238,0.08),transparent_50%)] opacity-100",cardPurpleBlur:"absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-gradient-to-b from-cyan-500/[0.12] via-sky-500/[0.06] to-transparent blur-3xl",cardPinkBlur:"absolute bottom-0 left-1/2 -translate-x-1/2 w-[500px] h-[250px] bg-gradient-to-t from-cyan-600/[0.08] via-transparent to-transparent blur-3xl",cardPulse1:"hidden",cardPulse2:"hidden",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] shadow-2xl p-0 overflow-hidden h-full relative",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"text-transparent bg-clip-text bg-gradient-to-r from-cyan-300 via-sky-300 to-cyan-300"},micButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",chatButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-sky-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-sky-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-sky-500/30 transition-all duration-500 ease-out group overflow-hidden",videoButton:"relative w-20 h-20 bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 rounded-3xl flex items-center justify-center hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-105 hover:shadow-2xl hover:shadow-cyan-500/30 transition-all duration-500 ease-out group overflow-hidden",popupTrigger:"bg-[#171b26]/90 backdrop-blur-xl border-2 border-cyan-500/30 text-white font-bold hover:bg-[#171b26] hover:border-cyan-400/50 hover:scale-[1.02] hover:shadow-2xl hover:shadow-cyan-500/30 focus:outline-none focus:ring-2 focus:ring-cyan-400/50 focus:ring-offset-2 focus:ring-offset-[#161a25] transition-all duration-300",promptSlider:"absolute w-full py-4 px-6 bg-[#1c2230]/60 backdrop-blur-xl rounded-2xl text-center text-white/90 text-sm font-medium transition-all duration-700 ease-in-out border border-[#2a3142]/80 shadow-xl",statusIndicator:"w-2.5 h-2.5 bg-emerald-400 rounded-full animate-pulse shadow-lg shadow-emerald-400/60",pulseRings:{ring1:"hidden",ring2:"hidden",ring3:"hidden"},controlBar:"border border-[#2a3142]/80 rounded-3xl py-4 flex flex-col justify-end h-full bg-[#161a25]/80 backdrop-blur-xl shadow-2xl",chatInput:{container:"bg-[#1c2230]/80 backdrop-blur-xl border-[#2a3142]/80 shadow-xl",textarea:"bg-[#1c2230]/60 border border-[#2a3142]/50 rounded-xl text-white placeholder-gray-400 font-medium px-4 py-3",sendButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 disabled:border-[#2a3142] disabled:opacity-40 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-cyan-500/30",attachButton:"text-gray-400 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl",endButton:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/40 hover:border-red-400/60 text-white font-bold hover:scale-105 transition-all duration-300 shadow-xl hover:shadow-red-500/40"},chatMessage:{own:"bg-[#243049]/70 text-white backdrop-blur-md shadow-lg border border-[#2a3142]/80",other:"bg-[#1c2230]/60 text-white border border-[#2a3142]/80 backdrop-blur-md shadow-lg"},chatHeader:{container:"bg-[#1c2230]/80 border-[#2a3142]/80 backdrop-blur-xl shadow-xl",backButton:"text-white/80 hover:text-white hover:bg-[#2a3142]/30 transition-all duration-300 rounded-xl"},spinner:"w-10 h-10 animate-spin text-cyan-400 mb-2",suggestedResponse:{container:"bg-[#1c2230]/70 text-white border-[#2a3142]/80 backdrop-blur-md hover:bg-[#1c2230]/80 hover:border-cyan-400/30 transition-all duration-300 shadow-lg"},video:{container:"bg-gradient-to-b from-[#0e1218] via-[#161a25] to-[#0e1218] text-white",header:"border-[#2a3142]/80 bg-[#1c2230]/80 backdrop-blur-xl shadow-xl",headerButton:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 transition-all duration-300 rounded-xl shadow-lg",statusDot:"bg-emerald-400 animate-pulse shadow-lg shadow-emerald-400/60",controlsBackground:"bg-gradient-to-t from-[#161a25] via-[#161a25]/90 to-[#161a25]/60 backdrop-blur-xl border-t border-[#2a3142]/80 shadow-2xl",controlEnabled:"bg-[#171b26]/90 hover:bg-[#171b26] border-2 border-cyan-500/30 hover:border-cyan-400/50 text-white hover:scale-105 hover:shadow-xl hover:shadow-cyan-500/30 transition-all duration-300 font-semibold",controlDisabled:"bg-[#1c2230]/50 hover:bg-[#1c2230]/60 text-white/40 border border-[#2a3142] transition-all duration-300",endCall:"bg-red-600/90 hover:bg-red-600 border-2 border-red-400/50 hover:border-red-400/70 text-white font-bold hover:scale-105 transition-all duration-300 shadow-2xl hover:shadow-red-500/50",tile:"bg-[#1c2230]/70 border border-[#2a3142]/80 shadow-2xl backdrop-blur-md rounded-2xl",placeholder:"bg-[#1c2230]/60 text-white/80",avatar:"bg-[#171b26]/80 text-white border-2 border-[#2a3142]/80",nameOverlay:"bg-gradient-to-t from-[#161a25] via-[#161a25]/80 to-transparent text-white backdrop-blur-sm font-bold",mutedIndicator:"bg-red-600 text-white shadow-xl shadow-red-500/40 font-semibold"}},zM={card:" text-white bg-gradient-to-br from-[#171727] to-[#12121F] border border-gray-800 w-full h-full flex flex-col justify-between overflow-hidden relative",cardTopGradient:"pointer-events-none absolute top-0 left-0 w-full h-10 z-10 bg-gradient-to-b from-[#171727]/90 to-transparent",cardRadial:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#3B82F6]/15 via-transparent to-transparent",cardPurpleBlur:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#8B5CF6]/25 to-transparent rounded-full blur-2xl",cardPinkBlur:"absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-[#EC4899]/20 to-transparent rounded-full blur-xl",cardPulse1:"absolute -top-2 -left-2 w-6 h-6 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full blur-sm opacity-50 animate-pulse",cardPulse2:"absolute -bottom-2 -right-2 w-4 h-4 bg-gradient-to-br from-[#EC4899] to-[#8B5CF6] rounded-full blur-sm opacity-40 animate-pulse",main:"w-full flex flex-col items-center justify-center max-w-md mx-auto bg-gradient-to-br from-[#171727] to-[#12121F] rounded-2xl shadow-xl p-0 overflow-hidden h-full",text:{primary:"text-white font-semibold",secondary:"text-white/95",muted:"text-white/70",accent:"bg-clip-text text-transparent bg-gradient-to-r from-[#3B82F6] via-[#8B5CF6] to-[#EC4899]"},micButton:"relative w-20 h-20 bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 mic-glow shadow-2xl group",chatButton:"relative w-20 h-20 bg-gradient-to-br from-[#10B981] to-[#059669] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",videoButton:"relative w-20 h-20 bg-gradient-to-br from-[#8B5CF6] to-[#EC4899] rounded-full flex items-center justify-center hover:scale-105 transition-all duration-300 shadow-2xl group",popupTrigger:"bg-gradient-to-br from-[#3B82F6] to-[#8B5CF6] text-white font-medium hover:from-[#2563EB] hover:to-[#7C3AED] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-900 shadow-xl",promptSlider:"absolute w-full py-3 px-2 bg-[#1E1E2E] rounded-xl text-center text-gray-200 text-sm transition-opacity duration-700 ease-in-out border border-gray-700",statusIndicator:"w-2 h-2 bg-[#10B981] rounded-full animate-pulse",pulseRings:{ring1:"w-32 h-32 rounded-full border-2 border-[#3B82F6]/40 pulse-ring",ring2:"absolute w-28 h-28 rounded-full border-2 border-[#8B5CF6]/30 pulse-ring",ring3:"absolute w-24 h-24 rounded-full border-2 border-[#EC4899]/20 pulse-ring"},controlBar:"border border-border rounded-3xl py-4 flex flex-col justify-end h-full bg-[#1E1E2E] shadow-2xl",chatInput:{container:"bg-[#1E1E2E] border-gray-700",textarea:"bg-[#1E1E2E] border-none text-white placeholder-gray-400",sendButton:"bg-[#3B82F6] hover:bg-[#2563EB] disabled:bg-gray-600 disabled:opacity-50 text-white",attachButton:"text-gray-400 hover:text-gray-300 hover:bg-gray-700",endButton:"bg-red-900/20 hover:bg-red-800/30 text-red-400 border-red-800"},chatMessage:{own:"bg-[#1E1E2E]/80 text-white",other:"bg-[#1E1E2E] text-white border border-gray-700"},chatHeader:{container:"bg-[#1E1E2E] border-gray-700",backButton:"text-gray-400 hover:text-white hover:bg-gray-700"},spinner:"w-10 h-10 animate-spin text-blue-400 mb-2",suggestedResponse:{container:"bg-[#221f3f] text-white border-none"},video:{container:"bg-gradient-to-br from-[#171727] to-[#12121F] text-white",header:"border-gray-700 bg-[#1E1E2E]/80",headerButton:"bg-[#1E1E2E] hover:bg-gray-700 text-gray-300",statusDot:"bg-[#10B981] animate-pulse",controlsBackground:"bg-[#1E1E2E]/90 backdrop-blur-sm border-t border-gray-700",controlEnabled:"bg-[#3B82F6] hover:bg-[#2563EB] text-white",controlDisabled:"bg-gray-700 hover:bg-gray-600 text-gray-300",endCall:"bg-red-600 hover:bg-red-700 text-white",tile:"bg-[#1E1E2E] border border-gray-700 shadow-xl",placeholder:"bg-[#1E1E2E] text-gray-300",avatar:"bg-gray-700 text-gray-300",nameOverlay:"bg-black/70 text-white",mutedIndicator:"bg-red-600/80 text-white"}},bg={dark:UM,light:BM,vox:VM,midnight:$M,levish:zM};function on(e){return bg[e]||bg.vox}function yg({timeout:e}){const[t,n]=O.useState(100),i=O.useRef(null),r=O.useRef(null);return O.useEffect(()=>{if(!e||e<=0)return;n(100),r.current=Date.now();const s=()=>{if(!e||r.current===null)return;const o=Date.now()-r.current,a=Math.max(0,100-o/e*100);n(a),a>0&&(i.current=requestAnimationFrame(s))};return i.current=requestAnimationFrame(s),()=>{i.current&&cancelAnimationFrame(i.current)}},[e]),!e||e<=0?null:m.jsx("div",{className:"w-full h-1 relative top-1 rounded-t-4xl bg-gray-700 overflow-hidden",children:m.jsx(Fe.div,{className:"h-1 rounded-t-4xl dark:bg-white bg-blue-200 ",initial:{width:"100%"},animate:{width:`${Math.max(t,2)}%`},transition:{duration:.1,ease:"linear"},style:{minWidth:"2%"}})})}function uo({interaction:e,theme:t,onDismiss:n,client:i,addLocalMessage:r}){var a;if(!e||!e.isVisible||!e.component)return null;const[s]=D.useState(()=>Date.now()),o=()=>e.component?D.createElement(e.component,{handler:e.handler||void 0,timeout:e.timeout,loadData:async l=>{console.log("InteractiveComponent: Loading data:",l)},presentationMode:e.presentationMode,data:e.data,client:i,addLocalMessage:r}):m.jsx("div",{className:"p-4 text-red-500",children:"Component not found"});switch(e.presentationMode){case"fullscreen":return m.jsx(ls,{children:m.jsxs(Fe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[9999] bg-black",children:[m.jsxs("div",{className:"flex flex-col",children:[m.jsx(yg,{timeout:e.timeout}),m.jsxs("div",{className:"flex items-center justify-between p-4 bg-black/80 text-white border-b border-gray-700",children:[m.jsx("h3",{className:"text-lg font-semibold",children:e.methodName.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase())}),m.jsx("button",{onClick:n||((a=e.handler)==null?void 0:a.dismissView),className:"p-2 rounded-full bg-white/20 hover:bg-white/30 text-white transition-colors",children:m.jsx(kt.X,{className:"w-5 h-5"})})]})]}),m.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:o()})]})});case"embedded":default:return m.jsx(ls,{children:m.jsx(Fe.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},className:"w-fit rounded-lg ",children:m.jsxs("div",{children:[m.jsx(yg,{timeout:e.timeout}),o()]})})})}}function ho({duration:e,theme:t="vox",onTimerExpired:n,className:i="",showIcon:r=!0}){const[s,o]=O.useState(e),[a,c]=O.useState(!1);O.useEffect(()=>{if(s<=0){c(!0),n==null||n();return}const u=setInterval(()=>{o(d=>{const h=d-1;return h<=0?(c(!0),n==null||n(),0):h})},1e3);return()=>clearInterval(u)},[s,n]),O.useEffect(()=>{o(e),c(!1)},[e]);const l=()=>a?"text-red-500":s<=60?"text-orange-500":s<=300?"text-yellow-500":t==="dark"?"text-gray-300":"text-gray-600";return m.jsxs("div",{className:`flex items-center gap-1 text-sm ${l()} ${i}`,children:[r&&m.jsx(kt.Clock,{className:"w-4 h-4"}),m.jsx("span",{className:"font-mono",children:bk(s)}),a&&m.jsx("span",{className:"text-xs ml-1 text-red-500",children:"(Expired)"})]})}function Cc({modality:e,theme:t,disabled:n=!1,showMicrophone:i=!1,microphoneEnabled:r=!0,microphoneLoading:s=!1,onToggleMicrophone:o,showCamera:a=!1,cameraEnabled:c=!0,cameraLoading:l=!1,onToggleCamera:u,showScreenShare:d=!1,screenShareEnabled:h=!1,screenShareLoading:f=!1,onToggleScreenShare:g,showChatToggle:p=!1,chatOpen:v=!1,onToggleChat:b,showTextInput:w=!1,textInputPlaceholder:S="Type a message...",onSendText:k,onSendAttachments:x,supportsAttachments:T=!1,showEndCall:P=!0,onEndCall:A}){var H;const N=on(t),[y,R]=O.useState(""),I=O.useRef(null),L=()=>{const C=y.trim();C&&k&&(k(C),R(""))},U=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),L())},K=C=>{const W=Array.from(C.target.files||[]);W.length>0&&x&&x(W),I.current&&(I.current.value="")},ue=Xe("flex items-center gap-3 px-2 sm:px-3 py-2 w-full backdrop-blur-xl overflow-hidden",w?"justify-between":"justify-center",t==="light"?"bg-white/95 border-gray-200":""),se=(C,W)=>{var Y,E,J;return W==="end-call"?Xe("p-3 rounded-full transition-all duration-200",((Y=N.video)==null?void 0:Y.endCall)||"bg-red-500 text-white hover:bg-red-600",n?"opacity-50 cursor-not-allowed":"hover:scale-105"):Xe("p-3 rounded-full transition-all duration-200",C?((E=N.video)==null?void 0:E.controlEnabled)||"bg-green-500 text-white":((J=N.video)==null?void 0:J.controlDisabled)||"bg-gray-500 text-white",n?"opacity-50 cursor-not-allowed":"hover:scale-105")},z=()=>m.jsx("div",{className:"w-5 h-5 animate-spin rounded-full border-2 border-current border-t-transparent"});return m.jsxs("div",{className:ue,children:[w&&m.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[T&&x&&m.jsxs(m.Fragment,{children:[m.jsx("button",{onClick:()=>{var C;return(C=I.current)==null?void 0:C.click()},disabled:n,className:Xe("p-2 rounded-full transition-all duration-200",t==="light"?"hover:bg-gray-100":"hover:bg-gray-800",n&&"opacity-50 cursor-not-allowed"),title:"Attach files",children:m.jsx(kt.Paperclip,{className:"w-5 h-5"})}),m.jsx("input",{ref:I,type:"file",multiple:!0,accept:"image/*",onChange:K,className:"hidden"})]}),m.jsx("input",{type:"text",value:y,onChange:C=>R(C.target.value),onKeyDown:U,disabled:n,placeholder:S,className:Xe("flex-1 min-w-0 px-4 py-2 rounded-full border outline-none transition-all",t==="light"?"bg-gray-100 border-gray-300 focus:border-blue-500 text-gray-900":"bg-gray-800 border-gray-700 focus:border-blue-400 text-white",n&&"opacity-50 cursor-not-allowed")}),m.jsx("button",{onClick:L,disabled:n||!y.trim(),className:Xe("p-2 rounded-full transition-all duration-200",y.trim()?((H=N.video)==null?void 0:H.controlEnabled)||"bg-blue-500 text-white hover:bg-blue-600":t==="light"?"bg-gray-200 text-gray-400":"bg-gray-700 text-gray-500",n&&"opacity-50 cursor-not-allowed",y.trim()&&!n&&"hover:scale-105"),title:"Send message",children:m.jsx(kt.SendHorizontal,{className:"w-5 h-5"})})]}),!w&&m.jsxs(m.Fragment,{children:[i&&o&&m.jsx("button",{onClick:o,disabled:n||s,className:se(r),title:r?"Mute microphone":"Unmute microphone",children:s?m.jsx(z,{}):r?m.jsx(kt.Mic,{className:"w-5 h-5"}):m.jsx(kt.MicOff,{className:"w-5 h-5"})}),a&&u&&m.jsx("button",{onClick:u,disabled:n||l,className:se(c),title:c?"Turn off camera":"Turn on camera",children:l?m.jsx(z,{}):c?m.jsx(kt.Camera,{className:"w-5 h-5"}):m.jsx(kt.CameraOff,{className:"w-5 h-5"})}),d&&g&&m.jsx("button",{onClick:g,disabled:n||f,className:se(h),title:h?"Stop screen share":"Share screen",children:f?m.jsx(z,{}):m.jsx(kt.Monitor,{className:"w-5 h-5"})}),p&&b&&m.jsx("button",{onClick:b,disabled:n,className:se(v),title:e==="voice"?v?"Hide transcription":"Show transcription":v?"Hide chat":"Show chat",children:m.jsx(kt.MessageCircle,{className:"w-5 h-5"})})]}),P&&A&&m.jsx("button",{onClick:A,disabled:n,className:se(!1,"end-call"),title:"End call",children:m.jsx(kt.PhoneOff,{className:"w-5 h-5"})})]})}Cc.displayName="UnifiedControlBar";const HM=({logLevel:e}={})=>{const t=Kx();D.useEffect(()=>(FC(e??"debug"),window.__lk_room=t,()=>{window.__lk_room=void 0}),[t,e])},vk=D.forwardRef((e,t)=>{const{alt:n,color:i="currentColor",size:r="1em",weight:s="regular",mirrored:o=!1,children:a,weights:c,...l}=e;return D.createElement("svg",{ref:t,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,fill:i,viewBox:"0 0 256 256",transform:o?"scale(-1, 1)":void 0,...l},!!n&&D.createElement("title",null,n),a,c.get(s))});vk.displayName="SSRBase";const WM=new Map([["bold",D.createElement(D.Fragment,null,D.createElement("path",{d:"M140,32V64a12,12,0,0,1-24,0V32a12,12,0,0,1,24,0Zm33.25,62.75a12,12,0,0,0,8.49-3.52L204.37,68.6a12,12,0,0,0-17-17L164.77,74.26a12,12,0,0,0,8.48,20.49ZM224,116H192a12,12,0,0,0,0,24h32a12,12,0,0,0,0-24Zm-42.26,48.77a12,12,0,1,0-17,17l22.63,22.63a12,12,0,0,0,17-17ZM128,180a12,12,0,0,0-12,12v32a12,12,0,0,0,24,0V192A12,12,0,0,0,128,180ZM74.26,164.77,51.63,187.4a12,12,0,0,0,17,17l22.63-22.63a12,12,0,1,0-17-17ZM76,128a12,12,0,0,0-12-12H32a12,12,0,0,0,0,24H64A12,12,0,0,0,76,128ZM68.6,51.63a12,12,0,1,0-17,17L74.26,91.23a12,12,0,0,0,17-17Z"}))],["duotone",D.createElement(D.Fragment,null,D.createElement("path",{d:"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z",opacity:"0.2"}),D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["fill",D.createElement(D.Fragment,null,D.createElement("path",{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm33.94,58.75,17-17a8,8,0,0,1,11.32,11.32l-17,17a8,8,0,0,1-11.31-11.31ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z"}))],["light",D.createElement(D.Fragment,null,D.createElement("path",{d:"M134,32V64a6,6,0,0,1-12,0V32a6,6,0,0,1,12,0Zm39.25,56.75A6,6,0,0,0,177.5,87l22.62-22.63a6,6,0,0,0-8.48-8.48L169,78.5a6,6,0,0,0,4.24,10.25ZM224,122H192a6,6,0,0,0,0,12h32a6,6,0,0,0,0-12Zm-46.5,47A6,6,0,0,0,169,177.5l22.63,22.62a6,6,0,0,0,8.48-8.48ZM128,186a6,6,0,0,0-6,6v32a6,6,0,0,0,12,0V192A6,6,0,0,0,128,186ZM78.5,169,55.88,191.64a6,6,0,1,0,8.48,8.48L87,177.5A6,6,0,1,0,78.5,169ZM70,128a6,6,0,0,0-6-6H32a6,6,0,0,0,0,12H64A6,6,0,0,0,70,128ZM64.36,55.88a6,6,0,0,0-8.48,8.48L78.5,87A6,6,0,1,0,87,78.5Z"}))],["regular",D.createElement(D.Fragment,null,D.createElement("path",{d:"M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm37.25,58.75a8,8,0,0,0,5.66-2.35l22.63-22.62a8,8,0,0,0-11.32-11.32L167.6,77.09a8,8,0,0,0,5.65,13.66ZM224,120H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z"}))],["thin",D.createElement(D.Fragment,null,D.createElement("path",{d:"M132,32V64a4,4,0,0,1-8,0V32a4,4,0,0,1,8,0Zm41.25,54.75a4,4,0,0,0,2.83-1.18L198.71,63a4,4,0,0,0-5.66-5.66L170.43,79.92a4,4,0,0,0,2.82,6.83ZM224,124H192a4,4,0,0,0,0,8h32a4,4,0,0,0,0-8Zm-47.92,46.43a4,4,0,1,0-5.65,5.65l22.62,22.63a4,4,0,0,0,5.66-5.66ZM128,188a4,4,0,0,0-4,4v32a4,4,0,0,0,8,0V192A4,4,0,0,0,128,188ZM79.92,170.43,57.29,193.05A4,4,0,0,0,63,198.71l22.62-22.63a4,4,0,1,0-5.65-5.65ZM68,128a4,4,0,0,0-4-4H32a4,4,0,0,0,0,8H64A4,4,0,0,0,68,128ZM63,57.29A4,4,0,0,0,57.29,63L79.92,85.57a4,4,0,1,0,5.65-5.65Z"}))]]),Qa=D.forwardRef((e,t)=>D.createElement(vk,{ref:t,...e,weights:WM}));Qa.displayName="SpinnerIcon";function qM({text:e,isComplete:t,isRealTimeStream:n=!1,speed:i=50}){const[r,s]=D.useState(""),[o,a]=D.useState(0);return D.useEffect(()=>{if(n){s(e);return}if(t){s(e);return}if(o<e.length){const c=setTimeout(()=>{s(e.slice(0,o+1)),a(o+1)},i);return()=>clearTimeout(c)}},[e,o,t,i,n]),D.useEffect(()=>{n||(a(0),s(""))},[e,n]),m.jsxs("span",{className:"relative",children:[m.jsx("span",{className:"inline-block",children:r}),!t&&m.jsx("span",{className:"inline-flex items-center ml-1",children:[0,1,2].map(c=>m.jsx(Fe.span,{className:"w-1.5 h-1.5 bg-current rounded-full mx-0.5",animate:{y:[0,-4,0],opacity:[.4,1,.4],scale:[.8,1,.8]},transition:{duration:.8,repeat:1/0,repeatType:"mirror",delay:c*.2,ease:"easeInOut"}},c))})]})}function GM(e,t){return e.startsWith("image/")?kt.Image:e.startsWith("video/")?kt.Video:e.startsWith("audio/")?kt.Music:e.includes("zip")||e.includes("rar")||e.includes("archive")?kt.Archive:kt.FileText}function KM(e){if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,i)).toFixed(2))+" "+n[i]}function YM({message:e,theme:t,isOwn:n}){const i=on(t),r=e.metadata,s=(r==null?void 0:r.fileName)||"Unknown file",o=(r==null?void 0:r.fileSize)||0,a=(r==null?void 0:r.mimeType)||"application/octet-stream",c=r==null?void 0:r.downloading,l=r==null?void 0:r.uploading,u=(r==null?void 0:r.downloadProgress)||0,d=(r==null?void 0:r.uploadProgress)||0,h=r==null?void 0:r.downloadUrl,f=r==null?void 0:r.file,g=GM(a),p=c||l,v=c?u:d,b=c?"Downloading...":l?"Uploading...":"Complete",[w,S]=D.useState(null);D.useEffect(()=>{if(h)S(h);else if(f&&a.startsWith("image/")){const P=URL.createObjectURL(f);return S(P),()=>URL.revokeObjectURL(P)}else S(null)},[h,f,a]);const k=()=>{if(h){const P=document.createElement("a");P.href=h,P.download=s,P.click()}},T=a.startsWith("image/")&&w;return m.jsxs("div",{className:"flex flex-col gap-2 max-w-full sm:max-w-sm",children:[T&&m.jsxs("div",{className:"relative rounded-lg overflow-hidden",children:[m.jsx("img",{src:w,alt:s,className:"max-w-full h-auto max-h-48 object-cover rounded-lg cursor-pointer",onClick:k}),m.jsx("div",{className:"absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors duration-200 cursor-pointer"})]}),m.jsxs("div",{className:`
|
|
49
49
|
flex items-center gap-3 p-3 rounded-lg border transition-all duration-200
|
|
50
50
|
${t==="light"?"bg-gray-50 border-gray-200 hover:bg-gray-100":"bg-gray-800/50 border-gray-700 hover:bg-gray-700/50"}
|
|
51
51
|
`,children:[m.jsx("div",{className:`
|
|
@@ -179,7 +179,13 @@ To suppress this warning, you need to explicitly provide the \`palette.${t}Chann
|
|
|
179
179
|
${n.promptSlider}
|
|
180
180
|
${o===i?"opacity-100 translate-y-0":"opacity-0 translate-y-4"}
|
|
181
181
|
whitespace-pre-line break-words transition-all duration-700 ease-out
|
|
182
|
-
`,style:{minHeight:"3rem",display:o===i?"flex":"none",alignItems:"center",justifyContent:"center"},children:m.jsx("span",{className:"italic",children:s})},o))})}const uw=O.forwardRef(({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:i,prompts:r=['"Click to talk"','"How can I assist you today?"'],statusMessage:s="Agent is ready",title:o="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:l=["voice","chat","video"]},u)=>{const d=on(c),h=l.includes("voice"),f=l.includes("chat"),g=l.includes("video"),p=[h,f,g].filter(Boolean).length;return m.jsxs("div",{className:"flex flex-col items-center h-full justify-center w-full relative px-8 py-16","aria-disabled":e,style:{background:"transparent"},children:[m.jsx("div",{className:"absolute inset-0 opacity-[0.01] pointer-events-none mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulance type='fractalNoise' baseFrequency='2' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E")`,backgroundRepeat:"repeat"}}),m.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-gradient-radial from-white/[0.02] to-transparent blur-3xl pointer-events-none"}),m.jsxs("div",{className:"flex flex-col items-center justify-center w-full max-w-2xl space-y-12 z-10",children:[m.jsx("div",{className:"text-center space-y-2 max-w-md",children:m.jsx("p",{className:`text-base leading-relaxed tracking-wide ${d.text.secondary}`,children:a})}),m.jsx("div",{className:"flex items-center justify-center w-full",children:h&&f&&g?m.jsxs("div",{className:"flex gap-5 items-center justify-center",children:[m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}),m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[m.jsx(lu,{onClick:n,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}),m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:i||t,children:[m.jsx(uu,{onClick:i||t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]})]}):p>1?m.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[h&&m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}),f&&m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[m.jsx(lu,{onClick:n,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}),g&&i&&m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:i,children:[m.jsx(uu,{onClick:i,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]})]}):m.jsx("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",children:h?m.jsxs(m.Fragment,{children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}):f?m.jsxs(m.Fragment,{children:[m.jsx(lu,{onClick:n,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}):g&&i?m.jsxs(m.Fragment,{children:[m.jsx(uu,{onClick:i,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]}):m.jsxs(m.Fragment,{children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]})})}),m.jsx("div",{className:"w-full flex justify-center",children:m.jsx(r4,{prompts:r,theme:c})})]})]})});uw.displayName="Welcome";class kf extends D.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return D.createElement(t,{error:this.state.error})}return D.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}const dw=({onClick:e,position:t="bottom-right",size:n=64,className:i="",style:r,ariaLabel:s="Open Voxket",logoScale:o=.7,isRunning:a=!1,logoUrl:c="/logo.png"})=>{const l={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},u={width:n,height:n,...r},d=D.useMemo(()=>{if(typeof window>"u"||!window.matchMedia)return!1;try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},[]);return m.jsxs("div",{className:"relative pointer-events-auto",children:[a&&m.jsxs(m.Fragment,{children:[m.jsx(Fe.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+24,height:n+24,left:-12,top:-12,background:"linear-gradient(45deg, rgba(6,182,212,0.3), rgba(34,211,238,0.3), rgba(6,182,212,0.3))",filter:"blur(8px)"},animate:d?void 0:{scale:[1,1.1,1],opacity:[.6,.9,.6]},transition:d?void 0:{duration:2,repeat:1/0,ease:"easeInOut"}}),m.jsx(Fe.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+16,height:n+16,left:-8,top:-8,background:"linear-gradient(135deg, rgba(6,182,212,0.4), rgba(34,211,238,0.4))",filter:"blur(4px)"},animate:d?void 0:{scale:[1,1.05,1],opacity:[.7,1,.7]},transition:d?void 0:{duration:1.5,repeat:1/0,ease:"easeInOut",delay:.2}})]}),m.jsxs(Fe.button,{type:"button",onClick:e,"aria-label":s,className:`fixed z-50 rounded-full bg-black flex items-center justify-center overflow-hidden focus:outline-none focus:ring-2 focus:ring-cyan-400/60 ${l[t]} ${i}`,style:{...u,boxShadow:a?"0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)":"0 8px 32px rgba(0,0,0,0.3)",border:a?"2px solid rgba(6,182,212,0.6)":"none"},initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1,...a&&!d?{boxShadow:["0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.8), 0 0 30px rgba(6,182,212,0.6), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)"]}:{}},exit:{scale:.9,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":t,"data-voxket-trigger":"true",transition:{...!d&&a?{boxShadow:{duration:2,repeat:1/0,ease:"easeInOut"}}:{}},children:[a&&m.jsxs(m.Fragment,{children:[m.jsx(Fe.span,{"aria-hidden":!0,className:"absolute inset-0 rounded-full pointer-events-none",style:{background:"conic-gradient(from 0deg, rgba(6,182,212,0.0) 0deg, rgba(6,182,212,1) 90deg, rgba(34,211,238,1) 180deg, rgba(6,182,212,0.0) 270deg)",WebkitMask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))",mask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))"},animate:d?void 0:{rotate:360},transition:d?void 0:{duration:3,repeat:1/0,ease:"linear"}}),m.jsx("span",{"aria-hidden":!0,className:"absolute inset-1 rounded-full pointer-events-none",style:{background:"radial-gradient(circle, rgba(6,182,212,0.1) 0%, transparent 70%)"}})]}),m.jsx("img",{src:c,alt:"Voxket",className:"object-contain select-none pointer-events-none relative z-10",style:{width:`${Math.max(0,Math.min(1,o))*100}%`,height:`${Math.max(0,Math.min(1,o))*100}%`,filter:a?"brightness(1.1) contrast(1.1)":"none"},draggable:!1})]})]})};function hw({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:i=!0,enableLocalStorage:r=!0,voxketSessionId:s}={}){const[o,a]=D.useState(null),[c,l]=D.useState([]),[u,d]=D.useState(null),[h,f]=D.useState([]),g=D.useCallback((w,S)=>{const k={timestamp:new Date,event:w,data:S,sessionId:o==null?void 0:o.sessionId,participantId:u==null?void 0:u.identity};if(l(x=>[...x,k]),r){const x=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");x.push(k),localStorage.setItem("voxket-session-logs",JSON.stringify(x))}return k},[o==null?void 0:o.sessionId,u==null?void 0:u.identity,i,r]);D.useEffect(()=>{if(!e)return;const w=()=>{const y=s||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,R=new Date,I={sessionId:y,startTime:R,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(I),g("SESSION_STARTED",{sessionId:y,startTime:R}),n==null||n(y)},S=()=>{if(o){const y=new Date,R=y.getTime()-o.startTime.getTime(),I={...o,endTime:y,duration:R,events:c};g("SESSION_ENDED",{sessionId:o.sessionId,duration:`${Math.round(R/1e3)}s`,totalMessages:o.totalMessages,connectionIssues:o.connectionIssues}),t==null||t(I),a(null),l([])}},k=y=>{g("CONNECTION_STATE_CHANGED",{state:y}),y===$e.Reconnecting&&o&&(a(R=>R?{...R,connectionIssues:R.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},x=y=>{g("TRACK_PUBLISHED",{trackKind:y.kind,trackSource:y.source})},T=y=>{g("TRACK_UNPUBLISHED",{trackKind:y.kind,trackSource:y.source})},P=(y,R)=>{o&&a(I=>I?{...I,totalMessages:I.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:R==null?void 0:R.identity,dataSize:y.length})},A=y=>{g("PARTICIPANT_CONNECTED",{participantId:y.identity,participantName:y.name}),f(R=>[...R,y]),o&&a(R=>R?{...R,participantCount:R.participantCount+1}:null)},N=y=>{g("PARTICIPANT_DISCONNECTED",{participantId:y.identity,participantName:y.name}),f(R=>R.filter(I=>I.identity!==y.identity))};return e.localParticipant&&d(e.localParticipant),e.on(j.Connected,w),e.on(j.Disconnected,S),e.on(j.ConnectionStateChanged,k),e.on(j.TrackPublished,x),e.on(j.TrackUnpublished,T),e.on(j.DataReceived,P),e.on(j.ParticipantConnected,A),e.on(j.ParticipantDisconnected,N),()=>{e.off(j.Connected,w),e.off(j.Disconnected,S),e.off(j.ConnectionStateChanged,k),e.off(j.TrackPublished,x),e.off(j.TrackUnpublished,T),e.off(j.DataReceived,P),e.off(j.ParticipantConnected,A),e.off(j.ParticipantDisconnected,N)}},[e,o,c,h.length,g,t,n]);const p=D.useCallback(()=>r?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,r]),v=D.useCallback(()=>{r&&localStorage.removeItem("voxket-session-logs"),l([])},[r]),b=D.useCallback(()=>{const w=p(),S=JSON.stringify(w,null,2),k="data:application/json;charset=utf-8,"+encodeURIComponent(S),x=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,T=document.createElement("a");T.setAttribute("href",k),T.setAttribute("download",x),T.click()},[p]);return{sessionMetrics:o,sessionLogs:c,logEvent:g,getSessionLogs:p,clearSessionLogs:v,exportSessionLogs:b}}class Sf{constructor(){Ie(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const i=(...r)=>{this.off(t,i),n(...r)};return this.on(t,i)}off(t,n){const i=this.listeners[t];if(!i)return;const r=i.indexOf(n);r>-1&&i.splice(r,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const i=this.listeners[t];if(!i)return;const r=[...i];for(const s of r)try{s(...n)}catch(o){console.error(`Error in event listener for ${String(t)}:`,o)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class fw{constructor(t){Ie(this,"plugins",new Map);Ie(this,"installedPlugins",new Set);Ie(this,"context");this.context={client:t,emit:t.emit.bind(t),on:t.on.bind(t),config:{}}}register(t){if(this.plugins.has(t.name))throw new Error(`Plugin '${t.name}' is already registered`);if(t.dependencies){for(const n of t.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${t.name}' depends on '${n}' which is not registered`)}this.plugins.set(t.name,t)}async install(t,n){const i=this.plugins.get(t);if(!i)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(i.dependencies)for(const s of i.dependencies)this.installedPlugins.has(s)||await this.install(s);const r={...this.context,config:{...i.config,...n}};i.install&&await i.install(r),this.installedPlugins.add(t),this.setupPluginEvents(i,r)}async uninstall(t){var i;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[r,s]of this.plugins)if(this.installedPlugins.has(r)&&((i=s.dependencies)!=null&&i.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",i=>{t.onSessionStart(n,i.id)}),t.onSessionEnd&&n.on("session.ended",i=>{t.onSessionEnd(n,i.id)}),t.onAgentResponse&&n.on("agent.response",i=>{t.onAgentResponse(n,i)})}}function s4(e){return e}function wf(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async i=>{n.onActivate&&await n.onActivate(i)},uninstall:async i=>{n.onDeactivate&&await n.onDeactivate(i)},onAgentResponse:n.onMessage}}const o4={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async e=>{console.log("Analytics plugin installed"),e.on("session.started",t=>{console.log("Analytics: Session started",t.id)}),e.on("session.ended",(t,n)=>{console.log("Analytics: Session ended",t.id,n)}),e.on("chat.message.sent",t=>{console.log("Analytics: User message sent",t.content.length)})}},a4={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async e=>{console.log("Debug plugin installed");const t=e.emit;e.emit=(n,...i)=>(console.log(`[Debug] Event: ${String(n)}`,i),t(n,...i))}},c4={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async e=>{console.log("Metrics plugin installed");const t=new Map;e.on("session.started",n=>{t.set(n.id,{startTime:Date.now(),events:[]})}),e.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}};class pw extends Sf{constructor(n){super();Ie(this,"room",null);Ie(this,"registeredMethods",new Map);Ie(this,"activeInteractions",new Map);Ie(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,i,r="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const s={methodName:n,component:i,presentationMode:r};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{console.log(`RpcManager: RPC method '${n}' called by ${o.callerIdentity}`),console.log("RpcManager: Payload:",o.payload),this.emit("rpc.method.called",{methodName:n,data:o});let a;console.log(`RpcManager: Current registration for '${n}':`,s);let c=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const l=await this.awaitUserInteraction(n,i,r,a,c);return JSON.stringify(l)}catch(l){throw console.error(`RpcManager: Error in RPC method '${n}':`,l),l}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(o){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,o),o}}async awaitUserInteraction(n,i,r,s,o){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${o} seconds`);const u={didSuccess:(h,f)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...f?{successView:f}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(l);const f={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:f}),a(f)},dismissView:()=>{var f;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(f=this.currentInteraction)==null?void 0:f.methodName),this.clearInteraction(l),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(h)},didTimeout:h=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const f={success:!0,message:`User interaction timed out after ${o} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},o);this.activeInteractions.set(l,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:i,presentationMode:r,timeout:o,data:s,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,s)}catch(f){console.error("RpcManager: Error loading data into component:",f),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const i=this.activeInteractions.get(n);i&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(i.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,i]of this.activeInteractions)clearTimeout(i.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class tt extends Error{constructor(t,n,i){super(t),this.code=n,this.details=i,this.name="VoxketError"}}class mw{constructor(t,n="User"){Ie(this,"chatMessages",[]);Ie(this,"activeTranscriptions",new Map);Ie(this,"room",null);Ie(this,"eventEmitter");Ie(this,"participantName");this.eventEmitter=t,this.participantName=n}setRoom(t){this.room=t}setParticipantName(t){this.participantName=t}getChatMessages(){return[...this.chatMessages]}addChatMessage(t){this.chatMessages.some(i=>i.id===t.id)||this.chatMessages.push(t)}updateChatMessage(t){const n=this.chatMessages.findIndex(i=>i.id===t.id);n!==-1&&(this.chatMessages[n]=t)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear(),console.log("🧹 ChatManager: Cleared chat messages and transcription history")}trackTranscription(t,n){this.activeTranscriptions.set(t,{messageId:n,timestamp:Date.now()})}getActiveTranscription(t){const n=Date.now(),i=this.activeTranscriptions.get(t);return i&&n-i.timestamp<1e3?i:null}async sendMessage(t,n){if(!this.room)throw new tt("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new tt("No local participant","CONNECTION_FAILED");try{const i={id:`msg_${Date.now()}`,content:t,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:n||{}};await this.room.localParticipant.sendText(t,{topic:"lk.chat",destinationIdentities:[]}),this.eventEmitter.emit("chat.message.sent",i)}catch(i){throw console.error("ChatManager: Failed to send chat message:",i),new tt("Failed to send message","NETWORK_ERROR",i)}}async sendAttachments(t,n){if(!this.room)throw new tt("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new tt("No local participant","CONNECTION_FAILED");if(!t||t.length===0)throw new tt("No files provided","INVALID_PARAMETER");const i=t.filter(r=>r.type.startsWith("image/"));if(i.length===0)throw new tt("Only image files are allowed","INVALID_PARAMETER");i.length!==t.length&&console.warn("ChatManager: Some non-image files were filtered out");try{const r=i.map(async(s,o)=>{const c={id:`att_${Date.now()}_${o}`,content:`📎 ${s.name}`,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:{...n,type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.type,uploading:!0}};this.eventEmitter.emit("chat.message.sent",c);const l=await this.room.localParticipant.sendFile(s,{mimeType:s.type,topic:"images",onProgress:d=>{const h={...c,metadata:{...c.metadata,uploadProgress:d}};this.eventEmitter.emit("chat.message.updated",h)}});try{const d=new FileReader,h=new Promise((p,v)=>{d.onload=()=>{typeof d.result=="string"?p(d.result):v(new Error("Failed to convert to base64"))},d.onerror=v});d.readAsDataURL(s);const g={type:"image",data:await h,filename:s.name,mimeType:s.type,size:s.size};await this.room.localParticipant.sendText(JSON.stringify(g),{topic:"images",destinationIdentities:[]})}catch(d){console.warn("ChatManager: Failed to send image data to agent:",d);try{const h=`I've shared an image: ${s.name}`;await this.room.localParticipant.sendText(h,{topic:"lk.chat",destinationIdentities:[]})}catch(h){console.warn("ChatManager: Failed to send image notification to agent:",h)}}const u={...c,metadata:{...c.metadata,uploading:!1,uploadProgress:1,streamId:l.id}};return this.eventEmitter.emit("chat.message.updated",u),l});await Promise.all(r)}catch(r){throw console.error("ChatManager: Failed to send attachments:",r),new tt("Failed to send attachments","NETWORK_ERROR",r)}}async sendAttachment(t,n){return this.sendAttachments([t],n)}convertMarkdownToText(t){if(!t)return"";let n=t;return n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/__(.*?)__/g,"$1"),n=n.replace(/\*(.*?)\*/g,"$1"),n=n.replace(/_(.*?)_/g,"$1"),n=n.replace(/~~(.*?)~~/g,"$1"),n=n.replace(/`([^`]+)`/g,"$1"),n=n.replace(/```[\s\S]*?```/g,""),n=n.replace(/^#{1,6}\s+/gm,""),n=n.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),n.trim()}}class gw{constructor(t){Ie(this,"room",null);Ie(this,"eventEmitter");Ie(this,"silencePreventionNode",null);Ie(this,"silencePreventionOscillator",null);Ie(this,"audioContext",null);this.eventEmitter=t,this.initializeAudioContext()}initializeAudioContext(){try{if(this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("🔊 MediaManager: AudioContext created:",{state:this.audioContext.state,sampleRate:this.audioContext.sampleRate})),this.audioContext.state==="suspended"){console.log("🔊 MediaManager: AudioContext suspended, will resume on user interaction");const t=async()=>{this.audioContext&&this.audioContext.state==="suspended"&&(await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed:",this.audioContext.state)),document.removeEventListener("click",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",t)};document.addEventListener("click",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0})}else this.audioContext.state==="running"&&console.log("✅ MediaManager: AudioContext already running")}catch(t){console.error("MediaManager: Failed to initialize AudioContext:",t)}}async ensureAudioContextRunning(){if(this.audioContext||this.initializeAudioContext(),this.audioContext&&this.audioContext.state==="suspended"){console.log("🔊 MediaManager: Attempting to resume suspended AudioContext");try{await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed successfully")}catch(t){console.error("MediaManager: Failed to resume AudioContext:",t)}}}setRoom(t){this.room=t}getLocalParticipant(){var t;return((t=this.room)==null?void 0:t.localParticipant)??null}getRemoteParticipants(){var t;return Array.from(((t=this.room)==null?void 0:t.remoteParticipants.values())??[])}async toggleMicrophone(t){return this.setMicrophoneEnabled(t!==!1)}async setMicrophoneEnabled(t){var n,i,r;try{if(!this.room||this.room.state!=="connected")throw console.warn("⚠️ MediaManager: Cannot enable microphone - room not connected",{hasRoom:!!this.room,roomState:(n=this.room)==null?void 0:n.state}),new tt("Cannot enable microphone: room not connected","CONNECTION_FAILED");await this.ensureAudioContextRunning();const s=(i=this.room)==null?void 0:i.localParticipant.isMicrophoneEnabled,o=t??!s;o&&this.startSilencePrevention(),await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(o,{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})),o?this.eventEmitter.emit("track.unmuted",{source:"microphone",enabled:!0}):(this.eventEmitter.emit("track.muted",{source:"microphone",enabled:!1}),this.stopSilencePrevention()),console.log("🎤 MediaManager: Microphone",o?"enabled":"disabled")}catch(s){throw console.error("MediaManager: Failed to toggle microphone:",s),this.stopSilencePrevention(),new tt("Failed to toggle microphone","PERMISSION_DENIED",s)}}startSilencePrevention(){try{if(this.audioContext||(this.audioContext=new AudioContext),this.silencePreventionOscillator)return;console.log("🔇 MediaManager: Starting silence prevention"),this.silencePreventionOscillator=this.audioContext.createOscillator(),this.silencePreventionNode=this.audioContext.createGain(),this.silencePreventionOscillator.frequency.value=20,this.silencePreventionNode.gain.value=.001,this.silencePreventionOscillator.connect(this.silencePreventionNode),this.silencePreventionNode.connect(this.audioContext.destination),this.silencePreventionOscillator.start(),console.log("✅ MediaManager: Silence prevention started")}catch(t){console.error("❌ MediaManager: Failed to start silence prevention:",t)}}stopSilencePrevention(){try{this.silencePreventionOscillator&&(console.log("🔇 MediaManager: Stopping silence prevention"),this.silencePreventionOscillator.stop(),this.silencePreventionOscillator.disconnect(),this.silencePreventionOscillator=null),this.silencePreventionNode&&(this.silencePreventionNode.disconnect(),this.silencePreventionNode=null)}catch(t){console.error("❌ MediaManager: Failed to stop silence prevention:",t)}}async toggleCamera(t){return this.setCameraEnabled(t!==!1)}async setCameraEnabled(t){var n,i;try{const r=(n=this.room)==null?void 0:n.localParticipant.isCameraEnabled,s=t??!r;await((i=this.room)==null?void 0:i.localParticipant.setCameraEnabled(s)),s?this.eventEmitter.emit("track.unmuted",{source:"camera",enabled:!0}):this.eventEmitter.emit("track.muted",{source:"camera",enabled:!1})}catch(r){throw new tt("Failed to toggle camera","PERMISSION_DENIED",r)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!0)),this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0})}catch(n){throw new tt("Failed to start screen share","PERMISSION_DENIED",n)}}async stopScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!1)),this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1})}catch(n){throw new tt("Failed to stop screen share","PERMISSION_DENIED",n)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="audioinput")}catch(t){throw new tt("Failed to get audio input devices","DEVICE_ERROR",t)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch(t){throw new tt("Failed to get video input devices","DEVICE_ERROR",t)}}async setAudioInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){throw new tt("Failed to set audio input device","DEVICE_ERROR",i)}}async setVideoInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){throw new tt("Failed to set video input device","DEVICE_ERROR",i)}}getMicrophoneTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===B.Source.Microphone)return n.track;return null}getCameraTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===B.Source.Camera)return n.track;return null}getScreenShareTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===B.Source.ScreenShare)return n.track;return null}get isMicrophoneEnabled(){const t=this.getMicrophoneTrack();return t?!t.isMuted:!1}get isCameraEnabled(){const t=this.getCameraTrack();return t?!t.isMuted:!1}get isScreenShareEnabled(){const t=this.getScreenShareTrack();return t?!t.isMuted:!1}getAgentAudioTrack(){const t=this.getRemoteParticipants();console.log("🔊 MediaManager.getAgentAudioTrack: Checking remote participants:",{count:t.length,participants:t.map(n=>({identity:n.identity,name:n.name,hasMicTrack:!!n.getTrackPublication(B.Source.Microphone)}))});for(const n of t){const i=n.getTrackPublication(B.Source.Microphone);if(i!=null&&i.track)return console.log("✅ MediaManager.getAgentAudioTrack: Found audio track for",n.identity),{source:B.Source.Microphone,participant:n,publication:i}}return console.log("❌ MediaManager.getAgentAudioTrack: No audio track found"),null}getAgentVideoTrack(){const t=this.getRemoteParticipants();for(const n of t){const i=n.getTrackPublication(B.Source.Camera);if(i!=null&&i.track)return{source:B.Source.Camera,participant:n,publication:i}}return null}getVideoTrackRefs(){const t=[],n=this.getLocalParticipant();if(n){const r=n.getTrackPublication(B.Source.Camera);r!=null&&r.track&&t.push({source:B.Source.Camera,participant:n,publication:r});const s=n.getTrackPublication(B.Source.ScreenShare);s!=null&&s.track&&t.push({source:B.Source.ScreenShare,participant:n,publication:s})}const i=this.getRemoteParticipants();for(const r of i){const s=r.getTrackPublication(B.Source.Camera);s!=null&&s.track&&t.push({source:B.Source.Camera,participant:r,publication:s});const o=r.getTrackPublication(B.Source.ScreenShare);o!=null&&o.track&&t.push({source:B.Source.ScreenShare,participant:r,publication:o})}return t}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===B.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===B.Source.ScreenShare)}getPublishPermissions(){const t=this.getLocalParticipant();if(!t)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const n=t.permissions;if(!n)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const i=r=>!!n.canPublish&&(n.canPublishSources.length===0||n.canPublishSources.includes(r));return{camera:i(1),microphone:i(2),screenShare:i(3),data:n.canPublishData??!1}}canPublishSource(t){return this.getPublishPermissions()[t]}}class bw{constructor(t,n){Ie(this,"room",null);Ie(this,"config");Ie(this,"eventEmitter");Ie(this,"connectionState",$e.Disconnected);Ie(this,"isConnected",!1);Ie(this,"currentAgentInfo",null);this.config=t,this.eventEmitter=n,this.initializeRoom()}initializeRoom(){this.room=new vi({adaptiveStream:!1,stopLocalTrackOnUnpublish:!1,audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},publishDefaults:{stopMicTrackOnMute:!1,preConnectBuffer:!0}}),this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(j.Connected,()=>{this.connectionState=$e.Connected,this.isConnected=!0,console.log("📡 ConnectionManager: Emitting connection.connected event"),this.eventEmitter.emit("connection.connected")}),this.room.on(j.Disconnected,t=>{console.log("ConnectionManager: Room disconnected, reason:",t),this.connectionState=$e.Disconnected,this.isConnected=!1,t&&console.log("ConnectionManager: Disconnect reason details:",{reason:t.toString(),connectionState:this.connectionState}),this.eventEmitter.emit("connection.disconnected",t==null?void 0:t.toString())}),this.room.on(j.ConnectionStateChanged,t=>{this.connectionState=t,t===$e.Connecting&&this.eventEmitter.emit("connection.connecting")}),this.room.on(j.ParticipantConnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.joined",n)}),this.room.on(j.ParticipantDisconnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.left",n)}),this.room.on(j.LocalTrackPublished,t=>{console.log("ConnectionManager: Local track published:",t.source),t.source===B.Source.ScreenShare?this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0}):t.source===B.Source.Microphone&&(console.log("✅ ConnectionManager: Local MICROPHONE track RE-PUBLISHED at:",new Date().toISOString()),console.log(" Track restart complete - audio should resume"))}),this.room.on(j.LocalTrackUnpublished,t=>{console.log(" ConnectionManager: Local track unpublished:",t.source),t.source===B.Source.ScreenShare?this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1}):t.source===B.Source.Microphone&&(console.warn("⚠️ ConnectionManager: Local MICROPHONE track UNPUBLISHED at:",new Date().toISOString()),console.log(" ⚠️ WARNING: This will cause audio disruption!"))}),this.room.on(j.LocalAudioSilenceDetected,()=>{var t,n;console.log("🔇 ConnectionManager: Local audio silence detected at:",new Date().toISOString()),console.log(" Remote participants count:",(t=this.room)==null?void 0:t.remoteParticipants.size),(n=this.room)==null||n.remoteParticipants.forEach(i=>{console.log(" Remote participant:",i.identity,{audioTracks:i.audioTrackPublications.size,hasAudio:Array.from(i.audioTrackPublications.values()).some(r=>r.track)})})}),this.room.on(j.TrackSubscribed,(t,n,i)=>{var r,s;console.log("🎵 ConnectionManager: Track subscribed:",{trackKind:t.kind,trackSource:t.source,participantIdentity:i.identity,isAgent:(r=i.identity)==null?void 0:r.startsWith("agent-")}),this.eventEmitter.emit("media.track.subscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((s=t.source)==null?void 0:s.toString())||"unknown",participantId:i.identity,isEnabled:!t.isMuted,isMuted:t.isMuted})}),this.room.on(j.TrackUnsubscribed,(t,n,i)=>{var r;console.log("🔇 ConnectionManager: Track unsubscribed:",{trackKind:t.kind,participantIdentity:i.identity}),this.eventEmitter.emit("media.track.unsubscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((r=t.source)==null?void 0:r.toString())||"unknown",participantId:i.identity,isEnabled:!1,isMuted:!0})}))}async fetchConnectionDetails(t,n,i,r){try{const s={agent_id:t,participant_name:n,participant_metadata:r||{user_id:""},modality:i[0],modalities:i},o={accept:"application/json","Content-Type":"application/json"};if(this.config.authToken)o.Authorization=`Bearer ${this.config.authToken}`;else if(this.config.appId&&this.config.appSecret)o["X-APP-ID"]=this.config.appId,o["X-APP-SECRET"]=this.config.appSecret;else throw new Error("Either authToken or both appId and appSecret must be provided");const a=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok){let u=`HTTP ${a.status}: Failed to fetch connection details`;try{const d=await a.json();d&&(d.error?u=`API Error: ${d.error}`:d.detail?u=`API Error: ${d.detail}`:d.message&&(u=`API Error: ${d.message}`))}catch{try{const h=await a.text();h&&(u=`API Error: ${h}`)}catch{}}throw new Error(u)}const c=await a.json();let l;return c.agent_info&&(l={id:c.agent_info.agent_info.id,name:c.agent_info.agent_info.name,capabilities:c.agent_info.capabilities,modality_supported:c.agent_info.modality_supported,session_settings:c.agent_info.session_settings||{}},this.currentAgentInfo=l),{serverUrl:c.wss_url,participantToken:c.token,voxketSessionId:c.session_id,agentInfo:l}}catch(s){console.error("ConnectionManager: fetchConnectionDetails failed:",s);const o=new tt(`Failed to fetch connection details: ${s instanceof Error?s.message:"Unknown error"}`,"CONNECTION_FAILED",s);throw this.eventEmitter.emit("connection.error",o),o}}async connect(t,n,i,r){var s;try{this.eventEmitter.emit("connection.connecting");const o=await this.fetchConnectionDetails(t,n,i,r);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){console.error("ConnectionManager: Connection failed:",o);const a=new tt(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.eventEmitter.emit("connection.error",a),a}}async disconnect(){try{this.room&&await this.room.disconnect(),this.isConnected=!1,this.currentAgentInfo=null,this.initializeRoom(),this.eventEmitter.emit("connection.disconnected")}catch(t){console.error("ConnectionManager: Disconnect failed:",t);const n=new tt("Failed to disconnect properly","NETWORK_ERROR",t);throw this.eventEmitter.emit("connection.error",n),n}}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===$e.Connected}getCurrentAgentInfo(){return this.currentAgentInfo}getParticipants(){if(!this.room)return[];const t=[];return this.room.localParticipant&&t.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(n=>{t.push({id:n.identity,name:n.name||n.identity,isLocal:!1})}),t}updateConfig(t){this.config={...this.config,...t}}}class yw{constructor(t,n,i){Ie(this,"room",null);Ie(this,"eventEmitter");Ie(this,"chatManager");Ie(this,"agentManager");Ie(this,"textStreamHandlersRegistered",!1);Ie(this,"_eventEmitters",new Map);this.eventEmitter=t,this.chatManager=n,this.agentManager=i}setRoom(t){this.room=t,t&&!this.textStreamHandlersRegistered&&(console.log("📡 StreamHandlerManager: Auto-registering handlers on room set"),this.setupTextStreamHandlers())}areHandlersRegistered(){return this.textStreamHandlersRegistered}resetHandlersFlag(){this.textStreamHandlersRegistered=!1}setupTextStreamHandlers(){this.room&&(this.registerChatHandler(),this.registerTranscriptionHandler(),this.registerSuggestedResponseHandler(),this.registerAgentStateHandler(),this.registerFunctionToolsHandler(),this.registerImageTextStreamHandler(),this.registerImageByteStreamHandler(),this.registerCommonTopicHandlers(),this.registerWildcardHandler(),this.textStreamHandlersRegistered=!0)}registerChatHandler(){try{this.room.registerTextStreamHandler("lk.chat",async(t,n)=>{try{const i=await t.readAll(),r={id:`msg_${Date.now()}_${n.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:i,timestamp:new Date,sender:{id:n.identity||"user",name:n.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.eventEmitter.emit("chat.message.received",r)}catch(i){console.error("StreamHandlerManager: Failed to process lk.chat message:",i)}})}catch(t){console.warn("StreamHandlerManager: lk.chat handler already registered, skipping:",t)}}registerTranscriptionHandler(){try{console.log("📡 StreamHandlerManager: Registering lk.transcription handler"),this.room.registerTextStreamHandler("lk.transcription",async(t,n)=>{var i,r;console.log("💬 StreamHandlerManager: Received lk.transcription stream from:",n.identity);try{const s=n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity),o=n.identity,a=this.chatManager.getActiveTranscription(o);let c,l=!0;a?(c=a.messageId,l=!1):(c=`msg_${s?"user":"agent"}_${n.identity}_${Date.now()}`,this.chatManager.trackTranscription(o,c));let u="";const d=this.agentManager.getCurrentAgentInfo(),h=(d==null?void 0:d.name)||n.identity||"AI Assistant",f=s?"participant":"agent",g=s?"User":h,p={id:c,content:"",timestamp:new Date,sender:{id:n.identity||"unknown",name:g,type:f},metadata:{topic:"lk.transcription",streaming:!0}};l&&this.eventEmitter.emit("chat.message.received",p);for await(const S of t){u+=S;const k=this.chatManager.convertMarkdownToText(u),x={...p,content:k,metadata:{...p.metadata,streaming:!0}};this.eventEmitter.emit("chat.message.updated",x)}const v=this.chatManager.convertMarkdownToText(u),b={...p,content:v,metadata:{...p.metadata,streaming:!1}};this.eventEmitter.emit("chat.message.updated",b);const w={id:c,text:v,isFinal:!0,startTime:p.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",w)}catch(s){console.error("StreamHandlerManager: Failed to process lk.transcription message:",s);try{const o=await t.readAll(),a=this.agentManager.getCurrentAgentInfo(),c=(a==null?void 0:a.name)||n.identity||"AI Assistant",l={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:o,timestamp:new Date,sender:{id:n.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription"}};this.eventEmitter.emit("chat.message.received",l),console.log("💬 StreamHandlerManager: Emitted chat.message.received:",{id:l.id,sender:l.sender.name,contentLength:l.content.length,preview:l.content.substring(0,50)});const u={id:l.id,text:l.content,isFinal:!0,startTime:l.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",u),console.log("📝 StreamHandlerManager: Emitted transcription.received:",{id:u.id,textLength:u.text.length})}catch(o){console.error("StreamHandlerManager: Fallback failed for lk.transcription:",o)}}})}catch(t){console.warn("StreamHandlerManager: lk.transcription handler already registered, skipping:",t)}}registerSuggestedResponseHandler(){try{this.room.registerTextStreamHandler("suggested_response",async t=>{const n=await t.readAll();let i=[];try{i=["tes","hello how are you","algebra make me learn that","what is the meaning of life"]}catch(r){console.warn("StreamHandlerManager: Failed to parse suggested_response:",r,n)}this.eventEmitter.emit("suggested.response",i)})}catch(t){console.warn("StreamHandlerManager: suggested_response handler already registered, skipping:",t)}}registerAgentStateHandler(){try{this.room.registerTextStreamHandler("agent_state_changed",async(t,n)=>{const i=await t.readAll();let r={};try{r=typeof i=="string"?JSON.parse(i.replace(/'/g,'"')):i}catch(s){console.warn("StreamHandlerManager: Failed to parse agent_state_changed:",s,i)}this.agentManager.handleAgentStateChanged(r)})}catch(t){console.warn("StreamHandlerManager: agent_state_changed handler already registered, skipping:",t)}}registerFunctionToolsHandler(){try{this.room.registerTextStreamHandler("function_tools_executed",async(t,n)=>{const i=await t.readAll();let r={};try{if(typeof i=="string")try{r=JSON.parse(i)}catch(s){let o=i;try{o=o.replace(/\bTrue\b/g,"true"),o=o.replace(/\bFalse\b/g,"false"),o=o.replace(/\bNone\b/g,"null");const a=o.replace(/\\"/g,"___ESCAPED_QUOTE___");let c="",l=!1;for(let u=0;u<a.length;u++){const d=a[u],h=u>0?a[u-1]:"";d==='"'&&h!=="\\"?(l=!l,c+=d):d==="'"&&h!=="\\"&&!l?c+='"':c+=d}o=c.replace(/___ESCAPED_QUOTE___/g,'\\"'),r=JSON.parse(o)}catch(a){console.warn("StreamHandlerManager: Enhanced parsing also failed:",a);try{let c=i.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null");r=new Function("return "+c)()}catch(c){throw console.error("StreamHandlerManager: All parsing methods failed:",c),s}}}else r=i}catch(s){console.warn("StreamHandlerManager: Failed to parse function_tool_executed:",s,i);let o=null;if(typeof i=="string"&&i.includes("visualization_data"))try{const a=i.match(/"arguments":\s*"({.*?})"/);if(a){const c=a[1].replace(/\\"/g,'"');o=JSON.parse(c),console.log("🛠️ StreamHandlerManager: Extracted visualization data:",o)}}catch(a){console.warn("StreamHandlerManager: Failed to extract visualization data:",a)}r={type:"function_tools_executed",function_calls:[],function_call_outputs:[],created_at:Date.now()/1e3,parseError:!0,rawData:i,extractedVisualizationData:o}}this.eventEmitter.emit("tool.executed",r)})}catch(t){console.warn("StreamHandlerManager: function_tool_executed handler already registered, skipping:",t)}}registerImageTextStreamHandler(){try{this.room.registerTextStreamHandler("images",async(t,n)=>{try{const i=await t.readAll()}catch(i){console.error("StreamHandlerManager: Error processing images stream:",i)}})}catch(t){console.warn("StreamHandlerManager: images text handler already registered, skipping:",t)}}registerImageByteStreamHandler(){try{this.room.registerByteStreamHandler("images",async(t,n)=>{var i,r;try{const s=t.info,o={id:`img_${Date.now()}_${n.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`🖼️ ${s.name||"Image"}`,sender:{id:n.identity||"agent",name:n.identity||"Agent",type:n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.mimeType,streamId:s.id,downloading:!0}};this.eventEmitter.emit("chat.message.received",o),t.onProgress&&(t.onProgress=d=>{const h={...o,metadata:{...o.metadata,downloadProgress:d||0}};this.eventEmitter.emit("chat.message.updated",h)});const a=[];for await(const d of t)a.push(d);const c=new Blob(a,{type:s.mimeType||"application/octet-stream"}),l=URL.createObjectURL(c),u={...o,metadata:{...o.metadata,downloading:!1,downloadProgress:1,downloadUrl:l,blob:c}};this.eventEmitter.emit("chat.message.updated",u)}catch(s){console.error("StreamHandlerManager: Error processing image attachment:",s)}})}catch(t){console.warn("StreamHandlerManager: image byte handler already registered, skipping:",t)}}registerCommonTopicHandlers(){["error","warning","status","system","debug","info"].forEach(n=>{try{this.room.registerTextStreamHandler(n,async(i,r)=>{try{const s=await i.readAll();if(console.log(`📝 StreamHandlerManager: Received '${n}' stream:`,s),n==="error"){let o={};try{o=typeof s=="string"?JSON.parse(s):s}catch{o={message:s}}console.warn("⚠️ StreamHandlerManager: Agent error:",o),this.eventEmitter.emit("agent.error",o)}else this.eventEmitter.emit("text.stream.received",{topic:n,data:s,participantInfo:r})}catch(s){console.error(`StreamHandlerManager: Failed to process '${n}' stream:`,s)}})}catch(i){console.warn(`StreamHandlerManager: Handler for '${n}' already registered, skipping:`,i)}})}registerWildcardHandler(){try{this.room.registerTextStreamHandler("*",async(t,n)=>{var i;try{const r=await t.readAll(),s=((i=t.info)==null?void 0:i.topic)||"unknown";if(this._eventEmitters.has(s)){const o=this._eventEmitters.get(s);try{o(r),console.log(`📝 StreamHandlerManager: Processed custom topic '${s}' via event emitter`)}catch(a){console.error(`StreamHandlerManager: Error in custom handler for topic '${s}':`,a)}}else console.log(`📝 StreamHandlerManager: Received unhandled text stream for topic '${s}':`,r),this.eventEmitter.emit("text.stream.unhandled",{topic:s,data:r,participantInfo:n})}catch(r){console.error("StreamHandlerManager: Failed to process unhandled text stream:",r)}})}catch(t){console.warn("StreamHandlerManager: Generic text stream handler already registered, skipping:",t)}}registerEventEmitter(t,n){if(!this.room)throw new Error("Room not available");this._eventEmitters.set(t,n),console.log(`📝 StreamHandlerManager: Stored handler for topic '${t}' in event emitters map`);try{this.room.registerTextStreamHandler(t,async i=>{try{const r=await i.readAll();console.log(`📝 StreamHandlerManager: Direct handler called for topic '${t}'`),n(r)}catch(r){console.error(`Error processing event for topic '${t}':`,r)}}),console.log(`📝 StreamHandlerManager: Successfully registered direct handler for topic '${t}'`)}catch(i){console.warn(`StreamHandlerManager: Direct handler registration failed for topic '${t}':`,i),console.log(`📝 StreamHandlerManager: Wildcard handler will process topic '${t}' instead`)}}getRegisteredEventEmitters(){return Array.from(this._eventEmitters.keys())}hasEventEmitter(t){return this._eventEmitters.has(t)}}const vw=O.createContext(null);function Pa({config:e,children:t,autoConnect:n=!1,client:i}){const[r,s]=O.useState(null),[o,a]=O.useState(!1),[c,l]=O.useState(!1),[u,d]=O.useState(null),[h,f]=O.useState(null),[g,p]=O.useState("idle"),[v,b]=O.useState(null),[w,S]=O.useState([]),[k,x]=O.useState([]),[T,P]=O.useState([]);O.useEffect(()=>{const H=i||new Po(e);s(H);const C=A(H);return n&&!i&&N(H),()=>{C(),i||H.disconnect().catch(console.error)}},[e,n,i]);const A=H=>{const C=()=>{l(!0),d(null)},W=()=>{a(!0),l(!1),d(null)},Y=()=>{a(!1),l(!1),f(null),p("idle"),S([]),x([]),P([])},E=de=>{d(de),l(!1)},J=de=>{f(de),p(de.state)},ne=de=>{p(de),h&&f({...h,state:de})},ie=(de,Pe)=>{f(null),p("idle"),b(Pe),S([]),x([]),P([])},re=de=>{S(Pe=>[...Pe,de])},X=de=>{S(Pe=>Pe.filter(ke=>ke.id!==de.id))},le=de=>{x(Pe=>[...Pe,de])},Z=de=>{x(Pe=>[...Pe,de])},Ae=de=>{console.log("📝 VoxketProvider: Received transcription:",de),P(Pe=>Pe.find(pe=>pe.id===de.id)?(console.log("📝 VoxketProvider: Duplicate transcription detected, skipping:",de.id),Pe):(console.log("📝 VoxketProvider: Adding new transcription:",de.id),[...Pe,de]))},F=()=>{console.log("🧹 VoxketProvider: Clearing chat messages and transcriptions"),x([]),P([])};return H.on("connection.connecting",C),H.on("connection.connected",W),H.on("connection.disconnected",Y),H.on("connection.error",E),H.on("session.created",J),H.on("session.state.changed",ne),H.on("session.ended",ie),H.on("participant.joined",re),H.on("participant.left",X),H.on("chat.message.received",le),H.on("chat.message.sent",Z),H.on("transcription.received",Ae),H.on("chat.history.cleared",F),()=>{console.log("📝 VoxketProvider: Cleaning up event listeners"),H.off("connection.connecting",C),H.off("connection.connected",W),H.off("connection.disconnected",Y),H.off("connection.error",E),H.off("session.created",J),H.off("session.state.changed",ne),H.off("session.ended",ie),H.off("participant.joined",re),H.off("participant.left",X),H.off("chat.message.received",le),H.off("chat.message.sent",Z),H.off("chat.history.cleared",F),H.off("transcription.received",Ae)}},N=async H=>{const C=H||r;if(C)try{await C.connect()}catch(W){console.error("Failed to connect:",W)}},z={client:r,isConnected:o,isConnecting:c,connectionError:u,currentSession:h,sessionState:g,sessionMetrics:v,participants:w,chatMessages:k,transcriptions:T,connect:()=>N(),disconnect:async()=>{if(r)try{await r.disconnect()}catch(H){console.error("Failed to disconnect:",H)}},createSession:async(H,C={})=>{if(!r)throw new Error("Client not initialized");const W={agentId:H,participantName:C.participantName||"User",metadata:C.metadata,modalities:C.modalities||["voice"]};return await r.createSession(W)},endSession:async()=>r?await r.endSession():null,sendChatMessage:async H=>{if(!r)throw new Error("Client not initialized");await r.sendChatMessage(H)},setMicrophoneEnabled:async H=>{if(!r)throw new Error("Client not initialized");await r.setMicrophoneEnabled(H)},setCameraEnabled:async H=>{if(!r)throw new Error("Client not initialized");await r.setCameraEnabled(H)},startScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.startScreenShare()},stopScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.stopScreenShare()}};return m.jsx(vw.Provider,{value:z,children:t})}function si(){const e=O.useContext(vw);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const Mi=new WeakSet,du=new WeakSet;class xw{constructor(t,n){Ie(this,"renderedComponents",new Map);Ie(this,"config");Ie(this,"voxketClient");this.config=t,this.voxketClient=n}renderUI(t={}){const n=this.resolveTarget(t.target||"body"),i=this.getTargetKey(n);if(du.has(n)){console.warn("⚠️ UIRenderer: Target is already being processed, skipping renderUI");return}if(Mi.has(n)){console.log("✋ UIRenderer: Target already has a React root in registry, updating existing props...");const s=this.renderedComponents.get(i);if(s&&s.root){const o=this.buildWidgetProps(t);try{s.root.render(O.createElement(Pa,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:O.createElement(Na,o)})),console.log("✅ UIRenderer: Successfully updated existing widget with new props");return}catch(a){throw console.error("Error re-rendering existing widget:",a),new Error(`Failed to update existing widget: ${a instanceof Error?a.message:"Unknown error"}`)}}else console.warn("⚠️ Registry inconsistency detected, cleaning up"),Mi.delete(n)}let r=this.renderedComponents.get(i);if(r&&r.target===n&&Mi.has(n)){console.log("🔄 UIRenderer: Reusing existing React root for target:",i);const s=r.root,o=this.buildWidgetProps(t);try{s.render(O.createElement(Pa,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:O.createElement(Na,o)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}return}du.add(n);try{if(r){console.log("🧹 UIRenderer: Cleaning up existing component for different target");try{r.root.unmount(),this.renderedComponents.delete(i),Mi.delete(r.target),n.innerHTML=""}catch(a){console.warn("Failed to cleanup existing root:",a)}}if(Mi.has(n)){console.warn("⚠️ UIRenderer: Target already in registry, skipping root creation");return}console.log("🆕 UIRenderer: Creating new React root for target:",i);const s=iT.createRoot(n);this.renderedComponents.set(i,{root:s,target:n}),Mi.add(n);const o=this.buildWidgetProps(t);if(!s||typeof s.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{s.render(O.createElement(Pa,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:O.createElement(Na,o)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}}finally{du.delete(n)}}removeUI(t){const n=t?this.resolveTarget(t):null;if(n){const i=this.getTargetKey(n),r=this.renderedComponents.get(i);if(r){console.log("🗑️ UIRenderer: Removing UI for target:",i),this.renderedComponents.delete(i);const s=r.target,o=()=>{var a;try{s&&s.isConnected?typeof((a=r.root)==null?void 0:a.unmount)=="function"&&(r.root.unmount(),console.log("✅ UIRenderer: UI unmounted for target:",i)):console.log("ℹ️ UIRenderer: Target element already disconnected, skipping unmount")}catch(c){console.warn("Failed to unmount React root:",c)}finally{requestAnimationFrame(()=>{try{n.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(l=>{try{l.parentNode&&l.remove()}catch(u){console.warn("Failed to remove element:",u)}})}finally{Mi.delete(n)}})}};queueMicrotask(()=>setTimeout(o,0))}else console.log("ℹ️ UIRenderer: No component found for target, cleaning registry:",i),Mi.delete(n),n.isConnected&&n.hasChildNodes()&&(n.innerHTML="");n===document.body&&n.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(o=>{if(o.classList.contains("bg-black")&&(o.classList.contains("backdrop-blur-sm")||o.classList.contains("bg-opacity-30")))try{o.remove()}catch(a){console.warn("Failed to remove fixed element:",a)}})}}removeAllUI(){for(const[t,n]of this.renderedComponents)n.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(n=>{if(n.classList.contains("bg-black")&&(n.classList.contains("backdrop-blur-sm")||n.classList.contains("bg-opacity-30")))try{n.remove()}catch(i){console.warn("Failed to remove overlay:",i)}})}resolveTarget(t){if(typeof t=="string"){const n=document.querySelector(t);if(!n)throw new Error(`Target element not found: ${t}`);return n}return t}getTargetKey(t){return t.id?t.id:t.className?t.tagName+"_"+t.className.replace(/\s+/g,"_"):t.tagName+"_"+t.outerHTML.length%1e3}buildWidgetProps(t){var i,r,s;const n=this.config;return{agentId:t.agentId||n.agentId||"default-agent",participantName:t.participantName||n.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:t.className,theme:typeof t.theme=="string"?t.theme:void 0,modalities:t.modality||n.modalities||["voice"],suportsChatInput:((i=t.modality)==null?void 0:i.includes("chat"))!==!1,suportsVideoInput:((r=t.modality)==null?void 0:r.includes("video"))===!0,suportsScreenShare:((s=t.modality)==null?void 0:s.includes("screen_share"))===!0,autoStart:t.autoStart,displayType:t.displayType||"widget",popupPosition:t.popupPosition||"bottom-right",popupTriggerText:t.popupTriggerText||"Open Chat",popupModalityMode:t.popupModalityMode||"all",width:t.width,height:t.height,onDisplayTypeChange:t.onDisplayTypeChange,prompts:t.prompts,statusMessage:t.statusMessage,welcomeTitle:t.welcomeTitle,welcomeSubTitle:t.welcomeSubTitle,loadingText:t.loadingText,voxketClient:this.voxketClient,participantMetadata:t.participantMetadata}}updateConfig(t){this.config=t}}class kw{constructor(t){Ie(this,"agentState","idle");Ie(this,"isAgentConnected",!1);Ie(this,"currentAgentInfo",null);Ie(this,"eventEmitter");this.eventEmitter=t}getAgentState(){return this.agentState}setAgentState(t){this.agentState!==t&&(this.agentState=t,this.eventEmitter.emit("agent.state.changed",{state:t}))}getIsAgentConnected(){return this.isAgentConnected}setAgentConnected(t){this.isAgentConnected=t,console.log(t?"🤖 AgentManager: Agent marked as connected":"🤖 AgentManager: Agent marked as disconnected")}getCurrentAgentInfo(){return this.currentAgentInfo}setCurrentAgentInfo(t){this.currentAgentInfo=t,console.log("📝 AgentManager: Agent info updated:",t)}reset(){this.agentState="idle",this.isAgentConnected=!1,this.currentAgentInfo=null,console.log("🔄 AgentManager: Agent state reset")}handleAgentStateChanged(t){this.isAgentConnected||(this.setAgentConnected(!0),this.eventEmitter.emit("agent.connected",t)),t.new_state==="speaking"?(this.setAgentState("speaking"),this.eventEmitter.emit("agent.speaking",t)):t.new_state==="thinking"?(this.setAgentState("thinking"),this.eventEmitter.emit("agent.thinking",t)):(t.new_state==="idle"||t.new_state==="listening")&&this.setAgentState("idle")}}class Po extends Sf{constructor(n){super();Ie(this,"config");Ie(this,"pluginManager");Ie(this,"rpcManager");Ie(this,"chatManager");Ie(this,"mediaManager");Ie(this,"connectionManager");Ie(this,"streamHandlerManager");Ie(this,"uiRenderer");Ie(this,"agentManager");Ie(this,"currentSession",null);if(!n.authToken&&(!n.appId||!n.appSecret))throw new Error("Either authToken or both appId and appSecret must be provided");this.config=n,this.chatManager=new mw(this,n.participantName||"User"),this.mediaManager=new gw(this),this.agentManager=new kw(this),this.connectionManager=new bw({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret,authToken:n.authToken},this),this.streamHandlerManager=new yw(this,this.chatManager,this.agentManager),this.uiRenderer=new xw(n,this),this.pluginManager=new fw(this),this.rpcManager=new pw,this.setupEventListeners(),this.setupRpcEventForwarding()}setupEventListeners(){this.on("connection.connected",()=>{var i,r,s,o,a,c,l;if(console.log("🔌 VoxketClient: connection.connected event fired",{hasSession:!!this.currentSession,sessionState:(i=this.currentSession)==null?void 0:i.state,sessionId:(r=this.currentSession)==null?void 0:r.id}),(o=(s=this.config).onConnected)==null||o.call(s),this.currentSession&&this.currentSession.state==="connecting"){const u=this.currentSession.state;this.currentSession.state="connected",this.emit("session.state.changed","connected",u),console.log("✅ VoxketClient: Session state changed to connected")}else console.log("⚠️ VoxketClient: Cannot update session state",{hasSession:!!this.currentSession,currentState:(a=this.currentSession)==null?void 0:a.state});const n=this.connectionManager.getRoom();if(n){this.rpcManager.setRoom(n);const u=Array.from(n.remoteParticipants.values()).find(d=>{var h;return(h=d.identity)==null?void 0:h.startsWith("agent-")});u&&(console.log("🤖 VoxketClient: Agent already in room, marking as connected",{agentIdentity:u.identity,hasAudioTrack:u.audioTrackPublications.size>0}),this.agentManager.getIsAgentConnected()||(this.agentManager.setAgentConnected(!0),this.emit("agent.connected",{identity:u.identity})))}(l=(c=this.currentSession)==null?void 0:c.activeModalities)!=null&&l.includes("voice")&&setTimeout(async()=>{try{this.mediaManager.getLocalParticipant()&&(this.mediaManager.isMicrophoneEnabled||(await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled after connection")))}catch(u){console.warn("VoxketClient: Failed to enable microphone after room connection:",u)}},100)}),this.on("connection.disconnected",n=>{var i,r,s;(r=(i=this.config).onDisconnected)==null||r.call(i,n),this.streamHandlerManager.resetHandlersFlag(),this.agentManager.reset(),this.chatManager.clearChatMessages(),n&&console.log("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(s=this.currentSession)==null?void 0:s.id})}),this.on("connection.error",n=>{var i,r;(r=(i=this.config).onError)==null||r.call(i,n)}),this.on("chat.message.received",n=>{var i,r;this.chatManager.addChatMessage(n),(r=(i=this.config).onMessageReceived)==null||r.call(i,n)}),this.on("chat.message.updated",n=>{this.chatManager.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.chatManager.addChatMessage(n)}),this.on("transcription.received",n=>{var i,r;(r=(i=this.config).onTranscriptionReceived)==null||r.call(i,n)}),this.on("session.state.changed",n=>{var i,r;(r=(i=this.config).onSessionStateChanged)==null||r.call(i,n)}),this.on("session.created",n=>{var i,r;(r=(i=this.config).onSessionStart)==null||r.call(i,n.id)}),this.on("session.ended",(n,i)=>{var r,s;(s=(r=this.config).onSessionEnd)==null||s.call(r,i)}),this.on("participant.joined",n=>{var i,r;(r=(i=this.config).onUserJoined)==null||r.call(i,n.id)}),this.on("participant.left",n=>{var i,r;(r=(i=this.config).onUserLeft)==null||r.call(i,n.id)})}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}async connect(n,i,r,s){const o=n||this.config.agentId||"default-agent",a=i||this.config.participantName||"User",c=r||this.config.modalities||["voice"],l=s||this.config.participantMetadata,u=await this.connectionManager.connect(o,a,c,l),d=this.connectionManager.getRoom();return this.chatManager.setRoom(d),this.mediaManager.setRoom(d),this.streamHandlerManager.setRoom(d),u.agentInfo&&this.agentManager.setCurrentAgentInfo(u.agentInfo),u}async disconnect(){await this.connectionManager.disconnect(),this.currentSession=null;const n=this.connectionManager.getRoom();this.chatManager.setRoom(n),this.mediaManager.setRoom(n),this.streamHandlerManager.setRoom(n)}async createSession(n){var i,r;try{const s=await this.connect(n.agentId,n.participantName,n.modalities,n.participantMetadata),o={id:s.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:s.agentInfo||this.agentManager.getCurrentAgentInfo()};this.currentSession=o,this.emit("session.created",o);const a=this.connectionManager.getRoom();if(a&&(a.state!=="connected"?(console.log("⏳ VoxketClient: Waiting for room to connect..."),await new Promise((l,u)=>{const d=setTimeout(()=>{u(new Error("Room connection timeout"))},1e4),h=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),console.log("✅ VoxketClient: Room connected successfully"),l()},f=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),u(new Error("Room disconnected while waiting for connection"))};a.once("connected",h),a.once("disconnected",f)})):console.log("✅ VoxketClient: Room already connected"),this.currentSession.state="connected",this.emit("session.state.changed","connected","connecting"),console.log("⏳ VoxketClient: Waiting for agent to connect..."),await new Promise(l=>{const u=setTimeout(()=>{console.warn("⚠️ VoxketClient: Agent connection timeout (30s), continuing anyway"),l(!1)},3e4),d=()=>{clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),console.log("✅ VoxketClient: Agent connected and ready"),l(!0)},h=f=>{var g,p;((g=f.id)!=null&&g.startsWith("agent-")||(p=f.name)!=null&&p.toLowerCase().includes("agent"))&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),console.log("✅ VoxketClient: Agent participant joined:",f.name||f.id),l(!0))};this.once("agent.connected",d),this.on("participant.joined",h),this.agentManager.getIsAgentConnected()&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),console.log("✅ VoxketClient: Agent already connected"),l(!0))})&&(this.currentSession.state="active",this.emit("session.state.changed","active","connected"))),(i=n.modalities)!=null&&i.includes("voice"))try{await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled successfully")}catch(c){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",c)}if((r=n.modalities)!=null&&r.includes("video"))try{await new Promise(c=>setTimeout(c,200)),await this.mediaManager.enableCamera(),console.log("🎥 VoxketClient: Camera enabled successfully")}catch(c){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",c)}return o}catch(s){throw console.error("VoxketClient: Failed to create session:",s),s instanceof tt?s:s instanceof TypeError&&s.message.includes("fetch")?new tt("Network connection failed","CONNECTION_FAILED",s):s instanceof Error&&s.message.includes("Failed to fetch connection details")?new tt(`API connection failed: ${s.message}`,"CONNECTION_FAILED",s):new tt(`Failed to create session: ${s instanceof Error?s.message:"Unknown error"}`,"SESSION_NOT_FOUND",s)}}async startSession(n,i){const r={agentId:n||this.config.agentId||"default-agent",participantName:(i==null?void 0:i.participantName)||this.config.participantName||"User",modalities:(i==null?void 0:i.modalities)||this.config.modalities||["voice","chat"],metadata:i==null?void 0:i.metadata,participantMetadata:i==null?void 0:i.participantMetadata};return this.createSession(r)}async endSession(){var n,i;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw new tt("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getSessionMetrics(){var n,i;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}async sendMessage(n,i){if(!this.currentSession)throw new tt("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendMessage(n,i)}async sendChatMessage(n,i){return this.sendMessage(n,i)}async sendAttachments(n,i){if(!this.currentSession)throw new tt("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendAttachments(n,i)}async sendAttachment(n,i){return this.chatManager.sendAttachment(n,i)}getChatMessages(){return this.chatManager.getChatMessages()}addChatMessage(n){this.chatManager.addChatMessage(n)}updateChatMessage(n){this.chatManager.updateChatMessage(n)}clearChatMessages(){this.chatManager.clearChatMessages(),this.dismissCurrentInteraction(),this.uiRenderer.removeAllUI()}toggleMicrophone(n){return this.mediaManager.toggleMicrophone(n)}async setMicrophoneEnabled(n){return this.mediaManager.setMicrophoneEnabled(n)}toggleCamera(n){return this.mediaManager.toggleCamera(n)}async setCameraEnabled(n){return this.mediaManager.setCameraEnabled(n)}async enableCamera(){return this.mediaManager.enableCamera()}async disableCamera(){return this.mediaManager.disableCamera()}async startScreenShare(){return this.mediaManager.startScreenShare()}async stopScreenShare(){return this.mediaManager.stopScreenShare()}async getAudioInputDevices(){return this.mediaManager.getAudioInputDevices()}async getVideoInputDevices(){return this.mediaManager.getVideoInputDevices()}async setAudioInputDevice(n){return this.mediaManager.setAudioInputDevice(n)}async setVideoInputDevice(n){return this.mediaManager.setVideoInputDevice(n)}get isMicrophoneEnabled(){return this.mediaManager.isMicrophoneEnabled}get isCameraEnabled(){return this.mediaManager.isCameraEnabled}get isScreenShareEnabled(){return this.mediaManager.isScreenShareEnabled}getMicrophoneTrack(){return this.mediaManager.getMicrophoneTrack()}getCameraTrack(){return this.mediaManager.getCameraTrack()}getScreenShareTrack(){return this.mediaManager.getScreenShareTrack()}getAgentAudioTrack(){return this.mediaManager.getAgentAudioTrack()}getAgentVideoTrack(){return this.mediaManager.getAgentVideoTrack()}getVideoTrackRefs(){return this.mediaManager.getVideoTrackRefs()}getCameraTrackRefs(){return this.mediaManager.getCameraTrackRefs()}getScreenShareTrackRefs(){return this.mediaManager.getScreenShareTrackRefs()}getPublishPermissions(){return this.mediaManager.getPublishPermissions()}canPublishSource(n){return this.mediaManager.canPublishSource(n)}getLocalParticipant(){return this.mediaManager.getLocalParticipant()}getRemoteParticipants(){return this.mediaManager.getRemoteParticipants()}getParticipants(){return this.connectionManager.getParticipants()}getRoom(){return this.connectionManager.getRoom()}getConnectionState(){return this.connectionManager.getConnectionState()}get connected(){return this.connectionManager.connected}getCurrentAgentInfo(){return this.agentManager.getCurrentAgentInfo()}getIsAgentConnected(){return this.agentManager.getIsAgentConnected()}getAgentState(){return this.agentManager.getAgentState()}renderUI(n={}){this.uiRenderer.renderUI(n)}removeUI(n){this.uiRenderer.removeUI(n)}removeAllUI(){this.uiRenderer.removeAllUI()}async registerFrontendRPC(n,i,r="embedded"){return this.rpcManager.registerFrontendRPC(n,i,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}registerEventListener(n,i){return this.on(n,i)}registerEventEmitter(n,i){return this.streamHandlerManager.registerEventEmitter(n,i)}getRegisteredEventEmitters(){return this.streamHandlerManager.getRegisteredEventEmitters()}hasEventEmitter(n){return this.streamHandlerManager.hasEventEmitter(n)}updateConfig(n){this.config={...this.config,...n},this.uiRenderer.updateConfig(this.config),this.connectionManager.updateConfig({baseUrl:this.config.baseUrl,appId:this.config.appId,appSecret:this.config.appSecret}),this.chatManager.setParticipantName(this.config.participantName||"User")}setParticipantMetadata(n){this.config.participantMetadata=n}getParticipantMetadata(){return this.config.participantMetadata}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new tt("Failed to start recording","RECORDING_ERROR",i)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new tt("Failed to stop recording","RECORDING_ERROR",i)}}}const l4=Fe.create(WS),u4=Fe.create(df),d4=Fe.create(qS),h4=Fe.create(uw);function f4({theme:e,mode:t,loadingText:n,sessionState:i}){const r=on(e),s=()=>{if(i==="connected")return"Connecting to agent...";if(n)return n;switch(t){case"voice":return"Connecting to voice agent...";case"chat":return"Starting chat session...";case"video":return"Connecting to video call...";default:return"Connecting..."}};return m.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[m.jsxs("div",{className:"text-center",children:[m.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:s()}),m.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),m.jsxs("div",{className:"flex space-x-1 mt-4",children:[m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}const p4=Fe.create(f4);function Qb({children:e,theme:t,displayType:n="widget",onClose:i,popupPosition:r="bottom-right",onExpand:s}){const o=on(t);if(n==="fullscreen")return m.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:a=>{a.target===a.currentTarget&&i&&i()},children:m.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:a=>{a.stopPropagation()},children:[i&&m.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),i()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:m.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,"data-theme":t,style:{minHeight:"600px",height:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return m.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:m.jsxs("div",{className:`fixed rounded-2xl ${a[r]} pointer-events-auto`,children:[i&&m.jsx("button",{onClick:i,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"×"}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} relative overflow-hidden w-full h-full`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})}function m4(e){if(typeof window>"u")return null;const{agentId:t,participantName:n,baseUrl:i,appSecret:r,appId:s,authToken:o,prompts:a,statusMessage:c,welcomeTitle:l,welcomeSubTitle:u,className:d,width:h,height:f,loadingText:g,suportsChatInput:p=!0,suportsVideoInput:v=!0,suportsScreenShare:b=!0,theme:w="vox",onSessionStart:S,onSessionEnd:k,enableSessionLogging:x=!0,onSessionLogsUpdate:T,onSessionMetricsUpdate:P,modalities:A=["voice"],displayType:N="widget",popupPosition:y="bottom-right",popupTriggerText:R="Open Chat",onPopupToggle:I,voxketClient:L,onDisplayTypeChange:U,participantMetadata:K,popupModalityMode:ue="all",popupTriggerLogoUrl:se}=e,[z,H]=D.useState(!1),[C,W]=D.useState(null),[Y,E]=D.useState(()=>{try{if(L)return!!L.getCurrentSession()}catch(_){console.error("Error checking existing session:",_)}return!1}),[J,ne]=D.useState(!1),[ie,re]=D.useState(t||""),[X,le]=D.useState(n||"User"),[Z,Ae]=D.useState(()=>{try{if(L)return L.getCurrentSession()}catch(_){console.error("Error getting current session:",_)}return null}),[F,de]=D.useState(()=>{var _,$,te;try{if(L){const ge=L.getCurrentSession();if((_=ge==null?void 0:ge.activeModalities)!=null&&_.includes("chat"))return"chat";if(($=ge==null?void 0:ge.activeModalities)!=null&&$.includes("voice"))return"voice";if((te=ge==null?void 0:ge.activeModalities)!=null&&te.includes("video"))return"video"}}catch(ge){console.error("Error determining current mode:",ge)}return"welcome"}),[Pe,ke]=D.useState(!1),[pe,Te]=D.useState(!1),[Ne,Ce]=D.useState(()=>A.length===1?A[0]:null),[Rt,$t]=D.useState(!1);D.useEffect(()=>{N==="fullscreen"&&console.log("🎯 Widget: Switched to fullscreen mode")},[N]),D.useEffect(()=>{Y&&!J?console.log("📊 Session started:",{currentMode:F,sessionId:Z==null?void 0:Z.id}):!Y&&!J&&F==="welcome"&&console.log("📊 Returned to welcome screen")},[Y,F,J]);const ot=D.useRef(null);if(!ot.current)try{if(L)console.log("🔄 Using existing VoxketClient to preserve session state"),ot.current=L;else if(!o&&(!s||!r)){const _="Missing required props: Either provide 'authToken' or both 'appId' and 'appSecret'";console.error("❌ VoxketClient creation failed:",_),W(new Error(_)),H(!0)}else if(i){const _={...o?{authToken:o}:{appId:s,appSecret:r},baseUrl:i,agentId:ie,participantName:X||"User",modalities:A,participantMetadata:K};console.log("🔧 Creating new VoxketClient with config:",{authMethod:o?"Bearer Token":"App Credentials",...o?{}:{appId:(s==null?void 0:s.substring(0,8))+"..."},baseUrl:i,agentId:ie,participantName:X||"User",modalities:A}),ot.current=new Po(_)}else{const _="Missing required prop: baseUrl";console.error("❌ VoxketClient creation failed:",_),W(new Error(_)),H(!0)}}catch(_){console.error("❌ Failed to create VoxketClient:",_),W(_),H(!0)}const be=ot.current;D.useEffect(()=>{const _=ot.current;return()=>{_&&!L&&(console.log("🧹 Widget unmounting: disconnecting VoxketClient"),_.disconnect().catch($=>{console.error("❌ Error during widget cleanup disconnect:",$)}))}},[L]);const Ft=D.useMemo(()=>N==="popup"&&Ne?[Ne]:A,[N,Ne,A]),at=D.useMemo(()=>{try{if(!be)return console.warn("⚠️ No VoxketClient available, creating fallback room"),new vi;const _=be.getRoom();return console.log("🏠 Widget: Room reference updated:",{roomExists:!!_,roomState:_==null?void 0:_.state,sessionStarted:Y,currentMode:F}),_||new vi}catch(_){return console.error("❌ Error getting room from client:",_),new vi}},[be,Y,F]);D.useEffect(()=>{if(at){const _=()=>{console.log("🏠 Widget: Room state changed:",{state:at.state,numParticipants:at.numParticipants,isConnected:at.state==="connected",sessionId:Z==null?void 0:Z.id})},$=(te,ge,ht)=>{console.log("🎵 Widget: Track subscribed:",{trackKind:te.kind,trackSource:te.source,participantSid:ht.sid,participantIdentity:ht.identity,sessionId:Z==null?void 0:Z.id})};return at.on(j.Connected,_),at.on(j.Disconnected,_),at.on(j.TrackSubscribed,$),()=>{at.off(j.Connected,_),at.off(j.Disconnected,_),at.off(j.TrackSubscribed,$)}}},[at,Z==null?void 0:Z.id]),D.useEffect(()=>{!J&&F==="welcome"?console.log("🎬 Widget: Welcome screen ready"):Y&&F!=="welcome"&&console.log("🎬 Widget: Session mode active:",F)},[F,J,Y]),D.useEffect(()=>{(F==="voice"||F==="video"||F==="chat")&&!Z&&!Y&&!J&&be&&!be.connected&&(console.log("🔄 Auto-correcting: Found orphaned mode without session, returning to welcome"),de("welcome"),ne(!1))},[F,Z,Y,J,be]);const{sessionMetrics:q,sessionLogs:ae,logEvent:Re}=hw({room:at,onSessionStart:S,onSessionEnd:k,enableConsoleLogging:x,enableLocalStorage:x,voxketSessionId:Z==null?void 0:Z.id});D.useEffect(()=>{T&&T(ae)},[ae,T]),D.useEffect(()=>{P&&q&&P(q)},[q,P]),D.useEffect(()=>{if(!be)return;const _=($,te)=>{console.log("📊 Widget: Session state changed:",{from:te,to:$,currentLoading:J}),($==="connecting"||$==="connected")&&(J||(console.log("⏳ Widget: Setting loading=true (waiting for agent)"),ne(!0))),$==="active"&&(console.log("✅ Widget: Session active, agent ready - removing loader"),ne(!1),E(!0)),($==="disconnected"||$==="error")&&(console.log("🔴 Widget: Session ended - resetting state"),ne(!1),E(!1),Ae(null),de("welcome"))};return be.on("session.state.changed",_),()=>{be.off("session.state.changed",_)}},[be,J]),D.useEffect(()=>{if(!be)return;const _=()=>{const $=be.connected,te=be.getCurrentSession();console.log("🔗 Connection state changed:",{isConnected:$,currentSessionId:te==null?void 0:te.id,currentMode:F,loading:J,sessionStarted:Y}),!$&&Y&&!J&&(console.log("🔴 Connection lost during active session - returning to welcome"),ne(!1),E(!1),Ae(null),de("welcome")),$&&te&&J&&(console.log("🟢 Connected with active session - removing loader"),ne(!1),E(!0),Ae(te))};return be.on("connectionStateChanged",_),be.on("sessionEnded",()=>{console.log("📞 Session ended - returning to welcome"),ne(!1),E(!1),Ae(null),de("welcome")}),()=>{be.off("connectionStateChanged",_),be.off("sessionEnded",()=>{})}},[be,F,J,Y]);const Ye=!!(!!(be!=null&&be.connected)&&Y&&Z);D.useEffect(()=>{const _=te=>{console.log("🔴 Widget: Room disconnected:",te),console.log("🔍 Widget: Current state on disconnect:",{currentMode:F,sessionStarted:Y,currentSessionId:Z==null?void 0:Z.id,loading:J}),ne(!1),E(!1),Ae(null),de("welcome"),console.log("🏠 Widget: Automatically returning to welcome screen after disconnect")},$=te=>{console.log("📹 Media devices error:",te)};return at.on(j.MediaDevicesError,$),at.on(j.Disconnected,_),()=>{at.off(j.Disconnected,_),at.off(j.MediaDevicesError,$)}},[at,F,Y,Z==null?void 0:Z.id,J]);const tn=async()=>{try{if(!be){console.error("❌ VoxketClient not available"),W(new Error("VoxketClient not initialized")),H(!0);return}ne(!0),de("voice"),console.log("🎤 Starting voice session...",{agentId:ie,participantName:X}),console.log("🎤 Pre-start state:",{currentMode:"voice",sessionStarted:!1,loading:!0}),Re("USER_STARTED_VOICE_SESSION",{agentId:ie,participantName:X});const _=await be.startSession(ie,{participantName:X||"User",modalities:["voice"],participantMetadata:be.getParticipantMetadata()||K});console.log("✅ Voice session started successfully:",_.id),Ae(_),E(!0),ne(!1),S&&S(_.id)}catch(_){console.error("❌ Failed to start voice session:",_),ne(!1),E(!1),de("welcome")}},Mn=async()=>{try{if(!be){console.error("❌ VoxketClient not available"),W(new Error("VoxketClient not initialized")),H(!0);return}ne(!0),de("chat"),console.log("💬 Starting chat session...",{agentId:ie,participantName:X}),Re("USER_STARTED_CHAT_SESSION",{agentId:ie,participantName:X});const _=await be.startSession(ie,{participantName:X||"User",modalities:["chat"],participantMetadata:be.getParticipantMetadata()||K});console.log("✅ Chat session started successfully:",_.id),Ae(_),E(!0),ne(!1),S&&S(_.id)}catch(_){console.error("❌ Failed to start chat session:",_),ne(!1),E(!1),de("welcome")}},gn=async()=>{try{if(!be){console.error("❌ VoxketClient not available"),W(new Error("VoxketClient not initialized")),H(!0);return}ne(!0),de("video"),console.log("📺 Starting video session...",{agentId:ie,participantName:X}),console.log("📺 Pre-start state:",{currentMode:"video",sessionStarted:!1,loading:!0}),Re("USER_STARTED_VIDEO_SESSION",{agentId:ie,participantName:X});const _=await be.startSession(ie,{participantName:X||"User",modalities:["video","voice"],participantMetadata:be.getParticipantMetadata()||K});console.log("✅ Video session started successfully:",_.id),Ae(_),E(!0),ne(!1),S&&S(_.id)}catch(_){console.error("❌ Failed to start video session:",_),ne(!1),E(!1),de("welcome")}},an=()=>{de("welcome"),ne(!1),U&&U(e.displayType||"widget"),Z&&Y?(console.log("🧹 Widget: Cleaning up active session"),E(!1),Ae(null),be&&(console.log("🔌 Widget: Disconnecting client and cleaning up room"),be.disconnect().catch(_=>{console.error("❌ Widget: Error during disconnect:",_)}))):(console.log("📝 Widget: No active session to clean up"),be&&be.connected&&(console.log("🔌 Widget: Force disconnecting client for fresh state"),be.disconnect().catch(_=>{console.error("❌ Widget: Error during force disconnect:",_)}))),N==="popup"&&!Pe&&ke(!0),console.log("✅ Widget: handleBackToWelcome completed",{newCurrentMode:"welcome",newLoading:!1,newSessionStarted:!1})},Cn=()=>{const _=!Pe;ke(_),I&&I(_),!_&&!(Z&&Y)&&(de("welcome"),E(!1),Ae(null))},qt=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},Wn=()=>{if(console.log("🔄 Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("⚠️ No onDisplayTypeChange callback provided for expand functionality");const _=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");_&&_.requestFullscreen&&_.requestFullscreen().catch($=>{console.warn("⚠️ Fullscreen API not supported or failed:",$)})}};D.useEffect(()=>{var _,$,te;if(L&&be){const ge=be.getCurrentSession();be.connected,ge&&(console.log("✅ Restoring session state:",ge.id),Ae(ge),E(!0),ne(!1),(_=ge.activeModalities)!=null&&_.includes("chat")?de("chat"):($=ge.activeModalities)!=null&&$.includes("voice")?de("voice"):(te=ge.activeModalities)!=null&&te.includes("video")&&de("video"))}},[L,be]),D.useEffect(()=>()=>{!L&&be&&be.disconnect()},[be,L]);let Gt=F==="video"?"w-[32rem]":"w-96",Tr=F==="video"?"h-[30rem]":"h-[25rem]",Cr={};if(h&&(h.startsWith("w-")?Gt=h:(Cr.width=h,Gt="")),f&&(f.startsWith("h-")?Tr=f:(Cr.height=f,Tr="")),N==="popup"&&!Pe)return console.log("🟡 Showing popup trigger button"),m.jsxs(m.Fragment,{children:[m.jsx(dw,{onClick:()=>{if(Ye){!Ne&&(Z!=null&&Z.activeModalities)&&(Z.activeModalities.includes("chat")?Ce("chat"):Z.activeModalities.includes("video")?Ce("video"):Z.activeModalities.includes("voice")&&Ce("voice")),Te(!1),ke(!0),I&&I(!0);return}if(ue!=="all"){Ce(ue),Te(!1),ke(!0),I&&I(!0);return}if(A.length===1){Ce(A[0]),Te(!1),ke(!0),I&&I(!0);return}Te(_=>!_),Ce(null),$t(!1)},position:y,ariaLabel:R,size:64,isRunning:Ye,logoUrl:se}),pe&&ue==="all"&&(()=>{const te={};y==="bottom-right"?(te.bottom=88,te.right=16):y==="bottom-left"?(te.bottom=88,te.left=16):y==="top-right"?(te.top=88,te.right=16):(te.top=88,te.left=16);const ge="absolute w-0 h-0 border-8",ht=y.startsWith("bottom")?m.jsx("div",{className:`${ge} border-transparent border-t-black`,style:{bottom:-16,right:y.endsWith("right")?16:void 0,left:y.endsWith("left")?16:void 0}}):m.jsx("div",{className:`${ge} border-transparent border-b-black`,style:{top:-16,right:y.endsWith("right")?16:void 0,left:y.endsWith("left")?16:void 0}});return m.jsx("div",{className:"fixed z-[51]",style:te,children:m.jsxs("div",{className:"relative bg-black text-white rounded-xl shadow-2xl px-3 py-3",children:[ht,m.jsx("div",{className:"text-xs uppercase tracking-wide mb-2 opacity-70",children:"Choose modality"}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("button",{type:"button",onClick:()=>{Ce("voice"),Te(!1),ke(!0),I&&I(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Voice",children:"Voice"}),m.jsx("button",{type:"button",onClick:()=>{Ce("chat"),Te(!1),ke(!0),I&&I(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Chat",children:"Chat"}),m.jsx("button",{type:"button",onClick:()=>{Ce("video"),Te(!1),ke(!0),I&&I(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Video",children:"Video"})]})]})})})()]});if(z||!be){const _=(C==null?void 0:C.message)||"VoxketWidget encountered an error. Please check your configuration.";return m.jsx("div",{className:`voxket-widget-root theme-${w} flex items-center justify-center p-8 ${d||""}`,style:{width:h||"400px",height:f||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:m.jsxs("div",{className:"text-center",children:[m.jsx("div",{className:"text-4xl mb-4",children:"⚠️"}),m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),m.jsx("p",{className:"text-sm mb-4",children:_}),m.jsx("button",{onClick:()=>{H(!1),W(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let ws=`voxket-widget-root theme-${w}`,Ji={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};N==="widget"?(ws+=` flex min-h-fit ${Gt} ${Tr} ${d}`,Ji={...Ji,...Cr}):(ws=`${d||""}`,Ji={});const oi=m.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden relative z-10",children:m.jsxs(ls,{mode:"wait",children:[F==="welcome"&&!J&&m.jsx(h4,{agentId:ie,participantName:X||"",onAgentIdChange:re,onParticipantNameChange:le,onStartCall:tn,onStartChat:Mn,onStartVideo:gn,disabled:Y||J,prompts:a,statusMessage:c,title:l,subTitle:u,theme:w,modalities:Ft,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),J&&(F==="voice"||F==="chat"||F==="video")&&m.jsx(p4,{theme:w,mode:F,loadingText:g,sessionState:Z==null?void 0:Z.state,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"}},`loading-${F}`),F==="voice"&&!J&&Y&&be&&m.jsxs(Ja.Provider,{value:at,children:[m.jsx(ug,{},`audio-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(ag,{label:"Start Audio"},`start-audio-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(l4,{loadingText:g,participantName:X||"User",sessionStarted:Y,disabled:!1,theme:w,client:be,displayType:N,onBack:N==="popup"?Cn:an,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"voice-session")]}),F==="chat"&&!J&&Y&&be&&m.jsx(u4,{client:be,theme:w,displayType:N,onBack:N==="popup"?Cn:an,onEndChat:an,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),F==="video"&&!J&&Y&&be&&m.jsxs(Ja.Provider,{value:at,children:[m.jsx(ug,{},`audio-video-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(ag,{label:"Start Audio"},`start-audio-video-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(d4,{client:be,theme:w,displayType:N,onBack:N==="popup"?Cn:an,onEndCall:an,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-session")]})]})});return N==="fullscreen"||N==="popup"?m.jsx(Qb,{theme:w,displayType:N,popupPosition:y,onClose:N==="fullscreen"?qt:Cn,children:oi}):m.jsx("div",{className:ws,style:Ji,children:m.jsx(Qb,{theme:w,displayType:N,popupPosition:y,onExpand:Wn,children:oi})})}function Na(e){return m.jsx(kf,{children:m.jsx(m4,{...e})})}function g4({logs:e,onClear:t,onExport:n}){const[i,r]=O.useState(!1),[s,o]=O.useState(""),a=e.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return i?m.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:m.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[m.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>o(c.target.value),className:"px-3 py-1 border rounded text-sm"}),m.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),m.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),m.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),m.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?m.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):m.jsx("div",{className:"space-y-2",children:a.map((c,l)=>m.jsxs("div",{className:"border rounded p-3 text-sm",children:[m.jsxs("div",{className:"flex items-center justify-between mb-1",children:[m.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),m.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&m.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&m.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:m.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):m.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function b4({metrics:e}){return e?m.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[m.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),m.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Session ID:"}),m.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Start Time:"}),m.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Messages:"}),m.jsx("div",{children:e.totalMessages})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Participants:"}),m.jsx("div",{children:e.participantCount})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),m.jsx("div",{children:e.connectionIssues})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Duration:"}),m.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function wr(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:i,endSession:r}=si(),s=O.useCallback(async(a,c)=>await i(a,c),[i]),o=O.useCallback(async()=>await r(),[r]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:o}}function Sw(){const{sessionMetrics:e,currentSession:t}=si();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function ww(){const{setMicrophoneEnabled:e,client:t}=si(),[n,i]=O.useState(!1),[r,s]=O.useState(!1),o=O.useCallback(async()=>{if(!r){s(!0);try{const l=!n;await e(l),i(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{s(!1)}}},[n,r,e]),a=O.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(!0),i(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{s(!1)}}},[n,r,e]),c=O.useCallback(async()=>{if(!(!n||r)){s(!0);try{await e(!1),i(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{s(!1)}}},[n,r,e]);return{isEnabled:n,isLoading:r,toggle:o,enable:a,disable:c}}function Tw(){const{setCameraEnabled:e}=si(),[t,n]=O.useState(!1),[i,r]=O.useState(!1),s=O.useCallback(async()=>{if(!i){r(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[t,i,e]),o=O.useCallback(async()=>{if(!(t||i)){r(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[t,i,e]),a=O.useCallback(async()=>{if(!(!t||i)){r(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[t,i,e]);return{isEnabled:t,isLoading:i,toggle:s,enable:o,disable:a}}function Cw(){const{startScreenShare:e,stopScreenShare:t}=si(),[n,i]=O.useState(!1),[r,s]=O.useState(!1),o=O.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(),i(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{s(!1)}}},[n,r,e]),a=O.useCallback(async()=>{if(!(!n||r)){s(!0);try{await t(),i(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{s(!1)}}},[n,r,t]),c=O.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:r,start:o,stop:a,toggle:c}}function y4(){const{client:e}=si(),[t,n]=O.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),i=O.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),r=O.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),s=O.useCallback(async()=>{try{i!=null&&i.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(p){throw console.error("Failed to toggle camera:",p),p}},[e,i]),o=O.useCallback(async()=>{try{t.tracks.find(v=>v.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(p){throw console.error("Failed to toggle screen share:",p),p}},[e,t.tracks]),a=O.useCallback(p=>{n(v=>({...v,layout:p}))},[]),c=O.useCallback(p=>{n(v=>({...v,pinnedTrack:p}))},[]),l=O.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=O.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(p=>({...p,isRecording:!0}))}catch(p){throw console.error("Failed to start recording:",p),p}},[e]),d=O.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(p=>({...p,isRecording:!1}))}catch(p){throw console.error("Failed to stop recording:",p),p}},[e]),h=O.useCallback(p=>t.tracks.find(v=>v.id===p),[t.tracks]),f=O.useCallback(p=>t.tracks.filter(v=>v.participantId===p),[t.tracks]),g=O.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return O.useEffect(()=>{if(!e)return;const p=w=>{n(S=>({...S,tracks:[...S.tracks.filter(k=>k.id!==w.id),w]}))},v=w=>{n(S=>{var k;return{...S,tracks:S.tracks.filter(x=>x.id!==w),pinnedTrack:((k=S.pinnedTrack)==null?void 0:k.id)===w?void 0:S.pinnedTrack}})},b=w=>{n(S=>({...S,tracks:S.tracks.map(k=>k.id===w.id?w:k)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",v),e.on("videoTrackUpdated",b),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",v),e.off("videoTrackUpdated",b)}},[e]),{tracks:t.tracks,localTrack:i,remoteTraracks:r,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:u,stopRecording:d,getTrackById:h,getTracksByParticipant:f,isTrackActive:g}}function zc(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=si(),[i,r]=O.useState(!1),s=O.useCallback(async l=>{if(!(!l.trim()||i||!n)){r(!0);try{await t(l.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{r(!1)}}},[t,i,n]),{userMessages:o,agentMessages:a,allMessages:c}=O.useMemo(()=>{const l=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:l,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:o,agentMessages:a,messageCount:c.length,isSending:i,canSend:!!n&&!i,send:s}}function v4(){const{send:e,isSending:t,canSend:n}=zc(),[i,r]=O.useState(""),s=O.useCallback(async()=>{if(!(!i.trim()||!n))try{await e(i),r("")}catch(a){throw a}},[i,e,n]),o=O.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:i,setValue:r,send:s,handleKeyPress:o,isSending:t,canSend:n&&i.trim().length>0}}function Tf(){const{isConnected:e,isConnecting:t,connectionError:n,connect:i,disconnect:r}=si(),s=O.useCallback(async()=>{if(!(e||t))try{await i()}catch(a){throw console.error("Failed to connect:",a),a}},[i,e,t]),o=O.useCallback(async()=>{if(e)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:o}}function Ew(){const{participants:e}=si();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const _w=O.createContext({}),No=()=>O.useContext(_w);function Rw({children:e,...t}){return m.jsx(_w.Provider,{value:t,children:e})}function Ia({name:e,children:t,fallback:n,className:i}){return m.jsx("div",{className:`voxket-slot voxket-slot--${e} ${i||""}`,children:t||n})}function Aw(e,t={}){return Object.assign(e,t)}function Pw({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:i=!0,customControls:r,className:s=""}){const o=wr(),a=ww(),c=Tw(),l=Cw(),u=No(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!i?m.jsx("div",{className:d,children:m.jsx("div",{className:"voxket-controls-inactive",children:m.jsx("p",{children:"Controls available during active session"})})}):m.jsxs("div",{className:d,children:[i&&m.jsx("div",{className:"voxket-session-actions",children:o.isActive?m.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):m.jsx(x4,{})}),o.isActive&&m.jsxs("div",{className:"voxket-media-controls",children:[e&&m.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[m.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&m.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[m.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&m.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[m.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),r&&m.jsx("div",{className:"voxket-custom-controls",children:r})]})}function x4(){wr();const[e,t]=O.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(i){console.error("Failed to start session:",i)}finally{t(!1)}};return m.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Cf({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:i=""}){const r=wr(),s=Tf(),o=No(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,i].filter(Boolean).join(" ");return m.jsxs("div",{className:a,children:[e&&m.jsxs("div",{className:"voxket-connection-status",children:[m.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),m.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&r.session&&m.jsxs("div",{className:"voxket-session-info",children:[m.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),m.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&m.jsxs("div",{className:"voxket-agent-info",children:[m.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),m.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),s.error&&m.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Ef({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:i=""}){const r=wr(),s=zc(),o=No(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,i].filter(Boolean).join(" ");return r.isActive?m.jsx("div",{className:a,children:n||m.jsxs(m.Fragment,{children:[e&&m.jsxs("div",{className:"voxket-chat-container",children:[m.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>m.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[m.jsxs("div",{className:"voxket-message-header",children:[m.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),m.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),m.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&m.jsx("div",{className:"voxket-empty-messages",children:m.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),m.jsx(k4,{})]}),t&&m.jsx("div",{className:"voxket-transcriptions",children:m.jsx("div",{className:"voxket-transcription-placeholder",children:m.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):m.jsx("div",{className:a,children:m.jsx("div",{className:"voxket-inactive-state",children:m.jsxs("div",{className:"voxket-inactive-message",children:[m.jsx("h3",{children:"Start a conversation"}),m.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function k4(){const e=zc(),[t,n]=O.useState(""),i=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},r=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i())};return m.jsxs("div",{className:"voxket-chat-input",children:[m.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),m.jsx("button",{onClick:i,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function _f({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:i,className:r=""}){const s=wr(),o=Sw(),a=Ew(),c=No(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?m.jsx("div",{className:l,children:i||m.jsxs(m.Fragment,{children:[n&&m.jsxs("div",{className:"voxket-session-status",children:[m.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),m.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&o.metrics&&m.jsxs("div",{className:"voxket-session-metrics",children:[m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),m.jsx("span",{className:"voxket-metric-value",children:S4(o.duration||0)})]}),m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),m.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),t&&m.jsxs("div",{className:"voxket-participants-info",children:[m.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&m.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>m.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):m.jsx("div",{className:l,children:m.jsx("div",{className:"voxket-footer-inactive",children:m.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function S4(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=Math.floor(n/60);return i>0?`${i}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function w4({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:i,onSessionEnd:r,variant:s="default",size:o="md",theme:a,className:c="",children:l}){var f;const u=wr(),d=Tf();O.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),O.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&i&&i(u.session.id)},[(f=u.session)==null?void 0:f.id,i]),O.useEffect(()=>()=>{u.isActive&&r&&u.stop().then(r).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return m.jsx(Rw,{variant:s,size:o,theme:a,className:c,children:m.jsx("div",{className:h,children:l||m.jsxs(m.Fragment,{children:[m.jsx(Ia,{name:"header",fallback:m.jsx(Cf,{})}),m.jsx(Ia,{name:"content",fallback:m.jsx(Ef,{})}),m.jsx(Ia,{name:"footer",fallback:m.jsx(_f,{})})]})})})}const Nw=Aw(w4,{Header:Cf,Content:Ef,Footer:_f,Controls:Pw}),fr={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},Ld={...fr,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},Fd={...fr,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},Iw=O.createContext(null),Mw=()=>{const e=O.useContext(Iw);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function T4({theme:e="default",themes:t={},children:n,cssVariables:i=!0,className:r=""}){const[s,o]=O.useState(()=>{const h={default:fr,dark:Ld,enterprise:Fd,...t};return typeof e=="string"?h[e]||fr:e}),[a,c]=O.useState(()=>({default:fr,dark:Ld,enterprise:Fd,...t})),l=h=>{if(typeof h=="string"){const f=a[h];f&&o(f)}else o(h)},u=h=>{c(f=>({...f,[h.name]:h}))};O.useEffect(()=>{if(i&&typeof document<"u"){const h=document.documentElement;Object.entries(Ow(s)).forEach(([f,g])=>{h.style.setProperty(`--voxket-${f}`,g)})}},[s,i]);const d={theme:s,setTheme:l,themes:a,registerTheme:u};return m.jsx(Iw.Provider,{value:d,children:m.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${r}`,children:n})})}function Ow(e){const t={},n=(i,r="")=>{for(const[s,o]of Object.entries(i)){const a=r?`${r}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):t[a]=String(o)}};return n(e),t}function C4(e=fr,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function E4(e){var n;const{theme:t}=Mw();return((n=t.components)==null?void 0:n[e])||{}}const _4=wf("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&R4(e),t.enableVoiceActivation&&A4(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&P4(e,t)}});function R4(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function A4(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function P4(e,t){console.log("Playing audio response:",t.content)}const N4=wf("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&I4(),t.enableFileUpload&&M4(e),t.enableCustomComponents&&O4(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?D4(e,t):t.type==="text"&&n.enableRichText&&L4(e,t)}});function I4(e){console.log("Rich text support enabled")}function M4(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function O4(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",F4),t.set("form",j4),t.set("card",U4),t.set("chart",B4)}function D4(e,t){const{componentType:n,props:i}=t.metadata;console.log("Rendering custom component:",n,i),e.emit("chat.component.render",{type:n,props:i,timestamp:new Date})}function L4(e,t){console.log("Processing rich text message:",t.content)}function F4(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function j4(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function U4(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function B4(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function Ma({track:e,participantName:t,showControls:n=!0,showName:i=!0,showMuteIndicator:r=!0,isPinned:s=!1,className:o="",onClick:a,onPin:c,onUnpin:l}){const u=O.useRef(null),[d,h]=O.useState(!1);O.useEffect(()=>{if(!u.current||!e.isEnabled)return;const v=u.current;return v.srcObject=null,()=>{v.srcObject&&(v.srcObject=null)}},[e]);const f=()=>{a==null||a(e)},g=v=>{v.stopPropagation(),s?l==null||l(e):c==null||c(e)},p=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return m.jsxs("div",{className:p,onClick:f,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[m.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&m.jsxs("div",{className:"voxket-video-placeholder",children:[m.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),m.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),m.jsxs("div",{className:"voxket-video-overlay",children:[i&&t&&m.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),r&&!e.isEnabled&&m.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(d||s)&&m.jsxs("div",{className:"voxket-video-controls",children:[m.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&m.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&m.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&m.jsx("div",{className:"voxket-video-loading",children:m.jsx("div",{className:"voxket-spinner"})})]})}function V4({tracks:e,layout:t,className:n="",onLayoutChange:i,onTrackClick:r,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,c]=O.useState(0),[l,u]=O.useState(null),d=O.useMemo(()=>{let w=[...e];t.type==="speaker"&&l&&(w=[l,...e.filter(x=>x.id!==l.id)]);const S=a*s,k=S+s;return w.slice(S,k)},[e,t,l,a,s]),h=Math.ceil(e.length/s),f=O.useMemo(()=>{const w=d.length;switch(t.type){case"grid":const S=Math.ceil(Math.sqrt(w)),k=Math.ceil(w/S);return{display:"grid",gridTemplateColumns:`repeat(${S}, 1fr)`,gridTemplateRows:`repeat(${k}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,d.length]),g=w=>{u(w)},p=()=>{u(null)},v=w=>{i==null||i({...t,type:w})},b=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${d.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?m.jsx("div",{className:"voxket-video-grid-empty",children:m.jsxs("div",{className:"voxket-video-grid-empty-content",children:[m.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),m.jsx("p",{children:"No video tracks available"})]})}):m.jsxs("div",{className:b,children:[m.jsxs("div",{className:"voxket-video-grid-controls",children:[m.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(w=>m.jsx("button",{className:`voxket-layout-btn ${t.type===w?"voxket-layout-btn--active":""}`,onClick:()=>v(w),title:`Switch to ${w} layout`,children:$4(w)},w))}),m.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),m.jsx("div",{className:"voxket-video-grid-content",style:f,children:t.type==="speaker"&&l?m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"voxket-video-speaker-main",children:m.jsx(Ma,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:r,onUnpin:p})}),m.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(w=>w.id!==l.id).map(w=>m.jsx(Ma,{track:w,participantName:`Participant ${w.participantId}`,showControls:!1,onClick:r,onPin:g},w.id))})]}):d.map(w=>m.jsx(Ma,{track:w,participantName:`Participant ${w.participantId}`,isPinned:(l==null?void 0:l.id)===w.id,onClick:r,onPin:g,onUnpin:p},w.id))}),o&&h>1&&m.jsxs("div",{className:"voxket-video-pagination",children:[m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),m.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function $4(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function z4({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:i,showLayoutControls:r=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=u=>{i==null||i({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return m.jsxs("div",{className:c,children:[s&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&m.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),o&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),m.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:u,icon:d,label:h})=>m.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(u),title:`Switch to ${h} layout`,children:[m.jsx("span",{className:"voxket-control-icon",children:d}),m.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),m.jsxs("div",{className:"voxket-video-settings",children:[m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Quality"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"high",children:"High (720p)"}),m.jsx("option",{value:"medium",children:"Medium (480p)"}),m.jsx("option",{value:"low",children:"Low (240p)"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"30",children:"30 fps"}),m.jsx("option",{value:"15",children:"15 fps"}),m.jsx("option",{value:"10",children:"10 fps"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"unlimited",children:"Unlimited"}),m.jsx("option",{value:"1000",children:"1 Mbps"}),m.jsx("option",{value:"500",children:"500 Kbps"}),m.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),m.jsxs("div",{className:"voxket-video-stats",children:[m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),m.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Source:"}),m.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Status:"}),m.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const Dw=({handler:e,loadData:t,data:n,client:i,addLocalMessage:r})=>{const[s,o]=D.useState(null),[a,c]=D.useState(!0),[l,u]=D.useState(!1),[d]=D.useState(Date.now()),[h,f]=D.useState("pending");D.useEffect(()=>{(async()=>{try{if(c(!0),n&&typeof n=="object"){const w={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(w),console.log("📋 AssignmentView: Assignment loaded from RPC data:",w)}}catch(w){console.error("📋 AssignmentView: Error loading assignment:",w),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const g=({message:b,assignment:w})=>{const S=b.toLowerCase().includes("declined"),k=S?"bg-red-50 border-red-200":"bg-green-50 border-green-200",x=S?"text-red-700":"text-green-700",T=S?"❌":"🎉";return m.jsxs("div",{className:`max-w-sm mx-auto ${k} border rounded-lg shadow p-3 flex flex-col items-center`,children:[m.jsx("div",{className:"text-2xl mb-2",children:T}),m.jsx("div",{className:`${x} font-semibold text-sm mb-1`,children:b}),m.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:w.title}),m.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},p=async()=>{if(!(!s||!e)){u(!0);try{const b={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",b),e.didSuccess(b),f("accepted")}catch(b){console.error("📋 AssignmentView: Error accepting assignment:",b),e.didFail({error:"Failed to accept assignment"}),f("error")}finally{u(!1)}}},v=async()=>{if(!(!s||!e)){u(!0);try{const b={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",b),e.didSuccess(b),f("declined")}catch(b){console.error("📋 AssignmentView: Error declining assignment:",b),e.didFail({error:"Failed to decline assignment"}),f("error")}finally{u(!1)}}};return a?m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"flex items-center justify-center py-4",children:[m.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),m.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?h==="accepted"||h==="declined"||h==="error"?m.jsx(g,{message:h==="accepted"?"Assignment accepted!":h==="declined"?"Assignment declined":"Assignment error occurred",assignment:s}):m.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[m.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:m.jsx("div",{className:"flex items-center justify-between",children:m.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),m.jsxs("div",{className:"p-3 text-black",children:[m.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:m.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),m.jsx("div",{className:"mb-3 text-black",children:m.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[m.jsx("span",{className:"text-xs mr-1",children:"📅"}),m.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("button",{onClick:p,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?m.jsxs("span",{className:"flex items-center justify-center",children:[m.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),m.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),m.jsx("button",{onClick:v,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"text-center py-4",children:[m.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),m.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function H4(){const[e,t]=D.useState(null),[n,i]=D.useState([]);D.useEffect(()=>{const a=new Po({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Dw,"embedded");const a=e.getRegisteredRpcMethods();i(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:c,timeout:l})=>{const[u,d]=D.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],f=p=>{d(p)},g=()=>{const p=h.find(v=>v.id===u);c==null||c.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),m.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),m.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>m.jsx("div",{onClick:()=>f(p.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===p.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:m.jsxs("div",{className:"flex justify-between items-center",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"font-medium",children:p.name}),m.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),m.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),m.jsxs("div",{className:"flex justify-end space-x-3",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),m.jsx("button",{onClick:g,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&m.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},o=async()=>{if(!e)return;const a=({handler:c})=>{const[l,u]=D.useState(0),[d,h]=D.useState(""),f=()=>{c==null||c.didSuccess({rating:l,comment:d,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),m.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>m.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),m.jsx("textarea",{value:d,onChange:g=>h(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),m.jsxs("div",{className:"flex justify-end space-x-2",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),m.jsx("button",{onClick:f,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return m.jsxs("div",{className:"p-6",children:[m.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),m.jsxs("div",{className:"space-y-4 mb-6",children:[m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),m.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),m.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?m.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>m.jsx("li",{className:"text-gray-700",children:m.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):m.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),m.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),m.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[m.jsxs("li",{children:["Register RPC methods with React components using ",m.jsx("code",{children:"client.registerFrontendRPC()"})]}),m.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),m.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),m.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),m.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),m.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),m.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),m.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
182
|
+
`,style:{minHeight:"3rem",display:o===i?"flex":"none",alignItems:"center",justifyContent:"center"},children:m.jsx("span",{className:"italic",children:s})},o))})}const uw=O.forwardRef(({disabled:e,onStartCall:t,onStartChat:n,onStartVideo:i,prompts:r=['"Click to talk"','"How can I assist you today?"'],statusMessage:s="Agent is ready",title:o="Choose how to interact",subTitle:a="Ask me anything or give me a task to complete",theme:c="vox",modalities:l=["voice","chat","video"]},u)=>{const d=on(c),h=l.includes("voice"),f=l.includes("chat"),g=l.includes("video"),p=[h,f,g].filter(Boolean).length;return m.jsxs("div",{className:"flex flex-col items-center h-full justify-center w-full relative px-8 py-16","aria-disabled":e,style:{background:"transparent"},children:[m.jsx("div",{className:"absolute inset-0 opacity-[0.01] pointer-events-none mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulance type='fractalNoise' baseFrequency='2' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E")`,backgroundRepeat:"repeat"}}),m.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] bg-gradient-radial from-white/[0.02] to-transparent blur-3xl pointer-events-none"}),m.jsxs("div",{className:"flex flex-col items-center justify-center w-full max-w-2xl space-y-12 z-10",children:[m.jsx("div",{className:"text-center space-y-2 max-w-md",children:m.jsx("p",{className:`text-base leading-relaxed tracking-wide ${d.text.secondary}`,children:a})}),m.jsx("div",{className:"flex items-center justify-center w-full",children:h&&f&&g?m.jsxs("div",{className:"flex gap-5 items-center justify-center",children:[m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}),m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[m.jsx(lu,{onClick:n,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}),m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:i||t,children:[m.jsx(uu,{onClick:i||t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]})]}):p>1?m.jsxs("div",{className:"flex gap-6 items-center justify-center",children:[h&&m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:t,children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}),f&&m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:n,children:[m.jsx(lu,{onClick:n,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}),g&&i&&m.jsxs("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",onClick:i,children:[m.jsx(uu,{onClick:i,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]})]}):m.jsx("div",{className:"flex flex-col items-center gap-3 group cursor-pointer",children:h?m.jsxs(m.Fragment,{children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]}):f?m.jsxs(m.Fragment,{children:[m.jsx(lu,{onClick:n,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Chat"})]}):g&&i?m.jsxs(m.Fragment,{children:[m.jsx(uu,{onClick:i,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Video"})]}):m.jsxs(m.Fragment,{children:[m.jsx(aa,{onClick:t,disabled:e,theme:c}),m.jsx("span",{className:`text-xs font-medium tracking-wider uppercase ${d.text.muted} group-hover:text-white transition-colors duration-300`,children:"Voice"})]})})}),m.jsx("div",{className:"w-full flex justify-center",children:m.jsx(r4,{prompts:r,theme:c})})]})]})});uw.displayName="Welcome";class kf extends D.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("VoxketWidget Error:",t,n)}render(){if(this.state.hasError){if(this.props.fallback){const t=this.props.fallback;return D.createElement(t,{error:this.state.error})}return D.createElement("div",{style:{padding:"20px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"}},"VoxketWidget encountered an error. Please check the console for details.")}return this.props.children}}const dw=({onClick:e,position:t="bottom-right",size:n=64,className:i="",style:r,ariaLabel:s="Open Voxket",logoScale:o=.7,isRunning:a=!1,logoUrl:c="/logo.png"})=>{const l={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"},u={width:n,height:n,...r},d="data:image/svg+xml;utf8,"+encodeURIComponent(`
|
|
183
|
+
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
184
|
+
<circle cx="32" cy="32" r="32" fill="#6366F1"/>
|
|
185
|
+
<path d="M20 28c0-4.418 4.924-8 11-8s11 3.582 11 8-4.924 8-11 8c-1.41 0-2.76-.16-4-.46L16 44l2.54-7.62C21.06 34.1 20 31.17 20 28Z" fill="#fff"/>
|
|
186
|
+
<text x="32" y="36" text-anchor="middle" font-size="16" fill="#6366F1" font-family="Arial, sans-serif" font-weight="bold">V</text>
|
|
187
|
+
</svg>
|
|
188
|
+
`),[h,f]=D.useState(c);D.useEffect(()=>{f(c)},[c]);const g=D.useMemo(()=>{if(typeof window>"u"||!window.matchMedia)return!1;try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}},[]);return m.jsxs("div",{className:"relative pointer-events-auto",children:[a&&m.jsxs(m.Fragment,{children:[m.jsx(Fe.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+24,height:n+24,left:-12,top:-12,background:"linear-gradient(45deg, rgba(6,182,212,0.3), rgba(34,211,238,0.3), rgba(6,182,212,0.3))",filter:"blur(8px)"},animate:g?void 0:{scale:[1,1.1,1],opacity:[.6,.9,.6]},transition:g?void 0:{duration:2,repeat:1/0,ease:"easeInOut"}}),m.jsx(Fe.div,{className:"absolute inset-0 rounded-full pointer-events-none",style:{width:n+16,height:n+16,left:-8,top:-8,background:"linear-gradient(135deg, rgba(6,182,212,0.4), rgba(34,211,238,0.4))",filter:"blur(4px)"},animate:g?void 0:{scale:[1,1.05,1],opacity:[.7,1,.7]},transition:g?void 0:{duration:1.5,repeat:1/0,ease:"easeInOut",delay:.2}})]}),m.jsxs(Fe.button,{type:"button",onClick:e,"aria-label":s,className:`fixed z-50 rounded-full bg-black flex items-center justify-center overflow-hidden focus:outline-none focus:ring-2 focus:ring-cyan-400/60 ${l[t]} ${i}`,style:{...u,boxShadow:a?"0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)":"0 8px 32px rgba(0,0,0,0.3)",border:a?"2px solid rgba(6,182,212,0.6)":"none"},initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1,...a&&!g?{boxShadow:["0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.8), 0 0 30px rgba(6,182,212,0.6), 0 8px 32px rgba(0,0,0,0.3)","0 0 0 2px rgba(6,182,212,0.5), 0 0 20px rgba(6,182,212,0.4), 0 8px 32px rgba(0,0,0,0.3)"]}:{}},exit:{scale:.9,opacity:0},whileHover:{scale:1.05},whileTap:{scale:.95},"data-position":t,"data-voxket-trigger":"true",transition:{...!g&&a?{boxShadow:{duration:2,repeat:1/0,ease:"easeInOut"}}:{}},children:[a&&m.jsxs(m.Fragment,{children:[m.jsx(Fe.span,{"aria-hidden":!0,className:"absolute inset-0 rounded-full pointer-events-none",style:{background:"conic-gradient(from 0deg, rgba(6,182,212,0.0) 0deg, rgba(6,182,212,1) 90deg, rgba(34,211,238,1) 180deg, rgba(6,182,212,0.0) 270deg)",WebkitMask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))",mask:"radial-gradient(farthest-side, transparent calc(100% - 2px), #000 calc(100% - 2px))"},animate:g?void 0:{rotate:360},transition:g?void 0:{duration:3,repeat:1/0,ease:"linear"}}),m.jsx("span",{"aria-hidden":!0,className:"absolute inset-1 rounded-full pointer-events-none",style:{background:"radial-gradient(circle, rgba(6,182,212,0.1) 0%, transparent 70%)"}})]}),m.jsx("img",{src:h,alt:"Voxket",className:"object-contain select-none pointer-events-none relative z-10",style:{width:`${Math.max(0,Math.min(1,o))*100}%`,height:`${Math.max(0,Math.min(1,o))*100}%`,filter:a?"brightness(1.1) contrast(1.1)":"none"},draggable:!1,onError:()=>f(d)})]})]})};function hw({room:e,onSessionEnd:t,onSessionStart:n,enableConsoleLogging:i=!0,enableLocalStorage:r=!0,voxketSessionId:s}={}){const[o,a]=D.useState(null),[c,l]=D.useState([]),[u,d]=D.useState(null),[h,f]=D.useState([]),g=D.useCallback((w,S)=>{const k={timestamp:new Date,event:w,data:S,sessionId:o==null?void 0:o.sessionId,participantId:u==null?void 0:u.identity};if(l(x=>[...x,k]),r){const x=JSON.parse(localStorage.getItem("voxket-session-logs")||"[]");x.push(k),localStorage.setItem("voxket-session-logs",JSON.stringify(x))}return k},[o==null?void 0:o.sessionId,u==null?void 0:u.identity,i,r]);D.useEffect(()=>{if(!e)return;const w=()=>{const y=s||`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,R=new Date,I={sessionId:y,startTime:R,totalMessages:0,connectionIssues:0,participantCount:h.length,events:[]};a(I),g("SESSION_STARTED",{sessionId:y,startTime:R}),n==null||n(y)},S=()=>{if(o){const y=new Date,R=y.getTime()-o.startTime.getTime(),I={...o,endTime:y,duration:R,events:c};g("SESSION_ENDED",{sessionId:o.sessionId,duration:`${Math.round(R/1e3)}s`,totalMessages:o.totalMessages,connectionIssues:o.connectionIssues}),t==null||t(I),a(null),l([])}},k=y=>{g("CONNECTION_STATE_CHANGED",{state:y}),y===$e.Reconnecting&&o&&(a(R=>R?{...R,connectionIssues:R.connectionIssues+1}:null),g("CONNECTION_ISSUE",{type:"reconnecting"}))},x=y=>{g("TRACK_PUBLISHED",{trackKind:y.kind,trackSource:y.source})},T=y=>{g("TRACK_UNPUBLISHED",{trackKind:y.kind,trackSource:y.source})},P=(y,R)=>{o&&a(I=>I?{...I,totalMessages:I.totalMessages+1}:null),g("DATA_RECEIVED",{participantId:R==null?void 0:R.identity,dataSize:y.length})},A=y=>{g("PARTICIPANT_CONNECTED",{participantId:y.identity,participantName:y.name}),f(R=>[...R,y]),o&&a(R=>R?{...R,participantCount:R.participantCount+1}:null)},N=y=>{g("PARTICIPANT_DISCONNECTED",{participantId:y.identity,participantName:y.name}),f(R=>R.filter(I=>I.identity!==y.identity))};return e.localParticipant&&d(e.localParticipant),e.on(j.Connected,w),e.on(j.Disconnected,S),e.on(j.ConnectionStateChanged,k),e.on(j.TrackPublished,x),e.on(j.TrackUnpublished,T),e.on(j.DataReceived,P),e.on(j.ParticipantConnected,A),e.on(j.ParticipantDisconnected,N),()=>{e.off(j.Connected,w),e.off(j.Disconnected,S),e.off(j.ConnectionStateChanged,k),e.off(j.TrackPublished,x),e.off(j.TrackUnpublished,T),e.off(j.DataReceived,P),e.off(j.ParticipantConnected,A),e.off(j.ParticipantDisconnected,N)}},[e,o,c,h.length,g,t,n]);const p=D.useCallback(()=>r?JSON.parse(localStorage.getItem("voxket-session-logs")||"[]"):c,[c,r]),v=D.useCallback(()=>{r&&localStorage.removeItem("voxket-session-logs"),l([])},[r]),b=D.useCallback(()=>{const w=p(),S=JSON.stringify(w,null,2),k="data:application/json;charset=utf-8,"+encodeURIComponent(S),x=`voxket-session-logs-${new Date().toISOString().split("T")[0]}.json`,T=document.createElement("a");T.setAttribute("href",k),T.setAttribute("download",x),T.click()},[p]);return{sessionMetrics:o,sessionLogs:c,logEvent:g,getSessionLogs:p,clearSessionLogs:v,exportSessionLogs:b}}class Sf{constructor(){Ie(this,"listeners",{})}on(t,n){return this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(n),()=>this.off(t,n)}once(t,n){const i=(...r)=>{this.off(t,i),n(...r)};return this.on(t,i)}off(t,n){const i=this.listeners[t];if(!i)return;const r=i.indexOf(n);r>-1&&i.splice(r,1)}removeAllListeners(t){t?delete this.listeners[t]:this.listeners={}}emit(t,...n){const i=this.listeners[t];if(!i)return;const r=[...i];for(const s of r)try{s(...n)}catch(o){console.error(`Error in event listener for ${String(t)}:`,o)}}listenerCount(t){var n;return((n=this.listeners[t])==null?void 0:n.length)??0}eventNames(){return Object.keys(this.listeners)}}class fw{constructor(t){Ie(this,"plugins",new Map);Ie(this,"installedPlugins",new Set);Ie(this,"context");this.context={client:t,emit:t.emit.bind(t),on:t.on.bind(t),config:{}}}register(t){if(this.plugins.has(t.name))throw new Error(`Plugin '${t.name}' is already registered`);if(t.dependencies){for(const n of t.dependencies)if(!this.plugins.has(n))throw new Error(`Plugin '${t.name}' depends on '${n}' which is not registered`)}this.plugins.set(t.name,t)}async install(t,n){const i=this.plugins.get(t);if(!i)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t))throw new Error(`Plugin '${t}' is already installed`);if(i.dependencies)for(const s of i.dependencies)this.installedPlugins.has(s)||await this.install(s);const r={...this.context,config:{...i.config,...n}};i.install&&await i.install(r),this.installedPlugins.add(t),this.setupPluginEvents(i,r)}async uninstall(t){var i;const n=this.plugins.get(t);if(!n)throw new Error(`Plugin '${t}' is not registered`);if(this.installedPlugins.has(t)){for(const[r,s]of this.plugins)if(this.installedPlugins.has(r)&&((i=s.dependencies)!=null&&i.includes(t)))throw new Error(`Cannot uninstall '${t}' because '${r}' depends on it`);n.uninstall&&await n.uninstall(this.context),this.installedPlugins.delete(t)}}isInstalled(t){return this.installedPlugins.has(t)}getInstalledPlugins(){return Array.from(this.installedPlugins)}getAvailablePlugins(){return Array.from(this.plugins.keys())}getPluginInfo(t){return this.plugins.get(t)}setupPluginEvents(t,n){t.onSessionStart&&n.on("session.started",i=>{t.onSessionStart(n,i.id)}),t.onSessionEnd&&n.on("session.ended",i=>{t.onSessionEnd(n,i.id)}),t.onAgentResponse&&n.on("agent.response",i=>{t.onAgentResponse(n,i)})}}function s4(e){return e}function wf(e,t,n){return{name:e,version:"1.0.0",description:`${t} modality plugin`,install:async i=>{n.onActivate&&await n.onActivate(i)},uninstall:async i=>{n.onDeactivate&&await n.onDeactivate(i)},onAgentResponse:n.onMessage}}const o4={name:"analytics",version:"1.0.0",description:"Built-in analytics tracking",install:async e=>{console.log("Analytics plugin installed"),e.on("session.started",t=>{console.log("Analytics: Session started",t.id)}),e.on("session.ended",(t,n)=>{console.log("Analytics: Session ended",t.id,n)}),e.on("chat.message.sent",t=>{console.log("Analytics: User message sent",t.content.length)})}},a4={name:"debug",version:"1.0.0",description:"Debug logging and development tools",install:async e=>{console.log("Debug plugin installed");const t=e.emit;e.emit=(n,...i)=>(console.log(`[Debug] Event: ${String(n)}`,i),t(n,...i))}},c4={name:"metrics",version:"1.0.0",description:"Advanced metrics collection",install:async e=>{console.log("Metrics plugin installed");const t=new Map;e.on("session.started",n=>{t.set(n.id,{startTime:Date.now(),events:[]})}),e.on("agent.response",n=>{console.log("Metrics: Agent response analyzed",{type:n.type,length:n.content.length,timestamp:n.timestamp})})}};class pw extends Sf{constructor(n){super();Ie(this,"room",null);Ie(this,"registeredMethods",new Map);Ie(this,"activeInteractions",new Map);Ie(this,"currentInteraction",null);n&&this.setRoom(n)}setRoom(n){this.room=n}async registerFrontendRPC(n,i,r="embedded"){if(console.log(`RpcManager: Starting registration for method '${n}'`),!this.room)throw console.error(`RpcManager: Cannot register '${n}' - no room instance`),new Error("Room not initialized. Cannot register RPC method.");if(!this.room.localParticipant)throw console.error(`RpcManager: Cannot register '${n}' - no local participant`),new Error("Local participant not available for RPC registration");console.log(`RpcManager: Room state: ${this.room.state}`),console.log(`RpcManager: Local participant: ${this.room.localParticipant.identity}`),console.log(`RpcManager: Registering frontend RPC method: ${n}`);const s={methodName:n,component:i,presentationMode:r};this.registeredMethods.set(n,s);try{this.room.registerRpcMethod(n,async o=>{console.log(`RpcManager: RPC method '${n}' called by ${o.callerIdentity}`),console.log("RpcManager: Payload:",o.payload),this.emit("rpc.method.called",{methodName:n,data:o});let a;console.log(`RpcManager: Current registration for '${n}':`,s);let c=o.responseTimeout||30;try{a=JSON.parse(o.payload)}catch{a=o.payload}try{const l=await this.awaitUserInteraction(n,i,r,a,c);return JSON.stringify(l)}catch(l){throw console.error(`RpcManager: Error in RPC method '${n}':`,l),l}}),this.emit("rpc.method.registered",{methodName:n}),console.log(`RpcManager: Successfully registered RPC method: ${n}`)}catch(o){throw console.error(`RpcManager: Failed to register RPC method '${n}':`,o),o}}async awaitUserInteraction(n,i,r,s,o){return new Promise((a,c)=>{const l=`${n}_${Date.now()}`;console.log(`RpcManager: Starting user interaction for method: ${n}, timeout: ${o} seconds`);const u={didSuccess:(h,f)=>{console.log(`RpcManager: User interaction successful for method: ${n}`,h),this.clearInteraction(l),this.currentInteraction=null;const g={success:!0,message:"User interaction completed successfully",data:h,timestamp:new Date,...f?{successView:f}:{}};this.emit("rpc.interaction.completed",{methodName:n,response:g}),a(g)},didFail:h=>{console.log(`RpcManager: User interaction failed for method: ${n}`,h),this.clearInteraction(l);const f={success:!1,message:"User interaction failed",error:h,timestamp:new Date};this.emit("rpc.interaction.completed",{methodName:n,response:f}),a(f)},dismissView:()=>{var f;console.log(`RpcManager: User dismissed interaction for method: ${n}`),console.log("RpcManager: Current interaction before dismiss:",(f=this.currentInteraction)==null?void 0:f.methodName),this.clearInteraction(l),this.currentInteraction=null,console.log("RpcManager: Current interaction after dismiss:",this.currentInteraction);const h={success:!0,data:{dismissed:!0,reason:"User dismissed the interaction"},message:"User interaction dismissed",timestamp:new Date};this.emit("rpc.interaction.dismissed",{methodName:n,response:h}),this.emit("rpc.interaction.completed",{methodName:n,response:h}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(h)},didTimeout:h=>{console.log(`RpcManager: User interaction timeout for method: ${n}`),this.clearInteraction(l),this.currentInteraction=null;const f={success:!0,message:`User interaction timed out after ${o} seconds, it should be considered as declined, agent don't need to retry`,timestamp:new Date,...h?{timeoutView:h}:{}};this.emit("rpc.interaction.timeout",{methodName:n,response:f}),setTimeout(()=>{var g;((g=this.currentInteraction)==null?void 0:g.methodName)===n&&(console.log(`RpcManager: Force clearing interaction for ${n}`),this.currentInteraction=null)},0),a(f)}},d=setTimeout(()=>{u.didTimeout&&u.didTimeout()},o);this.activeInteractions.set(l,{resolve:h=>a(JSON.parse(h)),reject:c,timeoutId:d}),this.currentInteraction={isVisible:!0,methodName:n,component:i,presentationMode:r,timeout:o,data:s,handler:u},this.emit("rpc.interaction.started",{methodName:n,presentationMode:r}),setTimeout(async()=>{var h;if((h=this.currentInteraction)!=null&&h.handler)try{console.log(`RpcManager: Component created for method: ${n} with data:`,s)}catch(f){console.error("RpcManager: Error loading data into component:",f),u.didFail({error:"Failed to load data into component"})}},100)})}clearInteraction(n){const i=this.activeInteractions.get(n);i&&(console.log(`RpcManager: Clearing interaction: ${n}`),clearTimeout(i.timeoutId),this.activeInteractions.delete(n))}getCurrentInteraction(){return this.currentInteraction}dismissCurrentInteraction(){var n;this.currentInteraction&&(console.log(`RpcManager: Dismissing current interaction: ${this.currentInteraction.methodName}`),(n=this.currentInteraction.handler)==null||n.dismissView(),setTimeout(()=>{this.currentInteraction&&(console.log("RpcManager: Force clearing lingering interaction"),this.currentInteraction=null)},0))}getRegisteredMethods(){return Array.from(this.registeredMethods.keys())}unregisterMethod(n){this.registeredMethods.delete(n),console.log(`RpcManager: Unregistered RPC method: ${n}`)}clear(){for(const[n,i]of this.activeInteractions)clearTimeout(i.timeoutId);this.activeInteractions.clear(),this.registeredMethods.clear(),this.currentInteraction=null,console.log("RpcManager: Cleared all registrations and interactions")}}class tt extends Error{constructor(t,n,i){super(t),this.code=n,this.details=i,this.name="VoxketError"}}class mw{constructor(t,n="User"){Ie(this,"chatMessages",[]);Ie(this,"activeTranscriptions",new Map);Ie(this,"room",null);Ie(this,"eventEmitter");Ie(this,"participantName");this.eventEmitter=t,this.participantName=n}setRoom(t){this.room=t}setParticipantName(t){this.participantName=t}getChatMessages(){return[...this.chatMessages]}addChatMessage(t){this.chatMessages.some(i=>i.id===t.id)||this.chatMessages.push(t)}updateChatMessage(t){const n=this.chatMessages.findIndex(i=>i.id===t.id);n!==-1&&(this.chatMessages[n]=t)}clearChatMessages(){this.chatMessages=[],this.activeTranscriptions.clear(),console.log("🧹 ChatManager: Cleared chat messages and transcription history")}trackTranscription(t,n){this.activeTranscriptions.set(t,{messageId:n,timestamp:Date.now()})}getActiveTranscription(t){const n=Date.now(),i=this.activeTranscriptions.get(t);return i&&n-i.timestamp<1e3?i:null}async sendMessage(t,n){if(!this.room)throw new tt("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new tt("No local participant","CONNECTION_FAILED");try{const i={id:`msg_${Date.now()}`,content:t,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:n||{}};await this.room.localParticipant.sendText(t,{topic:"lk.chat",destinationIdentities:[]}),this.eventEmitter.emit("chat.message.sent",i)}catch(i){throw console.error("ChatManager: Failed to send chat message:",i),new tt("Failed to send message","NETWORK_ERROR",i)}}async sendAttachments(t,n){if(!this.room)throw new tt("No room connection","CONNECTION_FAILED");if(!this.room.localParticipant)throw new tt("No local participant","CONNECTION_FAILED");if(!t||t.length===0)throw new tt("No files provided","INVALID_PARAMETER");const i=t.filter(r=>r.type.startsWith("image/"));if(i.length===0)throw new tt("Only image files are allowed","INVALID_PARAMETER");i.length!==t.length&&console.warn("ChatManager: Some non-image files were filtered out");try{const r=i.map(async(s,o)=>{const c={id:`att_${Date.now()}_${o}`,content:`📎 ${s.name}`,sender:{id:"user",name:this.participantName,type:"participant"},timestamp:new Date,metadata:{...n,type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.type,uploading:!0}};this.eventEmitter.emit("chat.message.sent",c);const l=await this.room.localParticipant.sendFile(s,{mimeType:s.type,topic:"images",onProgress:d=>{const h={...c,metadata:{...c.metadata,uploadProgress:d}};this.eventEmitter.emit("chat.message.updated",h)}});try{const d=new FileReader,h=new Promise((p,v)=>{d.onload=()=>{typeof d.result=="string"?p(d.result):v(new Error("Failed to convert to base64"))},d.onerror=v});d.readAsDataURL(s);const g={type:"image",data:await h,filename:s.name,mimeType:s.type,size:s.size};await this.room.localParticipant.sendText(JSON.stringify(g),{topic:"images",destinationIdentities:[]})}catch(d){console.warn("ChatManager: Failed to send image data to agent:",d);try{const h=`I've shared an image: ${s.name}`;await this.room.localParticipant.sendText(h,{topic:"lk.chat",destinationIdentities:[]})}catch(h){console.warn("ChatManager: Failed to send image notification to agent:",h)}}const u={...c,metadata:{...c.metadata,uploading:!1,uploadProgress:1,streamId:l.id}};return this.eventEmitter.emit("chat.message.updated",u),l});await Promise.all(r)}catch(r){throw console.error("ChatManager: Failed to send attachments:",r),new tt("Failed to send attachments","NETWORK_ERROR",r)}}async sendAttachment(t,n){return this.sendAttachments([t],n)}convertMarkdownToText(t){if(!t)return"";let n=t;return n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/__(.*?)__/g,"$1"),n=n.replace(/\*(.*?)\*/g,"$1"),n=n.replace(/_(.*?)_/g,"$1"),n=n.replace(/~~(.*?)~~/g,"$1"),n=n.replace(/`([^`]+)`/g,"$1"),n=n.replace(/```[\s\S]*?```/g,""),n=n.replace(/^#{1,6}\s+/gm,""),n=n.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),n.trim()}}class gw{constructor(t){Ie(this,"room",null);Ie(this,"eventEmitter");Ie(this,"silencePreventionNode",null);Ie(this,"silencePreventionOscillator",null);Ie(this,"audioContext",null);this.eventEmitter=t,this.initializeAudioContext()}initializeAudioContext(){try{if(this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("🔊 MediaManager: AudioContext created:",{state:this.audioContext.state,sampleRate:this.audioContext.sampleRate})),this.audioContext.state==="suspended"){console.log("🔊 MediaManager: AudioContext suspended, will resume on user interaction");const t=async()=>{this.audioContext&&this.audioContext.state==="suspended"&&(await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed:",this.audioContext.state)),document.removeEventListener("click",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",t)};document.addEventListener("click",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0})}else this.audioContext.state==="running"&&console.log("✅ MediaManager: AudioContext already running")}catch(t){console.error("MediaManager: Failed to initialize AudioContext:",t)}}async ensureAudioContextRunning(){if(this.audioContext||this.initializeAudioContext(),this.audioContext&&this.audioContext.state==="suspended"){console.log("🔊 MediaManager: Attempting to resume suspended AudioContext");try{await this.audioContext.resume(),console.log("✅ MediaManager: AudioContext resumed successfully")}catch(t){console.error("MediaManager: Failed to resume AudioContext:",t)}}}setRoom(t){this.room=t}getLocalParticipant(){var t;return((t=this.room)==null?void 0:t.localParticipant)??null}getRemoteParticipants(){var t;return Array.from(((t=this.room)==null?void 0:t.remoteParticipants.values())??[])}async toggleMicrophone(t){return this.setMicrophoneEnabled(t!==!1)}async setMicrophoneEnabled(t){var n,i,r;try{if(!this.room||this.room.state!=="connected")throw console.warn("⚠️ MediaManager: Cannot enable microphone - room not connected",{hasRoom:!!this.room,roomState:(n=this.room)==null?void 0:n.state}),new tt("Cannot enable microphone: room not connected","CONNECTION_FAILED");await this.ensureAudioContextRunning();const s=(i=this.room)==null?void 0:i.localParticipant.isMicrophoneEnabled,o=t??!s;o&&this.startSilencePrevention(),await((r=this.room)==null?void 0:r.localParticipant.setMicrophoneEnabled(o,{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0})),o?this.eventEmitter.emit("track.unmuted",{source:"microphone",enabled:!0}):(this.eventEmitter.emit("track.muted",{source:"microphone",enabled:!1}),this.stopSilencePrevention()),console.log("🎤 MediaManager: Microphone",o?"enabled":"disabled")}catch(s){throw console.error("MediaManager: Failed to toggle microphone:",s),this.stopSilencePrevention(),new tt("Failed to toggle microphone","PERMISSION_DENIED",s)}}startSilencePrevention(){try{if(this.audioContext||(this.audioContext=new AudioContext),this.silencePreventionOscillator)return;console.log("🔇 MediaManager: Starting silence prevention"),this.silencePreventionOscillator=this.audioContext.createOscillator(),this.silencePreventionNode=this.audioContext.createGain(),this.silencePreventionOscillator.frequency.value=20,this.silencePreventionNode.gain.value=.001,this.silencePreventionOscillator.connect(this.silencePreventionNode),this.silencePreventionNode.connect(this.audioContext.destination),this.silencePreventionOscillator.start(),console.log("✅ MediaManager: Silence prevention started")}catch(t){console.error("❌ MediaManager: Failed to start silence prevention:",t)}}stopSilencePrevention(){try{this.silencePreventionOscillator&&(console.log("🔇 MediaManager: Stopping silence prevention"),this.silencePreventionOscillator.stop(),this.silencePreventionOscillator.disconnect(),this.silencePreventionOscillator=null),this.silencePreventionNode&&(this.silencePreventionNode.disconnect(),this.silencePreventionNode=null)}catch(t){console.error("❌ MediaManager: Failed to stop silence prevention:",t)}}async toggleCamera(t){return this.setCameraEnabled(t!==!1)}async setCameraEnabled(t){var n,i;try{const r=(n=this.room)==null?void 0:n.localParticipant.isCameraEnabled,s=t??!r;await((i=this.room)==null?void 0:i.localParticipant.setCameraEnabled(s)),s?this.eventEmitter.emit("track.unmuted",{source:"camera",enabled:!0}):this.eventEmitter.emit("track.muted",{source:"camera",enabled:!1})}catch(r){throw new tt("Failed to toggle camera","PERMISSION_DENIED",r)}}async enableCamera(){return this.setCameraEnabled(!0)}async disableCamera(){return this.setCameraEnabled(!1)}async startScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!0)),this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0})}catch(n){throw new tt("Failed to start screen share","PERMISSION_DENIED",n)}}async stopScreenShare(){var t;try{await((t=this.room)==null?void 0:t.localParticipant.setScreenShareEnabled(!1)),this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1})}catch(n){throw new tt("Failed to stop screen share","PERMISSION_DENIED",n)}}async getAudioInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="audioinput")}catch(t){throw new tt("Failed to get audio input devices","DEVICE_ERROR",t)}}async getVideoInputDevices(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch(t){throw new tt("Failed to get video input devices","DEVICE_ERROR",t)}}async setAudioInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){throw new tt("Failed to set audio input device","DEVICE_ERROR",i)}}async setVideoInputDevice(t){var n;try{if(!((n=this.room)!=null&&n.localParticipant))throw new Error("Not connected to room")}catch(i){throw new tt("Failed to set video input device","DEVICE_ERROR",i)}}getMicrophoneTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===B.Source.Microphone)return n.track;return null}getCameraTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===B.Source.Camera)return n.track;return null}getScreenShareTrack(){const t=this.getLocalParticipant();if(!t)return null;for(const[,n]of t.trackPublications)if(n.source===B.Source.ScreenShare)return n.track;return null}get isMicrophoneEnabled(){const t=this.getMicrophoneTrack();return t?!t.isMuted:!1}get isCameraEnabled(){const t=this.getCameraTrack();return t?!t.isMuted:!1}get isScreenShareEnabled(){const t=this.getScreenShareTrack();return t?!t.isMuted:!1}getAgentAudioTrack(){const t=this.getRemoteParticipants();console.log("🔊 MediaManager.getAgentAudioTrack: Checking remote participants:",{count:t.length,participants:t.map(n=>({identity:n.identity,name:n.name,hasMicTrack:!!n.getTrackPublication(B.Source.Microphone)}))});for(const n of t){const i=n.getTrackPublication(B.Source.Microphone);if(i!=null&&i.track)return console.log("✅ MediaManager.getAgentAudioTrack: Found audio track for",n.identity),{source:B.Source.Microphone,participant:n,publication:i}}return console.log("❌ MediaManager.getAgentAudioTrack: No audio track found"),null}getAgentVideoTrack(){const t=this.getRemoteParticipants();for(const n of t){const i=n.getTrackPublication(B.Source.Camera);if(i!=null&&i.track)return{source:B.Source.Camera,participant:n,publication:i}}return null}getVideoTrackRefs(){const t=[],n=this.getLocalParticipant();if(n){const r=n.getTrackPublication(B.Source.Camera);r!=null&&r.track&&t.push({source:B.Source.Camera,participant:n,publication:r});const s=n.getTrackPublication(B.Source.ScreenShare);s!=null&&s.track&&t.push({source:B.Source.ScreenShare,participant:n,publication:s})}const i=this.getRemoteParticipants();for(const r of i){const s=r.getTrackPublication(B.Source.Camera);s!=null&&s.track&&t.push({source:B.Source.Camera,participant:r,publication:s});const o=r.getTrackPublication(B.Source.ScreenShare);o!=null&&o.track&&t.push({source:B.Source.ScreenShare,participant:r,publication:o})}return t}getCameraTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===B.Source.Camera)}getScreenShareTrackRefs(){return this.getVideoTrackRefs().filter(t=>t.source===B.Source.ScreenShare)}getPublishPermissions(){const t=this.getLocalParticipant();if(!t)return{camera:!1,microphone:!1,screenShare:!1,data:!1};const n=t.permissions;if(!n)return{camera:!0,microphone:!0,screenShare:!0,data:!0};const i=r=>!!n.canPublish&&(n.canPublishSources.length===0||n.canPublishSources.includes(r));return{camera:i(1),microphone:i(2),screenShare:i(3),data:n.canPublishData??!1}}canPublishSource(t){return this.getPublishPermissions()[t]}}class bw{constructor(t,n){Ie(this,"room",null);Ie(this,"config");Ie(this,"eventEmitter");Ie(this,"connectionState",$e.Disconnected);Ie(this,"isConnected",!1);Ie(this,"currentAgentInfo",null);this.config=t,this.eventEmitter=n,this.initializeRoom()}initializeRoom(){this.room=new vi({adaptiveStream:!1,stopLocalTrackOnUnpublish:!1,audioCaptureDefaults:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0},publishDefaults:{stopMicTrackOnMute:!1,preConnectBuffer:!0}}),this.setupRoomEventListeners()}setupRoomEventListeners(){this.room&&(this.room.on(j.Connected,()=>{this.connectionState=$e.Connected,this.isConnected=!0,console.log("📡 ConnectionManager: Emitting connection.connected event"),this.eventEmitter.emit("connection.connected")}),this.room.on(j.Disconnected,t=>{console.log("ConnectionManager: Room disconnected, reason:",t),this.connectionState=$e.Disconnected,this.isConnected=!1,t&&console.log("ConnectionManager: Disconnect reason details:",{reason:t.toString(),connectionState:this.connectionState}),this.eventEmitter.emit("connection.disconnected",t==null?void 0:t.toString())}),this.room.on(j.ConnectionStateChanged,t=>{this.connectionState=t,t===$e.Connecting&&this.eventEmitter.emit("connection.connecting")}),this.room.on(j.ParticipantConnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.joined",n)}),this.room.on(j.ParticipantDisconnected,t=>{const n={id:t.identity,name:t.name||t.identity,isLocal:!1};this.eventEmitter.emit("participant.left",n)}),this.room.on(j.LocalTrackPublished,t=>{console.log("ConnectionManager: Local track published:",t.source),t.source===B.Source.ScreenShare?this.eventEmitter.emit("track.unmuted",{source:"screenShare",enabled:!0}):t.source===B.Source.Microphone&&(console.log("✅ ConnectionManager: Local MICROPHONE track RE-PUBLISHED at:",new Date().toISOString()),console.log(" Track restart complete - audio should resume"))}),this.room.on(j.LocalTrackUnpublished,t=>{console.log(" ConnectionManager: Local track unpublished:",t.source),t.source===B.Source.ScreenShare?this.eventEmitter.emit("track.muted",{source:"screenShare",enabled:!1}):t.source===B.Source.Microphone&&(console.warn("⚠️ ConnectionManager: Local MICROPHONE track UNPUBLISHED at:",new Date().toISOString()),console.log(" ⚠️ WARNING: This will cause audio disruption!"))}),this.room.on(j.LocalAudioSilenceDetected,()=>{var t,n;console.log("🔇 ConnectionManager: Local audio silence detected at:",new Date().toISOString()),console.log(" Remote participants count:",(t=this.room)==null?void 0:t.remoteParticipants.size),(n=this.room)==null||n.remoteParticipants.forEach(i=>{console.log(" Remote participant:",i.identity,{audioTracks:i.audioTrackPublications.size,hasAudio:Array.from(i.audioTrackPublications.values()).some(r=>r.track)})})}),this.room.on(j.TrackSubscribed,(t,n,i)=>{var r,s;console.log("🎵 ConnectionManager: Track subscribed:",{trackKind:t.kind,trackSource:t.source,participantIdentity:i.identity,isAgent:(r=i.identity)==null?void 0:r.startsWith("agent-")}),this.eventEmitter.emit("media.track.subscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((s=t.source)==null?void 0:s.toString())||"unknown",participantId:i.identity,isEnabled:!t.isMuted,isMuted:t.isMuted})}),this.room.on(j.TrackUnsubscribed,(t,n,i)=>{var r;console.log("🔇 ConnectionManager: Track unsubscribed:",{trackKind:t.kind,participantIdentity:i.identity}),this.eventEmitter.emit("media.track.unsubscribed",{id:t.sid||n.trackSid,kind:t.kind,source:((r=t.source)==null?void 0:r.toString())||"unknown",participantId:i.identity,isEnabled:!1,isMuted:!0})}))}async fetchConnectionDetails(t,n,i,r){try{const s={agent_id:t,participant_name:n,participant_metadata:r||{user_id:""},modality:i[0],modalities:i},o={accept:"application/json","Content-Type":"application/json"};if(this.config.authToken)o.Authorization=`Bearer ${this.config.authToken}`;else if(this.config.appId&&this.config.appSecret)o["X-APP-ID"]=this.config.appId,o["X-APP-SECRET"]=this.config.appSecret;else throw new Error("Either authToken or both appId and appSecret must be provided");const a=await fetch(`${this.config.baseUrl}/api/live/agent/session`,{method:"POST",headers:o,body:JSON.stringify(s)});if(!a.ok){let u=`HTTP ${a.status}: Failed to fetch connection details`;try{const d=await a.json();d&&(d.error?u=`API Error: ${d.error}`:d.detail?u=`API Error: ${d.detail}`:d.message&&(u=`API Error: ${d.message}`))}catch{try{const h=await a.text();h&&(u=`API Error: ${h}`)}catch{}}throw new Error(u)}const c=await a.json();let l;return c.agent_info&&(l={id:c.agent_info.agent_info.id,name:c.agent_info.agent_info.name,capabilities:c.agent_info.capabilities,modality_supported:c.agent_info.modality_supported,session_settings:c.agent_info.session_settings||{}},this.currentAgentInfo=l),{serverUrl:c.wss_url,participantToken:c.token,voxketSessionId:c.session_id,agentInfo:l}}catch(s){console.error("ConnectionManager: fetchConnectionDetails failed:",s);const o=new tt(`Failed to fetch connection details: ${s instanceof Error?s.message:"Unknown error"}`,"CONNECTION_FAILED",s);throw this.eventEmitter.emit("connection.error",o),o}}async connect(t,n,i,r){var s;try{this.eventEmitter.emit("connection.connecting");const o=await this.fetchConnectionDetails(t,n,i,r);return await((s=this.room)==null?void 0:s.connect(o.serverUrl,o.participantToken)),this.isConnected=!0,o}catch(o){console.error("ConnectionManager: Connection failed:",o);const a=new tt(`Failed to connect to Voxket services: ${o instanceof Error?o.message:"Unknown error"}`,"CONNECTION_FAILED",o);throw this.eventEmitter.emit("connection.error",a),a}}async disconnect(){try{this.room&&await this.room.disconnect(),this.isConnected=!1,this.currentAgentInfo=null,this.initializeRoom(),this.eventEmitter.emit("connection.disconnected")}catch(t){console.error("ConnectionManager: Disconnect failed:",t);const n=new tt("Failed to disconnect properly","NETWORK_ERROR",t);throw this.eventEmitter.emit("connection.error",n),n}}getRoom(){return this.room}getConnectionState(){return this.connectionState}get connected(){return this.isConnected&&this.connectionState===$e.Connected}getCurrentAgentInfo(){return this.currentAgentInfo}getParticipants(){if(!this.room)return[];const t=[];return this.room.localParticipant&&t.push({id:this.room.localParticipant.identity,name:this.room.localParticipant.name||this.room.localParticipant.identity,isLocal:!0}),this.room.remoteParticipants.forEach(n=>{t.push({id:n.identity,name:n.name||n.identity,isLocal:!1})}),t}updateConfig(t){this.config={...this.config,...t}}}class yw{constructor(t,n,i){Ie(this,"room",null);Ie(this,"eventEmitter");Ie(this,"chatManager");Ie(this,"agentManager");Ie(this,"textStreamHandlersRegistered",!1);Ie(this,"_eventEmitters",new Map);this.eventEmitter=t,this.chatManager=n,this.agentManager=i}setRoom(t){this.room=t,t&&!this.textStreamHandlersRegistered&&(console.log("📡 StreamHandlerManager: Auto-registering handlers on room set"),this.setupTextStreamHandlers())}areHandlersRegistered(){return this.textStreamHandlersRegistered}resetHandlersFlag(){this.textStreamHandlersRegistered=!1}setupTextStreamHandlers(){this.room&&(this.registerChatHandler(),this.registerTranscriptionHandler(),this.registerSuggestedResponseHandler(),this.registerAgentStateHandler(),this.registerFunctionToolsHandler(),this.registerImageTextStreamHandler(),this.registerImageByteStreamHandler(),this.registerCommonTopicHandlers(),this.registerWildcardHandler(),this.textStreamHandlersRegistered=!0)}registerChatHandler(){try{this.room.registerTextStreamHandler("lk.chat",async(t,n)=>{try{const i=await t.readAll(),r={id:`msg_${Date.now()}_${n.identity||"user"}_${Math.random().toString(36).substr(2,9)}`,content:i,timestamp:new Date,sender:{id:n.identity||"user",name:n.identity||"User",type:"participant"},metadata:{topic:"lk.chat"}};this.eventEmitter.emit("chat.message.received",r)}catch(i){console.error("StreamHandlerManager: Failed to process lk.chat message:",i)}})}catch(t){console.warn("StreamHandlerManager: lk.chat handler already registered, skipping:",t)}}registerTranscriptionHandler(){try{console.log("📡 StreamHandlerManager: Registering lk.transcription handler"),this.room.registerTextStreamHandler("lk.transcription",async(t,n)=>{var i,r;console.log("💬 StreamHandlerManager: Received lk.transcription stream from:",n.identity);try{const s=n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity),o=n.identity,a=this.chatManager.getActiveTranscription(o);let c,l=!0;a?(c=a.messageId,l=!1):(c=`msg_${s?"user":"agent"}_${n.identity}_${Date.now()}`,this.chatManager.trackTranscription(o,c));let u="";const d=this.agentManager.getCurrentAgentInfo(),h=(d==null?void 0:d.name)||n.identity||"AI Assistant",f=s?"participant":"agent",g=s?"User":h,p={id:c,content:"",timestamp:new Date,sender:{id:n.identity||"unknown",name:g,type:f},metadata:{topic:"lk.transcription",streaming:!0}};l&&this.eventEmitter.emit("chat.message.received",p);for await(const S of t){u+=S;const k=this.chatManager.convertMarkdownToText(u),x={...p,content:k,metadata:{...p.metadata,streaming:!0}};this.eventEmitter.emit("chat.message.updated",x)}const v=this.chatManager.convertMarkdownToText(u),b={...p,content:v,metadata:{...p.metadata,streaming:!1}};this.eventEmitter.emit("chat.message.updated",b);const w={id:c,text:v,isFinal:!0,startTime:p.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",w)}catch(s){console.error("StreamHandlerManager: Failed to process lk.transcription message:",s);try{const o=await t.readAll(),a=this.agentManager.getCurrentAgentInfo(),c=(a==null?void 0:a.name)||n.identity||"AI Assistant",l={id:`msg_${Date.now()}_agent_transcription_${Math.random().toString(36).substr(2,9)}`,content:o,timestamp:new Date,sender:{id:n.identity||"agent",name:c,type:"agent"},metadata:{topic:"lk.transcription"}};this.eventEmitter.emit("chat.message.received",l),console.log("💬 StreamHandlerManager: Emitted chat.message.received:",{id:l.id,sender:l.sender.name,contentLength:l.content.length,preview:l.content.substring(0,50)});const u={id:l.id,text:l.content,isFinal:!0,startTime:l.timestamp.getTime(),participantId:n.identity||"agent"};this.eventEmitter.emit("transcription.received",u),console.log("📝 StreamHandlerManager: Emitted transcription.received:",{id:u.id,textLength:u.text.length})}catch(o){console.error("StreamHandlerManager: Fallback failed for lk.transcription:",o)}}})}catch(t){console.warn("StreamHandlerManager: lk.transcription handler already registered, skipping:",t)}}registerSuggestedResponseHandler(){try{this.room.registerTextStreamHandler("suggested_response",async t=>{const n=await t.readAll();let i=[];try{i=["tes","hello how are you","algebra make me learn that","what is the meaning of life"]}catch(r){console.warn("StreamHandlerManager: Failed to parse suggested_response:",r,n)}this.eventEmitter.emit("suggested.response",i)})}catch(t){console.warn("StreamHandlerManager: suggested_response handler already registered, skipping:",t)}}registerAgentStateHandler(){try{this.room.registerTextStreamHandler("agent_state_changed",async(t,n)=>{const i=await t.readAll();let r={};try{r=typeof i=="string"?JSON.parse(i.replace(/'/g,'"')):i}catch(s){console.warn("StreamHandlerManager: Failed to parse agent_state_changed:",s,i)}this.agentManager.handleAgentStateChanged(r)})}catch(t){console.warn("StreamHandlerManager: agent_state_changed handler already registered, skipping:",t)}}registerFunctionToolsHandler(){try{this.room.registerTextStreamHandler("function_tools_executed",async(t,n)=>{const i=await t.readAll();let r={};try{if(typeof i=="string")try{r=JSON.parse(i)}catch(s){let o=i;try{o=o.replace(/\bTrue\b/g,"true"),o=o.replace(/\bFalse\b/g,"false"),o=o.replace(/\bNone\b/g,"null");const a=o.replace(/\\"/g,"___ESCAPED_QUOTE___");let c="",l=!1;for(let u=0;u<a.length;u++){const d=a[u],h=u>0?a[u-1]:"";d==='"'&&h!=="\\"?(l=!l,c+=d):d==="'"&&h!=="\\"&&!l?c+='"':c+=d}o=c.replace(/___ESCAPED_QUOTE___/g,'\\"'),r=JSON.parse(o)}catch(a){console.warn("StreamHandlerManager: Enhanced parsing also failed:",a);try{let c=i.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null");r=new Function("return "+c)()}catch(c){throw console.error("StreamHandlerManager: All parsing methods failed:",c),s}}}else r=i}catch(s){console.warn("StreamHandlerManager: Failed to parse function_tool_executed:",s,i);let o=null;if(typeof i=="string"&&i.includes("visualization_data"))try{const a=i.match(/"arguments":\s*"({.*?})"/);if(a){const c=a[1].replace(/\\"/g,'"');o=JSON.parse(c),console.log("🛠️ StreamHandlerManager: Extracted visualization data:",o)}}catch(a){console.warn("StreamHandlerManager: Failed to extract visualization data:",a)}r={type:"function_tools_executed",function_calls:[],function_call_outputs:[],created_at:Date.now()/1e3,parseError:!0,rawData:i,extractedVisualizationData:o}}this.eventEmitter.emit("tool.executed",r)})}catch(t){console.warn("StreamHandlerManager: function_tool_executed handler already registered, skipping:",t)}}registerImageTextStreamHandler(){try{this.room.registerTextStreamHandler("images",async(t,n)=>{try{const i=await t.readAll()}catch(i){console.error("StreamHandlerManager: Error processing images stream:",i)}})}catch(t){console.warn("StreamHandlerManager: images text handler already registered, skipping:",t)}}registerImageByteStreamHandler(){try{this.room.registerByteStreamHandler("images",async(t,n)=>{var i,r;try{const s=t.info,o={id:`img_${Date.now()}_${n.identity||"agent"}_${Math.random().toString(36).substr(2,9)}`,content:`🖼️ ${s.name||"Image"}`,sender:{id:n.identity||"agent",name:n.identity||"Agent",type:n.identity===((r=(i=this.room)==null?void 0:i.localParticipant)==null?void 0:r.identity)?"participant":"agent"},timestamp:new Date,metadata:{type:"attachment",fileName:s.name,fileSize:s.size,mimeType:s.mimeType,streamId:s.id,downloading:!0}};this.eventEmitter.emit("chat.message.received",o),t.onProgress&&(t.onProgress=d=>{const h={...o,metadata:{...o.metadata,downloadProgress:d||0}};this.eventEmitter.emit("chat.message.updated",h)});const a=[];for await(const d of t)a.push(d);const c=new Blob(a,{type:s.mimeType||"application/octet-stream"}),l=URL.createObjectURL(c),u={...o,metadata:{...o.metadata,downloading:!1,downloadProgress:1,downloadUrl:l,blob:c}};this.eventEmitter.emit("chat.message.updated",u)}catch(s){console.error("StreamHandlerManager: Error processing image attachment:",s)}})}catch(t){console.warn("StreamHandlerManager: image byte handler already registered, skipping:",t)}}registerCommonTopicHandlers(){["error","warning","status","system","debug","info"].forEach(n=>{try{this.room.registerTextStreamHandler(n,async(i,r)=>{try{const s=await i.readAll();if(console.log(`📝 StreamHandlerManager: Received '${n}' stream:`,s),n==="error"){let o={};try{o=typeof s=="string"?JSON.parse(s):s}catch{o={message:s}}console.warn("⚠️ StreamHandlerManager: Agent error:",o),this.eventEmitter.emit("agent.error",o)}else this.eventEmitter.emit("text.stream.received",{topic:n,data:s,participantInfo:r})}catch(s){console.error(`StreamHandlerManager: Failed to process '${n}' stream:`,s)}})}catch(i){console.warn(`StreamHandlerManager: Handler for '${n}' already registered, skipping:`,i)}})}registerWildcardHandler(){try{this.room.registerTextStreamHandler("*",async(t,n)=>{var i;try{const r=await t.readAll(),s=((i=t.info)==null?void 0:i.topic)||"unknown";if(this._eventEmitters.has(s)){const o=this._eventEmitters.get(s);try{o(r),console.log(`📝 StreamHandlerManager: Processed custom topic '${s}' via event emitter`)}catch(a){console.error(`StreamHandlerManager: Error in custom handler for topic '${s}':`,a)}}else console.log(`📝 StreamHandlerManager: Received unhandled text stream for topic '${s}':`,r),this.eventEmitter.emit("text.stream.unhandled",{topic:s,data:r,participantInfo:n})}catch(r){console.error("StreamHandlerManager: Failed to process unhandled text stream:",r)}})}catch(t){console.warn("StreamHandlerManager: Generic text stream handler already registered, skipping:",t)}}registerEventEmitter(t,n){if(!this.room)throw new Error("Room not available");this._eventEmitters.set(t,n),console.log(`📝 StreamHandlerManager: Stored handler for topic '${t}' in event emitters map`);try{this.room.registerTextStreamHandler(t,async i=>{try{const r=await i.readAll();console.log(`📝 StreamHandlerManager: Direct handler called for topic '${t}'`),n(r)}catch(r){console.error(`Error processing event for topic '${t}':`,r)}}),console.log(`📝 StreamHandlerManager: Successfully registered direct handler for topic '${t}'`)}catch(i){console.warn(`StreamHandlerManager: Direct handler registration failed for topic '${t}':`,i),console.log(`📝 StreamHandlerManager: Wildcard handler will process topic '${t}' instead`)}}getRegisteredEventEmitters(){return Array.from(this._eventEmitters.keys())}hasEventEmitter(t){return this._eventEmitters.has(t)}}const vw=O.createContext(null);function Pa({config:e,children:t,autoConnect:n=!1,client:i}){const[r,s]=O.useState(null),[o,a]=O.useState(!1),[c,l]=O.useState(!1),[u,d]=O.useState(null),[h,f]=O.useState(null),[g,p]=O.useState("idle"),[v,b]=O.useState(null),[w,S]=O.useState([]),[k,x]=O.useState([]),[T,P]=O.useState([]);O.useEffect(()=>{const H=i||new Po(e);s(H);const C=A(H);return n&&!i&&N(H),()=>{C(),i||H.disconnect().catch(console.error)}},[e,n,i]);const A=H=>{const C=()=>{l(!0),d(null)},W=()=>{a(!0),l(!1),d(null)},Y=()=>{a(!1),l(!1),f(null),p("idle"),S([]),x([]),P([])},E=de=>{d(de),l(!1)},J=de=>{f(de),p(de.state)},ne=de=>{p(de),h&&f({...h,state:de})},ie=(de,Pe)=>{f(null),p("idle"),b(Pe),S([]),x([]),P([])},re=de=>{S(Pe=>[...Pe,de])},X=de=>{S(Pe=>Pe.filter(ke=>ke.id!==de.id))},le=de=>{x(Pe=>[...Pe,de])},Z=de=>{x(Pe=>[...Pe,de])},Ae=de=>{console.log("📝 VoxketProvider: Received transcription:",de),P(Pe=>Pe.find(pe=>pe.id===de.id)?(console.log("📝 VoxketProvider: Duplicate transcription detected, skipping:",de.id),Pe):(console.log("📝 VoxketProvider: Adding new transcription:",de.id),[...Pe,de]))},F=()=>{console.log("🧹 VoxketProvider: Clearing chat messages and transcriptions"),x([]),P([])};return H.on("connection.connecting",C),H.on("connection.connected",W),H.on("connection.disconnected",Y),H.on("connection.error",E),H.on("session.created",J),H.on("session.state.changed",ne),H.on("session.ended",ie),H.on("participant.joined",re),H.on("participant.left",X),H.on("chat.message.received",le),H.on("chat.message.sent",Z),H.on("transcription.received",Ae),H.on("chat.history.cleared",F),()=>{console.log("📝 VoxketProvider: Cleaning up event listeners"),H.off("connection.connecting",C),H.off("connection.connected",W),H.off("connection.disconnected",Y),H.off("connection.error",E),H.off("session.created",J),H.off("session.state.changed",ne),H.off("session.ended",ie),H.off("participant.joined",re),H.off("participant.left",X),H.off("chat.message.received",le),H.off("chat.message.sent",Z),H.off("chat.history.cleared",F),H.off("transcription.received",Ae)}},N=async H=>{const C=H||r;if(C)try{await C.connect()}catch(W){console.error("Failed to connect:",W)}},z={client:r,isConnected:o,isConnecting:c,connectionError:u,currentSession:h,sessionState:g,sessionMetrics:v,participants:w,chatMessages:k,transcriptions:T,connect:()=>N(),disconnect:async()=>{if(r)try{await r.disconnect()}catch(H){console.error("Failed to disconnect:",H)}},createSession:async(H,C={})=>{if(!r)throw new Error("Client not initialized");const W={agentId:H,participantName:C.participantName||"User",metadata:C.metadata,modalities:C.modalities||["voice"]};return await r.createSession(W)},endSession:async()=>r?await r.endSession():null,sendChatMessage:async H=>{if(!r)throw new Error("Client not initialized");await r.sendChatMessage(H)},setMicrophoneEnabled:async H=>{if(!r)throw new Error("Client not initialized");await r.setMicrophoneEnabled(H)},setCameraEnabled:async H=>{if(!r)throw new Error("Client not initialized");await r.setCameraEnabled(H)},startScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.startScreenShare()},stopScreenShare:async()=>{if(!r)throw new Error("Client not initialized");await r.stopScreenShare()}};return m.jsx(vw.Provider,{value:z,children:t})}function si(){const e=O.useContext(vw);if(!e)throw new Error("useVoxket must be used within a VoxketProvider");return e}const Mi=new WeakSet,du=new WeakSet;class xw{constructor(t,n){Ie(this,"renderedComponents",new Map);Ie(this,"config");Ie(this,"voxketClient");this.config=t,this.voxketClient=n}renderUI(t={}){const n=this.resolveTarget(t.target||"body"),i=this.getTargetKey(n);if(du.has(n)){console.warn("⚠️ UIRenderer: Target is already being processed, skipping renderUI");return}if(Mi.has(n)){console.log("✋ UIRenderer: Target already has a React root in registry, updating existing props...");const s=this.renderedComponents.get(i);if(s&&s.root){const o=this.buildWidgetProps(t);try{s.root.render(O.createElement(Pa,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:O.createElement(Na,o)})),console.log("✅ UIRenderer: Successfully updated existing widget with new props");return}catch(a){throw console.error("Error re-rendering existing widget:",a),new Error(`Failed to update existing widget: ${a instanceof Error?a.message:"Unknown error"}`)}}else console.warn("⚠️ Registry inconsistency detected, cleaning up"),Mi.delete(n)}let r=this.renderedComponents.get(i);if(r&&r.target===n&&Mi.has(n)){console.log("🔄 UIRenderer: Reusing existing React root for target:",i);const s=r.root,o=this.buildWidgetProps(t);try{s.render(O.createElement(Pa,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:O.createElement(Na,o)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}return}du.add(n);try{if(r){console.log("🧹 UIRenderer: Cleaning up existing component for different target");try{r.root.unmount(),this.renderedComponents.delete(i),Mi.delete(r.target),n.innerHTML=""}catch(a){console.warn("Failed to cleanup existing root:",a)}}if(Mi.has(n)){console.warn("⚠️ UIRenderer: Target already in registry, skipping root creation");return}console.log("🆕 UIRenderer: Creating new React root for target:",i);const s=iT.createRoot(n);this.renderedComponents.set(i,{root:s,target:n}),Mi.add(n);const o=this.buildWidgetProps(t);if(!s||typeof s.render!="function")throw new Error("Invalid React root. Make sure React 18+ is properly installed and configured.");try{s.render(O.createElement(Pa,{config:this.config,autoConnect:t.autoStart||!1,client:this.voxketClient,children:O.createElement(Na,o)}))}catch(a){throw console.error("Error rendering Voxket widget:",a),new Error(`Failed to render Voxket widget: ${a instanceof Error?a.message:"Unknown error"}`)}}finally{du.delete(n)}}removeUI(t){const n=t?this.resolveTarget(t):null;if(n){const i=this.getTargetKey(n),r=this.renderedComponents.get(i);if(r){console.log("🗑️ UIRenderer: Removing UI for target:",i),this.renderedComponents.delete(i);const s=r.target,o=()=>{var a;try{s&&s.isConnected?typeof((a=r.root)==null?void 0:a.unmount)=="function"&&(r.root.unmount(),console.log("✅ UIRenderer: UI unmounted for target:",i)):console.log("ℹ️ UIRenderer: Target element already disconnected, skipping unmount")}catch(c){console.warn("Failed to unmount React root:",c)}finally{requestAnimationFrame(()=>{try{n.querySelectorAll('[id*="voxket"], [class*="voxket"], .fixed.inset-0.z-50').forEach(l=>{try{l.parentNode&&l.remove()}catch(u){console.warn("Failed to remove element:",u)}})}finally{Mi.delete(n)}})}};queueMicrotask(()=>setTimeout(o,0))}else console.log("ℹ️ UIRenderer: No component found for target, cleaning registry:",i),Mi.delete(n),n.isConnected&&n.hasChildNodes()&&(n.innerHTML="");n===document.body&&n.querySelectorAll(".fixed.z-50, .fixed.inset-0").forEach(o=>{if(o.classList.contains("bg-black")&&(o.classList.contains("backdrop-blur-sm")||o.classList.contains("bg-opacity-30")))try{o.remove()}catch(a){console.warn("Failed to remove fixed element:",a)}})}}removeAllUI(){for(const[t,n]of this.renderedComponents)n.root.unmount();this.renderedComponents.clear(),this.forceCleanupFullscreenOverlays()}forceCleanupFullscreenOverlays(){document.body.querySelectorAll(".fixed.inset-0.z-50").forEach(n=>{if(n.classList.contains("bg-black")&&(n.classList.contains("backdrop-blur-sm")||n.classList.contains("bg-opacity-30")))try{n.remove()}catch(i){console.warn("Failed to remove overlay:",i)}})}resolveTarget(t){if(typeof t=="string"){const n=document.querySelector(t);if(!n)throw new Error(`Target element not found: ${t}`);return n}return t}getTargetKey(t){return t.id?t.id:t.className?t.tagName+"_"+t.className.replace(/\s+/g,"_"):t.tagName+"_"+t.outerHTML.length%1e3}buildWidgetProps(t){var i,r,s;const n=this.config;return{agentId:t.agentId||n.agentId||"default-agent",participantName:t.participantName||n.participantName||"User",baseUrl:this.config.baseUrl,appSecret:this.config.appSecret,appId:this.config.appId,className:t.className,theme:typeof t.theme=="string"?t.theme:void 0,modalities:t.modality||n.modalities||["voice"],suportsChatInput:((i=t.modality)==null?void 0:i.includes("chat"))!==!1,suportsVideoInput:((r=t.modality)==null?void 0:r.includes("video"))===!0,suportsScreenShare:((s=t.modality)==null?void 0:s.includes("screen_share"))===!0,autoStart:t.autoStart,displayType:t.displayType||"widget",popupPosition:t.popupPosition||"bottom-right",popupTriggerText:t.popupTriggerText||"Open Chat",popupModalityMode:t.popupModalityMode||"all",width:t.width,height:t.height,onDisplayTypeChange:t.onDisplayTypeChange,prompts:t.prompts,statusMessage:t.statusMessage,welcomeTitle:t.welcomeTitle,welcomeSubTitle:t.welcomeSubTitle,loadingText:t.loadingText,voxketClient:this.voxketClient,participantMetadata:t.participantMetadata}}updateConfig(t){this.config=t}}class kw{constructor(t){Ie(this,"agentState","idle");Ie(this,"isAgentConnected",!1);Ie(this,"currentAgentInfo",null);Ie(this,"eventEmitter");this.eventEmitter=t}getAgentState(){return this.agentState}setAgentState(t){this.agentState!==t&&(this.agentState=t,this.eventEmitter.emit("agent.state.changed",{state:t}))}getIsAgentConnected(){return this.isAgentConnected}setAgentConnected(t){this.isAgentConnected=t,console.log(t?"🤖 AgentManager: Agent marked as connected":"🤖 AgentManager: Agent marked as disconnected")}getCurrentAgentInfo(){return this.currentAgentInfo}setCurrentAgentInfo(t){this.currentAgentInfo=t,console.log("📝 AgentManager: Agent info updated:",t)}reset(){this.agentState="idle",this.isAgentConnected=!1,this.currentAgentInfo=null,console.log("🔄 AgentManager: Agent state reset")}handleAgentStateChanged(t){this.isAgentConnected||(this.setAgentConnected(!0),this.eventEmitter.emit("agent.connected",t)),t.new_state==="speaking"?(this.setAgentState("speaking"),this.eventEmitter.emit("agent.speaking",t)):t.new_state==="thinking"?(this.setAgentState("thinking"),this.eventEmitter.emit("agent.thinking",t)):(t.new_state==="idle"||t.new_state==="listening")&&this.setAgentState("idle")}}class Po extends Sf{constructor(n){super();Ie(this,"config");Ie(this,"pluginManager");Ie(this,"rpcManager");Ie(this,"chatManager");Ie(this,"mediaManager");Ie(this,"connectionManager");Ie(this,"streamHandlerManager");Ie(this,"uiRenderer");Ie(this,"agentManager");Ie(this,"currentSession",null);if(!n.authToken&&(!n.appId||!n.appSecret))throw new Error("Either authToken or both appId and appSecret must be provided");this.config=n,this.chatManager=new mw(this,n.participantName||"User"),this.mediaManager=new gw(this),this.agentManager=new kw(this),this.connectionManager=new bw({baseUrl:n.baseUrl,appId:n.appId,appSecret:n.appSecret,authToken:n.authToken},this),this.streamHandlerManager=new yw(this,this.chatManager,this.agentManager),this.uiRenderer=new xw(n,this),this.pluginManager=new fw(this),this.rpcManager=new pw,this.setupEventListeners(),this.setupRpcEventForwarding()}setupEventListeners(){this.on("connection.connected",()=>{var i,r,s,o,a,c,l;if(console.log("🔌 VoxketClient: connection.connected event fired",{hasSession:!!this.currentSession,sessionState:(i=this.currentSession)==null?void 0:i.state,sessionId:(r=this.currentSession)==null?void 0:r.id}),(o=(s=this.config).onConnected)==null||o.call(s),this.currentSession&&this.currentSession.state==="connecting"){const u=this.currentSession.state;this.currentSession.state="connected",this.emit("session.state.changed","connected",u),console.log("✅ VoxketClient: Session state changed to connected")}else console.log("⚠️ VoxketClient: Cannot update session state",{hasSession:!!this.currentSession,currentState:(a=this.currentSession)==null?void 0:a.state});const n=this.connectionManager.getRoom();if(n){this.rpcManager.setRoom(n);const u=Array.from(n.remoteParticipants.values()).find(d=>{var h;return(h=d.identity)==null?void 0:h.startsWith("agent-")});u&&(console.log("🤖 VoxketClient: Agent already in room, marking as connected",{agentIdentity:u.identity,hasAudioTrack:u.audioTrackPublications.size>0}),this.agentManager.getIsAgentConnected()||(this.agentManager.setAgentConnected(!0),this.emit("agent.connected",{identity:u.identity})))}(l=(c=this.currentSession)==null?void 0:c.activeModalities)!=null&&l.includes("voice")&&setTimeout(async()=>{try{this.mediaManager.getLocalParticipant()&&(this.mediaManager.isMicrophoneEnabled||(await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled after connection")))}catch(u){console.warn("VoxketClient: Failed to enable microphone after room connection:",u)}},100)}),this.on("connection.disconnected",n=>{var i,r,s;(r=(i=this.config).onDisconnected)==null||r.call(i,n),this.streamHandlerManager.resetHandlersFlag(),this.agentManager.reset(),this.chatManager.clearChatMessages(),n&&console.log("🔍 VoxketClient: Disconnect reason details:",{reason:n.toString(),currentSession:(s=this.currentSession)==null?void 0:s.id})}),this.on("connection.error",n=>{var i,r;(r=(i=this.config).onError)==null||r.call(i,n)}),this.on("chat.message.received",n=>{var i,r;this.chatManager.addChatMessage(n),(r=(i=this.config).onMessageReceived)==null||r.call(i,n)}),this.on("chat.message.updated",n=>{this.chatManager.updateChatMessage(n)}),this.on("chat.message.sent",n=>{this.chatManager.addChatMessage(n)}),this.on("transcription.received",n=>{var i,r;(r=(i=this.config).onTranscriptionReceived)==null||r.call(i,n)}),this.on("session.state.changed",n=>{var i,r;(r=(i=this.config).onSessionStateChanged)==null||r.call(i,n)}),this.on("session.created",n=>{var i,r;(r=(i=this.config).onSessionStart)==null||r.call(i,n.id)}),this.on("session.ended",(n,i)=>{var r,s;(s=(r=this.config).onSessionEnd)==null||s.call(r,i)}),this.on("participant.joined",n=>{var i,r;(r=(i=this.config).onUserJoined)==null||r.call(i,n.id)}),this.on("participant.left",n=>{var i,r;(r=(i=this.config).onUserLeft)==null||r.call(i,n.id)})}setupRpcEventForwarding(){if(!this.rpcManager){console.warn("RpcManager not initialized, skipping event forwarding setup");return}this.rpcManager.on("rpc.method.registered",n=>this.emit("rpc.method.registered",n)),this.rpcManager.on("rpc.method.called",n=>this.emit("rpc.method.called",n)),this.rpcManager.on("rpc.interaction.started",n=>this.emit("rpc.interaction.started",n)),this.rpcManager.on("rpc.interaction.completed",n=>this.emit("rpc.interaction.completed",n)),this.rpcManager.on("rpc.interaction.timeout",n=>this.emit("rpc.interaction.timeout",n)),this.rpcManager.on("rpc.interaction.dismissed",n=>this.emit("rpc.interaction.dismissed",n))}async connect(n,i,r,s){const o=n||this.config.agentId||"default-agent",a=i||this.config.participantName||"User",c=r||this.config.modalities||["voice"],l=s||this.config.participantMetadata,u=await this.connectionManager.connect(o,a,c,l),d=this.connectionManager.getRoom();return this.chatManager.setRoom(d),this.mediaManager.setRoom(d),this.streamHandlerManager.setRoom(d),u.agentInfo&&this.agentManager.setCurrentAgentInfo(u.agentInfo),u}async disconnect(){await this.connectionManager.disconnect(),this.currentSession=null;const n=this.connectionManager.getRoom();this.chatManager.setRoom(n),this.mediaManager.setRoom(n),this.streamHandlerManager.setRoom(n)}async createSession(n){var i,r;try{const s=await this.connect(n.agentId,n.participantName,n.modalities,n.participantMetadata),o={id:s.voxketSessionId,agentId:n.agentId,state:"connecting",startedAt:new Date,metadata:n.metadata||{},activeModalities:n.modalities||["voice"],agentInfo:s.agentInfo||this.agentManager.getCurrentAgentInfo()};this.currentSession=o,this.emit("session.created",o);const a=this.connectionManager.getRoom();if(a&&(a.state!=="connected"?(console.log("⏳ VoxketClient: Waiting for room to connect..."),await new Promise((l,u)=>{const d=setTimeout(()=>{u(new Error("Room connection timeout"))},1e4),h=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),console.log("✅ VoxketClient: Room connected successfully"),l()},f=()=>{clearTimeout(d),a.off("connected",h),a.off("disconnected",f),u(new Error("Room disconnected while waiting for connection"))};a.once("connected",h),a.once("disconnected",f)})):console.log("✅ VoxketClient: Room already connected"),this.currentSession.state="connected",this.emit("session.state.changed","connected","connecting"),console.log("⏳ VoxketClient: Waiting for agent to connect..."),await new Promise(l=>{const u=setTimeout(()=>{console.warn("⚠️ VoxketClient: Agent connection timeout (30s), continuing anyway"),l(!1)},3e4),d=()=>{clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),console.log("✅ VoxketClient: Agent connected and ready"),l(!0)},h=f=>{var g,p;((g=f.id)!=null&&g.startsWith("agent-")||(p=f.name)!=null&&p.toLowerCase().includes("agent"))&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),console.log("✅ VoxketClient: Agent participant joined:",f.name||f.id),l(!0))};this.once("agent.connected",d),this.on("participant.joined",h),this.agentManager.getIsAgentConnected()&&(clearTimeout(u),this.off("agent.connected",d),this.off("participant.joined",h),console.log("✅ VoxketClient: Agent already connected"),l(!0))})&&(this.currentSession.state="active",this.emit("session.state.changed","active","connected"))),(i=n.modalities)!=null&&i.includes("voice"))try{await this.mediaManager.setMicrophoneEnabled(!0),this.emit("track.unmuted",{source:"microphone",enabled:!0}),console.log("🎤 VoxketClient: Microphone enabled successfully")}catch(c){console.warn("VoxketClient: Failed to enable microphone, but continuing with session:",c)}if((r=n.modalities)!=null&&r.includes("video"))try{await new Promise(c=>setTimeout(c,200)),await this.mediaManager.enableCamera(),console.log("🎥 VoxketClient: Camera enabled successfully")}catch(c){console.warn("VoxketClient: Failed to enable camera, but continuing with session:",c)}return o}catch(s){throw console.error("VoxketClient: Failed to create session:",s),s instanceof tt?s:s instanceof TypeError&&s.message.includes("fetch")?new tt("Network connection failed","CONNECTION_FAILED",s):s instanceof Error&&s.message.includes("Failed to fetch connection details")?new tt(`API connection failed: ${s.message}`,"CONNECTION_FAILED",s):new tt(`Failed to create session: ${s instanceof Error?s.message:"Unknown error"}`,"SESSION_NOT_FOUND",s)}}async startSession(n,i){const r={agentId:n||this.config.agentId||"default-agent",participantName:(i==null?void 0:i.participantName)||this.config.participantName||"User",modalities:(i==null?void 0:i.modalities)||this.config.modalities||["voice","chat"],metadata:i==null?void 0:i.metadata,participantMetadata:i==null?void 0:i.participantMetadata};return this.createSession(r)}async endSession(){var n,i;if(!this.currentSession)return null;try{const r={sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]};return this.currentSession.endedAt=new Date,this.currentSession.state="disconnected",this.emit("session.ended",this.currentSession,r),await this.disconnect(),r}catch(r){throw new tt("Failed to end session","SESSION_NOT_FOUND",r)}}getCurrentSession(){return this.currentSession}getSessionMetrics(){var n,i;return this.currentSession?{sessionId:this.currentSession.id,duration:Date.now()-(((n=this.currentSession.startedAt)==null?void 0:n.getTime())||0),messageCount:0,participantCount:((i=this.connectionManager.getRoom())==null?void 0:i.remoteParticipants.size)||0,audioQuality:{avgBitrate:64e3,avgLatency:150,packetLoss:.01,jitter:.05},videoQuality:{avgBitrate:5e5,avgLatency:150,packetLoss:.01,jitter:.05},networkStats:{totalBytesReceived:0,totalBytesSent:0,connectionType:"webrtc",avgRoundTripTime:150},events:[]}:null}async sendMessage(n,i){if(!this.currentSession)throw new tt("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendMessage(n,i)}async sendChatMessage(n,i){return this.sendMessage(n,i)}async sendAttachments(n,i){if(!this.currentSession)throw new tt("No active session","SESSION_NOT_FOUND");return this.dismissCurrentInteraction(),this.chatManager.sendAttachments(n,i)}async sendAttachment(n,i){return this.chatManager.sendAttachment(n,i)}getChatMessages(){return this.chatManager.getChatMessages()}addChatMessage(n){this.chatManager.addChatMessage(n)}updateChatMessage(n){this.chatManager.updateChatMessage(n)}clearChatMessages(){this.chatManager.clearChatMessages(),this.dismissCurrentInteraction(),this.uiRenderer.removeAllUI()}toggleMicrophone(n){return this.mediaManager.toggleMicrophone(n)}async setMicrophoneEnabled(n){return this.mediaManager.setMicrophoneEnabled(n)}toggleCamera(n){return this.mediaManager.toggleCamera(n)}async setCameraEnabled(n){return this.mediaManager.setCameraEnabled(n)}async enableCamera(){return this.mediaManager.enableCamera()}async disableCamera(){return this.mediaManager.disableCamera()}async startScreenShare(){return this.mediaManager.startScreenShare()}async stopScreenShare(){return this.mediaManager.stopScreenShare()}async getAudioInputDevices(){return this.mediaManager.getAudioInputDevices()}async getVideoInputDevices(){return this.mediaManager.getVideoInputDevices()}async setAudioInputDevice(n){return this.mediaManager.setAudioInputDevice(n)}async setVideoInputDevice(n){return this.mediaManager.setVideoInputDevice(n)}get isMicrophoneEnabled(){return this.mediaManager.isMicrophoneEnabled}get isCameraEnabled(){return this.mediaManager.isCameraEnabled}get isScreenShareEnabled(){return this.mediaManager.isScreenShareEnabled}getMicrophoneTrack(){return this.mediaManager.getMicrophoneTrack()}getCameraTrack(){return this.mediaManager.getCameraTrack()}getScreenShareTrack(){return this.mediaManager.getScreenShareTrack()}getAgentAudioTrack(){return this.mediaManager.getAgentAudioTrack()}getAgentVideoTrack(){return this.mediaManager.getAgentVideoTrack()}getVideoTrackRefs(){return this.mediaManager.getVideoTrackRefs()}getCameraTrackRefs(){return this.mediaManager.getCameraTrackRefs()}getScreenShareTrackRefs(){return this.mediaManager.getScreenShareTrackRefs()}getPublishPermissions(){return this.mediaManager.getPublishPermissions()}canPublishSource(n){return this.mediaManager.canPublishSource(n)}getLocalParticipant(){return this.mediaManager.getLocalParticipant()}getRemoteParticipants(){return this.mediaManager.getRemoteParticipants()}getParticipants(){return this.connectionManager.getParticipants()}getRoom(){return this.connectionManager.getRoom()}getConnectionState(){return this.connectionManager.getConnectionState()}get connected(){return this.connectionManager.connected}getCurrentAgentInfo(){return this.agentManager.getCurrentAgentInfo()}getIsAgentConnected(){return this.agentManager.getIsAgentConnected()}getAgentState(){return this.agentManager.getAgentState()}renderUI(n={}){this.uiRenderer.renderUI(n)}removeUI(n){this.uiRenderer.removeUI(n)}removeAllUI(){this.uiRenderer.removeAllUI()}async registerFrontendRPC(n,i,r="embedded"){return this.rpcManager.registerFrontendRPC(n,i,r)}getCurrentInteraction(){return this.rpcManager.getCurrentInteraction()}dismissCurrentInteraction(){this.rpcManager.dismissCurrentInteraction()}getRegisteredRpcMethods(){return this.rpcManager.getRegisteredMethods()}unregisterRpcMethod(n){this.rpcManager.unregisterMethod(n)}registerPlugin(n){this.pluginManager.register(n)}getPluginManager(){return this.pluginManager}registerEventListener(n,i){return this.on(n,i)}registerEventEmitter(n,i){return this.streamHandlerManager.registerEventEmitter(n,i)}getRegisteredEventEmitters(){return this.streamHandlerManager.getRegisteredEventEmitters()}hasEventEmitter(n){return this.streamHandlerManager.hasEventEmitter(n)}updateConfig(n){this.config={...this.config,...n},this.uiRenderer.updateConfig(this.config),this.connectionManager.updateConfig({baseUrl:this.config.baseUrl,appId:this.config.appId,appSecret:this.config.appSecret}),this.chatManager.setParticipantName(this.config.participantName||"User")}setParticipantMetadata(n){this.config.participantMetadata=n}getParticipantMetadata(){return this.config.participantMetadata}async startRecording(){var n;try{this.emit("recording.started",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new tt("Failed to start recording","RECORDING_ERROR",i)}}async stopRecording(){var n;try{this.emit("recording.stopped",{sessionId:(n=this.currentSession)==null?void 0:n.id,timestamp:new Date})}catch(i){throw new tt("Failed to stop recording","RECORDING_ERROR",i)}}}const l4=Fe.create(WS),u4=Fe.create(df),d4=Fe.create(qS),h4=Fe.create(uw);function f4({theme:e,mode:t,loadingText:n,sessionState:i}){const r=on(e),s=()=>{if(i==="connected")return"Connecting to agent...";if(n)return n;switch(t){case"voice":return"Connecting to voice agent...";case"chat":return"Starting chat session...";case"video":return"Connecting to video call...";default:return"Connecting..."}};return m.jsxs("div",{className:"flex flex-col items-center justify-center h-full w-full p-8",children:[m.jsxs("div",{className:"text-center",children:[m.jsx("h3",{className:`text-lg font-semibold mb-2 ${r.text.accent}`,children:s()}),m.jsx("p",{className:`text-sm ${r.text.muted}`,children:"Please wait a moment..."})]}),m.jsxs("div",{className:"flex space-x-1 mt-4",children:[m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"0ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"150ms"}}),m.jsx("div",{className:"w-2 h-2 rounded-full animate-bounce bg-blue-500",style:{animationDelay:"300ms"}})]})]})}const p4=Fe.create(f4);function Qb({children:e,theme:t,displayType:n="widget",onClose:i,popupPosition:r="bottom-right",onExpand:s}){const o=on(t);if(n==="fullscreen")return m.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/40 bg-opacity-30 backdrop-blur-sm flex items-center justify-center p-8",onClick:a=>{a.target===a.currentTarget&&i&&i()},children:m.jsxs("div",{className:"w-full h-full max-w-7xl max-h-[95vh] rounded-2xl relative bg-transparent flex flex-col",onClick:a=>{a.stopPropagation()},children:[i&&m.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),i()},className:"absolute top-4 cursor-pointer right-4 z-[10000] w-12 h-12 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 shadow-lg border border-gray-700 backdrop-blur-sm",title:"Exit Fullscreen",type:"button",children:m.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:m.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} w-full h-full flex flex-col rounded-xl shadow-2xl relative overflow-hidden`,"data-theme":t,style:{minHeight:"600px",height:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:"relative z-10 flex flex-col h-full",children:e}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})});if(n==="popup"){const a={"top-left":"top-4 left-4","top-right":"top-4 right-4","bottom-left":"bottom-4 left-4","bottom-right":"bottom-4 right-4"};return m.jsx("div",{className:"fixed rounded-2xl inset-0 z-[9999] pointer-events-none",children:m.jsxs("div",{className:`fixed rounded-2xl ${a[r]} pointer-events-auto`,children:[i&&m.jsx("button",{onClick:i,className:"absolute -top-2 -right-2 z-10 w-8 h-8 rounded-full bg-gray-900 bg-opacity-90 text-white flex items-center justify-center hover:bg-gray-800 transition-all duration-200 text-sm shadow-lg border border-gray-700",children:"×"}),m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} rounded-2xl flex flex-col relative overflow-hidden`,"data-theme":t,style:{width:"350px",height:"500px",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})]})})}return m.jsxs("div",{id:"voice-card",className:`voxket-widget-root theme-${t} ${o.card} relative overflow-hidden w-full h-full`,"data-theme":t,style:{height:"100%",maxHeight:"100%",contain:"layout style paint",overscrollBehavior:"contain",backgroundColor:t==="midnight"?"#161a25":void 0},children:[m.jsx("div",{className:o.cardTopGradient}),m.jsx("div",{className:o.cardPurpleBlur}),m.jsx("div",{className:o.cardPinkBlur}),m.jsx("div",{className:"relative z-10 flex flex-col h-full w-full",children:e}),m.jsx("div",{className:o.cardPulse1}),m.jsx("div",{className:o.cardPulse2,style:{animationDelay:"1s"}})]})}function m4(e){if(typeof window>"u")return null;const{agentId:t,participantName:n,baseUrl:i,appSecret:r,appId:s,authToken:o,prompts:a,statusMessage:c,welcomeTitle:l,welcomeSubTitle:u,className:d,width:h,height:f,loadingText:g,suportsChatInput:p=!0,suportsVideoInput:v=!0,suportsScreenShare:b=!0,theme:w="vox",onSessionStart:S,onSessionEnd:k,enableSessionLogging:x=!0,onSessionLogsUpdate:T,onSessionMetricsUpdate:P,modalities:A=["voice"],displayType:N="widget",popupPosition:y="bottom-right",popupTriggerText:R="Open Chat",onPopupToggle:I,voxketClient:L,onDisplayTypeChange:U,participantMetadata:K,popupModalityMode:ue="all",popupTriggerLogoUrl:se}=e,[z,H]=D.useState(!1),[C,W]=D.useState(null),[Y,E]=D.useState(()=>{try{if(L)return!!L.getCurrentSession()}catch(_){console.error("Error checking existing session:",_)}return!1}),[J,ne]=D.useState(!1),[ie,re]=D.useState(t||""),[X,le]=D.useState(n||"User"),[Z,Ae]=D.useState(()=>{try{if(L)return L.getCurrentSession()}catch(_){console.error("Error getting current session:",_)}return null}),[F,de]=D.useState(()=>{var _,$,te;try{if(L){const ge=L.getCurrentSession();if((_=ge==null?void 0:ge.activeModalities)!=null&&_.includes("chat"))return"chat";if(($=ge==null?void 0:ge.activeModalities)!=null&&$.includes("voice"))return"voice";if((te=ge==null?void 0:ge.activeModalities)!=null&&te.includes("video"))return"video"}}catch(ge){console.error("Error determining current mode:",ge)}return"welcome"}),[Pe,ke]=D.useState(!1),[pe,Te]=D.useState(!1),[Ne,Ce]=D.useState(()=>A.length===1?A[0]:null),[Rt,$t]=D.useState(!1);D.useEffect(()=>{N==="fullscreen"&&console.log("🎯 Widget: Switched to fullscreen mode")},[N]),D.useEffect(()=>{Y&&!J?console.log("📊 Session started:",{currentMode:F,sessionId:Z==null?void 0:Z.id}):!Y&&!J&&F==="welcome"&&console.log("📊 Returned to welcome screen")},[Y,F,J]);const ot=D.useRef(null);if(!ot.current)try{if(L)console.log("🔄 Using existing VoxketClient to preserve session state"),ot.current=L;else if(!o&&(!s||!r)){const _="Missing required props: Either provide 'authToken' or both 'appId' and 'appSecret'";console.error("❌ VoxketClient creation failed:",_),W(new Error(_)),H(!0)}else if(i){const _={...o?{authToken:o}:{appId:s,appSecret:r},baseUrl:i,agentId:ie,participantName:X||"User",modalities:A,participantMetadata:K};console.log("🔧 Creating new VoxketClient with config:",{authMethod:o?"Bearer Token":"App Credentials",...o?{}:{appId:(s==null?void 0:s.substring(0,8))+"..."},baseUrl:i,agentId:ie,participantName:X||"User",modalities:A}),ot.current=new Po(_)}else{const _="Missing required prop: baseUrl";console.error("❌ VoxketClient creation failed:",_),W(new Error(_)),H(!0)}}catch(_){console.error("❌ Failed to create VoxketClient:",_),W(_),H(!0)}const be=ot.current;D.useEffect(()=>{const _=ot.current;return()=>{_&&!L&&(console.log("🧹 Widget unmounting: disconnecting VoxketClient"),_.disconnect().catch($=>{console.error("❌ Error during widget cleanup disconnect:",$)}))}},[L]);const Ft=D.useMemo(()=>N==="popup"&&Ne?[Ne]:A,[N,Ne,A]),at=D.useMemo(()=>{try{if(!be)return console.warn("⚠️ No VoxketClient available, creating fallback room"),new vi;const _=be.getRoom();return console.log("🏠 Widget: Room reference updated:",{roomExists:!!_,roomState:_==null?void 0:_.state,sessionStarted:Y,currentMode:F}),_||new vi}catch(_){return console.error("❌ Error getting room from client:",_),new vi}},[be,Y,F]);D.useEffect(()=>{if(at){const _=()=>{console.log("🏠 Widget: Room state changed:",{state:at.state,numParticipants:at.numParticipants,isConnected:at.state==="connected",sessionId:Z==null?void 0:Z.id})},$=(te,ge,ht)=>{console.log("🎵 Widget: Track subscribed:",{trackKind:te.kind,trackSource:te.source,participantSid:ht.sid,participantIdentity:ht.identity,sessionId:Z==null?void 0:Z.id})};return at.on(j.Connected,_),at.on(j.Disconnected,_),at.on(j.TrackSubscribed,$),()=>{at.off(j.Connected,_),at.off(j.Disconnected,_),at.off(j.TrackSubscribed,$)}}},[at,Z==null?void 0:Z.id]),D.useEffect(()=>{!J&&F==="welcome"?console.log("🎬 Widget: Welcome screen ready"):Y&&F!=="welcome"&&console.log("🎬 Widget: Session mode active:",F)},[F,J,Y]),D.useEffect(()=>{(F==="voice"||F==="video"||F==="chat")&&!Z&&!Y&&!J&&be&&!be.connected&&(console.log("🔄 Auto-correcting: Found orphaned mode without session, returning to welcome"),de("welcome"),ne(!1))},[F,Z,Y,J,be]);const{sessionMetrics:q,sessionLogs:ae,logEvent:Re}=hw({room:at,onSessionStart:S,onSessionEnd:k,enableConsoleLogging:x,enableLocalStorage:x,voxketSessionId:Z==null?void 0:Z.id});D.useEffect(()=>{T&&T(ae)},[ae,T]),D.useEffect(()=>{P&&q&&P(q)},[q,P]),D.useEffect(()=>{if(!be)return;const _=($,te)=>{console.log("📊 Widget: Session state changed:",{from:te,to:$,currentLoading:J}),($==="connecting"||$==="connected")&&(J||(console.log("⏳ Widget: Setting loading=true (waiting for agent)"),ne(!0))),$==="active"&&(console.log("✅ Widget: Session active, agent ready - removing loader"),ne(!1),E(!0)),($==="disconnected"||$==="error")&&(console.log("🔴 Widget: Session ended - resetting state"),ne(!1),E(!1),Ae(null),de("welcome"))};return be.on("session.state.changed",_),()=>{be.off("session.state.changed",_)}},[be,J]),D.useEffect(()=>{if(!be)return;const _=()=>{const $=be.connected,te=be.getCurrentSession();console.log("🔗 Connection state changed:",{isConnected:$,currentSessionId:te==null?void 0:te.id,currentMode:F,loading:J,sessionStarted:Y}),!$&&Y&&!J&&(console.log("🔴 Connection lost during active session - returning to welcome"),ne(!1),E(!1),Ae(null),de("welcome")),$&&te&&J&&(console.log("🟢 Connected with active session - removing loader"),ne(!1),E(!0),Ae(te))};return be.on("connectionStateChanged",_),be.on("sessionEnded",()=>{console.log("📞 Session ended - returning to welcome"),ne(!1),E(!1),Ae(null),de("welcome")}),()=>{be.off("connectionStateChanged",_),be.off("sessionEnded",()=>{})}},[be,F,J,Y]);const Ye=!!(!!(be!=null&&be.connected)&&Y&&Z);D.useEffect(()=>{const _=te=>{console.log("🔴 Widget: Room disconnected:",te),console.log("🔍 Widget: Current state on disconnect:",{currentMode:F,sessionStarted:Y,currentSessionId:Z==null?void 0:Z.id,loading:J}),ne(!1),E(!1),Ae(null),de("welcome"),console.log("🏠 Widget: Automatically returning to welcome screen after disconnect")},$=te=>{console.log("📹 Media devices error:",te)};return at.on(j.MediaDevicesError,$),at.on(j.Disconnected,_),()=>{at.off(j.Disconnected,_),at.off(j.MediaDevicesError,$)}},[at,F,Y,Z==null?void 0:Z.id,J]);const tn=async()=>{try{if(!be){console.error("❌ VoxketClient not available"),W(new Error("VoxketClient not initialized")),H(!0);return}ne(!0),de("voice"),console.log("🎤 Starting voice session...",{agentId:ie,participantName:X}),console.log("🎤 Pre-start state:",{currentMode:"voice",sessionStarted:!1,loading:!0}),Re("USER_STARTED_VOICE_SESSION",{agentId:ie,participantName:X});const _=await be.startSession(ie,{participantName:X||"User",modalities:["voice"],participantMetadata:be.getParticipantMetadata()||K});console.log("✅ Voice session started successfully:",_.id),Ae(_),E(!0),ne(!1),S&&S(_.id)}catch(_){console.error("❌ Failed to start voice session:",_),ne(!1),E(!1),de("welcome")}},Mn=async()=>{try{if(!be){console.error("❌ VoxketClient not available"),W(new Error("VoxketClient not initialized")),H(!0);return}ne(!0),de("chat"),console.log("💬 Starting chat session...",{agentId:ie,participantName:X}),Re("USER_STARTED_CHAT_SESSION",{agentId:ie,participantName:X});const _=await be.startSession(ie,{participantName:X||"User",modalities:["chat"],participantMetadata:be.getParticipantMetadata()||K});console.log("✅ Chat session started successfully:",_.id),Ae(_),E(!0),ne(!1),S&&S(_.id)}catch(_){console.error("❌ Failed to start chat session:",_),ne(!1),E(!1),de("welcome")}},gn=async()=>{try{if(!be){console.error("❌ VoxketClient not available"),W(new Error("VoxketClient not initialized")),H(!0);return}ne(!0),de("video"),console.log("📺 Starting video session...",{agentId:ie,participantName:X}),console.log("📺 Pre-start state:",{currentMode:"video",sessionStarted:!1,loading:!0}),Re("USER_STARTED_VIDEO_SESSION",{agentId:ie,participantName:X});const _=await be.startSession(ie,{participantName:X||"User",modalities:["video","voice"],participantMetadata:be.getParticipantMetadata()||K});console.log("✅ Video session started successfully:",_.id),Ae(_),E(!0),ne(!1),S&&S(_.id)}catch(_){console.error("❌ Failed to start video session:",_),ne(!1),E(!1),de("welcome")}},an=()=>{de("welcome"),ne(!1),U&&U(e.displayType||"widget"),Z&&Y?(console.log("🧹 Widget: Cleaning up active session"),E(!1),Ae(null),be&&(console.log("🔌 Widget: Disconnecting client and cleaning up room"),be.disconnect().catch(_=>{console.error("❌ Widget: Error during disconnect:",_)}))):(console.log("📝 Widget: No active session to clean up"),be&&be.connected&&(console.log("🔌 Widget: Force disconnecting client for fresh state"),be.disconnect().catch(_=>{console.error("❌ Widget: Error during force disconnect:",_)}))),N==="popup"&&!Pe&&ke(!0),console.log("✅ Widget: handleBackToWelcome completed",{newCurrentMode:"welcome",newLoading:!1,newSessionStarted:!1})},Cn=()=>{const _=!Pe;ke(_),I&&I(_),!_&&!(Z&&Y)&&(de("welcome"),E(!1),Ae(null))},qt=()=>{console.log("🔄 Closing fullscreen, switching to widget display type"),e.onDisplayTypeChange?e.onDisplayTypeChange("widget"):console.warn("⚠️ No onDisplayTypeChange callback provided")},Wn=()=>{if(console.log("🔄 Expand to fullscreen requested"),e.onDisplayTypeChange)e.onDisplayTypeChange("fullscreen");else{console.warn("⚠️ No onDisplayTypeChange callback provided for expand functionality");const _=document.getElementById("voice-card")||document.querySelector(".voxket-widget-container");_&&_.requestFullscreen&&_.requestFullscreen().catch($=>{console.warn("⚠️ Fullscreen API not supported or failed:",$)})}};D.useEffect(()=>{var _,$,te;if(L&&be){const ge=be.getCurrentSession();be.connected,ge&&(console.log("✅ Restoring session state:",ge.id),Ae(ge),E(!0),ne(!1),(_=ge.activeModalities)!=null&&_.includes("chat")?de("chat"):($=ge.activeModalities)!=null&&$.includes("voice")?de("voice"):(te=ge.activeModalities)!=null&&te.includes("video")&&de("video"))}},[L,be]),D.useEffect(()=>()=>{!L&&be&&be.disconnect()},[be,L]);let Gt=F==="video"?"w-[32rem]":"w-96",Tr=F==="video"?"h-[30rem]":"h-[25rem]",Cr={};if(h&&(h.startsWith("w-")?Gt=h:(Cr.width=h,Gt="")),f&&(f.startsWith("h-")?Tr=f:(Cr.height=f,Tr="")),N==="popup"&&!Pe)return console.log("🟡 Showing popup trigger button"),m.jsxs(m.Fragment,{children:[m.jsx(dw,{onClick:()=>{if(Ye){!Ne&&(Z!=null&&Z.activeModalities)&&(Z.activeModalities.includes("chat")?Ce("chat"):Z.activeModalities.includes("video")?Ce("video"):Z.activeModalities.includes("voice")&&Ce("voice")),Te(!1),ke(!0),I&&I(!0);return}if(ue!=="all"){Ce(ue),Te(!1),ke(!0),I&&I(!0);return}if(A.length===1){Ce(A[0]),Te(!1),ke(!0),I&&I(!0);return}Te(_=>!_),Ce(null),$t(!1)},position:y,ariaLabel:R,size:64,isRunning:Ye,logoUrl:se}),pe&&ue==="all"&&(()=>{const te={};y==="bottom-right"?(te.bottom=88,te.right=16):y==="bottom-left"?(te.bottom=88,te.left=16):y==="top-right"?(te.top=88,te.right=16):(te.top=88,te.left=16);const ge="absolute w-0 h-0 border-8",ht=y.startsWith("bottom")?m.jsx("div",{className:`${ge} border-transparent border-t-black`,style:{bottom:-16,right:y.endsWith("right")?16:void 0,left:y.endsWith("left")?16:void 0}}):m.jsx("div",{className:`${ge} border-transparent border-b-black`,style:{top:-16,right:y.endsWith("right")?16:void 0,left:y.endsWith("left")?16:void 0}});return m.jsx("div",{className:"fixed z-[51]",style:te,children:m.jsxs("div",{className:"relative bg-black text-white rounded-xl shadow-2xl px-3 py-3",children:[ht,m.jsx("div",{className:"text-xs uppercase tracking-wide mb-2 opacity-70",children:"Choose modality"}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("button",{type:"button",onClick:()=>{Ce("voice"),Te(!1),ke(!0),I&&I(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Voice",children:"Voice"}),m.jsx("button",{type:"button",onClick:()=>{Ce("chat"),Te(!1),ke(!0),I&&I(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Chat",children:"Chat"}),m.jsx("button",{type:"button",onClick:()=>{Ce("video"),Te(!1),ke(!0),I&&I(!0)},className:"px-3 py-2 rounded-md bg-white/10 hover:bg-white/20 text-white text-sm",title:"Video",children:"Video"})]})]})})})()]});if(z||!be){const _=(C==null?void 0:C.message)||"VoxketWidget encountered an error. Please check your configuration.";return m.jsx("div",{className:`voxket-widget-root theme-${w} flex items-center justify-center p-8 ${d||""}`,style:{width:h||"400px",height:f||"500px",border:"1px solid #ff4444",borderRadius:"8px",background:"#fff5f5",color:"#cc0000"},children:m.jsxs("div",{className:"text-center",children:[m.jsx("div",{className:"text-4xl mb-4",children:"⚠️"}),m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Widget Error"}),m.jsx("p",{className:"text-sm mb-4",children:_}),m.jsx("button",{onClick:()=>{H(!1),W(null),window.location.reload()},className:"px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Retry"})]})})}let ws=`voxket-widget-root theme-${w}`,Ji={scrollMargin:0,scrollPadding:0,contain:"layout style paint"};N==="widget"?(ws+=` flex min-h-fit ${Gt} ${Tr} ${d}`,Ji={...Ji,...Cr}):(ws=`${d||""}`,Ji={});const oi=m.jsx("div",{className:"h-full w-full flex flex-col overflow-hidden relative z-10",children:m.jsxs(ls,{mode:"wait",children:[F==="welcome"&&!J&&m.jsx(h4,{agentId:ie,participantName:X||"",onAgentIdChange:re,onParticipantNameChange:le,onStartCall:tn,onStartChat:Mn,onStartVideo:gn,disabled:Y||J,prompts:a,statusMessage:c,title:l,subTitle:u,theme:w,modalities:Ft,initial:{opacity:0,y:0},animate:{opacity:1,y:0},exit:{opacity:0,y:40},transition:{duration:.3,ease:"easeInOut"}},"welcome"),J&&(F==="voice"||F==="chat"||F==="video")&&m.jsx(p4,{theme:w,mode:F,loadingText:g,sessionState:Z==null?void 0:Z.state,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.3,ease:"easeInOut"}},`loading-${F}`),F==="voice"&&!J&&Y&&be&&m.jsxs(Ja.Provider,{value:at,children:[m.jsx(ug,{},`audio-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(ag,{label:"Start Audio"},`start-audio-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(l4,{loadingText:g,participantName:X||"User",sessionStarted:Y,disabled:!1,theme:w,client:be,displayType:N,onBack:N==="popup"?Cn:an,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"voice-session")]}),F==="chat"&&!J&&Y&&be&&m.jsx(u4,{client:be,theme:w,displayType:N,onBack:N==="popup"?Cn:an,onEndChat:an,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"chat-view"),F==="video"&&!J&&Y&&be&&m.jsxs(Ja.Provider,{value:at,children:[m.jsx(ug,{},`audio-video-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(ag,{label:"Start Audio"},`start-audio-video-${(Z==null?void 0:Z.id)||"no-session"}`),m.jsx(d4,{client:be,theme:w,displayType:N,onBack:N==="popup"?Cn:an,onEndCall:an,disabled:!1,initial:{opacity:0,y:40},animate:{opacity:1,y:0},exit:{opacity:0,y:-40},transition:{duration:.3,ease:"easeInOut"}},"video-session")]})]})});return N==="fullscreen"||N==="popup"?m.jsx(Qb,{theme:w,displayType:N,popupPosition:y,onClose:N==="fullscreen"?qt:Cn,children:oi}):m.jsx("div",{className:ws,style:Ji,children:m.jsx(Qb,{theme:w,displayType:N,popupPosition:y,onExpand:Wn,children:oi})})}function Na(e){return m.jsx(kf,{children:m.jsx(m4,{...e})})}function g4({logs:e,onClear:t,onExport:n}){const[i,r]=O.useState(!1),[s,o]=O.useState(""),a=e.filter(c=>!s||c.event.toLowerCase().includes(s.toLowerCase()));return i?m.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:m.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[80vh] flex flex-col m-4",children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[m.jsxs("h2",{className:"text-lg font-semibold",children:["Session Logs (",e.length,")"]}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("input",{type:"text",placeholder:"Filter events...",value:s,onChange:c=>o(c.target.value),className:"px-3 py-1 border rounded text-sm"}),m.jsx("button",{onClick:t,className:"px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700",children:"Clear"}),m.jsx("button",{onClick:n,className:"px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700",children:"Export"}),m.jsx("button",{onClick:()=>r(!1),className:"px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700",children:"Close"})]})]}),m.jsx("div",{className:"flex-1 overflow-auto p-4",children:a.length===0?m.jsx("p",{className:"text-gray-500 text-center py-8",children:"No logs found"}):m.jsx("div",{className:"space-y-2",children:a.map((c,l)=>m.jsxs("div",{className:"border rounded p-3 text-sm",children:[m.jsxs("div",{className:"flex items-center justify-between mb-1",children:[m.jsx("span",{className:"font-semibold text-blue-600",children:c.event}),m.jsx("span",{className:"text-gray-500 text-xs",children:new Date(c.timestamp).toLocaleTimeString()})]}),c.sessionId&&m.jsxs("div",{className:"text-xs text-gray-600 mb-1",children:["Session: ",c.sessionId]}),c.data&&m.jsx("div",{className:"bg-gray-50 p-2 rounded text-xs",children:m.jsx("pre",{className:"whitespace-pre-wrap overflow-auto",children:JSON.stringify(c.data,null,2)})})]},l))})})]})}):m.jsxs("button",{onClick:()=>r(!0),className:"fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-blue-700 transition-colors text-sm z-50",children:["Session Logs (",e.length,")"]})}function b4({metrics:e}){return e?m.jsxs("div",{className:"bg-gray-100 p-4 rounded-lg",children:[m.jsx("h3",{className:"font-semibold mb-2",children:"Current Session"}),m.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Session ID:"}),m.jsx("div",{className:"font-mono text-xs",children:e.sessionId})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Start Time:"}),m.jsx("div",{children:new Date(e.startTime).toLocaleString()})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Messages:"}),m.jsx("div",{children:e.totalMessages})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Participants:"}),m.jsx("div",{children:e.participantCount})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Connection Issues:"}),m.jsx("div",{children:e.connectionIssues})]}),m.jsxs("div",{children:[m.jsx("span",{className:"text-gray-600",children:"Duration:"}),m.jsxs("div",{children:[Math.round((Date.now()-new Date(e.startTime).getTime())/1e3),"s"]})]})]})]}):null}function wr(){const{currentSession:e,sessionState:t,sessionMetrics:n,createSession:i,endSession:r}=si(),s=O.useCallback(async(a,c)=>await i(a,c),[i]),o=O.useCallback(async()=>await r(),[r]);return{session:e,state:t,metrics:n,isActive:e!==null&&t!=="disconnected",isConnecting:t==="connecting",isConnected:t==="connected"||t==="active",start:s,stop:o}}function Sw(){const{sessionMetrics:e,currentSession:t}=si();return{metrics:e,sessionId:t==null?void 0:t.id,duration:e==null?void 0:e.duration,participantCount:e==null?void 0:e.participantCount,messageCount:e==null?void 0:e.messageCount,audioQuality:e==null?void 0:e.audioQuality,networkStats:e==null?void 0:e.networkStats}}function ww(){const{setMicrophoneEnabled:e,client:t}=si(),[n,i]=O.useState(!1),[r,s]=O.useState(!1),o=O.useCallback(async()=>{if(!r){s(!0);try{const l=!n;await e(l),i(l)}catch(l){console.error("Failed to toggle microphone:",l)}finally{s(!1)}}},[n,r,e]),a=O.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(!0),i(!0)}catch(l){console.error("Failed to enable microphone:",l)}finally{s(!1)}}},[n,r,e]),c=O.useCallback(async()=>{if(!(!n||r)){s(!0);try{await e(!1),i(!1)}catch(l){console.error("Failed to disable microphone:",l)}finally{s(!1)}}},[n,r,e]);return{isEnabled:n,isLoading:r,toggle:o,enable:a,disable:c}}function Tw(){const{setCameraEnabled:e}=si(),[t,n]=O.useState(!1),[i,r]=O.useState(!1),s=O.useCallback(async()=>{if(!i){r(!0);try{const c=!t;await e(c),n(c)}catch(c){console.error("Failed to toggle camera:",c)}finally{r(!1)}}},[t,i,e]),o=O.useCallback(async()=>{if(!(t||i)){r(!0);try{await e(!0),n(!0)}catch(c){console.error("Failed to enable camera:",c)}finally{r(!1)}}},[t,i,e]),a=O.useCallback(async()=>{if(!(!t||i)){r(!0);try{await e(!1),n(!1)}catch(c){console.error("Failed to disable camera:",c)}finally{r(!1)}}},[t,i,e]);return{isEnabled:t,isLoading:i,toggle:s,enable:o,disable:a}}function Cw(){const{startScreenShare:e,stopScreenShare:t}=si(),[n,i]=O.useState(!1),[r,s]=O.useState(!1),o=O.useCallback(async()=>{if(!(n||r)){s(!0);try{await e(),i(!0)}catch(l){console.error("Failed to start screen share:",l)}finally{s(!1)}}},[n,r,e]),a=O.useCallback(async()=>{if(!(!n||r)){s(!0);try{await t(),i(!1)}catch(l){console.error("Failed to stop screen share:",l)}finally{s(!1)}}},[n,r,t]),c=O.useCallback(async()=>{n?await a():await o()},[n,o,a]);return{isSharing:n,isLoading:r,start:o,stop:a,toggle:c}}function y4(){const{client:e}=si(),[t,n]=O.useState({tracks:[],layout:{type:"grid",showLocalVideo:!0,aspectRatio:"16:9"},isRecording:!1}),i=O.useMemo(()=>t.tracks.find(p=>p.isLocal),[t.tracks]),r=O.useMemo(()=>t.tracks.filter(p=>!p.isLocal),[t.tracks]),s=O.useCallback(async()=>{try{i!=null&&i.isEnabled?await(e==null?void 0:e.disableCamera()):await(e==null?void 0:e.enableCamera())}catch(p){throw console.error("Failed to toggle camera:",p),p}},[e,i]),o=O.useCallback(async()=>{try{t.tracks.find(v=>v.isScreenShare)?await(e==null?void 0:e.stopScreenShare()):await(e==null?void 0:e.startScreenShare())}catch(p){throw console.error("Failed to toggle screen share:",p),p}},[e,t.tracks]),a=O.useCallback(p=>{n(v=>({...v,layout:p}))},[]),c=O.useCallback(p=>{n(v=>({...v,pinnedTrack:p}))},[]),l=O.useCallback(()=>{n(p=>({...p,pinnedTrack:void 0}))},[]),u=O.useCallback(async()=>{try{await(e==null?void 0:e.startRecording()),n(p=>({...p,isRecording:!0}))}catch(p){throw console.error("Failed to start recording:",p),p}},[e]),d=O.useCallback(async()=>{try{await(e==null?void 0:e.stopRecording()),n(p=>({...p,isRecording:!1}))}catch(p){throw console.error("Failed to stop recording:",p),p}},[e]),h=O.useCallback(p=>t.tracks.find(v=>v.id===p),[t.tracks]),f=O.useCallback(p=>t.tracks.filter(v=>v.participantId===p),[t.tracks]),g=O.useCallback(p=>p.isEnabled&&t.tracks.includes(p),[t.tracks]);return O.useEffect(()=>{if(!e)return;const p=w=>{n(S=>({...S,tracks:[...S.tracks.filter(k=>k.id!==w.id),w]}))},v=w=>{n(S=>{var k;return{...S,tracks:S.tracks.filter(x=>x.id!==w),pinnedTrack:((k=S.pinnedTrack)==null?void 0:k.id)===w?void 0:S.pinnedTrack}})},b=w=>{n(S=>({...S,tracks:S.tracks.map(k=>k.id===w.id?w:k)}))};return e.on("videoTrackAdded",p),e.on("videoTrackRemoved",v),e.on("videoTrackUpdated",b),()=>{e.off("videoTrackAdded",p),e.off("videoTrackRemoved",v),e.off("videoTrackUpdated",b)}},[e]),{tracks:t.tracks,localTrack:i,remoteTraracks:r,pinnedTrack:t.pinnedTrack,layout:t.layout,isRecording:t.isRecording,toggleCamera:s,toggleScreenShare:o,setLayout:a,pinTrack:c,unpinTrack:l,startRecording:u,stopRecording:d,getTrackById:h,getTracksByParticipant:f,isTrackActive:g}}function zc(){const{chatMessages:e,sendChatMessage:t,currentSession:n}=si(),[i,r]=O.useState(!1),s=O.useCallback(async l=>{if(!(!l.trim()||i||!n)){r(!0);try{await t(l.trim())}catch(u){throw console.error("Failed to send chat message:",u),u}finally{r(!1)}}},[t,i,n]),{userMessages:o,agentMessages:a,allMessages:c}=O.useMemo(()=>{const l=e.filter(d=>d.sender.type==="participant"),u=e.filter(d=>d.sender.type==="agent");return{userMessages:l,agentMessages:u,allMessages:e}},[e]);return{messages:c,userMessages:o,agentMessages:a,messageCount:c.length,isSending:i,canSend:!!n&&!i,send:s}}function v4(){const{send:e,isSending:t,canSend:n}=zc(),[i,r]=O.useState(""),s=O.useCallback(async()=>{if(!(!i.trim()||!n))try{await e(i),r("")}catch(a){throw a}},[i,e,n]),o=O.useCallback(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),s())},[s]);return{value:i,setValue:r,send:s,handleKeyPress:o,isSending:t,canSend:n&&i.trim().length>0}}function Tf(){const{isConnected:e,isConnecting:t,connectionError:n,connect:i,disconnect:r}=si(),s=O.useCallback(async()=>{if(!(e||t))try{await i()}catch(a){throw console.error("Failed to connect:",a),a}},[i,e,t]),o=O.useCallback(async()=>{if(e)try{await r()}catch(a){throw console.error("Failed to disconnect:",a),a}},[r,e]);return{isConnected:e,isConnecting:t,isDisconnected:!e&&!t,error:n,hasError:!!n,connect:s,disconnect:o}}function Ew(){const{participants:e}=si();return{participants:e,count:e.length,localParticipant:e.find(t=>t.isLocal),remoteParticipants:e.filter(t=>!t.isLocal)}}const _w=O.createContext({}),No=()=>O.useContext(_w);function Rw({children:e,...t}){return m.jsx(_w.Provider,{value:t,children:e})}function Ia({name:e,children:t,fallback:n,className:i}){return m.jsx("div",{className:`voxket-slot voxket-slot--${e} ${i||""}`,children:t||n})}function Aw(e,t={}){return Object.assign(e,t)}function Pw({showMicrophoneControl:e=!0,showCameraControl:t=!0,showScreenShareControl:n=!0,showSessionActions:i=!0,customControls:r,className:s=""}){const o=wr(),a=ww(),c=Tw(),l=Cw(),u=No(),d=["voxket-session-controls",`voxket-session-controls--${u.variant||"default"}`,`voxket-session-controls--${u.size||"md"}`,o.isActive?"voxket-session-controls--active":"voxket-session-controls--inactive",s].filter(Boolean).join(" ");return!o.isActive&&!i?m.jsx("div",{className:d,children:m.jsx("div",{className:"voxket-controls-inactive",children:m.jsx("p",{children:"Controls available during active session"})})}):m.jsxs("div",{className:d,children:[i&&m.jsx("div",{className:"voxket-session-actions",children:o.isActive?m.jsx("button",{onClick:o.stop,className:"voxket-button voxket-button--danger",children:"End Session"}):m.jsx(x4,{})}),o.isActive&&m.jsxs("div",{className:"voxket-media-controls",children:[e&&m.jsxs("button",{onClick:a.toggle,disabled:a.isLoading,className:`voxket-button voxket-button--media ${a.isEnabled?"voxket-button--active":""}`,title:a.isEnabled?"Mute microphone":"Unmute microphone",children:[m.jsx("span",{className:"voxket-icon",children:"🎤"}),a.isLoading?"Loading...":a.isEnabled?"Mute":"Unmute"]}),t&&m.jsxs("button",{onClick:c.toggle,disabled:c.isLoading,className:`voxket-button voxket-button--media ${c.isEnabled?"voxket-button--active":""}`,title:c.isEnabled?"Stop camera":"Start camera",children:[m.jsx("span",{className:"voxket-icon",children:"📹"}),c.isLoading?"Loading...":c.isEnabled?"Stop Video":"Start Video"]}),n&&m.jsxs("button",{onClick:l.toggle,disabled:l.isLoading,className:`voxket-button voxket-button--media ${l.isSharing?"voxket-button--active":""}`,title:l.isSharing?"Stop screen share":"Start screen share",children:[m.jsx("span",{className:"voxket-icon",children:"🖥️"}),l.isLoading?"Loading...":l.isSharing?"Stop Share":"Share Screen"]})]}),r&&m.jsx("div",{className:"voxket-custom-controls",children:r})]})}function x4(){wr();const[e,t]=O.useState(!1),n=async()=>{t(!0);try{console.log("Start session - agentId needed")}catch(i){console.error("Failed to start session:",i)}finally{t(!1)}};return m.jsx("button",{onClick:n,disabled:e,className:"voxket-button voxket-button--primary",children:e?"Starting...":"Start Session"})}function Cf({showConnectionStatus:e=!0,showSessionInfo:t=!0,showAgentInfo:n=!0,className:i=""}){const r=wr(),s=Tf(),o=No(),a=["voxket-session-header",`voxket-session-header--${o.variant||"default"}`,`voxket-session-header--${o.size||"md"}`,i].filter(Boolean).join(" ");return m.jsxs("div",{className:a,children:[e&&m.jsxs("div",{className:"voxket-connection-status",children:[m.jsx("div",{className:`voxket-status-indicator ${s.isConnected?"connected":"disconnected"}`}),m.jsx("span",{className:"voxket-status-text",children:s.isConnecting?"Connecting...":s.isConnected?"Connected":"Disconnected"})]}),t&&r.session&&m.jsxs("div",{className:"voxket-session-info",children:[m.jsxs("div",{className:"voxket-session-id",children:["Session: ",r.session.id.slice(-8)]}),m.jsxs("div",{className:"voxket-session-state",children:["State: ",r.state]})]}),n&&r.session&&m.jsxs("div",{className:"voxket-agent-info",children:[m.jsxs("div",{className:"voxket-agent-id",children:["Agent: ",r.session.agentId]}),m.jsxs("div",{className:"voxket-modalities",children:["Modalities: ",r.session.activeModalities.join(", ")]})]}),s.error&&m.jsxs("div",{className:"voxket-error-message",children:["Error: ",s.error.message]})]})}function Ef({showChat:e=!0,showTranscriptions:t=!1,customContent:n,className:i=""}){const r=wr(),s=zc(),o=No(),a=["voxket-session-content",`voxket-session-content--${o.variant||"default"}`,`voxket-session-content--${o.size||"md"}`,i].filter(Boolean).join(" ");return r.isActive?m.jsx("div",{className:a,children:n||m.jsxs(m.Fragment,{children:[e&&m.jsxs("div",{className:"voxket-chat-container",children:[m.jsxs("div",{className:"voxket-chat-messages",children:[s.messages.map(c=>m.jsxs("div",{className:`voxket-message voxket-message--${c.sender.type}`,children:[m.jsxs("div",{className:"voxket-message-header",children:[m.jsx("span",{className:"voxket-message-sender",children:c.sender.name}),m.jsx("span",{className:"voxket-message-time",children:c.timestamp.toLocaleTimeString()})]}),m.jsx("div",{className:"voxket-message-content",children:c.content})]},c.id)),s.messages.length===0&&m.jsx("div",{className:"voxket-empty-messages",children:m.jsx("p",{children:"No messages yet. Start the conversation!"})})]}),m.jsx(k4,{})]}),t&&m.jsx("div",{className:"voxket-transcriptions",children:m.jsx("div",{className:"voxket-transcription-placeholder",children:m.jsx("p",{children:"Voice transcriptions will appear here"})})})]})}):m.jsx("div",{className:a,children:m.jsx("div",{className:"voxket-inactive-state",children:m.jsxs("div",{className:"voxket-inactive-message",children:[m.jsx("h3",{children:"Start a conversation"}),m.jsx("p",{children:"Begin a session to start chatting with the AI agent"})]})})})}function k4(){const e=zc(),[t,n]=O.useState(""),i=async()=>{if(!(!t.trim()||!e.canSend))try{await e.send(t),n("")}catch(s){console.error("Failed to send message:",s)}},r=s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),i())};return m.jsxs("div",{className:"voxket-chat-input",children:[m.jsx("input",{type:"text",value:t,onChange:s=>n(s.target.value),onKeyPress:r,placeholder:"Type your message...",disabled:!e.canSend,className:"voxket-input"}),m.jsx("button",{onClick:i,disabled:!e.canSend||!t.trim(),className:"voxket-send-button",children:e.isSending?"Sending...":"Send"})]})}function _f({showMetrics:e=!0,showParticipants:t=!0,showStatus:n=!0,customFooter:i,className:r=""}){const s=wr(),o=Sw(),a=Ew(),c=No(),l=["voxket-session-footer",`voxket-session-footer--${c.variant||"default"}`,`voxket-session-footer--${c.size||"md"}`,r].filter(Boolean).join(" ");return s.isActive?m.jsx("div",{className:l,children:i||m.jsxs(m.Fragment,{children:[n&&m.jsxs("div",{className:"voxket-session-status",children:[m.jsx("div",{className:"voxket-status-indicator voxket-status-indicator--active"}),m.jsx("span",{className:"voxket-status-text",children:"Session Active"})]}),e&&o.metrics&&m.jsxs("div",{className:"voxket-session-metrics",children:[m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Duration:"}),m.jsx("span",{className:"voxket-metric-value",children:S4(o.duration||0)})]}),m.jsxs("div",{className:"voxket-metric",children:[m.jsx("span",{className:"voxket-metric-label",children:"Messages:"}),m.jsx("span",{className:"voxket-metric-value",children:o.metrics.messageCount})]})]}),t&&m.jsxs("div",{className:"voxket-participants-info",children:[m.jsxs("span",{className:"voxket-participants-count",children:[a.count," participant",a.count!==1?"s":""]}),a.remoteParticipants.length>0&&m.jsx("div",{className:"voxket-participant-list",children:a.remoteParticipants.map(u=>m.jsx("span",{className:"voxket-participant-name",children:u.name},u.id))})]})]})}):m.jsx("div",{className:l,children:m.jsx("div",{className:"voxket-footer-inactive",children:m.jsx("span",{className:"voxket-status-text",children:"Ready to start session"})})})}function S4(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=Math.floor(n/60);return i>0?`${i}:${(n%60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}`:`${n}:${(t%60).toString().padStart(2,"0")}`}function w4({agentId:e,sessionConfig:t,autoStart:n=!1,onSessionStart:i,onSessionEnd:r,variant:s="default",size:o="md",theme:a,className:c="",children:l}){var f;const u=wr(),d=Tf();O.useEffect(()=>{n&&e&&d.isConnected&&!u.isActive&&u.start(e,t).catch(console.error)},[n,e,d.isConnected,u.isActive]),O.useEffect(()=>{var g;(g=u.session)!=null&&g.id&&i&&i(u.session.id)},[(f=u.session)==null?void 0:f.id,i]),O.useEffect(()=>()=>{u.isActive&&r&&u.stop().then(r).catch(console.error)},[]);const h=["voxket-session",`voxket-session--${s}`,`voxket-session--${o}`,u.isActive?"voxket-session--active":"voxket-session--inactive",c].filter(Boolean).join(" ");return m.jsx(Rw,{variant:s,size:o,theme:a,className:c,children:m.jsx("div",{className:h,children:l||m.jsxs(m.Fragment,{children:[m.jsx(Ia,{name:"header",fallback:m.jsx(Cf,{})}),m.jsx(Ia,{name:"content",fallback:m.jsx(Ef,{})}),m.jsx(Ia,{name:"footer",fallback:m.jsx(_f,{})})]})})})}const Nw=Aw(w4,{Header:Cf,Content:Ef,Footer:_f,Controls:Pw}),fr={name:"default",colors:{primary:"#3B82F6",secondary:"#6B7280",accent:"#8B5CF6",background:"#FFFFFF",surface:"#F9FAFB",text:{primary:"#111827",secondary:"#6B7280",muted:"#9CA3AF",inverse:"#FFFFFF"},status:{success:"#10B981",warning:"#F59E0B",error:"#EF4444",info:"#3B82F6"},border:"#E5E7EB",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,semibold:600,bold:700},lineHeight:{tight:1.25,normal:1.5,relaxed:1.75}},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem"},borderRadius:{none:"0",sm:"0.25rem",md:"0.5rem",lg:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1)"}},Ld={...fr,name:"dark",colors:{primary:"#60A5FA",secondary:"#9CA3AF",accent:"#A78BFA",background:"#111827",surface:"#1F2937",text:{primary:"#F9FAFB",secondary:"#D1D5DB",muted:"#9CA3AF",inverse:"#111827"},status:{success:"#34D399",warning:"#FBBF24",error:"#F87171",info:"#60A5FA"},border:"#374151",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.3)"}},Fd={...fr,name:"enterprise",colors:{primary:"#1E40AF",secondary:"#64748B",accent:"#7C3AED",background:"#FFFFFF",surface:"#F8FAFC",text:{primary:"#0F172A",secondary:"#475569",muted:"#94A3B8",inverse:"#FFFFFF"},status:{success:"#059669",warning:"#D97706",error:"#DC2626",info:"#1E40AF"},border:"#CBD5E1",shadow:"0 1px 3px 0 rgba(0, 0, 0, 0.1)"},borderRadius:{none:"0",sm:"0.125rem",md:"0.25rem",lg:"0.375rem",full:"9999px"}},Iw=O.createContext(null),Mw=()=>{const e=O.useContext(Iw);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e};function T4({theme:e="default",themes:t={},children:n,cssVariables:i=!0,className:r=""}){const[s,o]=O.useState(()=>{const h={default:fr,dark:Ld,enterprise:Fd,...t};return typeof e=="string"?h[e]||fr:e}),[a,c]=O.useState(()=>({default:fr,dark:Ld,enterprise:Fd,...t})),l=h=>{if(typeof h=="string"){const f=a[h];f&&o(f)}else o(h)},u=h=>{c(f=>({...f,[h.name]:h}))};O.useEffect(()=>{if(i&&typeof document<"u"){const h=document.documentElement;Object.entries(Ow(s)).forEach(([f,g])=>{h.style.setProperty(`--voxket-${f}`,g)})}},[s,i]);const d={theme:s,setTheme:l,themes:a,registerTheme:u};return m.jsx(Iw.Provider,{value:d,children:m.jsx("div",{className:`voxket-theme voxket-theme--${s.name} ${r}`,children:n})})}function Ow(e){const t={},n=(i,r="")=>{for(const[s,o]of Object.entries(i)){const a=r?`${r}-${s}`:s;typeof o=="object"&&o!==null&&!Array.isArray(o)?n(o,a):t[a]=String(o)}};return n(e),t}function C4(e=fr,t){return{...e,...t,colors:{...e.colors,...t.colors},typography:{...e.typography,...t.typography},spacing:{...e.spacing,...t.spacing},borderRadius:{...e.borderRadius,...t.borderRadius},shadows:{...e.shadows,...t.shadows}}}function E4(e){var n;const{theme:t}=Mw();return((n=t.components)==null?void 0:n[e])||{}}const _4=wf("voice-modality","voice",{onActivate:async e=>{const t=e.config;t.enableTranscription&&R4(e),t.enableVoiceActivation&&A4(e,t),console.log("Voice modality activated",t)},onDeactivate:async e=>{console.log("Voice modality deactivated")},onMessage:async(e,t)=>{t.type==="audio"&&P4(e,t)}});function R4(e,t){e.on("participant.speaking.started",n=>{console.log("Transcription: Started for",n.name)}),e.on("participant.speaking.stopped",n=>{console.log("Transcription: Stopped for",n.name)})}function A4(e,t){const n=t.silenceThreshold||-50;console.log("Voice activation setup with threshold:",n)}function P4(e,t){console.log("Playing audio response:",t.content)}const N4=wf("chat-modality","chat",{onActivate:async e=>{const t=e.config;t.enableRichText&&I4(),t.enableFileUpload&&M4(e),t.enableCustomComponents&&O4(),console.log("Chat modality activated",t)},onDeactivate:async e=>{console.log("Chat modality deactivated")},onMessage:async(e,t)=>{const n=e.config;t.type==="ui_component"?D4(e,t):t.type==="text"&&n.enableRichText&&L4(e,t)}});function I4(e){console.log("Rich text support enabled")}function M4(e){console.log("File upload enabled"),e.on("chat.file.uploaded",t=>{console.log("File uploaded:",t.name)})}function O4(e){console.log("Custom components enabled");const t=new Map;t.set("quick-actions",F4),t.set("form",j4),t.set("card",U4),t.set("chart",B4)}function D4(e,t){const{componentType:n,props:i}=t.metadata;console.log("Rendering custom component:",n,i),e.emit("chat.component.render",{type:n,props:i,timestamp:new Date})}function L4(e,t){console.log("Processing rich text message:",t.content)}function F4(e){return{type:"quick-actions",actions:e.actions||[],layout:e.layout||"horizontal"}}function j4(e){return{type:"form",fields:e.fields||[],submitAction:e.submitAction,validation:e.validation}}function U4(e){return{type:"card",title:e.title,content:e.content,actions:e.actions,variant:e.variant||"default"}}function B4(e){return{type:"chart",chartType:e.chartType||"line",data:e.data,options:e.options}}function Ma({track:e,participantName:t,showControls:n=!0,showName:i=!0,showMuteIndicator:r=!0,isPinned:s=!1,className:o="",onClick:a,onPin:c,onUnpin:l}){const u=O.useRef(null),[d,h]=O.useState(!1);O.useEffect(()=>{if(!u.current||!e.isEnabled)return;const v=u.current;return v.srcObject=null,()=>{v.srcObject&&(v.srcObject=null)}},[e]);const f=()=>{a==null||a(e)},g=v=>{v.stopPropagation(),s?l==null||l(e):c==null||c(e)},p=["voxket-video-tile",e.isLocal?"voxket-video-tile--local":"voxket-video-tile--remote",e.isScreenShare?"voxket-video-tile--screen-share":"voxket-video-tile--camera",s?"voxket-video-tile--pinned":"",e.isEnabled?"":"voxket-video-tile--disabled",d?"voxket-video-tile--hovered":"",o].filter(Boolean).join(" ");return m.jsxs("div",{className:p,onClick:f,onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),style:{aspectRatio:e.dimensions?`${e.dimensions.width} / ${e.dimensions.height}`:"16 / 9"},children:[m.jsx("video",{ref:u,className:"voxket-video-element",autoPlay:!0,playsInline:!0,muted:e.isLocal}),!e.isEnabled&&m.jsxs("div",{className:"voxket-video-placeholder",children:[m.jsx("div",{className:"voxket-video-placeholder-icon",children:e.isScreenShare?"🖥️":"📹"}),m.jsx("p",{className:"voxket-video-placeholder-text",children:e.isScreenShare?"Screen sharing paused":"Camera off"})]}),m.jsxs("div",{className:"voxket-video-overlay",children:[i&&t&&m.jsxs("div",{className:"voxket-video-name",children:[t,e.isLocal&&" (You)"]}),r&&!e.isEnabled&&m.jsx("div",{className:"voxket-video-mute-indicator",children:"🔇"}),n&&(d||s)&&m.jsxs("div",{className:"voxket-video-controls",children:[m.jsx("button",{className:`voxket-video-control-btn ${s?"voxket-video-control-btn--active":""}`,onClick:g,title:s?"Unpin video":"Pin video",children:"📌"}),e.isScreenShare&&m.jsx("div",{className:"voxket-video-indicator",children:"🖥️"}),e.source&&m.jsx("div",{className:"voxket-video-source",children:e.source})]})]}),!e.isEnabled&&m.jsx("div",{className:"voxket-video-loading",children:m.jsx("div",{className:"voxket-spinner"})})]})}function V4({tracks:e,layout:t,className:n="",onLayoutChange:i,onTrackClick:r,maxVisibleTracks:s=9,showPagination:o=!0}){const[a,c]=O.useState(0),[l,u]=O.useState(null),d=O.useMemo(()=>{let w=[...e];t.type==="speaker"&&l&&(w=[l,...e.filter(x=>x.id!==l.id)]);const S=a*s,k=S+s;return w.slice(S,k)},[e,t,l,a,s]),h=Math.ceil(e.length/s),f=O.useMemo(()=>{const w=d.length;switch(t.type){case"grid":const S=Math.ceil(Math.sqrt(w)),k=Math.ceil(w/S);return{display:"grid",gridTemplateColumns:`repeat(${S}, 1fr)`,gridTemplateRows:`repeat(${k}, 1fr)`,gap:"8px"};case"speaker":return{display:"flex",flexDirection:"column",gap:"8px"};case"sidebar":return{display:"flex",gap:"8px"};case"gallery":return{display:"flex",flexWrap:"wrap",gap:"8px",justifyContent:"center"};default:return{}}},[t.type,d.length]),g=w=>{u(w)},p=()=>{u(null)},v=w=>{i==null||i({...t,type:w})},b=["voxket-video-grid",`voxket-video-grid--${t.type}`,`voxket-video-grid--${d.length}-tracks`,n].filter(Boolean).join(" ");return e.length===0?m.jsx("div",{className:"voxket-video-grid-empty",children:m.jsxs("div",{className:"voxket-video-grid-empty-content",children:[m.jsx("div",{className:"voxket-video-grid-empty-icon",children:"📹"}),m.jsx("p",{children:"No video tracks available"})]})}):m.jsxs("div",{className:b,children:[m.jsxs("div",{className:"voxket-video-grid-controls",children:[m.jsx("div",{className:"voxket-video-layout-controls",children:["grid","speaker","sidebar","gallery"].map(w=>m.jsx("button",{className:`voxket-layout-btn ${t.type===w?"voxket-layout-btn--active":""}`,onClick:()=>v(w),title:`Switch to ${w} layout`,children:$4(w)},w))}),m.jsxs("div",{className:"voxket-video-count",children:[e.length," participant",e.length!==1?"s":""]})]}),m.jsx("div",{className:"voxket-video-grid-content",style:f,children:t.type==="speaker"&&l?m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"voxket-video-speaker-main",children:m.jsx(Ma,{track:l,participantName:`Participant ${l.participantId}`,isPinned:!0,onClick:r,onUnpin:p})}),m.jsx("div",{className:"voxket-video-speaker-sidebar",children:d.filter(w=>w.id!==l.id).map(w=>m.jsx(Ma,{track:w,participantName:`Participant ${w.participantId}`,showControls:!1,onClick:r,onPin:g},w.id))})]}):d.map(w=>m.jsx(Ma,{track:w,participantName:`Participant ${w.participantId}`,isPinned:(l==null?void 0:l.id)===w.id,onClick:r,onPin:g,onUnpin:p},w.id))}),o&&h>1&&m.jsxs("div",{className:"voxket-video-pagination",children:[m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.max(0,a-1)),disabled:a===0,children:"←"}),m.jsxs("span",{className:"voxket-pagination-info",children:["Page ",a+1," of ",h]}),m.jsx("button",{className:"voxket-pagination-btn",onClick:()=>c(Math.min(h-1,a+1)),disabled:a===h-1,children:"→"})]})]})}function $4(e){switch(e){case"grid":return"⊞";case"speaker":return"🎤";case"sidebar":return"⫸";case"gallery":return"⊡";case"picture-in-picture":return"⧉";default:return"⊞"}}function z4({localTrack:e,onToggleCamera:t,onToggleScreenShare:n,onLayoutChange:i,showLayoutControls:r=!0,showCameraControls:s=!0,showScreenShareControls:o=!0,className:a=""}){const c=["voxket-video-controls",a].filter(Boolean).join(" "),l=u=>{i==null||i({type:u,showLocalVideo:!0,aspectRatio:"16:9"})};return m.jsxs("div",{className:c,children:[s&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Camera"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isEnabled?"voxket-control-btn--active":""}`,onClick:t,title:e!=null&&e.isEnabled?"Turn off camera":"Turn on camera",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isEnabled?"📹":"📷"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isEnabled?"Camera On":"Camera Off"})]}),(e==null?void 0:e.dimensions)&&m.jsxs("div",{className:"voxket-video-info",children:[e.dimensions.width," × ",e.dimensions.height]})]}),o&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Screen Share"}),m.jsxs("button",{className:`voxket-control-btn ${e!=null&&e.isScreenShare?"voxket-control-btn--active":""}`,onClick:n,title:e!=null&&e.isScreenShare?"Stop screen sharing":"Start screen sharing",children:[m.jsx("span",{className:"voxket-control-icon",children:e!=null&&e.isScreenShare?"🛑":"🖥️"}),m.jsx("span",{className:"voxket-control-label",children:e!=null&&e.isScreenShare?"Stop Sharing":"Share Screen"})]})]}),r&&m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Layout"}),m.jsx("div",{className:"voxket-layout-buttons",children:[{type:"grid",icon:"⊞",label:"Grid"},{type:"speaker",icon:"🎤",label:"Speaker"},{type:"sidebar",icon:"⫸",label:"Sidebar"},{type:"gallery",icon:"⊡",label:"Gallery"}].map(({type:u,icon:d,label:h})=>m.jsxs("button",{className:"voxket-layout-control-btn",onClick:()=>l(u),title:`Switch to ${h} layout`,children:[m.jsx("span",{className:"voxket-control-icon",children:d}),m.jsx("span",{className:"voxket-control-label",children:h})]},u))})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Video Settings"}),m.jsxs("div",{className:"voxket-video-settings",children:[m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Quality"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"high",children:"High (720p)"}),m.jsx("option",{value:"medium",children:"Medium (480p)"}),m.jsx("option",{value:"low",children:"Low (240p)"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Frame Rate"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"30",children:"30 fps"}),m.jsx("option",{value:"15",children:"15 fps"}),m.jsx("option",{value:"10",children:"10 fps"})]})]}),m.jsxs("div",{className:"voxket-setting-group",children:[m.jsx("label",{className:"voxket-setting-label",children:"Bandwidth"}),m.jsxs("select",{className:"voxket-setting-select",children:[m.jsx("option",{value:"unlimited",children:"Unlimited"}),m.jsx("option",{value:"1000",children:"1 Mbps"}),m.jsx("option",{value:"500",children:"500 Kbps"}),m.jsx("option",{value:"250",children:"250 Kbps"})]})]})]})]}),m.jsxs("div",{className:"voxket-video-controls-section",children:[m.jsx("h4",{className:"voxket-video-controls-title",children:"Statistics"}),m.jsxs("div",{className:"voxket-video-stats",children:[m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Resolution:"}),m.jsx("span",{className:"voxket-stat-value",children:e!=null&&e.dimensions?`${e.dimensions.width}×${e.dimensions.height}`:"N/A"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Source:"}),m.jsx("span",{className:"voxket-stat-value",children:(e==null?void 0:e.source)||"None"})]}),m.jsxs("div",{className:"voxket-stat-item",children:[m.jsx("span",{className:"voxket-stat-label",children:"Status:"}),m.jsx("span",{className:`voxket-stat-value ${e!=null&&e.isEnabled?"voxket-stat-value--active":"voxket-stat-value--inactive"}`,children:e!=null&&e.isEnabled?"Active":"Inactive"})]})]})]})]})}const Dw=({handler:e,loadData:t,data:n,client:i,addLocalMessage:r})=>{const[s,o]=D.useState(null),[a,c]=D.useState(!0),[l,u]=D.useState(!1),[d]=D.useState(Date.now()),[h,f]=D.useState("pending");D.useEffect(()=>{(async()=>{try{if(c(!0),n&&typeof n=="object"){const w={title:n.title||"Untitled Assignment",description:n.description||"No description provided",estimated_time_of_completion:n.estimated_time_of_completion||"Unknown"};o(w),console.log("📋 AssignmentView: Assignment loaded from RPC data:",w)}}catch(w){console.error("📋 AssignmentView: Error loading assignment:",w),o({title:"Assignment Loading Error",description:"There was an error loading the assignment details. Please try again.",estimated_time_of_completion:"Unknown"})}finally{c(!1)}})()},[n,t]);const g=({message:b,assignment:w})=>{const S=b.toLowerCase().includes("declined"),k=S?"bg-red-50 border-red-200":"bg-green-50 border-green-200",x=S?"text-red-700":"text-green-700",T=S?"❌":"🎉";return m.jsxs("div",{className:`max-w-sm mx-auto ${k} border rounded-lg shadow p-3 flex flex-col items-center`,children:[m.jsx("div",{className:"text-2xl mb-2",children:T}),m.jsx("div",{className:`${x} font-semibold text-sm mb-1`,children:b}),m.jsx("div",{className:"text-xs text-gray-600 text-center mb-1",children:w.title}),m.jsx("div",{className:"text-xs text-gray-500",children:"Thank you for your response!"})]})},p=async()=>{if(!(!s||!e)){u(!0);try{const b={message:"accepted"};console.log("📋 AssignmentView: Assignment accepted:",b),e.didSuccess(b),f("accepted")}catch(b){console.error("📋 AssignmentView: Error accepting assignment:",b),e.didFail({error:"Failed to accept assignment"}),f("error")}finally{u(!1)}}},v=async()=>{if(!(!s||!e)){u(!0);try{const b={message:"declined"};console.log("📋 AssignmentView: Assignment declined:",b),e.didSuccess(b),f("declined")}catch(b){console.error("📋 AssignmentView: Error declining assignment:",b),e.didFail({error:"Failed to decline assignment"}),f("error")}finally{u(!1)}}};return a?m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"flex items-center justify-center py-4",children:[m.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"}),m.jsx("span",{className:"ml-2 text-xs text-gray-600",children:"Loading assignment..."})]})}):s?h==="accepted"||h==="declined"||h==="error"?m.jsx(g,{message:h==="accepted"?"Assignment accepted!":h==="declined"?"Assignment declined":"Assignment error occurred",assignment:s}):m.jsxs("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg overflow-hidden",children:[m.jsx("div",{className:"bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3",children:m.jsx("div",{className:"flex items-center justify-between",children:m.jsx("h3",{className:"text-xs font-semibold text-white truncate",children:s.title})})}),m.jsxs("div",{className:"p-3 text-black",children:[m.jsx("div",{className:"bg-gray-50 rounded p-2 mb-3",children:m.jsx("p",{className:"text-xs text-black leading-snug",children:s.description})}),m.jsx("div",{className:"mb-3 text-black",children:m.jsxs("div",{className:"flex items-center text-xs text-gray-600",children:[m.jsx("span",{className:"text-xs mr-1",children:"📅"}),m.jsxs("span",{children:["Est: ",s.estimated_time_of_completion]})]})}),m.jsxs("div",{className:"flex gap-2",children:[m.jsx("button",{onClick:p,disabled:l,className:"flex-1 bg-green-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:l?m.jsxs("span",{className:"flex items-center justify-center",children:[m.jsx("div",{className:"animate-spin rounded-full h-2 w-2 border-b-2 border-white mr-1"}),m.jsx("span",{className:"text-xs",children:"Processing..."})]}):"Accept"}),m.jsx("button",{onClick:v,disabled:l,className:"flex-1 bg-red-600 text-white py-2 px-3 rounded text-xs font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"Decline"})]})]})]}):m.jsx("div",{className:"max-w-sm mx-auto bg-white rounded-lg shadow-lg p-3",children:m.jsxs("div",{className:"text-center py-4",children:[m.jsx("div",{className:"text-red-600 text-sm font-semibold mb-2",children:"⚠️ Assignment Error"}),m.jsx("p",{className:"text-xs text-gray-600 mb-3",children:"Failed to load assignment details."})]})})};function H4(){const[e,t]=D.useState(null),[n,i]=D.useState([]);D.useEffect(()=>{const a=new Po({appId:"your-app-id",appSecret:"your-app-secret",baseUrl:"https://your-voxket-api.com",agentId:"your-agent-id",participantName:"User",modalities:["chat"]});return t(a),a.on("rpc.method.called",c=>{console.log("RPC Method Called:",c)}),a.on("rpc.interaction.completed",c=>{console.log("RPC Interaction Completed:",c)}),()=>{a.disconnect()}},[]);const r=async()=>{if(e)try{await e.registerFrontendRPC("give_assignment",Dw,"embedded");const a=e.getRegisteredRpcMethods();i(a),console.log("✅ Assignment RPC registered successfully")}catch(a){console.error("❌ Failed to register assignment RPC:",a)}},s=async()=>{if(!e)return;const a=({handler:c,timeout:l})=>{const[u,d]=D.useState(""),h=[{id:"pro",name:"Pro Plan",price:"$29/month"},{id:"enterprise",name:"Enterprise Plan",price:"$99/month"},{id:"basic",name:"Basic Plan",price:"$9/month"}],f=p=>{d(p)},g=()=>{const p=h.find(v=>v.id===u);c==null||c.didSuccess({selectedProduct:u,productName:p==null?void 0:p.name,price:p==null?void 0:p.price,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-6 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-xl font-bold mb-4",children:"Choose Your Plan"}),m.jsx("p",{className:"text-gray-600 mb-4",children:"Select the plan that best fits your needs:"}),m.jsx("div",{className:"space-y-3 mb-6",children:h.map(p=>m.jsx("div",{onClick:()=>f(p.id),className:`p-4 border rounded-lg cursor-pointer transition-all ${u===p.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300"}`,children:m.jsxs("div",{className:"flex justify-between items-center",children:[m.jsxs("div",{children:[m.jsx("h4",{className:"font-medium",children:p.name}),m.jsx("p",{className:"text-gray-600 text-sm",children:p.price})]}),m.jsx("div",{className:`w-4 h-4 rounded-full ${u===p.id?"bg-blue-500":"border-2 border-gray-300"}`})]})},p.id))}),m.jsxs("div",{className:"flex justify-end space-x-3",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Cancel"}),m.jsx("button",{onClick:g,disabled:!u,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Select Plan"})]}),l&&m.jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Time remaining: ",l," seconds"]})]})};try{await e.registerFrontendRPC("recommend_product",a,"modal");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Product Recommendation RPC registered successfully")}catch(c){console.error("❌ Failed to register product recommendation RPC:",c)}},o=async()=>{if(!e)return;const a=({handler:c})=>{const[l,u]=D.useState(0),[d,h]=D.useState(""),f=()=>{c==null||c.didSuccess({rating:l,comment:d,timestamp:new Date().toISOString()})};return m.jsxs("div",{className:"p-4 bg-white rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-3",children:"How was your experience?"}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Rate your experience:"}),m.jsx("div",{className:"flex space-x-1",children:[1,2,3,4,5].map(g=>m.jsx("button",{onClick:()=>u(g),className:`text-2xl ${g<=l?"text-yellow-400":"text-gray-300"}`,children:"⭐"},g))})]}),m.jsxs("div",{className:"mb-4",children:[m.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"Additional comments:"}),m.jsx("textarea",{value:d,onChange:g=>h(g.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",rows:3,placeholder:"Tell us more about your experience..."})]}),m.jsxs("div",{className:"flex justify-end space-x-2",children:[m.jsx("button",{onClick:()=>c==null?void 0:c.dismissView(),className:"px-3 py-1 text-sm border border-gray-300 text-gray-700 rounded hover:bg-gray-50",children:"Skip"}),m.jsx("button",{onClick:f,disabled:l===0,className:"px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50",children:"Submit"})]})]})};try{await e.registerFrontendRPC("collect_feedback",a,"embedded");const c=e.getRegisteredRpcMethods();i(c),console.log("✅ Feedback RPC registered successfully")}catch(c){console.error("❌ Failed to register feedback RPC:",c)}};return m.jsxs("div",{className:"p-6",children:[m.jsx("h2",{className:"text-2xl font-bold mb-6",children:"Frontend RPC Examples"}),m.jsxs("div",{className:"space-y-4 mb-6",children:[m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Register RPC Methods"}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:r,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Register Assignment RPC"}),m.jsx("button",{onClick:s,className:"px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600",children:"Register Product Recommendation RPC"}),m.jsx("button",{onClick:o,className:"px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600",children:"Register Feedback RPC"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Registered Methods"}),n.length>0?m.jsx("ul",{className:"list-disc list-inside space-y-1",children:n.map(a=>m.jsx("li",{className:"text-gray-700",children:m.jsx("code",{className:"bg-gray-100 px-2 py-1 rounded",children:a})},a))}):m.jsx("p",{className:"text-gray-500",children:"No methods registered yet"})]})]}),m.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2",children:"How it works"}),m.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-sm text-gray-700",children:[m.jsxs("li",{children:["Register RPC methods with React components using ",m.jsx("code",{children:"client.registerFrontendRPC()"})]}),m.jsx("li",{children:"When the agent calls an RPC method, the corresponding component will be displayed"}),m.jsx("li",{children:"Users interact with the component, and the response is sent back to the agent"}),m.jsx("li",{children:"Components can be displayed in different modes: embedded, modal, or fullscreen"}),m.jsx("li",{children:"Each component has a timeout and can handle success/failure scenarios"})]})]}),m.jsxs("div",{className:"mt-6 bg-blue-50 p-4 rounded-lg",children:[m.jsx("h3",{className:"text-lg font-semibold mb-2 text-blue-800",children:"Agent Side"}),m.jsx("p",{className:"text-sm text-blue-700 mb-2",children:"On the agent side, you can call these RPC methods like this:"}),m.jsx("pre",{className:"bg-white p-3 rounded text-xs text-gray-800 overflow-x-auto",children:`// Agent calls RPC method
|
|
183
189
|
const response = await participant.performRpc({
|
|
184
190
|
method: 'give_assignment',
|
|
185
191
|
data: JSON.stringify({
|