@nexlylab/widget-runtime 1.35.9

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.
Files changed (64) hide show
  1. package/README.md +34 -0
  2. package/dist/chunks/ClickToLoadEmbed-BPEGNGjL-Dqu4sV5j.js +1 -0
  3. package/dist/chunks/PanelInfoVideo--D2cI0c1-YtsGmc4D.js +2 -0
  4. package/dist/chunks/PanelVideoOverlay-DrBuXCt3-9CT-CwTr.js +2 -0
  5. package/dist/chunks/_commonjsHelpers-C6fGbg64-BC8KDfbh.js +1 -0
  6. package/dist/chunks/accent-legibility-BJF2VO5n-CDPQ7suO.js +1 -0
  7. package/dist/chunks/allowed-elements-C0OfX2zF-DIBV8lKu.js +27 -0
  8. package/dist/chunks/assistant-link-components--y4CIv5J-FQ5HkTEk.js +1 -0
  9. package/dist/chunks/assistant-link-policy-BCMS2TZD-CPsH3B9n.js +1 -0
  10. package/dist/chunks/block-helpers-Cg_zAqG6-DnN2COvk.js +1 -0
  11. package/dist/chunks/block-rating-_Uu_PSxk-DTJYlp2H.js +1 -0
  12. package/dist/chunks/external-url-TVXjKwdN-B68X1DIx.js +1 -0
  13. package/dist/chunks/index-0kAq-v64-Cj9hKhnd.js +49 -0
  14. package/dist/chunks/index-5dQRR-Cl-BHLOwZ63.js +1 -0
  15. package/dist/chunks/index-7NFiiSKb-Dth9nSwh.js +1 -0
  16. package/dist/chunks/index-B1X1Ctdv-B3fhz3xE.js +3 -0
  17. package/dist/chunks/index-B23y2jUJ-BaO0_6Gs.js +377 -0
  18. package/dist/chunks/index-BBDMWdMz-J8TktO92.js +1 -0
  19. package/dist/chunks/index-BPDIV1BN-DINkyYvc.js +1 -0
  20. package/dist/chunks/index-BPeArT5W-CMIft78k.js +3 -0
  21. package/dist/chunks/index-BTKcrkR9-BBbzbp4w.js +1 -0
  22. package/dist/chunks/index-B_mVvI0v-Lf3DGRi2.js +1 -0
  23. package/dist/chunks/index-Bc5yGuC9-DsvbkSc6.js +1 -0
  24. package/dist/chunks/index-BcsmWDTX-Dw9WA5Ac.js +1 -0
  25. package/dist/chunks/index-Be2ZbAFE-WSc7N-DC.js +1 -0
  26. package/dist/chunks/index-Bo2sRqLv-Ll1lwYMy.js +1 -0
  27. package/dist/chunks/index-BsKaoBfe-DzbRA9nQ.js +1 -0
  28. package/dist/chunks/index-BtQSeiip-l41McWo2.js +1 -0
  29. package/dist/chunks/index-C1c5Hlou-rjlUnXTU.js +1 -0
  30. package/dist/chunks/index-C262wwK4-DpyhuXqd.js +1 -0
  31. package/dist/chunks/index-C5rGq5Qc-F1s-uhpT.js +1 -0
  32. package/dist/chunks/index-CF98EbKR-voVzYeB8.js +1 -0
  33. package/dist/chunks/index-CK3WH5JE-D7wryOBp.js +1 -0
  34. package/dist/chunks/index-CO4N_on8-BFhGhIH1.js +5 -0
  35. package/dist/chunks/index-CQDEV8t8-BBhp-ba9.js +1 -0
  36. package/dist/chunks/index-CR83G6nv-Dgqjnh9U.js +1 -0
  37. package/dist/chunks/index-CWvBoml1-DWT7kbPC.js +1 -0
  38. package/dist/chunks/index-CaM1AB5V-BG8W_sZc.js +1 -0
  39. package/dist/chunks/index-CuMYPeuW-cS-al9E9.js +1 -0
  40. package/dist/chunks/index-CxpblUvs-B1tIB9c8.js +1 -0
  41. package/dist/chunks/index-D0EFzbHX-C1E9R_PY.js +1 -0
  42. package/dist/chunks/index-D6lq5r1c-ieawp1gM.js +1 -0
  43. package/dist/chunks/index-D9Pfcey3-Z7aU4-qs.js +1 -0
  44. package/dist/chunks/index-D9Zgyes_-q6-4GTjm.js +3 -0
  45. package/dist/chunks/index-DFMp0RDj-B7Ae5UrP.js +1 -0
  46. package/dist/chunks/index-DFTMYCH_-DzHCU5QM.js +1 -0
  47. package/dist/chunks/index-DH5dF-Vu-DEb4grOY.js +1 -0
  48. package/dist/chunks/index-DZADUAKv-DPfvWVuj.js +1 -0
  49. package/dist/chunks/index-DfEcosms-Mz6A-R9-.js +1 -0
  50. package/dist/chunks/index-Dwb8DcvL-CuiYrL-M.js +1 -0
  51. package/dist/chunks/index-P0zUoKcv-CISBzElt.js +1 -0
  52. package/dist/chunks/index-ZVYeZzJW-C1mWtfbE.js +1 -0
  53. package/dist/chunks/index-c47JESC5-BsVnPG2P.js +1 -0
  54. package/dist/chunks/index-gUmBjv1--Cmmz_3u0.js +1 -0
  55. package/dist/chunks/index-jHz_pdpv-CylxZ7NI.js +5 -0
  56. package/dist/chunks/index-n_QR9xVp-DxMysJse.js +1 -0
  57. package/dist/chunks/index-vKPrckpA-DBDxHMt7.js +1 -0
  58. package/dist/chunks/index-xcFa26x2-BZjWwuev.js +1 -0
  59. package/dist/chunks/index-zZnmAAiq-DY2zrqZq.js +1 -0
  60. package/dist/chunks/index.modern-CioVZ357-C7XPucLH.js +5 -0
  61. package/dist/chunks/inert-assistant-components-B6Cx9pG5-DWb6n3Yq.js +1 -0
  62. package/dist/chunks/use-deferred-rating-XlgCUwcY-DDVOwURi.js +1 -0
  63. package/dist/nexly.js +60 -0
  64. package/package.json +49 -0
@@ -0,0 +1,377 @@
1
+ var na={},Il=Object.defineProperty,_l=(i,e,t)=>e in i?Il(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_=(i,e,t)=>_l(i,typeof e!="symbol"?e+"":e,t);class Wo{constructor(e={}){_(this,"queue",[]),_(this,"outgoingQueue",[]),_(this,"disconnectionDetails",null),_(this,"onDisconnectCallback",null),_(this,"onMessageCallback",null),_(this,"onModeChangeCallback",null),_(this,"onDebug"),_(this,"onOutgoingMessageCallback",null),this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;const t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;const t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}onOutgoingMessage(e){this.onOutgoingMessageCallback=e;const t=this.outgoingQueue;this.outgoingQueue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}updateMode(e){this.onModeChangeCallback?.(e)}disconnect(e){this.disconnectionDetails||(this.disconnectionDetails=e,this.onDisconnectCallback?.(e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}handleOutgoingMessage(e){this.onOutgoingMessageCallback?this.onOutgoingMessageCallback(e):this.outgoingQueue.push(e)}}function gi(i){const[e,t]=i.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${i}`);const n=Number.parseInt(t);if(Number.isNaN(n))throw new Error(`Invalid sample rate: ${t}`);return{format:e,sampleRate:n}}function fi(i){return i!=null&&typeof i=="object"&&!Array.isArray(i)}function Ml(i,e="Expected a JSON object"){if(!fi(i))throw new Error(e)}async function Ho(i){try{const e=await i.json();if(!fi(e))return i.statusText||"Unknown error";const t=e.detail,n=fi(t)?t.message:t;if(typeof n=="string")return n}catch(e){console.warn("Failed to parse API error response as JSON:",e)}return i.statusText||"Unknown error"}class ia extends Error{constructor(e,t){super(e),_(this,"closeCode"),_(this,"closeReason"),this.name="SessionConnectionError",this.closeCode=t?.closeCode,this.closeReason=t?.closeReason}}const Dl="1.23.0";let vi=Object.freeze({name:"js_sdk",version:Dl});function yi(i){return!!i.type}function Al(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var Ol=Object.defineProperty,Nl=(i,e,t)=>e in i?Ol(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ra=(i,e,t)=>Nl(i,typeof e!="symbol"?e+"":e,t);class fe{constructor(){ra(this,"_locking"),ra(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}}function re(i,e){if(!i)throw new Error(e)}const xl=34028234663852886e22,Ll=-34028234663852886e22,Ul=4294967295,Fl=2147483647,Bl=-2147483648;function ni(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>Fl||i<Bl)throw new Error("invalid int 32: "+i)}function Ar(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Ul||i<0)throw new Error("invalid uint 32: "+i)}function zo(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>xl||i<Ll))throw new Error("invalid float 32: "+i)}const Ko=Symbol("@bufbuild/protobuf/enum-type");function jl(i){const e=i[Ko];return re(e,"missing enum type on enum object"),e}function Go(i,e,t,n){i[Ko]=Jo(e,t.map(r=>({no:r.no,name:r.name,localName:i[r.no]})))}function Jo(i,e,t){const n=Object.create(null),r=Object.create(null),s=[];for(const a of e){const o=Qo(a);s.push(o),n[a.name]=o,r[a.no]=o}return{typeName:i,values:s,findName(a){return n[a]},findNumber(a){return r[a]}}}function ql(i,e,t){const n={};for(const r of e){const s=Qo(r);n[s.localName]=s.no,n[s.no]=s.localName}return Go(n,i,e),n}function Qo(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class gs{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),r=n.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,s=r.makeReadOptions(t);return r.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,r=n.makeWriteOptions(e),s=r.writerFactory();return n.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,r=n.makeWriteOptions(e);return n.writeMessage(this,r)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Vl(i,e,t,n){var r;const s=(r=n?.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new gs),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function Wl(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function ir(i,e,t){for(let s=0;s<28;s=s+7){const a=i>>>s,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const n=i>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){const a=e>>>s,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const ii=4294967296;function sa(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,r=0;function s(a,o){const c=Number(i.slice(a,o));r*=t,n=n*t+c,n>=ii&&(r=r+(n/ii|0),n=n%ii)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?$o(n,r):fs(n,r)}function Hl(i,e){let t=fs(i,e);const n=t.hi&2147483648;n&&(t=$o(t.lo,t.hi));const r=Yo(t.lo,t.hi);return n?"-"+r:r}function Yo(i,e){var t=zl(i,e);if(i=t.lo,e=t.hi,e<=2097151)return String(ii*e+i);const n=i&16777215,r=(i>>>24|e<<8)&16777215,s=e>>16&65535;let a=n+r*6777216+s*6710656,o=r+s*8147497,c=s*2;const d=1e7;return a>=d&&(o+=Math.floor(a/d),a%=d),o>=d&&(c+=Math.floor(o/d),o%=d),c.toString()+aa(o)+aa(a)}function zl(i,e){return{lo:i>>>0,hi:e>>>0}}function fs(i,e){return{lo:i|0,hi:e|0}}function $o(i,e){return e=~e,i?i=~i+1:e+=1,fs(i,e)}const aa=i=>{const e=String(i);return"0000000".slice(e.length)+e};function oa(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Kl(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Gl(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof na!="object"||na.BUF_BIGINT_DISABLE!=="1")){const n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),s=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(o){const c=typeof o=="bigint"?o:BigInt(o);if(c>r||c<n)throw new Error("int64 invalid: ".concat(o));return c},uParse(o){const c=typeof o=="bigint"?o:BigInt(o);if(c>a||c<s)throw new Error("uint64 invalid: ".concat(o));return c},enc(o){return i.setBigInt64(0,this.parse(o),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(o){return i.setBigInt64(0,this.uParse(o),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(o,c){return i.setInt32(0,o,!0),i.setInt32(4,c,!0),i.getBigInt64(0,!0)},uDec(o,c){return i.setInt32(0,o,!0),i.setInt32(4,c,!0),i.getBigUint64(0,!0)}}}const e=n=>re(/^-?[0-9]+$/.test(n),"int64 invalid: ".concat(n)),t=n=>re(/^[0-9]+$/.test(n),"uint64 invalid: ".concat(n));return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),e(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),t(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),e(n),sa(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),t(n),sa(n)},dec(n,r){return Hl(n,r)},uDec(n,r){return Yo(n,r)}}}const ne=Gl();var R;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(R||(R={}));var Rt;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Rt||(Rt={}));function vt(i,e,t){if(e===t)return!0;if(i==R.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return e==t}return!1}function dn(i,e){switch(i){case R.BOOL:return!1;case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return e==0?ne.zero:"0";case R.DOUBLE:case R.FLOAT:return 0;case R.BYTES:return new Uint8Array(0);case R.STRING:return"";default:return 0}}function Xo(i,e){switch(i){case R.BOOL:return e===!1;case R.STRING:return e==="";case R.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function Or(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function Zo(i){if(Array.isArray(i))return i}function U(i,e,t){return(e=tu(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Jl(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function Ql(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,a,o=[],c=!0,d=!1;try{if(s=(t=t.call(i)).next,e===0){if(Object(t)!==t)return;c=!1}else for(;!(c=(n=s.call(t)).done)&&(o.push(n.value),o.length!==e);c=!0);}catch(l){d=!0,r=l}finally{try{if(!c&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(d)throw r}}return o}}function ec(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ca(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,n)}return t}function Yl(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ca(Object(t),!0).forEach(function(n){U(i,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):ca(Object(t)).forEach(function(n){Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n))})}return i}function $l(i,e){if(i==null)return{};var t,n,r=Xl(i,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);for(n=0;n<s.length;n++)t=s[n],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(i,t)&&(r[t]=i[t])}return r}function Xl(i,e){if(i==null)return{};var t={};for(var n in i)if({}.hasOwnProperty.call(i,n)){if(e.indexOf(n)!==-1)continue;t[n]=i[n]}return t}function x(i,e){return Zo(i)||Ql(i,e)||tc(i,e)||ec()}function Zl(i){return Zo(i)||Jl(i)||tc(i)||ec()}function eu(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function tu(i){var e=eu(i,"string");return typeof e=="symbol"?e:e+""}function tc(i,e){if(i){if(typeof i=="string")return Or(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Or(i,e):void 0}}var oe;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(oe||(oe={}));class nu{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ar(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ni(e),oa(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){zo(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ar(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ni(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ni(e),e=(e<<1^e>>31)>>>0,oa(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ne.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ne.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ne.enc(e);return ir(t.lo,t.hi,this.buf),this}sint64(e){let t=ne.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return ir(r,s,this.buf),this}uint64(e){let t=ne.uEnc(e);return ir(t.lo,t.hi,this.buf),this}}class iu{constructor(e,t){this.varint64=Wl,this.uint32=Kl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case oe.Varint:for(;this.buf[this.pos++]&128;);break;case oe.Bit64:this.pos+=4;case oe.Bit32:this.pos+=4;break;case oe.LengthDelimited:let r=this.uint32();this.pos+=r;break;case oe.StartGroup:for(;;){const s=this.tag(),a=x(s,2),o=a[0],c=a[1];if(c===oe.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(c,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ne.dec(...this.varint64())}uint64(){return ne.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=x(e,2),n=t[0],r=t[1],s=-(n&1);return n=(n>>>1|(r&1)<<31)^s,r=r>>>1^s,ne.dec(n,r)}bool(){let e=this.varint64(),t=x(e,2),n=t[0],r=t[1];return n!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ne.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ne.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function ru(i,e,t,n){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof n=="function"?n():n;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=i.util.newFieldList([s]).list()[0]}return r},runtime:i}}function nc(i){const e=i.field.localName,t=Object.create(null);return t[e]=su(i),[t,()=>t[e]]}function su(i){const e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return dn(e.T,e.L);case"message":const t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function au(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}let dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ni=[];for(let i=0;i<dt.length;i++)Ni[dt[i].charCodeAt(0)]=i;Ni[45]=dt.indexOf("+");Ni[95]=dt.indexOf("/");const ic={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,r=0,s,a=0;for(let o=0;o<i.length;o++){if(s=Ni[i.charCodeAt(o)],s===void 0)switch(i[o]){case"=":r=0;case`
3
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:a=s,r=1;break;case 1:t[n++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[n++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[n++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,r=0;for(let s=0;s<i.length;s++)switch(n=i[s],t){case 0:e+=dt[n>>2],r=(n&3)<<4,t=1;break;case 1:e+=dt[r|n>>4],r=(n&15)<<2,t=2;break;case 2:e+=dt[r|n>>6],e+=dt[n&63],t=0;break}return t&&(e+=dt[r],e+="=",t==1&&(e+="=")),e}};function ou(i,e,t){sc(e,i);const n=e.runtime.bin.makeReadOptions(t),r=au(i.getType().runtime.bin.listUnknownFields(i),e.field),s=nc(e),a=x(s,2),o=a[0],c=a[1];for(const d of r)e.runtime.bin.readField(o,n.readerFactory(d.data),e.field,d.wireType,n);return c()}function cu(i,e,t,n){sc(e,i);const r=e.runtime.bin.makeReadOptions(n),s=e.runtime.bin.makeWriteOptions(n);if(rc(i,e)){const d=i.getType().runtime.bin.listUnknownFields(i).filter(l=>l.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const l of d)i.getType().runtime.bin.onUnknownField(i,l.no,l.wireType,l.data)}const a=s.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,s);const c=r.readerFactory(a.finish());for(;c.pos<c.len;){const d=c.tag(),l=x(d,2),u=l[0],h=l[1],p=c.skip(h,u);i.getType().runtime.bin.onUnknownField(i,u,h,p)}}function rc(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function sc(i,e){re(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function ac(i,e){const t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!Xo(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function da(i,e){const t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?dn(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function lt(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(gs.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function oc(i,e){return lt(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}R.DOUBLE,R.FLOAT,R.INT64,R.UINT64,R.INT32,R.UINT32,R.BOOL,R.STRING,R.BYTES;const la={ignoreUnknownFields:!1},ua={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function du(i){return i?Object.assign(Object.assign({},la),i):la}function lu(i){return i?Object.assign(Object.assign({},ua),i):ua}const bi=Symbol(),ri=Symbol();function uu(){return{makeReadOptions:du,makeWriteOptions:lu,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Xe(e)));n=n??new i;const r=new Map,s=t.typeRegistry;for(const o of Object.entries(e)){var a=x(o,2);const c=a[0],d=a[1],l=i.fields.findJsonName(c);if(l){if(l.oneof){if(d===null&&l.kind=="scalar")continue;const u=r.get(l.oneof);if(u!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(l.oneof.name,'" present: "').concat(u,'", "').concat(c,'"'));r.set(l.oneof,c)}ha(n,d,l,t,i)}else{let u=!1;if(s?.findExtension&&c.startsWith("[")&&c.endsWith("]")){const h=s.findExtension(c.substring(1,c.length-1));if(h&&h.extendee.typeName==i.typeName){u=!0;const p=nc(h),f=x(p,2),g=f[0],b=f[1];ha(g,d,h.field,t,h),cu(n,h,b(),t)}}if(!u&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(c,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let r;try{for(r of t.fields.byNumber()){if(!ac(r,i)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!pu(r))continue}const a=r.oneof?i[r.oneof.localName].value:i[r.localName],o=pa(r,a,e);o!==void 0&&(n[e.useProtoFieldName?r.name:r.jsonName]=o)}const s=e.typeRegistry;if(s?.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(i)){const o=s.findExtensionFor(t.typeName,a.no);if(o&&rc(i,o)){const c=ou(i,o,e),d=pa(o.field,c,e);d!==void 0&&(n[o.field.jsonName]=d)}}}catch(s){const a=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=s instanceof Error?s.message:String(s);throw new Error(a+(o.length>0?": ".concat(o):""))}return n},readScalar(i,e,t){return Rn(i,e,t??Rt.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Xo(i,e)))return si(i,e)},debug:Xe}}function Xe(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function ha(i,e,t,n,r){let s=t.localName;if(t.repeated){if(re(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(e)));const o=i[s];for(const c of e){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(c)));switch(t.kind){case"message":o.push(t.T.fromJson(c,n));break;case"enum":const d=rr(t.T,c,n.ignoreUnknownFields,!0);d!==ri&&o.push(d);break;case"scalar":try{o.push(Rn(t.T,c,t.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(c));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(e)));const o=i[s];for(const c of Object.entries(e)){var a=x(c,2);const d=a[0],l=a[1];if(l===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let u;try{u=hu(t.K,d)}catch(h){let p="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(e));throw h instanceof Error&&h.message.length>0&&(p+=": ".concat(h.message)),new Error(p)}switch(t.V.kind){case"message":o[u]=t.V.T.fromJson(l,n);break;case"enum":const h=rr(t.V.T,l,n.ignoreUnknownFields,!0);h!==ri&&(o[u]=h);break;case"scalar":try{o[u]=Rn(t.V.T,l,Rt.BIGINT,!0)}catch(p){let f="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(e));throw p instanceof Error&&p.message.length>0&&(f+=": ".concat(p.message)),new Error(f)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let c=i[s];lt(c)?c.fromJson(e,n):(i[s]=c=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[s]=o.fieldWrapper.unwrapField(c)));break;case"enum":const d=rr(t.T,e,n.ignoreUnknownFields,!1);switch(d){case bi:da(t,i);break;case ri:break;default:i[s]=d;break}break;case"scalar":try{const l=Rn(t.T,e,t.L,!1);l===bi?da(t,i):i[s]=l}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Xe(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function hu(i,e){if(i===R.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Rn(i,e,Rt.BIGINT,!0).toString()}function Rn(i,e,t,n){if(e===null)return n?dn(i,t):bi;switch(i){case R.DOUBLE:case R.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return i==R.FLOAT&&zo(r),r;case R.INT32:case R.FIXED32:case R.SFIXED32:case R.SINT32:case R.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return i==R.UINT32||i==R.FIXED32?Ar(s):ni(s),s;case R.INT64:case R.SFIXED64:case R.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ne.parse(e);return t?a.toString():a;case R.FIXED64:case R.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ne.uParse(e);return t?o.toString():o;case R.BOOL:if(typeof e!="boolean")break;return e;case R.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case R.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return ic.dec(e)}throw new Error}function rr(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:bi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=i.findName(e);if(r!==void 0)return r.no;if(t)return ri;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Xe(e)))}function pu(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function pa(i,e,t){if(i.kind=="map"){re(typeof e=="object"&&e!=null);const a={},o=Object.entries(e);switch(i.V.kind){case"scalar":for(const d of o){var n=x(d,2);const l=n[0],u=n[1];a[l.toString()]=si(i.V.T,u)}break;case"message":for(const d of o){var r=x(d,2);const l=r[0],u=r[1];a[l.toString()]=u.toJson(t)}break;case"enum":const c=i.V.T;for(const d of o){var s=x(d,2);const l=s[0],u=s[1];a[l.toString()]=sr(c,u,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(i.repeated){re(Array.isArray(e));const a=[];switch(i.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(si(i.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(sr(i.T,e[o],t.enumAsInteger));break;case"message":for(let o=0;o<e.length;o++)a.push(e[o].toJson(t));break}return t.emitDefaultValues||a.length>0?a:void 0}switch(i.kind){case"scalar":return si(i.T,e);case"enum":return sr(i.T,e,t.enumAsInteger);case"message":return oc(i.T,e).toJson(t)}}function sr(i,e,t){var n;return re(typeof e=="number"),i.typeName=="google.protobuf.NullValue"?null:t?e:(n=i.findNumber(e)?.name)!==null&&n!==void 0?n:e}function si(i,e){switch(i){case R.INT32:case R.SFIXED32:case R.SINT32:case R.FIXED32:case R.UINT32:return re(typeof e=="number"),e;case R.FLOAT:case R.DOUBLE:return re(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case R.STRING:return re(typeof e=="string"),e;case R.BOOL:return re(typeof e=="boolean"),e;case R.UINT64:case R.FIXED64:case R.INT64:case R.SFIXED64:case R.SINT64:return re(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case R.BYTES:return re(e instanceof Uint8Array),ic.enc(e)}}const Kt=Symbol("@bufbuild/protobuf/unknown-fields"),ma={readUnknownFields:!0,readerFactory:i=>new iu(i)},ga={writeUnknownFields:!0,writerFactory:()=>new nu};function mu(i){return i?Object.assign(Object.assign({},ma),i):ma}function gu(i){return i?Object.assign(Object.assign({},ga),i):ga}function fu(){return{makeReadOptions:mu,makeWriteOptions:gu,listUnknownFields(i){var e;return(e=i[Kt])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Kt]},writeUnknownFields(i,e){const t=i[Kt];if(t)for(const n of t)e.tag(n.no,n.wireType).raw(n.data)},onUnknownField(i,e,t,n){const r=i;Array.isArray(r[Kt])||(r[Kt]=[]),r[Kt].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,r){const s=i.getType(),a=r?e.len:e.pos+t;let o,c;for(;e.pos<a;){var d=e.tag(),l=x(d,2);if(o=l[0],c=l[1],r===!0&&c==oe.EndGroup)break;const u=s.fields.find(o);if(!u){const h=e.skip(c,o);n.readUnknownFields&&this.onUnknownField(i,o,c,h);continue}fa(i,e,u,c,n)}if(r&&(c!=oe.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:fa,writeMessage(i,e,t){const n=i.getType();for(const r of n.fields.byNumber()){if(!ac(r,i)){if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?i[r.oneof.localName].value:i[r.localName];va(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&va(i,e,t,n)}}}function fa(i,e,t,n,r){let s=t.repeated,a=t.localName;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=a&&delete i.value,i.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?R.INT32:t.T;let c=ki;if(t.kind=="scalar"&&t.L>0&&(c=yu),s){let f=i[a];if(n==oe.LengthDelimited&&o!=R.STRING&&o!=R.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)f.push(c(e,o))}else f.push(c(e,o))}else i[a]=c(e,o);break;case"message":const d=t.T;s?i[a].push(ai(e,new d,r,t)):lt(i[a])?ai(e,i[a],r,t):(i[a]=ai(e,new d,r,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=d.fieldWrapper.unwrapField(i[a])));break;case"map":let l=vu(t,e,r),u=x(l,2),h=u[0],p=u[1];i[a][h]=p;break}}function ai(i,e,t,n){const r=e.getType().runtime.bin,s=n?.delimited;return r.readMessage(e,i,s?n.no:i.uint32(),t,s),e}function vu(i,e,t){const n=e.uint32(),r=e.pos+n;let s,a;for(;e.pos<r;){const o=e.tag();switch(x(o,1)[0]){case 1:s=ki(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=ki(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=ai(e,new i.V.T,t,void 0);break}break}}if(s===void 0&&(s=dn(i.K,Rt.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(i.V.kind){case"scalar":a=dn(i.V.T,Rt.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[s,a]}function yu(i,e){const t=ki(i,e);return typeof t=="bigint"?t.toString():t}function ki(i,e){switch(e){case R.STRING:return i.string();case R.BOOL:return i.bool();case R.DOUBLE:return i.double();case R.FLOAT:return i.float();case R.INT32:return i.int32();case R.INT64:return i.int64();case R.UINT64:return i.uint64();case R.FIXED64:return i.fixed64();case R.BYTES:return i.bytes();case R.FIXED32:return i.fixed32();case R.SFIXED32:return i.sfixed32();case R.SFIXED64:return i.sfixed64();case R.SINT64:return i.sint64();case R.UINT32:return i.uint32();case R.SINT32:return i.sint32()}}function va(i,e,t,n){re(e!==void 0);const r=i.repeated;switch(i.kind){case"scalar":case"enum":let a=i.kind=="enum"?R.INT32:i.T;if(r)if(re(Array.isArray(e)),i.packed)ku(t,a,i.no,e);else for(const o of e)Pn(t,a,i.no,o);else Pn(t,a,i.no,e);break;case"message":if(r){re(Array.isArray(e));for(const o of e)ya(t,n,i,o)}else ya(t,n,i,e);break;case"map":re(typeof e=="object"&&e!=null);for(const o of Object.entries(e)){var s=x(o,2);const c=s[0],d=s[1];bu(t,n,i,c,d)}break}}function bu(i,e,t,n,r){i.tag(t.no,oe.LengthDelimited),i.fork();let s=n;switch(t.K){case R.INT32:case R.FIXED32:case R.UINT32:case R.SFIXED32:case R.SINT32:s=Number.parseInt(n);break;case R.BOOL:re(n=="true"||n=="false"),s=n=="true";break}switch(Pn(i,t.K,1,s),t.V.kind){case"scalar":Pn(i,t.V.T,2,r);break;case"enum":Pn(i,R.INT32,2,r);break;case"message":re(r!==void 0),i.tag(2,oe.LengthDelimited).bytes(r.toBinary(e));break}i.join()}function ya(i,e,t,n){const r=oc(t.T,n);t.delimited?i.tag(t.no,oe.StartGroup).raw(r.toBinary(e)).tag(t.no,oe.EndGroup):i.tag(t.no,oe.LengthDelimited).bytes(r.toBinary(e))}function Pn(i,e,t,n){re(n!==void 0);let r=cc(e),s=x(r,2),a=s[0],o=s[1];i.tag(t,a)[o](n)}function ku(i,e,t,n){if(!n.length)return;i.tag(t,oe.LengthDelimited).fork();let r=cc(e),s=x(r,2),a=s[1];for(let o=0;o<n.length;o++)i[a](n[o]);i.join()}function cc(i){let e=oe.Varint;switch(i){case R.BYTES:case R.STRING:e=oe.LengthDelimited;break;case R.DOUBLE:case R.FIXED64:case R.SFIXED64:e=oe.Bit64;break;case R.FIXED32:case R.SFIXED32:case R.FLOAT:e=oe.Bit32;break}const t=R[i].toLowerCase();return[e,t]}function Tu(){return{setEnumType:Go,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const r of t.fields.byMember()){const s=r.localName,a=e,o=i;if(o[s]!=null)switch(r.kind){case"oneof":const c=o[s].case;if(c===void 0)continue;const d=r.findField(c);let l=o[s].value;d&&d.kind=="message"&&!lt(l,d.T)?l=new d.T(l):d&&d.kind==="scalar"&&d.T===R.BYTES&&(l=vn(l)),a[s]={case:c,value:l};break;case"scalar":case"enum":let u=o[s];r.T===R.BYTES&&(u=r.repeated?u.map(vn):vn(u)),a[s]=u;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===R.BYTES)for(const f of Object.entries(o[s])){var n=x(f,2);const g=n[0],b=n[1];a[s][g]=vn(b)}else Object.assign(a[s],o[s]);break;case"message":const p=r.V.T;for(const f of Object.keys(o[s])){let g=o[s][f];p.fieldWrapper||(g=new p(g)),a[s][f]=g}break}break;case"message":const h=r.T;if(r.repeated)a[s]=o[s].map(p=>lt(p,h)?p:new h(p));else{const p=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?a[s]=vn(p):a[s]=p:a[s]=lt(p,h)?p:new h(p)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const r=e[n.localName],s=t[n.localName];if(n.repeated){if(r.length!==s.length)return!1;switch(n.kind){case"message":return r.every((a,o)=>n.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>vt(n.T,a,s[o]));case"enum":return r.every((a,o)=>vt(R.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let a=r,o=s;return n.T.fieldWrapper&&(a!==void 0&&!lt(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!lt(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return vt(R.INT32,r,s);case"scalar":return vt(n.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=n.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 vt(R.INT32,r.value,s.value);case"scalar":return vt(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(r).concat(Object.keys(s));switch(n.V.kind){case"message":const l=n.V.T;return d.every(h=>l.equals(r[h],s[h]));case"enum":return d.every(h=>vt(R.INT32,r[h],s[h]));case"scalar":const u=n.V.T;return d.every(h=>vt(u,r[h],s[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const a=i[s.localName];let o;if(s.repeated)o=a.map(Jn);else if(s.kind=="map"){o=n[s.localName];for(const c of Object.entries(a)){var r=x(c,2);const d=r[0],l=r[1];o[d]=Jn(l)}}else s.kind=="oneof"?o=s.findField(a.case)?{case:a.case,value:Jn(a.value)}:{case:void 0}:o=Jn(a);n[s.localName]=o}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Jn(i){if(i===void 0)return i;if(lt(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function vn(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function Su(i,e,t){return{syntax:i,json:uu(),bin:fu(),util:Object.assign(Object.assign({},Tu()),{newFieldList:e,initFields:t}),makeMessageType(n,r,s){return Vl(this,n,r,s)},makeEnum:ql,makeEnumType:Jo,getEnumType:jl,makeExtension(n,r,s){return ru(this,n,r,s)}}}class wu{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function dc(i,e){const t=lc(i);return e?t:_u(Iu(t))}function Cu(i){return dc(i,!1)}const Eu=lc;function lc(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let r=i.charAt(n);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const Ru=new Set(["constructor","toString","toJSON","valueOf"]),Pu=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),uc=i=>"".concat(i,"$"),Iu=i=>Pu.has(i)?uc(i):i,_u=i=>Ru.has(i)?uc(i):i;class Mu{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Cu(e)}addField(e){re(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function Du(i,e){var t,n,r,s,a,o;const c=[];let d;for(const l of typeof i=="function"?i():i){const u=l;if(u.localName=dc(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Eu(l.name),u.repeated=(n=l.repeated)!==null&&n!==void 0?n:!1,l.kind=="scalar"&&(u.L=(r=l.L)!==null&&r!==void 0?r:Rt.BIGINT),u.delimited=(s=l.delimited)!==null&&s!==void 0?s:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=R.BYTES&&l.T!=R.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Mu(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const y=Su("proto3",i=>new wu(i,e=>Du(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=dn(e.T,e.L);break}}});class _e extends gs{constructor(e){super(),this.seconds=ne.zero,this.nanos=0,y.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(y.json.debug(e)));const n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[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=ne.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?n="."+r.substring(0,3)+"Z":r.substring(6)==="000"?n="."+r.substring(0,6)+"Z":n="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return _e.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new _e({seconds:ne.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new _e().fromBinary(e,t)}static fromJson(e,t){return new _e().fromJson(e,t)}static fromJsonString(e,t){return new _e().fromJsonString(e,t)}static equals(e,t){return y.util.equals(_e,e,t)}}_e.runtime=y;_e.typeName="google.protobuf.Timestamp";_e.fields=y.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Au=y.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:_e},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ou,repeated:!0},{no:5,name:"events",kind:"message",T:xu,repeated:!0}]),Ou=y.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:Nu,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Nu=y.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:_e},{no:3,name:"value",kind:"scalar",T:2}]),xu=y.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:_e},{no:7,name:"normalized_end_timestamp",kind:"message",T:_e,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),hc=y.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),We=y.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),de=y.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"}]),vs=y.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Jt=y.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ln=y.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Ne=y.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"},{no:16,name:"AGENT_ERROR"}]),st=y.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"}]),Lu=y.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),me=y.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"}]),ln=y.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),xi=y.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:Ti,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:Pc}]),Ti=y.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Uu=y.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:y.getEnumType(de),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},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}]),Vt=y.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:y.getEnumType($t)},{no:4,name:"tracks",kind:"message",T:Qt,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:Uu},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:y.getEnumType(Un)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:y.getEnumType(Ne)},{no:18,name:"kind_details",kind:"enum",T:y.getEnumType(Fu),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:Li,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:y.getEnumType(Fn),repeated:!0}]),$t=y.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Un=y.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),Fu=y.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),G=y.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Bu=y.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:Tt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:y.getEnumType(gc)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Qt=y.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:y.getEnumType(We)},{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:y.getEnumType(de)},{no:10,name:"layers",kind:"message",T:Tt,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:Bu,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:y.getEnumType(G)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Pc},{no:19,name:"audio_features",kind:"enum",T:y.getEnumType(me),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:y.getEnumType(hc)},{no:21,name:"packet_trailer_features",kind:"enum",T:y.getEnumType(ln),repeated:!0}]),Li=y.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:y.getEnumType(G)},{no:5,name:"frame_encoding",kind:"message",T:pc,opt:!0},{no:6,name:"schema",kind:"message",T:ys,opt:!0}]),pc=y.makeMessageType("livekit.DataTrackFrameEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:y.getEnumType(ju),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),ju=y.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),qu=y.makeMessageType("livekit.DataTrackSchemaEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:y.getEnumType(Vu),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),Vu=y.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),ys=y.makeMessageType("livekit.DataTrackSchemaId",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:qu}]),Wu=y.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),bs=y.makeMessageType("livekit.DataBlobKey",()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:ys,oneof:"key"}]),mc=y.makeMessageType("livekit.DataBlob",()=>[{no:1,name:"key",kind:"message",T:bs},{no:2,name:"contents",kind:"scalar",T:12}]),Tt=y.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:y.getEnumType(vs)},{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},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),gc=y.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Ce=y.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:y.getEnumType(St)},{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:ks,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Hu,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:bc,oneof:"value"},{no:7,name:"transcription",kind:"message",T:zu,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Au,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Si,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ts,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Ui,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ss,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Fi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ht,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:ws,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:fc,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),St=y.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),fc=y.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:y.getEnumType(G)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),vc=y.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ks,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Si,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Ts,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Ui,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ss,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Fi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ht,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:ws,oneof:"value"}]),Hu=y.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:yc,repeated:!0}]),yc=y.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}]),ks=y.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}]),bc=y.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),zu=y.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:Ku,repeated:!0}]),Ku=y.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}]),Si=y.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}]),Ts=y.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},{no:6,name:"compressed_payload",kind:"scalar",T:12}]),Ui=y.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Ss=y.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:kc,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),kc=y.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}]),Tc=y.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Sc=y.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:y.getEnumType(wc)},{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}]),wc=y.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Cc=y.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:y.getEnumType(Ec)},{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},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:y.getEnumType(Fn),repeated:!0}]),Ec=y.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"},{no:14,name:"ESP32"}]),Fn=y.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),Rc=y.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:ba},{no:2,name:"screen",kind:"message",T:ba},{no:3,name:"resume_connection",kind:"enum",T:y.getEnumType(Ln)},{no:4,name:"disabled_codecs",kind:"message",T:Gu},{no:5,name:"force_relay",kind:"enum",T:y.getEnumType(Ln)}]),ba=y.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:y.getEnumType(Ln)}]),Gu=y.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ti,repeated:!0},{no:2,name:"publish",kind:"message",T:Ti,repeated:!0}]),Pc=y.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Nr=y.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),ke=y.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Ic=y.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:y.getEnumType(Nr)},{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"}),_c=y.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Fi=y.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:y.getEnumType(G)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ic,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:_c,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:y.getEnumType(ke)}],{localName:"DataStream_Header"}),ht=y.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"}),ws=y.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"}),Ju=y.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),He=y.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),xr=y.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Qu=y.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Yu=y.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Pt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Pt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Bi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Bn,oneof:"message"},{no:5,name:"mute",kind:"message",T:ji,oneof:"message"},{no:6,name:"subscription",kind:"message",T:qi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ac,oneof:"message"},{no:8,name:"leave",kind:"message",T:Vi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Nc,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Uc,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ds,oneof:"message"},{no:13,name:"simulate",kind:"message",T:$e,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:_s,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:jc,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Is,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Oc,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Cs,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Rs,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Mc,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:rh,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:ah,oneof:"message"}]),ka=y.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:eh,oneof:"message"},{no:2,name:"answer",kind:"message",T:Pt,oneof:"message"},{no:3,name:"offer",kind:"message",T:Pt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Bi,oneof:"message"},{no:5,name:"update",kind:"message",T:ih,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ps,oneof:"message"},{no:8,name:"leave",kind:"message",T:Vi,oneof:"message"},{no:9,name:"mute",kind:"message",T:ji,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ch,oneof:"message"},{no:11,name:"room_update",kind:"message",T:dh,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:uh,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ph,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:gh,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:vh,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:nh,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:th,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:bh,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Sh,oneof:"message"},{no:22,name:"request_response",kind:"message",T:wh,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ch,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:yh,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Ph,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:fh,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Es,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:$u,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Xu,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:sh,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:oh,oneof:"message"}]),Lr=y.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Tt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:y.getEnumType(gc)}]),Bn=y.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:y.getEnumType(We)},{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:y.getEnumType(de)},{no:9,name:"layers",kind:"message",T:Tt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Lr,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:y.getEnumType(G)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:y.getEnumType(hc)},{no:17,name:"audio_features",kind:"enum",T:y.getEnumType(me),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:y.getEnumType(ln),repeated:!0}]),Cs=y.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:y.getEnumType(G)},{no:4,name:"frame_encoding",kind:"message",T:pc,opt:!0},{no:5,name:"schema",kind:"message",T:ys,opt:!0}]),Es=y.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Li}]),Rs=y.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),$u=y.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Li}]),Xu=y.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Zu}}]),Zu=y.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),Bi=y.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:y.getEnumType(He)},{no:3,name:"final",kind:"scalar",T:8}]),ji=y.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),eh=y.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:xi},{no:2,name:"participant",kind:"message",T:Vt},{no:3,name:"other_participants",kind:"message",T:Vt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:xc,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:Rc},{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:Sc},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ti,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),th=y.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:xc,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Rc},{no:3,name:"server_info",kind:"message",T:Sc},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Ps=y.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Qt}]),nh=y.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Pt=y.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},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),ih=y.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Vt,repeated:!0}]),qi=y.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:Tc,repeated:!0}]),Mc=y.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:Dc,repeated:!0}]),Dc=y.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Wu}],{localName:"UpdateDataSubscription_Update"}),rh=y.makeMessageType("livekit.StoreDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:mc}]),sh=y.makeMessageType("livekit.StoreDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:bs}]),ah=y.makeMessageType("livekit.GetDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:bs}]),oh=y.makeMessageType("livekit.GetDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:mc}]),Ac=y.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:y.getEnumType(vs)},{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}]),Is=y.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:y.getEnumType(me),repeated:!0}]),Oc=y.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}]),Vi=y.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:y.getEnumType(Ne)},{no:3,name:"action",kind:"enum",T:y.getEnumType(Xt)},{no:4,name:"regions",kind:"message",T:kh}]),Xt=y.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Nc=y.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Tt,repeated:!0}]),_s=y.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}]),xc=y.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}]),ch=y.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:yc,repeated:!0}]),dh=y.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:xi}]),lh=y.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:y.getEnumType(Jt)},{no:3,name:"score",kind:"scalar",T:2}]),uh=y.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:lh,repeated:!0}]),hh=y.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:y.getEnumType(xr)}]),ph=y.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:hh,repeated:!0}]),Ms=y.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:y.getEnumType(vs)},{no:2,name:"enabled",kind:"scalar",T:8}]),mh=y.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Ms,repeated:!0}]),gh=y.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Ms,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:mh,repeated:!0}]),fh=y.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Ju,repeated:!0}]),Lc=y.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}]),Uc=y.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Lc,repeated:!0}]),vh=y.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}]),yh=y.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:xi},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Vt},{no:4,name:"other_participants",kind:"message",T:Vt,repeated:!0}]),Ds=y.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Pt},{no:2,name:"subscription",kind:"message",T:qi},{no:3,name:"publish_tracks",kind:"message",T:Ps,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Bc,repeated:!0},{no:5,name:"offer",kind:"message",T:Pt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Fc,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Es,repeated:!0}]),Fc=y.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Bc=y.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:y.getEnumType(He)}]),$e=y.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:y.getEnumType(Qu),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"}]),jc=y.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),bh=y.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),kh=y.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Th,repeated:!0}]),Th=y.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}]),Sh=y.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:y.getEnumType(Lu)}]),wh=y.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:y.getEnumType(Dt)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Bi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Bn,oneof:"request"},{no:6,name:"mute",kind:"message",T:ji,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:_s,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Is,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Oc,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Cs,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Rs,oneof:"request"}]),Dt=y.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),Ch=y.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),qc=y.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),Eh=y.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Cc},{no:2,name:"connection_settings",kind:"message",T:qc},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Bn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Pt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:y.getEnumType(st)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ds}]),Rh=y.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:y.getEnumType(Ur)},{no:2,name:"join_request",kind:"scalar",T:12}]),Ur=y.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Ph=y.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Ih(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Fr={exports:{}},_h=Fr.exports,Ta;function Mh(){return Ta||(Ta=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(_h,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(g,b){var k=g[b];if(typeof k.bind=="function")return k.bind(g);try{return Function.prototype.bind.call(k,g)}catch{return function(){return Function.prototype.apply.apply(k,[g,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 d(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&n?c:console[g]!==void 0?o(console,g):console.log!==void 0?o(console,"log"):e}function l(){for(var g=this.getLevel(),b=0;b<r.length;b++){var k=r[b];this[k]=b<g?e:this.methodFactory(k,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,b,k){return d(g)||u.apply(this,arguments)}function p(g,b){var k=this,S,M,v,T="loglevel";typeof g=="string"?T+=":"+g:typeof g=="symbol"&&(T=void 0);function C(F){var q=(r[F]||"silent").toUpperCase();if(!(typeof window===t||!T)){try{window.localStorage[T]=q;return}catch{}try{window.document.cookie=encodeURIComponent(T)+"="+q+";"}catch{}}}function O(){var F;if(!(typeof window===t||!T)){try{F=window.localStorage[T]}catch{}if(typeof F===t)try{var q=window.document.cookie,X=encodeURIComponent(T),he=q.indexOf(X+"=");he!==-1&&(F=/^([^;]+)/.exec(q.slice(he+X.length+1))[1])}catch{}return k.levels[F]===void 0&&(F=void 0),F}}function L(){if(!(typeof window===t||!T)){try{window.localStorage.removeItem(T)}catch{}try{window.document.cookie=encodeURIComponent(T)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function A(F){var q=F;if(typeof q=="string"&&k.levels[q.toUpperCase()]!==void 0&&(q=k.levels[q.toUpperCase()]),typeof q=="number"&&q>=0&&q<=k.levels.SILENT)return q;throw new TypeError("log.setLevel() called with invalid level: "+F)}k.name=g,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=b||h,k.getLevel=function(){return v??M??S},k.setLevel=function(F,q){return v=A(F),q!==!1&&C(v),l.call(k)},k.setDefaultLevel=function(F){M=A(F),O()||k.setLevel(F,!1)},k.resetLevel=function(){v=null,L(),l.call(k)},k.enableAll=function(F){k.setLevel(k.levels.TRACE,F)},k.disableAll=function(F){k.setLevel(k.levels.SILENT,F)},k.rebuild=function(){if(a!==k&&(S=A(a.getLevel())),l.call(k),a===k)for(var F in s)s[F].rebuild()},S=A(a?a.getLevel():"WARN");var j=O();j!=null&&(v=A(j)),l.call(k)}a=new p,a.getLogger=function(g){if(typeof g!="symbol"&&typeof g!="string"||g==="")throw new TypeError("You must supply a name when creating a logger.");var b=s[g];return b||(b=s[g]=new p(g,a.methodFactory)),b};var f=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=f),a},a.getLoggers=function(){return s},a.default=a,a})})(Fr)),Fr.exports}var Wi=Mh(),Br;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Br||(Br={}));var ae;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee",i.DataTracks="livekit-data-tracks",i.Region="livekit-region",i.ICE="livekit-ice",i.Stats="livekit-stats"})(ae||(ae={}));let B=Wi.getLogger(ae.Default);Object.values(ae).map(i=>Wi.getLogger(i));B.setDefaultLevel(Br.info);function ve(i,e){const t=Wi.getLogger(i);return t.setDefaultLevel(B.getLevel()),e?Dh(t,e):t}function Dh(i,e){const t=r=>(s,a)=>{const o=e(),c=o||a?Object.assign(Object.assign({},o),a):void 0;i[r](s,c)},n=Object.create(i);return n.trace=t("trace"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error"),n}const Ah=Wi.getLogger(ae.E2EE),yn=7e3,Oh=[0,300,4*300,9*300,16*300,yn,yn,yn,yn,yn];class Nh{constructor(e){this._retryDelays=e!==void 0?[...e]:Oh}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function xh(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function m(i,e,t,n){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(l){try{d(n.next(l))}catch(u){a(u)}}function c(l){try{d(n.throw(l))}catch(u){a(u)}}function d(l){l.done?s(l.value):r(l.value).then(o,c)}d((n=n.apply(i,e||[])).next())})}function Sa(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pt(i){return this instanceof pt?(this.v=i,this):new pt(i)}function Vc(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(p){return function(f){return Promise.resolve(f).then(p,u)}}function o(p,f){n[p]&&(r[p]=function(g){return new Promise(function(b,k){s.push([p,g,b,k])>1||c(p,g)})},f&&(r[p]=f(r[p])))}function c(p,f){try{d(n[p](f))}catch(g){h(s[0][3],g)}}function d(p){p.value instanceof pt?Promise.resolve(p.value.v).then(l,u):h(s[0][2],p)}function l(p){c("next",p)}function u(p){c("throw",p)}function h(p,f){p(f),s.shift(),s.length&&c(s[0][0],s[0][1])}}function Lh(i){var e,t;return e={},n("next"),n("throw",function(r){throw r}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(r,s){e[r]=i[r]?function(a){return(t=!t)?{value:pt(i[r](a)),done:!1}:s?s(a):a}:s}}function Fe(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof Sa=="function"?Sa(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(a){return new Promise(function(o,c){a=i[s](a),r(o,c,a.done,a.value)})}}function r(s,a,o,c){Promise.resolve(c).then(function(d){s({value:d,done:o})},a)}}var Qn={exports:{}},wa;function Uh(){if(wa)return Qn.exports;wa=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(v,T,C){return Function.prototype.apply.call(v,T,C)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(v){return Object.getOwnPropertyNames(v).concat(Object.getOwnPropertySymbols(v))}:t=function(v){return Object.getOwnPropertyNames(v)};function n(v){console&&console.warn&&console.warn(v)}var r=Number.isNaN||function(v){return v!==v};function s(){s.init.call(this)}Qn.exports=s,Qn.exports.once=k,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(v){if(typeof v!="number"||v<0||r(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");a=v}}),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(v){if(typeof v!="number"||v<0||r(v))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+v+".");return this._maxListeners=v,this};function c(v){return v._maxListeners===void 0?s.defaultMaxListeners:v._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(v){for(var T=[],C=1;C<arguments.length;C++)T.push(arguments[C]);var O=v==="error",L=this._events;if(L!==void 0)O=O&&L.error===void 0;else if(!O)return!1;if(O){var A;if(T.length>0&&(A=T[0]),A instanceof Error)throw A;var j=new Error("Unhandled error."+(A?" ("+A.message+")":""));throw j.context=A,j}var F=L[v];if(F===void 0)return!1;if(typeof F=="function")e(F,this,T);else for(var q=F.length,X=f(F,q),C=0;C<q;++C)e(X[C],this,T);return!0};function d(v,T,C,O){var L,A,j;if(o(C),A=v._events,A===void 0?(A=v._events=Object.create(null),v._eventsCount=0):(A.newListener!==void 0&&(v.emit("newListener",T,C.listener?C.listener:C),A=v._events),j=A[T]),j===void 0)j=A[T]=C,++v._eventsCount;else if(typeof j=="function"?j=A[T]=O?[C,j]:[j,C]:O?j.unshift(C):j.push(C),L=c(v),L>0&&j.length>L&&!j.warned){j.warned=!0;var F=new Error("Possible EventEmitter memory leak detected. "+j.length+" "+String(T)+" listeners added. Use emitter.setMaxListeners() to increase limit");F.name="MaxListenersExceededWarning",F.emitter=v,F.type=T,F.count=j.length,n(F)}return v}s.prototype.addListener=function(v,T){return d(this,v,T,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(v,T){return d(this,v,T,!0)};function l(){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 u(v,T,C){var O={fired:!1,wrapFn:void 0,target:v,type:T,listener:C},L=l.bind(O);return L.listener=C,O.wrapFn=L,L}s.prototype.once=function(v,T){return o(T),this.on(v,u(this,v,T)),this},s.prototype.prependOnceListener=function(v,T){return o(T),this.prependListener(v,u(this,v,T)),this},s.prototype.removeListener=function(v,T){var C,O,L,A,j;if(o(T),O=this._events,O===void 0)return this;if(C=O[v],C===void 0)return this;if(C===T||C.listener===T)--this._eventsCount===0?this._events=Object.create(null):(delete O[v],O.removeListener&&this.emit("removeListener",v,C.listener||T));else if(typeof C!="function"){for(L=-1,A=C.length-1;A>=0;A--)if(C[A]===T||C[A].listener===T){j=C[A].listener,L=A;break}if(L<0)return this;L===0?C.shift():g(C,L),C.length===1&&(O[v]=C[0]),O.removeListener!==void 0&&this.emit("removeListener",v,j||T)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(v){var T,C,O;if(C=this._events,C===void 0)return this;if(C.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):C[v]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete C[v]),this;if(arguments.length===0){var L=Object.keys(C),A;for(O=0;O<L.length;++O)A=L[O],A!=="removeListener"&&this.removeAllListeners(A);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=C[v],typeof T=="function")this.removeListener(v,T);else if(T!==void 0)for(O=T.length-1;O>=0;O--)this.removeListener(v,T[O]);return this};function h(v,T,C){var O=v._events;if(O===void 0)return[];var L=O[T];return L===void 0?[]:typeof L=="function"?C?[L.listener||L]:[L]:C?b(L):f(L,L.length)}s.prototype.listeners=function(v){return h(this,v,!0)},s.prototype.rawListeners=function(v){return h(this,v,!1)},s.listenerCount=function(v,T){return typeof v.listenerCount=="function"?v.listenerCount(T):p.call(v,T)},s.prototype.listenerCount=p;function p(v){var T=this._events;if(T!==void 0){var C=T[v];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(v,T){for(var C=new Array(T),O=0;O<T;++O)C[O]=v[O];return C}function g(v,T){for(;T+1<v.length;T++)v[T]=v[T+1];v.pop()}function b(v){for(var T=new Array(v.length),C=0;C<T.length;++C)T[C]=v[C].listener||v[C];return T}function k(v,T){return new Promise(function(C,O){function L(j){v.removeListener(T,A),O(j)}function A(){typeof v.removeListener=="function"&&v.removeListener("error",L),C([].slice.call(arguments))}M(v,T,A,{once:!0}),T!=="error"&&S(v,L,{once:!0})})}function S(v,T,C){typeof v.on=="function"&&M(v,"error",T,C)}function M(v,T,C,O){if(typeof v.on=="function")O.once?v.once(T,C):v.on(T,C);else if(typeof v.addEventListener=="function")v.addEventListener(T,function L(A){O.once&&v.removeEventListener(T,L),C(A)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return Qn.exports}var De=Uh();let Wc=!0,Hc=!0;function Cn(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function zt(i,e,t){if(!i.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){As("Unable to polyfill events");return}const n=i.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return r.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),r.apply(this,[a,c])};const s=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function Fh(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Wc=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Bh(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Hc=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function As(){if(typeof window=="object"){if(Wc)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Os(i,e){Hc&&console.warn(i+" is deprecated, please use "+e+" instead.")}function jh(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const t=i.navigator;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(n){const r=parseInt(n.version,10);if(r>=90)return{browser:"chrome",version:r}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Cn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Cn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Cn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Cn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Ca(i){return Object.prototype.toString.call(i)==="[object Object]"}function zc(i){return Ca(i)?Object.keys(i).reduce(function(e,t){const n=Ca(i[t]),r=n?zc(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function jr(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?jr(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{jr(i,i.get(r),t)})}))}function Ea(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&jr(i,o,r)})}),r}const Ra=As;function Kc(i,e){if(e.version>=64)return;const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},r=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(f=>f.kind==="videoinput");let p=h.find(f=>u.some(g=>f.label.toLowerCase().includes(g)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=d.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=n(o.video),Ra("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return Ra("chrome: "+JSON.stringify(o)),c(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){r(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(s(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return r(c,d=>o(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(s(l))))}}}function Gc(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Jc(i,e){if(!(e.version>102))if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.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=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",r=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.track.id):s={track:r.track};const a=new Event("track");a.track=r.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(r=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===r.id):s={track:r};const a=new Event("track");a.track=r,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else zt(i,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function Qc(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=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(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){let c=r.apply(this,arguments);return c||(c=e(this,a),this._senders.push(c)),c};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const o=this._senders.indexOf(a);o!==-1&&this._senders.splice(o,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(s=>{this._senders.push(e(this,s))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(s=>{const a=this._senders.find(o=>o.track===s);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const t=e.apply(this,[]);return t.forEach(n=>n._pc=this),t},Object.defineProperty(i.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 Yc(i,e){if(e.version>=67||!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const n=i.RTCPeerConnection.prototype.getSenders;n&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=n.apply(this,[]);return s.forEach(a=>a._pc=this),s});const r=i.RTCPeerConnection.prototype.addTrack;r&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=r.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Ea(a,s.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const n=i.RTCPeerConnection.prototype.getReceivers;n&&(i.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(s=>s._pc=this),r}),zt(i,"track",r=>(r.receiver._pc=r.srcElement,r)),i.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>Ea(s,r.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let r,s,a;return this.getSenders().forEach(o=>{o.track===n&&(r?a=!0:r=o)}),this.getReceivers().forEach(o=>(o.track===n&&(s?a=!0:s=o),o.track===n)),a||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 $c(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(s,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const o=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(o)===-1&&this._shimmedLocalStreams[a.id].push(o):this._shimmedLocalStreams[a.id]=[a,o],o};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(c=>{if(this.getSenders().find(d=>d.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const o=this.getSenders().filter(c=>a.indexOf(c)===-1);this._shimmedLocalStreams[s.id]=[s].concat(o)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],n.apply(this,arguments)};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const o=this._shimmedLocalStreams[a].indexOf(s);o!==-1&&this._shimmedLocalStreams[a].splice(o,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function Xc(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return $c(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(l=>this._reverseStreams[l.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const l=new i.MediaStream(d.getTracks());this._streams[d.id]=l,this._reverseStreams[l.id]=d,d=l}n.apply(this,[d])};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const u=[].slice.call(arguments,1);if(u.length!==1||!u[0].getTracks().find(p=>p===d))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===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const h=this._streams[l.id];if(h)h.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new i.MediaStream([d]);this._streams[l.id]=p,this._reverseStreams[p.id]=l,this.addStream(p)}return this.getSenders().find(p=>p.track===d)};function s(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const p=d._reverseStreams[h],f=d._streams[p.id];u=u.replace(new RegExp(f.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const p=d._reverseStreams[h],f=d._streams[p.id];u=u.replace(new RegExp(p.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=i.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[p=>{const f=s(this,p);h[0].apply(null,[f])},p=>{h[1]&&h[1].apply(null,p)},arguments[2]]):l.apply(this,arguments).then(p=>s(this,p))}};i.RTCPeerConnection.prototype[d]=u[d]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:s(this,d)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(d._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let l;Object.keys(this._streams).forEach(u=>{this._streams[u].getTracks().find(h=>d.track===h)&&(l=this._streams[u])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qr(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function Zc(i,e){e.version>102||zt(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Pa=Object.freeze({__proto__:null,fixNegotiationNeeded:Zc,shimAddTrackRemoveTrack:Xc,shimAddTrackRemoveTrackWithNative:$c,shimGetSendersWithDtmf:Qc,shimGetUserMedia:Kc,shimMediaStream:Gc,shimOnTrack:Jc,shimPeerConnection:qr,shimSenderReceiverGetStats:Yc});function ed(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){Os("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a.audio,"autoGainControl","mozAutoGainControl"),r(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function qh(i,e){i.navigator.mediaDevices&&(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=function(t){if(!(t&&t.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return t.video===!0?t.video={mediaSource:e}:t.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(t)}))}function td(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Vr(i,e){typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||(!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]}))}function nd(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const r=Array.prototype.slice.call(arguments),s=r[0],a=r[1],o=r[2];return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[s||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(a,o)}}function id(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function rd(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const t=e.apply(this,[]);return t.forEach(n=>n._pc=this),t}),zt(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function sd(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){Os("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function ad(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function od(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;const t=i.RTCPeerConnection.prototype.addTransceiver;t&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const r=n.length>0;r&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=t.apply(this,arguments);if(r){const a=s.sender,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function cd(i,e){if(!(typeof i=="object"&&i.RTCRtpSender)||e.version>=110)return;const t=i.RTCRtpSender.prototype.getParameters;t&&(i.RTCRtpSender.prototype.getParameters=function(){const n=t.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function dd(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;const t=i.RTCPeerConnection.prototype.createOffer;i.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 ld(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;const t=i.RTCPeerConnection.prototype.createAnswer;i.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 Ia=Object.freeze({__proto__:null,shimAddTransceiver:od,shimCreateAnswer:ld,shimCreateOffer:dd,shimGetDisplayMedia:qh,shimGetParameters:cd,shimGetStats:nd,shimGetUserMedia:ed,shimOnTrack:td,shimPeerConnection:Vr,shimRTCDataChannel:ad,shimReceiverGetStats:rd,shimRemoveStream:sd,shimSenderGetStats:id});function ud(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(t){this._localStreams||(this._localStreams=[]),this._localStreams.includes(t)||this._localStreams.push(t),t.getAudioTracks().forEach(n=>e.call(this,n,t)),t.getVideoTracks().forEach(n=>e.call(this,n,t))},i.RTCPeerConnection.prototype.addTrack=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r&&r.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach(r=>{n.includes(r.track)&&this.removeTrack(r)})})}}function hd(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.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 e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const t=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(r=>{if(t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.indexOf(r)>=0)return;t._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,t.dispatchEvent(s)})}),e.apply(t,arguments)}}}function pd(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,d){const l=arguments.length>=2?arguments[2]:arguments[0],u=t.apply(this,[l]);return d?(u.then(c,d),Promise.resolve()):u},e.createAnswer=function(c,d){const l=arguments.length>=2?arguments[2]:arguments[0],u=n.apply(this,[l]);return d?(u.then(c,d),Promise.resolve()):u};let o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function md(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(gd(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(t,n,r){e.mediaDevices.getUserMedia(t).then(n,r)}.bind(e))}function gd(i){return i&&i.video!==void 0?Object.assign({},i,{video:zc(i.video)}):i}function fd(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(t,n){if(t&&t.iceServers){const r=[];for(let s=0;s<t.iceServers.length;s++){let a=t.iceServers[s];a.urls===void 0&&a.url?(Os("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,r.push(a)):r.push(t.iceServers[s])}t.iceServers=r}return new e(t,n)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function vd(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function yd(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(t){if(t){typeof t.offerToReceiveAudio<"u"&&(t.offerToReceiveAudio=!!t.offerToReceiveAudio);const n=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");t.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):t.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio",{direction:"recvonly"}),typeof t.offerToReceiveVideo<"u"&&(t.offerToReceiveVideo=!!t.offerToReceiveVideo);const r=this.getTransceivers().find(s=>s.receiver.track.kind==="video");t.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):t.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function bd(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var _a=Object.freeze({__proto__:null,shimAudioContext:bd,shimCallbacksAPI:pd,shimConstraints:gd,shimCreateOfferLegacy:yd,shimGetUserMedia:md,shimLocalStreamsAPI:ud,shimRTCIceServerUrls:fd,shimRemoteStreamsAPI:hd,shimTrackEventTransceiver:vd}),Ma={exports:{}},Da;function Vh(){return Da||(Da=1,(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
4
+ `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
5
+ m=`).map((n,r)=>(r>0?"m="+n:n).trim()+`\r
6
+ `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(r=>r.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const r={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let s=8;s<n.length;s+=2)switch(n[s]){case"raddr":r.relatedAddress=n[s+1];break;case"rport":r.relatedPort=parseInt(n[s+1],10);break;case"tcptype":r.tcpType=n[s+1];break;case"ufrag":r.ufrag=n[s+1],r.usernameFragment=n[s+1];break;default:r[n[s]]===void 0&&(r[n[s]]=n[s+1]);break}return r},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const r=t.component;r==="rtp"?n.push(1):r==="rtcp"?n.push(2):n.push(r),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const s=t.type;return n.push("typ"),n.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const r={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),r.name=n[0],r.clockRate=parseInt(n[1],10),r.channels=n.length===3?parseInt(n[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const r=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r
7
+ `},e.parseExtmap=function(t){const n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
8
+ `},e.parseFmtp=function(t){const n={};let r;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)r=s[a].trim().split("="),n[r[0].trim()]=r[1];return n},e.writeFmtp=function(t){let n="",r=t.payloadType;if(t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),n+="a=fmtp:"+r+" "+s.join(";")+`\r
9
+ `}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",r=t.payloadType;return t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{n+="a=rtcp-fb:"+r+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
10
+ `}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),r={ssrc:parseInt(t.substring(7,n),10)},s=t.indexOf(":",n);return s>-1?(r.attribute=t.substring(n+1,s),r.value=t.substring(s+1)):r.attribute=t.substring(n+1),r},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(r=>parseInt(r,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let r="a=setup:"+n+`\r
11
+ `;return t.fingerprints.forEach(s=>{r+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
12
+ `}),r},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
13
+ `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const r=e.matchPrefix(t+n,"a=ice-ufrag:")[0],s=e.matchPrefix(t+n,"a=ice-pwd:")[0];return r&&s?{usernameFragment:r.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r
14
+ a=ice-pwd:`+t.password+`\r
15
+ `;return t.iceLite&&(n+=`a=ice-lite\r
16
+ `),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(t)[0].split(" ");n.profile=r[2];for(let a=3;a<r.length;a++){const o=r[a],c=e.matchPrefix(t,"a=rtpmap:"+o+" ")[0];if(c){const d=e.parseRtpMap(c),l=e.matchPrefix(t,"a=fmtp:"+o+" ");switch(d.parameters=l.length?e.parseFmtp(l[0]):{},d.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+o+" ").map(e.parseRtcpFb),n.codecs.push(d),d.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(d.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(a=>{n.headerExtensions.push(e.parseExtmap(a))});const s=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(a=>{s.forEach(o=>{a.rtcpFeedback.find(c=>c.type===o.type&&c.parameter===o.parameter)||a.rtcpFeedback.push(o)})}),n},e.writeRtpDescription=function(t,n){let r="";r+="m="+t+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
17
+ `,r+=`c=IN IP4 0.0.0.0\r
18
+ `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
19
+ `,n.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return n.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r
20
+ `),n.headerExtensions&&n.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){const n=[],r=e.parseRtpParameters(t),s=r.fecMechanisms.indexOf("RED")!==-1,a=r.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=o.length>0&&o[0].ssrc;let d;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(p=>parseInt(p,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(d=l[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&d&&(p.rtx={ssrc:d}),n.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},n.push(p))}}),n.length===0&&c&&n.push({ssrc:c});let u=e.matchPrefix(t,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-2e3*8:u=void 0,n.forEach(h=>{h.maxBitrate=u})),n},e.parseRtcpParameters=function(t){const n={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
21
+ `),t.mux&&(n+=`a=rtcp-mux\r
22
+ `),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
23
+ `),n},e.parseMsid=function(t){let n;const r=e.matchPrefix(t,"a=msid:");if(r.length===1)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return n=s[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:");let s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const c=o[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,n){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
24
+ `,`c=IN IP4 0.0.0.0\r
25
+ `,"a=sctp-port:"+n.port+`\r
26
+ `]:r=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r
27
+ `,`c=IN IP4 0.0.0.0\r
28
+ `,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r
29
+ `],n.maxMessageSize!==void 0&&r.push("a=max-message-size:"+n.maxMessageSize+`\r
30
+ `),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,r){let s;const a=n!==void 0?n:2;return t?s=t:s=e.generateSessionId(),`v=0\r
31
+ o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
32
+ s=-\r
33
+ t=0 0\r
34
+ `},e.getDirection=function(t,n){const r=e.splitLines(t);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 n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const n=e.splitLines(t)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},e.parseOLine=function(t){const n=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e})(Ma)),Ma.exports}var kd=Vh(),Zt=Ih(kd),Wh=Al({__proto__:null,default:Zt},[kd]);function oi(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(t){if(typeof t=="object"&&t.candidate&&t.candidate.indexOf("a=")===0&&(t=JSON.parse(JSON.stringify(t)),t.candidate=t.candidate.substring(2)),t.candidate&&t.candidate.length){const n=new e(t),r=Zt.parseCandidate(t.candidate);for(const s in r)s in n||Object.defineProperty(n,s,{value:r[s]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new e(t)},i.RTCIceCandidate.prototype=e.prototype,zt(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Wr(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||zt(i,"icecandidate",e=>{if(e.candidate){const t=Zt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ci(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>102||e.browser==="firefox"&&e.version>=113)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=Zt.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=Zt.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},r=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},s=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=Zt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76&&this.getConfiguration().sdpSemantics==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0}),t(arguments[0])){const o=n(arguments[0]),c=r(o),d=s(arguments[0],o);let l;c===0&&d===0?l=Number.POSITIVE_INFINITY:c===0||d===0?l=Math.max(c,d):l=Math.min(c,d);const u={};Object.defineProperty(u,"maxMessageSize",{get(){return l}}),this._sctp=u}return a.apply(this,arguments)}}function di(i,e){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>=149||e.browser==="firefox"&&e.version>60)return;function t(r,s){const a=r.send;r.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(r.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return a.apply(r,arguments)}}const n=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return t(r,this),r},zt(i,"datachannel",r=>(t(r.channel,r.target),r))}function Hr(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function zr(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
35
+ a=extmap-allow-mixed`)!==-1){const r=n.sdp.split(`
36
+ `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
37
+ `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:r}):n.sdp=r}return t.apply(this,arguments)}}function li(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ui(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let n=arguments[0]||{};if(typeof n!="object"||n.type&&n.sdp)return t.apply(this,arguments);if(n={type:n.type,sdp:n.sdp},!n.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":n.type="offer";break;default:n.type="answer";break}return n.sdp||n.type!=="offer"&&n.type!=="answer"?t.apply(this,[n]):(n.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(r=>t.apply(this,[r]))})}var Hh=Object.freeze({__proto__:null,removeExtmapAllowMixed:zr,shimAddIceCandidateNullOrEmpty:li,shimConnectionState:Hr,shimMaxMessageSize:ci,shimParameterlessSetLocalDescription:ui,shimRTCIceCandidate:oi,shimRTCIceCandidateRelayProtocol:Wr,shimSendThrowTypeError:di});function zh(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=i.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=As,r=jh(e),s={browserDetails:r,commonShim:Hh,extractVersion:Cn,disableLog:Fh,disableWarnings:Bh,sdp:Wh};switch(r.browser){case"chrome":if(!Pa||!qr||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(r.version===null)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=Pa,li(e,r),ui(e),Kc(e,r),Gc(e),qr(e,r),Jc(e,r),Xc(e,r),Qc(e),Yc(e,r),Zc(e,r),oi(e),Wr(e),Hr(e),ci(e,r),di(e,r),zr(e,r);break;case"firefox":if(!Ia||!Vr||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=Ia,li(e,r),ui(e),ed(e,r),Vr(e,r),nd(e,r),td(e),sd(e),id(e),rd(e),ad(e),od(e,r),cd(e,r),dd(e,r),ld(e,r),oi(e),Hr(e),ci(e,r),di(e,r);break;case"safari":if(!_a||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=_a,li(e,r),ui(e),fd(e),yd(e),pd(e),ud(e),hd(e),vd(e),md(e),bd(e),oi(e),Wr(e),ci(e,r),di(e,r),zr(e,r);break;default:n("Unsupported browser!");break}return s}zh({window:typeof window>"u"?void 0:window});var Kr,Td;class Ee extends(Td=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Kr=Ee;Ee.resolve=i=>Reflect.get(Td,"resolve",Kr).call(Kr,i);const Kh=/version\/(\d+(\.?_?\d+)+)/i;let ar;function Re(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();return(ar===void 0||e)&&(ar=Gh.find(r=>r.test.test(t))?.describe(t)),ar}const Gh=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:hi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:or(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:hi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:or(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:hi(Kh,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:or(i)}}}];function hi(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function or(i){return i.includes("mac os")?hi(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Jh="2.22.1";const Qh=Jh,Yh=17,Sd=0,Gr=1,wd=2,$h=wd;class gt extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof n?.cause<"u"&&(this.cause=n?.cause)}}class Be extends gt{}var Q;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(Q||(Q={}));class N extends Be{constructor(e,t,n,r){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=r,this.reasonName=Q[t]}static notAllowed(e,t,n){return new N(e,Q.NotAllowed,t,n)}static timeout(e){return new N(e,Q.Timeout)}static leaveRequest(e,t){return new N(e,Q.LeaveRequest,void 0,t)}static internal(e,t){return new N(e,Q.InternalError,void 0,t)}static cancelled(e){return new N(e,Q.Cancelled)}static serverUnreachable(e,t){return new N(e,Q.ServerUnreachable,t)}static websocket(e,t,n){return new N(e,Q.WebSocket,t,n)}static serviceNotFound(e,t){return new N(e,Q.ServiceNotFound,void 0,t)}}class Ns extends gt{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class ut extends gt{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Xh extends gt{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class ee extends gt{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class wt extends gt{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class Zh extends gt{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class Aa extends gt{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Oa extends Be{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:Dt[t]}}var ie;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",i[i.HeaderTooLarge=9]="HeaderTooLarge",i[i.PayloadTooLarge=10]="PayloadTooLarge"})(ie||(ie={}));class le extends Be{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ie[t]}}class Gt extends gt{constructor(e){super(18,e),this.name="SignalReconnectError"}}var wi;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(wi||(wi={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(wi||(wi={}));class Y{}Y.setTimeout=function(){return setTimeout(...arguments)};Y.setInterval=function(){return setInterval(...arguments)};Y.clearTimeout=function(){return clearTimeout(...arguments)};Y.clearInterval=function(){return clearInterval(...arguments)};var E;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived",i.DataTrackPublished="dataTrackPublished",i.DataTrackUnpublished="dataTrackUnpublished",i.LocalDataTrackPublished="localDataTrackPublished",i.LocalDataTrackUnpublished="localDataTrackUnpublished"})(E||(E={}));var D;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(D||(D={}));var P;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved",i.PublishDataTrackResponse="publishDataTrackResponse",i.UnPublishDataTrackResponse="unPublishDataTrackResponse",i.DataTrackSubscriberHandles="dataTrackSubscriberHandles",i.DataTrackPacketReceived="dataTrackPacketReceived",i.Joined="joined",i.TokenRefreshed="tokenRefreshed",i.ServerRegionsReported="serverRegionsReported"})(P||(P={}));var I;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(I||(I={}));function cr(i){const e={};for(const n of Object.entries(i)){var t=x(n,2);const r=t[0],s=t[1];s!==void 0&&(e[r]=s)}return e}function dr(i,e){return i&&e?"".concat(i,"x").concat(e):void 0}function Jr(i){return Math.round(i*1e4)/1e4}function ep(i){const e=i.jitterBufferDelay,t=i.jitterBufferEmittedCount;return e!==void 0&&t?Jr(e/t):void 0}function tp(i,e){if(i.playoutDelay!==void 0)return Jr(i.playoutDelay);const t=e?.totalPlayoutDelay,n=e?.totalSamplesCount;return t!==void 0&&n?Jr(t/n):void 0}function Qr(i){var e,t;const n=new Map,r=[],s=[],a=[];let o;i.forEach(g=>n.set(g.id,g));const c=g=>{var b;return g.codecId?(b=n.get(g.codecId))===null||b===void 0?void 0:b.mimeType:void 0},d=(g,b)=>g[b]?n.get(g[b]):void 0;i.forEach(g=>{switch(g.type){case"inbound-rtp":{const b=d(g,"playoutId");s.push(cr({kind:g.kind,ssrc:g.ssrc,mid:g.mid,trackId:g.trackIdentifier,codec:c(g),decoder:g.decoderImplementation,resolution:dr(g.frameWidth,g.frameHeight),fps:g.framesPerSecond,bytesReceived:g.bytesReceived,packetsReceived:g.packetsReceived,packetsLost:g.packetsLost,packetsDiscarded:g.packetsDiscarded,framesReceived:g.framesReceived,framesDecoded:g.framesDecoded,framesDropped:g.framesDropped,keyFramesDecoded:g.keyFramesDecoded,freezeCount:g.freezeCount,totalFreezesDuration:g.totalFreezesDuration,pauseCount:g.pauseCount,nackCount:g.nackCount,pliCount:g.pliCount,firCount:g.firCount,jitter:g.jitter,jitterBuffer:ep(g),playoutDelay:tp(g,b),audioLevel:g.audioLevel,totalSamplesReceived:g.totalSamplesReceived,concealedSamples:g.concealedSamples}));break}case"outbound-rtp":{const b=d(g,"remoteId"),k=d(g,"mediaSourceId");a.push(cr({kind:g.kind,ssrc:g.ssrc,mid:g.mid,rid:g.rid,trackId:k?.trackIdentifier,active:g.active,codec:c(g),encoder:g.encoderImplementation,resolution:dr(g.frameWidth,g.frameHeight),fps:g.framesPerSecond,captureResolution:dr(k?.width,k?.height),captureFps:k?.framesPerSecond,audioLevel:k?.audioLevel,targetBitrate:g.targetBitrate,bytesSent:g.bytesSent,packetsSent:g.packetsSent,retransmittedPacketsSent:g.retransmittedPacketsSent,framesEncoded:g.framesEncoded,keyFramesEncoded:g.keyFramesEncoded,limitedBy:g.qualityLimitationReason==="none"?void 0:g.qualityLimitationReason,nackCount:g.nackCount,pliCount:g.pliCount,firCount:g.firCount,remotePacketsLost:b?.packetsLost,remoteFractionLost:b?.fractionLost,remoteJitter:b?.jitter,remoteRoundTripTime:b?.roundTripTime}));break}case"transport":o=g;break;case"candidate-pair":r.push(g);break}});const l=o?.selectedCandidatePairId,u=(t=(e=l?n.get(l):void 0)!==null&&e!==void 0?e:r.find(g=>g.selected))!==null&&t!==void 0?t:r.find(g=>g.nominated),h=u?.localCandidateId?n.get(u.localCandidateId):void 0,p=u?.remoteCandidateId?n.get(u.remoteCandidateId):void 0,f=cr({ice:o?.iceState,dtls:o?.dtlsState,route:h&&p?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(p.candidateType):void 0,network:h?.networkType,currentRoundTripTime:u?.currentRoundTripTime,availableOutgoingBitrate:u?.availableOutgoingBitrate,availableIncomingBitrate:u?.availableIncomingBitrate,bytesSent:u?.bytesSent,bytesReceived:u?.bytesReceived,candidatePairChanges:o?.selectedCandidatePairChanges});return{connection:Object.keys(f).length>0?f:void 0,outbound:a.length>0?a:void 0,inbound:s.length>0?s:void 0}}function np(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}class ${constructor(e,t,n,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,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 ip=["vp8","h264"],rp=["vp8","h264","vp9","av1","h265"];function Cd(i){return!!ip.find(e=>e===i)}const sp=Cd;var Na;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(Na||(Na={}));var Yr;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Yr||(Yr={}));const jn={h90:new $(160,90,9e4,20),h180:new $(320,180,16e4,20),h216:new $(384,216,18e4,20),h360:new $(640,360,45e4,20),h540:new $(960,540,8e5,25),h720:new $(1280,720,17e5,30),h1080:new $(1920,1080,3e6,30),h1440:new $(2560,1440,5e6,30),h2160:new $(3840,2160,8e6,30)},$r={h120:new $(160,120,7e4,20),h180:new $(240,180,125e3,20),h240:new $(320,240,14e4,20),h360:new $(480,360,33e4,20),h480:new $(640,480,5e5,20),h540:new $(720,540,6e5,25),h720:new $(960,720,13e5,30),h1080:new $(1440,1080,23e5,30),h1440:new $(1920,1440,38e5,30)},xs={h360fps3:new $(640,360,2e5,3,"medium"),h360fps15:new $(640,360,4e5,15,"medium"),h720fps5:new $(1280,720,8e5,5,"medium"),h720fps15:new $(1280,720,15e5,15,"medium"),h720fps30:new $(1280,720,2e6,30,"medium"),h1080fps15:new $(1920,1080,25e5,15,"medium"),h1080fps30:new $(1920,1080,5e6,30,"medium"),original:new $(0,0,7e6,30,"medium")};function Ed(i,e,t){var n,r,s,a;const o=Id(i??{}),c=o.optionsWithoutProcessor,d=o.audioProcessor,l=o.videoProcessor,u=e?.processor,h=t?.processor,p=c??{};return p.audio===!0&&(p.audio={}),p.video===!0&&(p.video={}),p.audio&&(Xr(p.audio,e),(n=(s=p.audio).deviceId)!==null&&n!==void 0||(s.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=d??u)),p.video&&(Xr(p.video,t),(r=(a=p.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=l??h)),p}function Xr(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Ls(i){var e,t,n,r;const s={};if(i.video)if(typeof i.video=="object"){const a={},o=a,c=i.video;Object.keys(c).forEach(d=>{d==="resolution"?Xr(o,c.resolution):o[d]=c[d]}),s.video=a,(e=(n=s.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else s.video=i.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return i.audio?typeof i.audio=="object"?(s.audio=i.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Rd(i){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const n=Pd();if(n){const r=n.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield Te(t),r.getByteTimeDomainData(a);const o=a.some(c=>c!==128&&c!==0);return n.close(),!o}return!1})()})}function Pd(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&!((i=window.document)===null||i===void 0)&&i.body){const n=()=>m(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}finally{(r=window.document.body)===null||r===void 0||r.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function ap(i){return i==="audioinput"?w.Source.Microphone:i==="videoinput"?w.Source.Camera:w.Source.Unknown}function Zr(i){return i===w.Source.Microphone?"audioinput":i===w.Source.Camera?"videoinput":void 0}function op(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,Ht()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function In(i){return i.split("/")[1].toLowerCase()}function cp(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Ps({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function H(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?H(i.track):{})}}function dp(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function lp(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],r={};for(const s of n)i[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Id(i){const e=Object.assign({},i);let t,n;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:np(e)}}function up(i){switch(i){case de.CAMERA:return w.Source.Camera;case de.MICROPHONE:return w.Source.Microphone;case de.SCREEN_SHARE:return w.Source.ScreenShare;case de.SCREEN_SHARE_AUDIO:return w.Source.ScreenShareAudio;default:return w.Source.Unknown}}function xa(i,e){return i.width*i.height<e.width*e.height}function hp(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}const pp=5e3,bn=[];var xe;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(xe||(xe={}));class w extends De.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=w.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=B,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),pp):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=ve((r=n.loggerName)!==null&&r!==void 0?r:ae.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=w.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),H(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===w.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===w.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(bn.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&bn.splice(bn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Yt(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?I.AudioPlaybackStarted:I.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?I.AudioPlaybackFailed:I.VideoPlaybackFailed,s):s.name==="AbortError"?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:s}),r&&e&&n.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(I.ElementAttached,e),e}detach(e){try{if(e){en(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(I.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{en(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(I.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle!==void 0&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then(e=>{e&&this.log.info("final track stats",Qr(e))}).catch(e=>this.log.debug("could not collect final track stats",{error:e})))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=ve(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),bn.forEach(n=>{n.parentElement||(t=!1)}),t&&bn.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===w.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Me()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Me()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Yt(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(r=>{t.removeTrack(r)}),t.addTrack(i)),(!Ht()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Ht()||Wt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function en(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function r(d){switch(d){case e.Audio:return We.AUDIO;case e.Video:return We.VIDEO;default:return We.DATA}}i.kindToProto=r;function s(d){switch(d){case We.AUDIO:return e.Audio;case We.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=s;function a(d){switch(d){case t.Camera:return de.CAMERA;case t.Microphone:return de.MICROPHONE;case t.ScreenShare:return de.SCREEN_SHARE;case t.ScreenShareAudio:return de.SCREEN_SHARE_AUDIO;default:return de.UNKNOWN}}i.sourceToProto=a;function o(d){switch(d){case de.CAMERA:return t.Camera;case de.MICROPHONE:return t.Microphone;case de.SCREEN_SHARE:return t.ScreenShare;case de.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(d){switch(d){case xr.ACTIVE:return n.Active;case xr.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(w||(w={}));const mp="|",tn="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function _d(i){const e=i.split(mp);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Te(i){return new Ee(e=>Y.setTimeout(e,i))}function es(){return"addTransceiver"in RTCPeerConnection.prototype}function ts(){return"addTrack"in RTCPeerConnection.prototype}function gp(){if(!("getCapabilities"in RTCRtpSender)||Ht()||Wt())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function fp(){if(!("getCapabilities"in RTCRtpSender)||Wt())return!1;if(Ht()){const t=Re();if(t?.version&&nt(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&nt(t.osVersion,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ze(i){return i==="av1"||i==="vp9"}function vp(i){var e;const t=(e=i.getHeaderExtensionsToNegotiate)===null||e===void 0?void 0:e.call(i);if(!t||!i.setHeaderExtensionsToNegotiate)return!1;const n=t.find(r=>r.uri===tn);if(!n)return!1;if(n.direction!=="stopped")return!0;n.direction="sendrecv";try{return i.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function ns(i){return!document||qn()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function yp(){return typeof RTCPeerConnection>"u"?!1:es()||ts()}function Wt(){var i;return((i=Re())===null||i===void 0?void 0:i.name)==="Firefox"}function bp(){const i=Re();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function is(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!bp()}function Ht(){var i;return((i=Re())===null||i===void 0?void 0:i.name)==="Safari"}function qn(){const i=Re();return i?.name==="Safari"||i?.os==="iOS"}function kp(){const i=Re();return i?.name==="Safari"&&i.version.startsWith("17.")||i?.os==="iOS"&&!!i?.osVersion&&nt(i.osVersion,"17")>=0}function Tp(i){return i||(i=Re()),i?.name==="Safari"&&nt(i.version,"18.3")>0||i?.os==="iOS"&&!!i?.osVersion&&nt(i.osVersion,"18.3")>0}function Md(){var i,e;return Me()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Sp(){const i=Re(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&nt(i.osVersion,e)>=0?!0:i.name==="Safari"&&nt(i.version,e)>=0}function Me(){return typeof document<"u"}function Qe(){return navigator.product=="ReactNative"}function un(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function lr(i){return un(i)?i.hostname.split(".")[0]:null}function Dd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ad(){if(!Qe())return;let i=Dd();if(i)return i.platform}function La(){if(Me())return window.devicePixelRatio;if(Qe()){let i=Dd();if(i)return i.devicePixelRatio}return 1}function nt(i,e){const t=i.split("."),n=e.split("."),r=Math.min(t.length,n.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(n[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function wp(i){for(const e of i)e.target.handleResize(e)}function Cp(i){for(const e of i)e.target.handleVisibilityChanged(e)}let ur=null;const Ua=()=>(ur||(ur=new ResizeObserver(wp)),ur);let hr=null;const Fa=()=>(hr||(hr=new IntersectionObserver(Cp,{root:null,rootMargin:"0px"})),hr);function Ep(i){var e;const t=new Cc({capabilities:i,sdk:Ec.JS,protocol:Yh,clientProtocol:$h,version:Qh});return Qe()&&(t.os=(e=Ad())!==null&&e!==void 0?e:""),t}function Ba(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=i,r.height=e;const s=r.getContext("2d");s?.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(i/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=r.captureStream().getTracks(),o=x(a,1),c=o[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}let kn;function pr(){if(!kn){const t=new AudioContext,n=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);const s=t.createMediaStreamDestination();n.connect(r),r.connect(s),n.start();var i=s.stream.getAudioTracks(),e=x(i,1);if(kn=e[0],!kn)throw Error("Could not get empty media stream audio track");kn.enabled=!1}return kn.clone()}class be{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,r)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=r,e&&(yield e(n,r))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}}function Od(i){return rp.includes(i)}function nn(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function Rp(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Vn(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function Pp(i,e){return i.segments.map(t=>{let n=t.id,r=t.text,s=t.language,a=t.startTime,o=t.endTime,c=t.final;var d;const l=(d=e.get(n))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,l),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:s,firstReceivedTime:l,lastReceivedTime:u}})}function Ip(i){const e=i.id,t=i.timestamp,n=i.message,r=i.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}function ja(i){switch(i.reason){case Q.LeaveRequest:return i.context;case Q.Cancelled:return Ne.CLIENT_INITIATED;case Q.NotAllowed:return Ne.USER_REJECTED;case Q.ServerUnreachable:return Ne.JOIN_FAILURE;default:return Ne.UNKNOWN_REASON}}function At(i){return i!==void 0?Number(i):void 0}function Je(i){return i!==void 0?BigInt(i):void 0}function rn(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function tt(i){return!!i&&i.kind==w.Kind.Audio}function mt(i){return!!i&&i.kind==w.Kind.Video}function Ye(i){return rn(i)&&mt(i)}function at(i){return rn(i)&&tt(i)}function rs(i){return!!i&&!i.isLocal}function _p(i){return!!i&&!i.isLocal}function mr(i){return rs(i)&&mt(i)}function Mp(i){return i.isLocal}function Dp(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let r=e;for(;r>0;){const s=n[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(n.slice(0,r)),n=n.slice(r)}return n.length>0&&t.push(n),t}function pi(i){return new ReadableStream({start(e){e.enqueue(i),e.close()}})}function Ap(i,e){return Vc(this,arguments,function*(){const t=i.getReader();let n=new Uint8Array(0);try{for(;;){const r=yield pt(t.read()),s=r.done,a=r.value;if(s)break;if(a.byteLength===0)continue;const o=new Uint8Array(n.byteLength+a.byteLength);for(o.set(n),o.set(a,n.byteLength),n=o;n.byteLength>=e;)yield yield pt(n.slice(0,e)),n=n.slice(e)}n.byteLength>0&&(yield yield pt(n))}finally{t.releaseLock()}})}function Op(i){var e;const t=i.get("Cache-Control");if(t){const n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function Ct(){return typeof CompressionStream<"u"}function Np(){return Ct()&&!Wt()}function qa(i,e){const t=_d(e.id),n=x(t,2),r=n[1];if(r?.startsWith("TR"))return r;if(i.id.startsWith("TR"))return i.id}function xp(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=Lp(i,e);return t?n:Us(n,"v1")}function Lp(i,e){const t=new URL(Rp(i));return e.forEach((n,r)=>{t.searchParams.set(r,n)}),Us(t,"rtc")}function Up(i){const e=new URL(Vn(i));return Us(e,"validate")}function Nd(i){return i.endsWith("/")?i:"".concat(i,"/")}function Us(i,e){return i.pathname="".concat(Nd(i.pathname)).concat(e),i}function Va(i){if(typeof i=="string")return ka.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return ka.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function Fp(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(i instanceof Error)return i.message;if(!(i instanceof AbortSignal))return e;const t=i.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Bp=10,Tn="lk_e2ee",jp="LKFrameEncryptionKey",qp={sharedKey:!1,ratchetSalt:jp,ratchetWindowSize:8,failureTolerance:Bp,keyringSize:16,keySize:128};var Et;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Et||(Et={}));var Wa;(function(i){i.KeyRatcheted="keyRatcheted"})(Wa||(Wa={}));var bt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(bt||(bt={}));var Ha;(function(i){i.Error="cryptorError"})(Ha||(Ha={}));function Vp(){return Fs()||Wp()}function Wp(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function Fs(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Hp(i){var e,t,n,r,s;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new vc({value:i.value})}class yv extends De.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,n,r)=>{B.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},qp),e),this.on(Et.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const r={key:e,participantIdentity:t,keyIndex:n};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(n??0),r),n!==void 0&&(this.latestManuallySetKeyIndex=n),this.emit(Et.SetKey,r,n!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(Et.RatchetRequest,e,t)}}var za;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(za||(za={}));function Wn(){return is()}function Hn(i){return!!i?.worker&&(Fs()||Wn())}function Ci(i){return!!(i?.timestamp||i?.frameId)}function zp(i){const e=[];return i?.timestamp&&e.push(ln.PTF_USER_TIMESTAMP),i?.frameId&&e.push(ln.PTF_FRAME_ID),e}function Kp(i){if(!i||i.length===0)return;const e={};return i.includes(ln.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),i.includes(ln.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function Bs(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var n,r;let s;const a=(n=t.isImmediate)!==null&&n!==void 0?n:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,c=t.maxWait;let d=Date.now(),l=[];function u(){if(c!==void 0){const p=Date.now()-d;if(p+e>=c)return c-p}return e}const h=function(){for(var p=arguments.length,f=new Array(p),g=0;g<p;g++)f[g]=arguments[g];const b=this;return new Promise((k,S)=>{const M=function(){if(s=void 0,d=Date.now(),!a){const T=i.apply(b,f);o&&o(T),l.forEach(C=>{let O=C.resolve;return O(T)}),l=[]}},v=a&&s===void 0;if(s!==void 0&&Y.clearTimeout(s),s=Y.setTimeout(M,u()),v){const T=i.apply(b,f);return o&&o(T),k(T)}l.push({resolve:k,reject:S})})};return h.cancel=function(p){s!==void 0&&Y.clearTimeout(s),l.forEach(f=>{let g=f.reject;return g(p)}),l=[]},h}const js=2e3;function Hi(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}class xd extends w{constructor(e,t,n,r,s){super(e,n,s),this.timeSyncLoop=()=>{var a;if(this.listenerCount(I.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);const o=(a=this.receiver)===null||a===void 0?void 0:a.getSynchronizationSources()[0];if(o){const c=o.timestamp,d=o.rtpTimestamp;d&&this.rtpTimestamp!==d&&(this.emit(I.TimeSyncUpdate,{timestamp:c,rtpTimestamp:d}),this.rtpTimestamp=d)}},this.onTimeSyncListenerAdded=a=>{a===I.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?I.Muted:I.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(I.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),js)),dp()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){const e=this;e.off("newListener",this.onTimeSyncListenerAdded),e.on("newListener",this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}}const gr=100;class qs extends xd{constructor(e,t,n,r,s){super(e,t,w.Kind.Video,n,s),this.elementInfos=[],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=Hi(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Bs(()=>{this.updateDimensions()},gr),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return(n=this.frameMetadataExtractor)===null||n===void 0?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===w.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?en(this._mediaStreamTrack,t):Yt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Gp(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(n=s.codecId,t={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)}),t&&n!==""&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const r=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),s=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!s||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-r<gr){Y.setTimeout(()=>{this.updateVisibility()},gr);return}this.lastVisible=o,this.emit(I.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,c=a.height()*s;o+c>n+r&&(n=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:n,height:r},this.emit(I.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?La():t||(La()>2?2:1)}}class Gp{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var r;const s=n.target,a=n.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=Sn(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var n,r;(r=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=Sn(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var n;this.isPiP=Sn(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??ss(e),this.isPiP=Me()&&Sn(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=ss(this.element),this.isPiP=Sn(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Fa().observe(this.element),Ua().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,r,s;(e=Fa())===null||e===void 0||e.unobserve(this.element),(t=Ua())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.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 Sn(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ss(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function ss(i,e){const t=e||window;let n=i.offsetTop,r=i.offsetLeft;const s=i.offsetWidth,a=i.offsetHeight,o=i,c=o.hidden,d=getComputedStyle(i),l=d.display;for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,r+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&n+a>t.pageYOffset&&r+s>t.pageXOffset&&!c&&l!=="none"}class Jp extends De.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var r,s;const a=n.data,o=a.kind,c=a.data;switch(o){case"error":if(B.error(c.error.message),c.uuid){const u=this.decryptDataRequests.get(c.uuid);if(u?.reject){u.reject(c.error);break}const h=this.encryptDataRequests.get(c.uuid);if(h?.reject){h.reject(c.error);break}}this.emit(bt.EncryptionError,c.error,c.participantIdentity);break;case"initAck":c.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)});break;case"enable":if(c.enabled&&this.keyProvider.getKeys().forEach(u=>{this.postKey(u,!1)}),this.encryptionEnabled!==c.enabled&&c.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(bt.ParticipantEncryptionStatusChanged,c.enabled,this.room.localParticipant),this.encryptionEnabled=c.enabled;else if(c.participantIdentity){const u=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(c.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(c.participantIdentity));this.emit(bt.ParticipantEncryptionStatusChanged,c.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(Et.KeyRatcheted,c.ratchetResult,c.participantIdentity,c.keyIndex);break;case"decryptDataResponse":const d=this.decryptDataRequests.get(c.uuid);d?.resolve&&d.resolve(c);break;case"encryptDataResponse":const l=this.encryptDataRequests.get(c.uuid);l?.resolve&&l.resolve(c);break;case"packetTrailerMetadata":this.handleFrameMetadata(c.trackId,c.rtpTimestamp,c.ssrc,c.metadata);break}},this.onWorkerError=n=>{B.error("e2ee worker encountered an error:",{error:n.error}),this.emit(bt.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Vp())throw new Ns("tried to setup end-to-end encryption on an unsupported browser");if(B.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Ah.getLevel()}};this.worker&&(B.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){B.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?B.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(const s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof qs&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(E.TrackPublished,(n,r)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==G.NONE,r.identity)),e.on(E.ConnectionStateChanged,n=>{n===K.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==G.NONE,r.identity)})})}).on(E.TrackUnsubscribed,(n,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(E.TrackSubscribed,(n,r,s)=>{this.setupE2EEReceiver(n,s.identity,r.trackInfo)}).on(E.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const n=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,n===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(D.LocalSenderCreated,(n,r)=>m(this,void 0,void 0,function*(){this.setupE2EESender(r,n)})),e.localParticipant.on(D.LocalTrackPublished,n=>{if(!mt(n.track)||!qn())return;const r={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:In(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(Et.SetKey,(n,r)=>this.postKey(n,r??!0)).on(Et.RatchetRequest,(n,r)=>this.postRatchetRequest(n,r))}encryptData(e){return m(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new be;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new be;return o.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,r=e.participantIdentity,s=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:n,keyIndex:s,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const r=e.kind==="video"&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?In(n.mimeType):void 0,r)}setupE2EESender(e,t){var n,r,s;if(!rn(e)||!t){t||B.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,mt(e)?(r=(n=e.publishOptions)===null||n===void 0?void 0:n.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,n,r,s){return m(this,void 0,void 0,function*(){if(this.worker){if(is()){const a={kind:"decode",participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(Tn in e&&r){const d={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:s}};this.worker.postMessage(d);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const d=e.createEncodedStreams();e.writableStream=d.writable,a=d.writable,e.readableStream=d.readable,o=d.readable}const c={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:n,isReuse:Tn in e,hasPacketTrailer:s}};this.worker.postMessage(c,[o,a])}e[Tn]=!0}})}handleSender(e,t,n,r){var s;if(!(Tn in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(is()){B.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:Ci(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{B.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Ci(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[Tn]=!0}}}const Qp=300;class Yp{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=Qp;){const r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class $p{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{const n=t.data;if(n.kind==="metadata"){const r=this.extractors.get(n.data.trackId);r&&r.storeMetadata(n.data.rtpTimestamp,n.data.ssrc,n.data.metadata)}},this.onWorkerError=t=>{B.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=e?.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),e.on(E.TrackSubscribed,(t,n,r)=>{t.kind==="video"&&this.setupReceiver(t,n.trackInfo)}).on(E.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(E.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var n,r,s;const a=e.receiver;if(!a)return;if(!(t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){!((n=this.room)===null||n===void 0)&&n.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Hn(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){B.warn("frame metadata transform not supported; skipping extraction");return}const o=new Yp,c=e.mediaStreamID;this.extractors.set(c,o),e.frameMetadataExtractor=o,!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)&&this.setupWorkerReceiver(a,c,!0)}setupPassthroughReceiver(e,t){if(Wn()){"transform"in e&&(e.transform=null);return}if(this.worker&&Hn({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;const r=this.worker;if(!r)return;if(Wn()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}const s=this.workerPipelines.get(e);if(s){const c={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:n}};r.postMessage(c),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){B.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(c){B.warn("failed to create encoded streams",{error:c});return}const o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof qs&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}}const Xp=500,Zp=15e3;class sn{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new sn),this._instance}addFailedConnectionAttempt(e){var t;const n=new URL(e),r=lr(n);if(!r)return;let s=(t=this.failedConnectionAttempts.get(r))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(r,s+1),this.backOffPromises.set(r,Te(Math.min(Xp*Math.pow(2,s),Zp)))}getBackOffPromise(e){const t=new URL(e),n=t&&lr(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&lr(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}sn._instance=null;const fr="default";class ge{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ge),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=ge.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){B.debug("awaiting getUserMedia promise");try{t?yield ge.userMediaPromiseMap.get(t):yield Promise.all(ge.userMediaPromiseMap.values())}catch{B.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Ht()&&n.hasDeviceInUse(t))&&(a.filter(o=>o.kind===t).length===0||a.some(o=>{const c=o.label==="",d=t?o.kind===t:!0;return c&&d}))){const o={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(o);a=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==fr)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===fr);if(!s){B.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==fr&&o.groupId===(n??s.groupId));if(!a){B.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?ge.userMediaPromiseMap.has(e):ge.userMediaPromiseMap.size>0}}ge.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];ge.userMediaPromiseMap=new Map;const Vs=65535,Ld=4294967295;class Ge{static u16(e){return new Ge(e,Vs)}static u32(e){return new Ge(e,Ld)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new Ge(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){const e=this.value;return this.increment(),new Ge(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}}class an{static fromRtpTicks(e){return new an(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Ld);return an.fromRtpTicks(e)}constructor(e,t){this.timestamp=Ge.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new an(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Ot{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new Ot(t,new Date,e)}static startingAtTime(e,t,n){return new Ot(n,e,t)}static rtpStartingNow(e){return Ot.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Ot.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=Ot.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(n),r.isBefore(this.previous)&&(r=this.previous),this.previous=r.clone(),r.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}}function Ws(i){if(i instanceof DataView)return i;if(i instanceof ArrayBuffer)return new DataView(i);if(i instanceof Uint8Array)return new DataView(i.buffer,i.byteOffset,i.byteLength);throw new Error("Error coercing ".concat(i," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Bt;(function(i){i[i.Reserved=0]="Reserved",i[i.TooLarge=1]="TooLarge"})(Bt||(Bt={}));class hn extends Be{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Bt[t]}isReason(e){return this.reason===e}static tooLarge(){return new hn("Value too large to be a valid track handle",Bt.TooLarge)}static reserved(e){return new hn("0x".concat(e.toString(16)," is a reserved value."),Bt.Reserved)}}const em={fromNumber(i){if(i===0)throw hn.reserved(i);if(i>Vs)throw hn.tooLarge();return i}};class tm{constructor(){this.value=0}get(){return this.value+=1,this.value>Vs?null:this.value}reset(){this.value=0}}const Ei={from(i){return{sid:i.sid,pubHandle:i.pubHandle,name:i.name,usesE2ee:i.encryption!==G.NONE}},toProtobuf(i){return new Li({sid:i.sid,pubHandle:i.pubHandle,name:i.name,encryption:i.usesE2ee?G.GCM:G.NONE})}};var _n;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(_n||(_n={}));class nm{constructor(){this.pendingTasks=new Map,this.taskMutex=new fe,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:_n.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=_n.RUNNING,yield e()}finally{t.status=_n.COMPLETED,this.pendingTasks.delete(t.id),n()}})}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())}}const im=["client"];var Ud=class{constructor(){U(this,"listeners",new Map)}on(i,e){let t=this.listeners.get(i);return t||(t=new Set,this.listeners.set(i,t)),t.add(e),{off:()=>{t.delete(e)}}}emit(i,e){const t=this.listeners.get("*");if(t)for(const r of t)r(i,e);const n=this.listeners.get(i);if(n)for(const r of n)r(e)}clear(){this.listeners.clear()}},on=class extends Error{constructor(i,e){super("non-serializable value at ".concat(i," (").concat(e,")")),this.path=i,this.label=e}};const rm=(i,e)=>as(i,e,new Set),as=(i,e,t)=>{if(i===null)return null;switch(typeof i){case"string":case"boolean":return i;case"number":if(!Number.isFinite(i))throw new on(e,am(i));return i;case"object":return sm(i,e,t);default:throw new on(e,typeof i)}},sm=(i,e,t)=>{var n,r;if(t.has(i))throw new on(e,"circular reference");if(Array.isArray(i)){if(i.length!==Object.keys(i).length)throw new on(e,"sparse array or array with non-index properties");t.add(i);const o=i.map((c,d)=>as(c,"".concat(e,"[").concat(d,"]"),t));return t.delete(i),o}const s=Object.getPrototypeOf(i);if(s!==Object.prototype&&s!==null)throw new on(e,(n=(r=i.constructor)===null||r===void 0?void 0:r.name)!==null&&n!==void 0?n:"object");t.add(i);const a={};for(const o of Object.keys(i)){const c=as(i[o],"".concat(e,".").concat(o),t);Object.defineProperty(a,o,{value:c,enumerable:!0,writable:!0,configurable:!0})}return t.delete(i),a},am=i=>Number.isNaN(i)?"NaN":i>0?"Infinity":"-Infinity",os=function(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new Set;if(i===null||typeof i!="object"||e.has(i))return i;if(Array.isArray(i)){e.add(i);const r=i.map(s=>os(s,e));return e.delete(i),r}const t=Object.getPrototypeOf(i);if(t!==Object.prototype&&t!==null)return i;e.add(i);const n={};for(const r of Object.keys(i)){const s=os(i[r],e);Object.defineProperty(n,r,{value:s,enumerable:!0,writable:!0,configurable:!0})}return e.delete(i),n},Mn=Symbol("machina.type"),Ka=20;var om=class{constructor(i){U(this,"id",void 0),U(this,"initialState",void 0),U(this,Mn,"BehavioralFsm"),U(this,"states",void 0),U(this,"emitter",new Ud),U(this,"clients",new WeakMap),U(this,"knownClients",new Set),U(this,"childSubscriptions",[]),U(this,"disposed",!1),U(this,"transitionDepth",0),this.id=i.id,this.initialState=i.initialState,this.states=i.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(i,e){var t;if(this.disposed)return;const n=this.getOrCreateClientMeta(i);for(var r=arguments.length,s=new Array(r>2?r-2:0),a=2;a<r;a++)s[a-2]=arguments[a];n.currentActionArgs=s;const o=(t=this.states[n.state])===null||t===void 0?void 0:t._child;if(o&&o.canHandle(i,e)){try{o.handle(i,e,...s)}finally{n.currentActionArgs=void 0}return}this.handleLocally(i,e,s,n)}canHandle(i,e){var t,n,r;if(this.disposed)return!1;const s=(t=(n=this.clients.get(i))===null||n===void 0?void 0:n.state)!==null&&t!==void 0?t:this.initialState,a=this.states[s];if((r=a?.[e])!==null&&r!==void 0?r:a?.["*"])return!0;const o=a?._child;return o?o.canHandle(i,e):!1}reset(i){this.disposed||this.transition(i,this.initialState)}currentState(i){var e;return(e=this.clients.get(i))===null||e===void 0?void 0:e.state}transition(i,e){if(this.disposed)return;const t=this.getOrCreateClientMeta(i),n=t.state;if(e!==n){if(!Object.hasOwn(this.states,e)){this.emitter.emit("invalidstate",{stateName:e,client:i});return}if(this.transitionDepth++,this.transitionDepth>Ka)throw this.transitionDepth=0,new Error("Max transition depth (".concat(Ka,') exceeded in FSM "').concat(this.id,'". Likely an infinite _onEnter → transition loop.'));try{const r=this.states[n],s=this.states[e];if(r!=null&&r._onExit&&typeof r._onExit=="function"){const d=this.buildHandlerArgs(i,"",t);r._onExit(d)}t.state=e;const a={fromState:n,toState:e,client:i};this.emitter.emit("transitioning",a);let o;if(s!=null&&s._onEnter&&typeof s._onEnter=="function"){const d=this.buildHandlerArgs(i,"",t);o=s._onEnter(d)}this.emitter.emit("transitioned",a);const c=s?._child;c&&c.reset(i),this.processQueue(i,t),typeof o=="string"&&t.state===e&&this.transition(i,o)}finally{this.transitionDepth--}}}compositeState(i){var e;const t=this.clients.get(i);if(!t)return"";const n=(e=this.states[t.state])===null||e===void 0?void 0:e._child;if(n){const r=n.compositeState(i);if(r)return"".concat(t.state,".").concat(r)}return t.state}rehydrate(i,e){if(this.disposed)return;if(typeof e=="string"){this.rehydrateCompositePath(i,e);return}const t=this.planSnapshotWrites(i,e);for(const n of t)n()}dehydrate(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;const t=this.clients.get(i);if(!t)return;const n={state:t.state,deferred:t.deferredQueue.map(s=>this.snapshotDeferredInput(s))},r=this.collectChildSnapshots(i,t.state,e);return r&&(n.children=r),n}planSnapshotWrites(i,e){if(this.disposed)return[];const t=e.state,n=e.deferred,r=e.children;if(!Object.hasOwn(this.states,t))throw new Error('rehydrate: unknown state "'.concat(t,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));const s=[];if(r)for(const c of Object.keys(r)){var a;if(!Object.hasOwn(this.states,c))throw new Error('rehydrate: unknown state "'.concat(c,'" in FSM "').concat(this.id,'" referenced by snapshot.children.'));const d=(a=this.states[c])===null||a===void 0?void 0:a._child;if(!d)throw new Error('rehydrate: state "'.concat(c,'" in FSM "').concat(this.id,'" has no _child, but the snapshot has a children["').concat(c,'"] entry.'));s.push(...d.planRehydrate(i,r[c]))}const o=n.map(c=>Yl({inputName:c.inputName,args:os(c.args)},c.untilState!==void 0?{untilState:c.untilState}:{}));return s.push(()=>{this.clients.has(i)||this.knownClients.add(new WeakRef(i)),this.clients.set(i,{state:t,deferredQueue:o})}),s}rehydrateCompositePath(i,e){const t=e.split("."),n=Zl(t),r=n[0],s=Or(n).slice(1);if(!Object.hasOwn(this.states,r))throw new Error('rehydrate: unknown state "'.concat(r,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));if(s.length>0){var a;const o=s.join("."),c=(a=this.states[r])===null||a===void 0?void 0:a._child;if(!c)throw new Error('rehydrate: state "'.concat(r,'" in FSM "').concat(this.id,'" has no _child, but composite path "').concat(e,'" requires one.'));c.rehydrate(i,o)}this.clients.has(i)||this.knownClients.add(new WeakRef(i)),this.clients.set(i,{state:r,deferredQueue:[]})}collectChildSnapshots(i,e,t){const n=new Map;for(const a of Object.keys(this.states)){var r;const o=(r=this.states[a])===null||r===void 0?void 0:r._child;if(!o)continue;const c=n.get(o.instance);c?c.stateNames.push(a):n.set(o.instance,{childLink:o,stateNames:[a]})}let s;for(const a of n.values()){const o=a.childLink,c=a.stateNames,d=t&&c.includes(e);if(o.instance[Mn]==="Fsm"&&!d)continue;const l=o.dehydrate(i,d);if(l){s??(s={});for(const u of c)s[u]=l}}return s}snapshotDeferredInput(i){let e;try{e=rm(i.args,"args")}catch(n){if(!(n instanceof on))throw n;const r=i.untilState?' (until "'.concat(i.untilState,'")'):"";throw new Error('dehydrate: deferred input "'.concat(i.inputName,'"').concat(r,' in FSM "').concat(this.id,'" has a non-serializable value at ').concat(n.path," (").concat(n.label,")"))}const t={inputName:i.inputName,args:e};return i.untilState!==void 0&&(t.untilState=i.untilState),t}on(i,e){return this.disposed?{off(){}}:this.emitter.on(i,e)}emit(i,e){this.disposed||this.emitter.emit(i,e)}dispose(i){this.disposed=!0;for(const t of this.childSubscriptions)t.off();if(!(i!=null&&i.preserveChildren)){const t=new Set;for(const n of Object.keys(this.states)){var e;const r=(e=this.states[n])===null||e===void 0?void 0:e._child;r&&!t.has(r.instance)&&(t.add(r.instance),r.dispose())}}this.emitter.clear()}wrapChildLinks(){for(const i of Object.keys(this.states)){const e=this.states[i],t=e?._child;if(t){if(typeof t!="object")throw new Error('State "'.concat(i,'"._child: expected an Fsm or BehavioralFsm instance, got ').concat(String(t)));if(!(Mn in t))throw new Error('State "'.concat(i,'"._child: expected an Fsm or BehavioralFsm instance, got a plain object'));e._child=cm(t)}}}setupChildSubscriptions(){const i=new Set;for(const t of Object.keys(this.states)){var e;const n=(e=this.states[t])===null||e===void 0?void 0:e._child;if(!n||i.has(n.instance))continue;i.add(n.instance);const r=n.onAny((s,a)=>{if(s==="nohandler"){var o;const l=a;if(l.client!==void 0)this.bubbleNohandler(l.client,n,l.inputName,(o=l.args)!==null&&o!==void 0?o:[]);else for(const u of this.knownClients){var c;const h=u.deref();if(h===void 0){this.knownClients.delete(u);continue}this.bubbleNohandler(h,n,l.inputName,(c=l.args)!==null&&c!==void 0?c:[])}return}const d=a;if(d&&typeof d=="object"&&"client"in d)this.isChildActiveForClient(d.client,n)&&this.emitter.emit(s,a);else for(const l of this.knownClients){const u=l.deref();if(!u){this.knownClients.delete(l);continue}if(this.isChildActiveForClient(u,n)){this.emitter.emit(s,a);break}}});this.childSubscriptions.push(r)}}bubbleNohandler(i,e,t,n){if(!this.isChildActiveForClient(i,e))return;const r=this.clients.get(i);r.currentActionArgs=n,this.handleLocally(i,t,n,r)}isChildActiveForClient(i,e){var t;const n=this.clients.get(i);return n?((t=this.states[n.state])===null||t===void 0||(t=t._child)===null||t===void 0?void 0:t.instance)===e.instance:!1}handleLocally(i,e,t,n){var r;const s=this.states[n.state],a=(r=s?.[e])!==null&&r!==void 0?r:s?.["*"];if(!a){this.emitter.emit("nohandler",{inputName:e,args:t,client:i}),n.currentActionArgs=void 0;return}try{this.emitter.emit("handling",{inputName:e,client:i});const o=this.buildHandlerArgs(i,e,n);let c;typeof a=="string"?c=a:typeof a=="function"&&(c=a(o,...t)),this.emitter.emit("handled",{inputName:e,client:i}),typeof c=="string"&&this.transition(i,c)}finally{n.currentActionArgs=void 0}}getOrCreateClientMeta(i){let e=this.clients.get(i);return e||(e={state:void 0,deferredQueue:[]},this.clients.set(i,e),this.knownClients.add(new WeakRef(i)),this.transition(i,this.initialState),e)}buildHandlerArgs(i,e,t){return{ctx:i,inputName:e,defer:n=>{if(!t.currentActionArgs)return;const r={inputName:e,args:[...t.currentActionArgs],untilState:n?.until};t.deferredQueue.push(r),this.emitter.emit("deferred",{inputName:e,client:i})},emit:(n,r)=>{this.emitter.emit(n,r)}}}processQueue(i,e){const t=[],n=[];for(const r of e.deferredQueue)r.untilState===void 0||r.untilState===e.state?t.push(r):n.push(r);e.deferredQueue=n;for(const r of t)this.handle(i,r.inputName,...r.args)}};function cm(i){if(!i||typeof i!="object")throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got ".concat(String(i)));const e=i[Mn];if(e==="BehavioralFsm")return{instance:i,canHandle(t,n){return i.canHandle(t,n)},handle(t,n){for(var r=arguments.length,s=new Array(r>2?r-2:0),a=2;a<r;a++)s[a-2]=arguments[a];i.handle(t,n,...s)},reset(t){i.transition(t,i.initialState)},onAny(t){return i.on("*",t)},compositeState(t){return i.compositeState(t)},rehydrate(t,n){i.rehydrate(t,n)},dehydrate(t,n){return i.dehydrate(t,n)},planRehydrate(t,n){return i.planSnapshotWrites(t,n)},dispose(){i.dispose()}};if(e==="Fsm")return{instance:i,canHandle(t,n){return i.canHandle(n)},handle(t,n){for(var r=arguments.length,s=new Array(r>2?r-2:0),a=2;a<r;a++)s[a-2]=arguments[a];i.handle(n,...s)},reset(t){i.reset()},onAny(t){return i.on("*",t)},compositeState(t){return i.compositeState()},rehydrate(t,n){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dehydrate(t,n){throw new Error("dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.")},planRehydrate(t,n){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dispose(){i.dispose()}};throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ".concat(String(e??"undefined")))}var dm=class{constructor(i){var e;U(this,"id",void 0),U(this,"initialState",void 0),U(this,Mn,"Fsm"),U(this,"states",void 0),U(this,"bfsm",void 0),U(this,"context",void 0),U(this,"emitter",new Ud),U(this,"disposed",!1),this.id=i.id,this.initialState=i.initialState,this.context=(e=i.context)!==null&&e!==void 0?e:{},this.bfsm=new om(i),this.states=i.states,this.bfsm.on("*",(t,n)=>{if(n&&typeof n=="object"&&"client"in n){n.client;const r=$l(n,im);this.emitter.emit(t,r)}else this.emitter.emit(t,n)}),this.bfsm.transition(this.context,i.initialState)}handle(i){if(!this.disposed){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];this.bfsm.handle(this.context,i,...t)}}canHandle(i){return this.disposed?!1:this.bfsm.canHandle(this.context,i)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(i){this.disposed||this.bfsm.transition(this.context,i)}compositeState(){return this.bfsm.compositeState(this.context)}on(i,e){return this.disposed?{off(){}}:this.emitter.on(i,e)}emit(i,e){this.disposed||this.bfsm.emit(i,e)}dispose(i){this.disposed=!0,this.bfsm.dispose(i),this.emitter.clear()}};function lm(i){return new dm(i)}function Fd(i,e){return e.attemptId===i.attemptId}const Ga=(i,e)=>{let t=i.ctx;if(Fd(t,e))return"connected"},vr=i=>{let e=i.ctx;return e.attemptId+=1,e.lastError=void 0,"connecting"},yr=i=>{let e=i.ctx;return e.attemptId+=1,e.lastError=void 0,"reconnecting"},wn=(i,e)=>{let t=i.ctx;return t.closeReason=e.reason,"disconnecting"},um={new:{connect:vr,close:wn},connecting:{connectComplete:Ga,connectFailed:(i,e)=>{let t=i.ctx;return t.lastError=e.error,"closed"},close:wn},connected:{reconnect:yr,transportFailed:(i,e)=>{let t=i.ctx;if(Fd(t,e))return t.lastError=e.reason,"offline"},close:wn},offline:{connect:vr,reconnect:yr,close:wn},reconnecting:{reconnectComplete:Ga,reconnectFailed:(i,e)=>{let t=i.ctx;return t.lastError=e.error,e.recoverable?"offline":"closed"},close:wn},disconnecting:{closeComplete:"closed"},closed:{connect:vr,reconnect:yr}};function hm(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"new";return lm({id:"signal",initialState:i,context:{attemptId:0},states:um})}class pm{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,r;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;const a=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=o.closeCode,d=o.reason;return s.close(c,d)};this.opened=new Ee((o,c)=>{const d=()=>{c(N.websocket("Encountered websocket error during connection establishment"))};s.onopen=()=>{o({readable:new ReadableStream({start(l){s.onmessage=u=>{let h=u.data;return l.enqueue(h)},s.onerror=u=>l.error(N.websocket(u instanceof Error?"".concat(u.name,": ").concat(u.message):"Encountered unknown websocket error: ".concat(String(u)))),s.onclose=u=>{u.wasClean?l.close():l.error(N.websocket("WS closed unexpectedly with code ".concat(u.code)))}},cancel:a}),writable:new WritableStream({write(l){s.send(l)},abort(){s.close()},close:a}),protocol:s.protocol,extensions:s.extensions}),s.removeEventListener("error",d)},s.addEventListener("error",d)}),this.closed=new Ee((o,c)=>{const d=()=>m(this,void 0,void 0,function*(){const l=new Ee(h=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",p=>{h(p)},{once:!0})}),u=yield Ee.race([Te(250),l]);u?o(u):c(N.websocket("Encountered unspecified websocket error without a timely close event"))});s.addEventListener("close",l=>{let u=l.code,h=l.reason;o({closeCode:u,reason:h}),s.removeEventListener("error",d)}),s.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>s.close()),this.close=a}}const mm=["syncState","trickle","offer","answer","simulate","leave"];function gm(i){return i instanceof N?i.reason!==Q.LeaveRequest&&i.reason!==Q.NotAllowed:!0}function fm(i){const e=mm.indexOf(i.case)>=0;return B.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var we;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(we||(we={}));function vm(i){switch(i){case"connected":return we.CONNECTED;case"connecting":return we.CONNECTING;case"reconnecting":return we.RECONNECTING;case"disconnecting":return we.DISCONNECTING;default:return we.DISCONNECTED}}const ym=250,bm=5e3;class Hs{get currentState(){return vm(this.lifecycleState)}get isDisconnected(){const e=this.currentState;return e===we.DISCONNECTING||e===we.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){const t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return m(this,void 0,void 0,function*(){this.log.debug("waiting for an in-flight close to settle before establishing a session"),(yield this.closingLock.lock())()})}get isEstablishingConnection(){return this.lifecycleState==="connecting"||this.lifecycleState==="reconnecting"}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;this.rtt=0,this.log=B,this._requestId=0,this.useV0SignalPath=!1,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.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=ve((n=t.loggerName)!==null&&n!==void 0?n:ae.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new nm,this.queuedRequests=[],this.closingLock=new fe,this.connectionLock=new fe,this.machine=hm(),this.machine.on("transitioned",r=>{let s=r.fromState,a=r.toState;this.log.debug("signal lifecycle: ".concat(s," -> ").concat(a))}),this.machine.on("nohandler",r=>{let s=r.inputName;this.log.debug("ignoring signal lifecycle input ".concat(s," in state ").concat(this.lifecycleState))}),this.machine}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,n,r){return m(this,arguments,void 0,function(s,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){if(d.lifecycleState==="disconnecting"&&(yield d.settleInFlightClose()),!d.sendLifecycleInput({type:"connect"}))throw N.internal("cannot establish a signal session from '".concat(d.lifecycleState,"', close the current one first"));d.options=o;try{return yield d.connect(s,a,o,c,l,u)}catch(h){throw d.sendLifecycleInput({type:"connectFailed",error:h}),h}})()})}reconnect(e,t,n,r){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}if(this.lifecycleState==="disconnecting"&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:"reconnect"}))throw N.internal("cannot resume the signal session from '".concat(this.lifecycleState,"'"));this.clearPingInterval();try{return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(s){throw this.sendLifecycleInput({type:"reconnectFailed",error:s,recoverable:gm(s)}),s}})}connect(e,t,n,r){return m(this,arguments,void 0,function(s,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){const h=yield d.connectionLock.lock();d.connectOptions=o,d.useV0SignalPath=l;const p=Ep(o.clientInfoCapabilities),f=l?km(a,p,o):yield Tm(a,p,o,u),g=xp(s,f,l).toString(),b=Up(g).toString();return new Promise((k,S)=>m(d,void 0,void 0,function*(){var M,v;try{let T=!1;const C=q=>m(this,void 0,void 0,function*(){if(T)return;T=!0;const X=q instanceof Event?q.currentTarget:q,he=Fp(X,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(he)).catch(it=>{this.log.error(it),this.close()}):this.close(),O(),S(q instanceof N?q:N.cancelled(he))});c?.addEventListener("abort",C);const O=()=>{clearTimeout(L),c?.removeEventListener("abort",C)},L=setTimeout(()=>{C(N.timeout("room connection has timed out (signal)"))},o.websocketTimeout),A=new URL(g);if(A.searchParams.has("access_token")&&A.searchParams.set("access_token","<redacted>"),this.ws){const q=performance.now();yield this.teardownTransport("replaced by a new connection attempt"),this.log.debug("closed previous ws connection in ".concat(performance.now()-q,"ms"))}const j=this.attemptId;this.log.info("signal connecting to ".concat(A),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new pm(g);let F=!1;this.ws.opened.catch(()=>{F=!0});try{this.ws.closed.then(pe=>{this.isEstablishingConnection&&!F&&S(N.internal("Websocket got closed during a (re)connection attempt: ".concat(pe.reason))),this.log.debug("websocket closed",{reason:pe.reason,code:pe.closeCode,attemptId:j,state:this.lifecycleState}),this.handleOnClose(pe.reason||(pe.closeCode===1e3?"server closed the signal connection":"Unexpected WS error"),j)}).catch(pe=>{this.isEstablishingConnection&&!F&&S(N.internal("Websocket error during a (re)connection attempt: ".concat(pe)))});const q=yield this.ws.opened.catch(pe=>m(this,void 0,void 0,function*(){if(this.lifecycleState!=="connected"){clearTimeout(L);const _t=yield this.handleConnectionError(pe,b);S(_t);return}this.handleWSError(pe),S(pe)}));if(clearTimeout(L),!q)return;const X=q.readable.getReader();this.streamWriter=q.writable.getWriter();let he,it;try{he=yield Promise.race([X.read(),new Promise((pe,_t)=>{it=setTimeout(()=>{_t(N.timeout("signal connection timed out while waiting for the first message"))},bm)})])}catch(pe){X.releaseLock(),S(pe),this.close();return}finally{clearTimeout(it)}if(X.releaseLock(),!he.value)throw N.internal("no message received as first message");const Ae=Va(he.value),ft=this.validateFirstMessage(Ae,(M=o.reconnect)!==null&&M!==void 0?M:!1);if(!ft.isValid){S(ft.error);return}((v=Ae.message)===null||v===void 0?void 0:v.case)==="join"&&(this.pingTimeoutDuration=Ae.message.value.pingTimeout,this.pingIntervalDuration=Ae.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(Ae.message.value));const fn=ft.shouldProcessFirstMessage?Ae:void 0;this.handleSignalConnected(q,L,j,fn),k(ft.response)}catch(q){S(q)}finally{O()}}finally{h()}}))})()})}startReadingLoop(e,t){return m(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Te(this.signalLatency));try{const n=yield e.read(),r=n.done,s=n.value;if(r)break;const a=Va(s);this.handleSignalResponse(a)}catch(n){this.log.error("error reading from signal stream",{error:n}),yield this.close(!1,"error in reading loop");break}}})}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){const r=t&&e.sendLifecycleInput({type:"close",reason:n}),s=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{r&&e.sendLifecycleInput({type:"closeComplete"}),s()}})()})}teardownTransport(e){return m(this,void 0,void 0,function*(){try{if(this.clearPingInterval(),this.ws){this.ws.close({closeCode:1e3,reason:e});const t=this.ws.closed;this.ws=void 0,this.streamWriter=void 0,yield Promise.race([t,Te(ym)])}}catch(t){this.log.debug("websocket error while closing",{error:t})}})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Nt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Nt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Bi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new ji({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new _s({requestId:o,metadata:n,name:r,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Nc({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Uc({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ne.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new jc({timestamp:ne.parse(Date.now()),rtt:ne.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Is({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Vi({reason:Ne.CLIENT_INITIATED,action:Xt.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new Cs({pubHandle:e,name:t,encryption:n?G.GCM:G.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new Rs({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Mc({updates:[new Dc({trackSid:e,subscribe:t})]})})}sendRequest(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){const s=!r&&!fm(t),a=n.lifecycleState==="reconnecting"||n.queuedRequests.length>0;if(s&&a){n.queuedRequests.push(()=>m(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}r||(yield n.requestQueue.flush()),n.signalLatency&&(yield Te(n.signalLatency));const o=t.case==="leave"&&!!n.streamWriter;if(n.isDisconnected&&!o){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t?.case));return}const c=new Yu({message:t});try{n.useJSON?yield n.streamWriter.write(c.toJsonString()):yield n.streamWriter.write(c.toBinary().buffer)}catch(d){n.log.error("error sending signal message",{error:d})}})()})}handleSignalResponse(e){var t,n;const r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){const a=Ja(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){const a=Ja(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=r.value.speakers)!==null&&n!==void 0?n:[]):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)):r.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(r.value):r.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(r.value):r.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(r.value):r.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(r.value):this.log.debug("unsupported message",{msgCase:r.case}));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.attemptId;return(function*(){const s=n.onClose;if(!n.sendLifecycleInput({type:"transportFailed",attemptId:r,reason:t})){n.log.debug("ignoring transport close in state ".concat(n.lifecycleState),{reason:t,attemptId:r,currentAttemptId:n.attemptId});return}yield n.teardownTransport(t),n.log.info("websocket connection closed: ".concat(t),{reason:t}),s&&s(t)})()})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=Y.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString())),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Y.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set");return}this.log.debug("start ping interval"),this.pingInterval=Y.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&Y.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n,r){if(clearTimeout(t),!this.sendLifecycleInput(this.lifecycleState==="reconnecting"?{type:"reconnectComplete",attemptId:n}:{type:"connectComplete",attemptId:n})){this.log.debug("discarding a connection whose attempt no longer owns the session",{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState});return}this.log.info("signal connected"),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),r)}validateFirstMessage(e,t){var n,r,s,a,o;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.lifecycleState==="reconnecting"&&((r=e.message)===null||r===void 0?void 0:r.case)!=="leave"?((s=e.message)===null||s===void 0?void 0:s.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:N.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:N.internal("Unexpected first message")}:{isValid:!1,error:N.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return m(this,void 0,void 0,function*(){try{const n=yield fetch(t);switch(n.status){case 404:const r=yield n.text();return r.includes("requested room does not exist")?N.notAllowed(r,n.status):N.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield n.text();return N.notAllowed(s,n.status);default:break}return e instanceof N?e:N.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof N?n:N.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}}function Ja(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Nt(i,e){return new Pt({sdp:i.sdp,type:i.type,id:e})}function km(i,e,t){var n;const r=new URLSearchParams;return r.set("access_token",i),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",Qe()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),r.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&r.set("network",navigator.connection.type),r}function Tm(i,e,t,n){return m(this,void 0,void 0,function*(){const r=new URLSearchParams;r.set("access_token",i);const s=new Eh({clientInfo:e,connectionSettings:new qc({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:n});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const a=s.toBinary();let o,c;if(Ct()){const u=new CompressionStream("gzip"),h=u.writable.getWriter();h.write(new Uint8Array(a)),h.close();const p=[],f=u.readable.getReader();for(;;){const S=yield f.read(),M=S.done,v=S.value;if(M)break;p.push(v)}const g=p.reduce((S,M)=>S+M.length,0),b=new Uint8Array(g);let k=0;for(const S of p)b.set(S,k),k+=S.length;o=b,c=Ur.GZIP}else o=a,c=Ur.NONE;const d=new Rh({joinRequest:o,compression:c}).toBinary(),l=u=>{const h=Array.from(u,p=>String.fromCodePoint(p)).join("");return btoa(h)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r})}class Sm{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const n of this._map.entries()){var t=x(n,2);const r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const n of this._map.entries()){var t=x(n,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const s of n.entries()){var r=x(s,2);const a=r[0],o=r[1];t.push(e(o,a,n))}return t}asValueMap(){const e=new Map;for(const n of this._map.entries()){var t=x(n,2);const r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}}var je={},Qa={},br={exports:{}},Ya;function zs(){if(Ya)return br.exports;Ya=1;var i=br.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.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(e){return e.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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.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(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{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(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),br.exports}var $a;function wm(){return $a||($a=1,(function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},n=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},r=zs(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],p=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var f=0;f<(r[h]||[]).length;f+=1){var g=r[h][f];if(g.reg.test(p))return n(g,l,p)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},i.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(Qa)),Qa}var kr,Xa;function Cm(){if(Xa)return kr;Xa=1;var i=zs(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.name]);return t.apply(null,l)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return kr=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||r,d=o.innerOrder||s,l=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(n(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){l.push(n(u,h,p))})})}),a.media.forEach(function(u){l.push(n("m",i.m[0],u)),d.forEach(function(h){i[h].forEach(function(p){p.name in u&&u[p.name]!=null?l.push(n(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(f){l.push(n(h,p,f))})})})}),l.join(`\r
38
+ `)+`\r
39
+ `},kr}var Za;function Em(){if(Za)return je;Za=1;var i=wm(),e=Cm(),t=zs();return je.grammar=t,je.write=e,je.parse=i.parse,je.parseParams=i.parseParams,je.parseFmtpConfig=i.parseFmtpConfig,je.parsePayloads=i.parsePayloads,je.parseRemoteCandidates=i.parseRemoteCandidates,je.parseImageAttributes=i.parseImageAttributes,je.parseSimulcastStreamList=i.parseSimulcastStreamList,je}var Ue=Em();const Rm=.9,Pm=1e3,Im=20;function _m(i,e,t,n){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;var s,a,o;if(!(!((s=i.msid)===null||s===void 0)&&s.includes(e)))return;const c=(o=(a=i.rtp.find(h=>h.codec.toUpperCase()===t.toUpperCase()))===null||a===void 0?void 0:a.payload)!==null&&o!==void 0?o:0;if(c===0)return 0;const d=Math.round(n*Rm),l=r?d:Math.min(d,Pm),u=i.fmtp.find(h=>h.payload===c);return u?u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l)):i.fmtp.push({payload:c,config:"x-google-start-bitrate=".concat(l)}),c}const kt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class eo extends De.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n;super(),this.log=B,this.iceLog=B,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Bs(r=>m(this,void 0,void 0,function*(){this.emit(kt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),Im),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,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.loggerOptions=t,this.log=ve((n=t.loggerName)!==null&&n!==void 0?n:ae.PCTransport,()=>this.logContext),this.iceLog=ve(ae.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new fe}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:t.candidate.candidate}),(n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;this.iceLog.debug("ICE candidate error",{event:t}),(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;this.log.debug("data channel opened by peer",{label:t.channel.label,id:t.channel.id}),(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return m(this,void 0,void 0,function*(){var n,r;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let s;if(e.type==="offer"){let a=xm(e),o=a.stereoMids,c=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=c}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const c=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const d=Ue.parse((n=c.sdp)!==null&&n!==void 0?n:"");d.media.forEach(l=>{Yn(l)}),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(c,Ue.write(d))}const a=Ue.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(c=>{const d=Dn(c.mid);c.type==="audio"&&this.trackBitrates.some(l=>{if(!l.transceiver||d!=l.transceiver.mid)return!1;let u=0;if(c.rtp.some(p=>p.codec.toUpperCase()===l.codec.toUpperCase()?(u=p.payload,!0):!1),u===0)return!0;let h=!1;for(const p of c.fmtp)if(p.payload===u){p.config=p.config.split(";").filter(f=>!f.includes("maxaveragebitrate")).join(";"),l.maxbr>0&&(p.config+=";maxaveragebitrate=".concat(l.maxbr*1e3)),h=!0;break}return h||l.maxbr>0&&c.fmtp.push({payload:u,config:"maxaveragebitrate=".concat(l.maxbr*1e3)}),!0})});const o=this.getPlaceholderMids();o.size>0&&io(a.media,c=>o.has(Dn(c.mid))),s=Ue.write(a)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(kt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(kt.NegotiationComplete),e.sdp&&Ue.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(kt.RTPVideoPayloadTypes,a.rtp)})),!0})}createInitialOffer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer");return}const n=this.latestOfferId+1;this.latestOfferId=n;const r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};const s=Ue.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{Yn(a)}),r.sdp=Ue.write(s),{offer:r,offerId:n}}finally{t()}})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const c=this._pc.remoteDescription;if(e?.iceRestart&&c)yield this._pc.setRemoteDescription(c);else{if(e?.iceRestart)throw new wt("ICE restart requested without a remote description, peer connection must be recreated");this.renegotiate=!0,this.log.debug("requesting renegotiation");return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection");return}this.log.debug("starting to negotiate");const r=this.latestOfferId+1;this.latestOfferId=r;const s=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:s.sdp});const a=Ue.parse((t=s.sdp)!==null&&t!==void 0?t:"");a.media.forEach(c=>{Yn(c),c.type==="audio"?no(c,["all"],[]):c.type==="video"&&this.trackBitrates.some(d=>{if(!d.cid)return!1;const l=_m(c,d.cid,d.codec,d.maxbr,d.isScreenShare);return l===void 0?!1:(l>0&&Ze(d.codec)&&!Ht()&&(this.ddExtID=Mm(c,a,this.ddExtID)),!0)})});const o=this.getPlaceholderMids();if(o.size>0&&io(a.media,c=>o.has(Dn(c.mid))),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:r});return}yield this.setMungedSDP(s,Ue.write(a)),this.onOffer(s,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Ue.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(r=>{Yn(r),r.type==="audio"&&no(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ue.write(n)),t})}getPlaceholderMids(){var e,t;return Nm((t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ee("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ee("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){var e;return(e=this._pc)===null||e===void 0?void 0:e.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,r=new Map;if((yield this._pc.getStats()).forEach(a=>{switch(a.type){case"transport":t=a.selectedCandidatePairId;break;case"candidate-pair":t===""&&a.selected&&(t=a.id),n.set(a.id,a);break;case"remote-candidate":r.set(a.id,"".concat(a.address,":").concat(a.port));break}}),t==="")return;const s=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return r.get(s)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){var r,s;const a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description")),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(o){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:o,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{n?yield(r=this._pc)===null||r===void 0?void 0:r.setRemoteDescription(e):yield(s=this._pc)===null||s===void 0?void 0:s.setLocalDescription(e)}catch(o){let c="unknown error";o instanceof Error?c=o.message:typeof o=="string"&&(c=o);const d={error:c,sdp:e.sdp};throw t&&t!==a&&(d.mungedSdp=t),!n&&this.pc.remoteDescription&&(d.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:d}),new wt(c)}})}}function Mm(i,e,t){var n,r;const s=Dm(e,t);return s===void 0?t:(!((n=i.ext)===null||n===void 0)&&n.some(a=>a.uri===tn)||((r=i.ext)!==null&&r!==void 0||(i.ext=[]),i.ext.push({value:s,uri:tn})),s)}function Dm(i,e){const t=Am(i,tn);return t!==void 0?to(i,t,tn)?void 0:t:e!==0&&!to(i,e,tn)?e:Om(i)}function Am(i,e){var t;for(const n of i.media){const r=(t=n.ext)===null||t===void 0?void 0:t.find(s=>s.uri===e);if(r)return r.value}}function to(i,e,t){return i.media.some(n=>{var r;return(r=n.ext)===null||r===void 0?void 0:r.some(s=>s.value===e&&s.uri!==t)})}function Om(i){let e=0;return i.media.forEach(t=>{var n;(n=t.ext)===null||n===void 0||n.forEach(r=>{r.value>e&&(e=r.value)})}),e+1===15?16:e+1}function Bd(i,e){return i.split(";").some(t=>t.trim()===e)}function no(i,e,t){const n=Dn(i.mid);let r=0;i.rtp.some(s=>s.codec.toLowerCase()==="opus"?(r=s.payload,!0):!1),r>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&i.rtcpFb.push({payload:r,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(s=>s.payload===r?(Bd(s.config,"stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Nm(i){const e=new Set;for(const t of i)t.mid&&!t.sender.track&&e.add(t.mid);return e}function io(i,e){var t,n;const r=new Map,s=new Set;for(const a of i){const o=e(a);for(const c of(t=a.fmtp)!==null&&t!==void 0?t:[])o?r.has(c.payload)||r.set(c.payload,c.config):(r.set(c.payload,c.config),s.add(c.payload))}if(r.size!==0){for(const a of i)if(e(a))for(const o of(n=a.fmtp)!==null&&n!==void 0?n:[]){const c=r.get(o.payload);c!==void 0&&o.config!==c&&(o.config=c)}}}function xm(i){var e;const t=[],n=[],r=Ue.parse((e=i.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;const c=Dn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec.toLowerCase()==="opus"?(s=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===s&&d.type==="nack")&&n.push(c),a.fmtp.some(d=>d.payload===s?(Bd(d.config,"sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:n}}function Yn(i){if(i.connection){const e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function Dn(i){return typeof i=="number"?i.toFixed(0):i}const cs="vp8",Lm={audioPreset:Yr.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:xs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:cs,backupCodec:!0,preConnectBuffer:!1},jd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},qd={deviceId:{ideal:"default"},resolution:jn.h720.resolution},Um={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Nh,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Ks={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Z;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(Z||(Z={}));class ro{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var r;this.peerConnectionTimeout=Ks.peerConnectionTimeout,this.log=B,this.iceLog=B,this.updateState=()=>{var s,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=Z.CONNECTED:c.some(d=>d==="failed")?this.state=Z.FAILED:c.some(d=>d==="connecting")?this.state=Z.CONNECTING:c.every(d=>d==="closed")?this.state=Z.CLOSED:c.some(d=>d==="closed")?this.state=Z.CLOSING:c.every(d=>d==="new")&&(this.state=Z.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(Z[o]," to ").concat(Z[this.state])),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.loggerOptions=t,this.log=ve((r=t.loggerName)!==null&&r!==void 0?r:ae.PCManager,()=>this.logContext),this.iceLog=ve(ae.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new eo(n,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new eo(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,He.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,He.PUBLISHER)},this.publisher.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=(s,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,s,a)},this.state=Z.NEW,this.connectionLock=new fe,this.remoteOfferLock=new fe}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(r){this.log.warn("could not removeTrack",{error:r})}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.iceLog.warn("triggering ICE restart"),this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===He.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return m(this,void 0,void 0,function*(){var n,r,s;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()});const a=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,t))?yield(s=this.subscriber)===null||s===void 0?void 0:s.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var n;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;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.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Ee((t,n)=>{const r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let s=!1;const a=()=>{s||(s=!0,clearTimeout(d),this.publisher.off(kt.OfferAnswered,o),e.signal.removeEventListener("abort",c))},o=l=>{l>r&&(a(),t())},c=()=>{a(),n(new wt("negotiation aborted"))},d=setTimeout(()=>{a(),n(new wt("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",c),this.publisher.on(kt.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?n(l):n(new Error(String(l)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(n=>n.receiver===e)?.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===He.PUBLISHER?this.publisher.getConnectedAddress():e===He.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((o,c)=>m(s,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection"),Y.clearTimeout(l),c(N.cancelled("room connection has been cancelled"))};r?.signal.aborted&&d(),r?.signal.addEventListener("abort",d);const l=Y.setTimeout(()=>{r?.signal.removeEventListener("abort",d),c(N.internal("could not establish pc connection"))},a);for(;this.state!==Z.CONNECTED;)if(yield Te(50),r?.signal.aborted){c(N.cancelled("room connection has been cancelled"));return}Y.clearTimeout(l),r?.signal.removeEventListener("abort",d),o()}))})()})}}class Vd{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new fe,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return m(this,void 0,void 0,function*(){const e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return m(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new ee("engine closed");const e=this.getChannel();if(!e)throw new ee("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new Ee((n,r)=>{const s=()=>{c(),n()},a=()=>{c(),r(new ee("DataChannel ".concat(this.kind," closed while draining the buffer")))},o=()=>{c(),r(new ee("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},c=()=>{e.removeEventListener("bufferedamountlow",s),e.removeEventListener("close",a),t.removeEventListener("abort",o)};if(t.aborted){o();return}e.addEventListener("bufferedamountlow",s),e.addEventListener("close",a),t.addEventListener("abort",o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,(e=this.onBufferStatusChanged)===null||e===void 0||e.call(this,n))}}class so extends Vd{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return m(this,void 0,void 0,function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100===0&&B.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount));return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(n instanceof TypeError)B.error(n);else throw n}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=Y.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(Y.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class ao{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Fm extends Vd{constructor(e){super(e),this.messageBuffer=new ao,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return m(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}const n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(r){if(this.isEngineClosed())throw r;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus()}})}replay(e){return m(this,void 0,void 0,function*(){const t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);const n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let r=this.messageBuffer.getUnsent();r.length>0;r=this.messageBuffer.getUnsent())for(const s of r)yield this.waitForHeadroomWithoutLock(),t.send(s.data),this.messageBuffer.markSent(s)}finally{n()}this.refreshBufferStatus()})}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new ao,this.sequence=1}}var W;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY",i[i.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(W||(W={}));const Bm=64*1024,jm=1024*1024,qm=8*1024,Vm=256*1024;function Wm(i){return i===W.RELIABLE?Bm:qm}function Hm(i){return i===W.RELIABLE?jm:Vm}const oo="_lossy",co="_reliable",lo="_data_track";class zm{constructor(e){this.opts=e;const t=n=>({kind:n,lowWaterMark:Wm(n),highWaterMark:Hm(n),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:r=>e.onBufferStatusChanged(n,r)});this.reliable=new Fm(Object.assign(Object.assign({},t(W.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new so(Object.assign(Object.assign({},t(W.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new so(Object.assign(Object.assign({},t(W.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case W.RELIABLE:return this.reliable;case W.LOSSY:return this.lossy;case W.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case W.RELIABLE:return this.reliableSub;case W.LOSSY:return this.lossySub;case W.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(const n of[this.lossy,this.reliable,this.dataTrack]){const r=n.channelHandle;r&&(r.onmessage=null,r.onerror=null,r.onclose=null)}const t=(n,r,s)=>{r.onmessage=s,r.onerror=this.opts.onDataError,r.onclose=()=>this.opts.onChannelClose(n.kind),r.bufferedAmountLowThreshold=n.lowWaterMark,r.onbufferedamountlow=()=>n.refreshBufferStatus(),n.attach(r)};t(this.lossy,e.createPublisherDataChannel(oo,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(co,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(lo,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===co)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===oo)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===lo)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){const e=t=>{t&&(t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close())};for(const t of[this.lossy,this.reliable,this.dataTrack]){const n=t.channelHandle;t.detach("peer connections cleaned up"),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const Gs=typeof MediaRecorder<"u";class Km{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Gm=Gs?MediaRecorder:Km;class Jm extends Gm{constructor(e,t){if(!Gs)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,r;const s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),r?.close(),r=void 0},o=c=>{r?.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:c=>{r=c,n=d=>m(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");s()||c.enqueue(l)}),this.addEventListener("dataavailable",n)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Qm(){return Gs}const Ym=1e3,$m=1e4;class Wd extends w{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),this.manuallyStopped=!1,this.pendingDeviceChange=!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=Bs(()=>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(I.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new fe,this.pauseUpstreamLock=new fe,this.trackChangeLock=new fe,this.trackChangeLock.lock().then(a=>m(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==w.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return m(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{en(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Yt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),s=this.processor.processedTrack}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{Yt(s??e,a)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ym;return(function*(){var n;if(e.kind===w.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=Re())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Te(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield Te(50)}throw new ut("unable to get track dimensions after timeout")})()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===nn(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),nn(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===w.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),r=n.deviceId,s=n.groupId,a=e.kind===w.Kind.Audio?"audioinput":"videoinput";return t?ge.getInstance().normalizeDeviceId(a,r,s):r})()})}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(e,t){return m(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new ut("unable to replace an unpublished track");let r,s;typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){})}restart(e,t){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const r=e,s=r.deviceId,a=r.facingMode,o=xh(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const c={audio:!1,video:!1};this.kind===w.Kind.Video?c.video=s||a?{deviceId:s,facingMode:a}:!0:c.audio=s?Object.assign({deviceId:s},o):!0,this.attachedElements.forEach(l=>{en(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const d=(yield navigator.mediaDevices.getUserMedia(c)).getTracks()[0];return this.kind===w.Kind.Video&&(yield d.applyConstraints(o)),d.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(d,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(I.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?I.Muted:I.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Md()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=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(I.UpstreamPaused,this);const n=Re();if(n?.name==="Safari"&&nt(n.version,"12.0")<0)throw new Ns("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;const t=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(I.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return m(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;const a=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),c={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext,localTrack:n};if(yield t.init(c),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Yt(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:l}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:d}))}),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const d of n.attachedElements)d!==n.processorElement&&r&&(en(n._mediaStreamTrack,d),Yt(n.processor.processedTrack,d));yield(s=n.sender)===null||s===void 0?void 0:s.replaceTrack(n.processor.processedTrack)}n.emit(I.TrackProcessorUpdate,n.processor)}finally{a()}yield n.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(I.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Qm()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Jm(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},$m)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Ri extends Wd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=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(e,w.Kind.Audio,t,n,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Hi(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(I.AudioTrackFeatureUpdate,this,me.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(I.AudioTrackFeatureUpdate,this,me.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===w.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===w.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=Ls({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}applyConstraints(e){return m(this,void 0,void 0,function*(){const t=yield this.trackChangeLock.lock();try{const n=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),n}finally{t()}})}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Me()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},js)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!Qe()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(I.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(r=>{if(r.type==="outbound-rtp"){n={type:"audio",streamId:r.id,packetsSent:r.packetsSent,bytesSent:r.bytesSent,timestamp:r.timestamp};const s=t.get(r.remoteId);s&&(n.packetsLost=s.packetsLost,n.jitter=s.jitter,n.roundTripTime=s.roundTripTime)}}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Rd(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(I.AudioSilenceDetected)),e})}}function Xm(i,e,t){switch(i.kind){case"audio":return new Ri(i,e,!1,void 0,t);case"video":return new Ii(i,e,!1,t);default:throw new ut("unsupported track type: ".concat(i.kind))}}const Zm=Object.values(jn),eg=Object.values($r),tg=Object.values(xs),ng=[jn.h180,jn.h360],ig=[$r.h180,$r.h360],rg=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(e=>{var t,n;return new $(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*(((t=i.encoding.maxFramerate)!==null&&t!==void 0?t:30)/((n=e.fps)!==null&&n!==void 0?n:30))))),e.fps,i.encoding.priority)}),ds=["q","h","f"];function Pi(i,e,t,n){var r,s;let a=n?.videoEncoding;i&&(a=n?.screenShareEncoding);const o=n?.simulcast,c=n?.scalabilityMode,d=n?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=sg(i,e,t,d),B.debug("using video encoding",a));const l=a.maxFramerate,u=new $(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ze(d)){const b=new zd(c),k=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const S=Re();if(qn()||Qe()||S?.name==="Chrome"&&nt(S?.version,"113")<0){const M=b.suffix=="h"?2:3,v=Tp(S);for(let T=0;T<b.spatial;T+=1)k.push({rid:ds[2-T],maxBitrate:a.maxBitrate/Math.pow(M,T),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:v?Math.pow(2,T):void 0});k[0].scalabilityMode=c}else k.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(k[0].priority=u.encoding.priority,k[0].networkPriority=u.encoding.priority),B.debug("using svc encoding",{encodings:k}),k}if(!o)return[a];let h;i?h=(r=ho(n?.screenShareSimulcastLayers))!==null&&r!==void 0?r:uo(i,u):h=(s=ho(n?.videoSimulcastLayers))!==null&&s!==void 0?s:uo(i,u);let p;if(h.length>0){const b=h[0];if(h.length>1){var f=h,g=x(f,2);p=g[1]}const k=Math.max(e,t);if(k>=960&&p)return Tr(e,t,[b,p,u],l);if(k>=480)return Tr(e,t,[b,u],l)}return Tr(e,t,[u])}function Hd(i,e,t){var n,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&B.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=i.mediaStreamTrack.getSettings(),c=(n=o.width)!==null&&n!==void 0?n:(r=i.dimensions)===null||r===void 0?void 0:r.width,d=(s=o.height)!==null&&s!==void 0?s:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===w.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Pi(i.source===w.Source.ScreenShare,c,d,t)}function sg(i,e,t,n){const r=ag(i,e,t);let s=r[0].encoding;const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.width>=a)break}if(n)switch(n){case"av1":case"h265":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 ag(i,e,t){if(i)return tg;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Zm:eg}function uo(i,e){if(i)return rg(e);const t=e.width,n=e.height,r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?ng:ig}function Tr(i,e,t,n){const r=[];if(t.forEach((s,a)=>{if(a>=ds.length)return;const o=Math.min(i,e),c={rid:ds[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},d=n&&s.encoding.maxFramerate?Math.min(n,s.encoding.maxFramerate):s.encoding.maxFramerate;d&&(c.maxFramerate=d);const l=Re(),u=l?.name==="Firefox"&&l.os!=="iOS"||a===0;s.encoding.priority&&u&&(c.priority=s.encoding.priority,c.networkPriority=s.encoding.priority),r.push(c)}),Qe()&&Ad()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var c;o.maxFramerate!=s&&(a&&(a=!1,B.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),B.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function ho(i){if(i)return i.slice().sort((e,t)=>{const n=e.encoding,r=t.encoding;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}class zd{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function og(i){switch(i.source){case w.Source.Camera:return"maintain-framerate";case w.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}const cg=5e3;class Ii extends Wd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,w.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(s.map(c=>[c.rid,c])),o=s.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(I.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=Hi(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new fe}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Me())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},js))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=Fe(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)s=d.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){n={error:l}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=Fe(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){s=d.value,o=!1;const l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===w.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===w.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={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},o=n.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let n=xe.LOW;n<=xe.HIGH;n+=1)t.push(new Ms({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ze(this.codec),t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,r,s,a;let o;if(e){const u=Ls({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=Fe(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){s=l.value,c=!1;const u=s;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){n={error:u}}finally{try{!c&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return m(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let r;try{r=yield this.waitForDimensions()}catch(o){this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:o}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===r.width&&this.lastEncodedDimensions.height===r.height)return;const s=this.source===w.Source.ScreenShare,a=Pi(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(const o of this.simulcastCodecs){var n=x(o,2);const c=n[0],d=n[1];if(!d.sender||((e=d.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!Cd(c))continue;const l=Object.assign({},this.publishOptions),u=Hd(this,c,l);u&&(yield this.applyEncodingsToSender(d.sender,u),d.encodings=u)}}catch(r){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{t()}})}applyEncodingsToSender(e,t){return m(this,void 0,void 0,function*(){const n=e.getParameters();!n.encodings||n.encodings.length!==t.length||(n.encodings.forEach((r,s)=>{if(r.active===!1)return;const a=t[s];a.scaleResolutionDownBy!==void 0&&(r.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(r.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(r.maxFramerate=a.maxFramerate),a.priority!==void 0&&(r.priority=a.priority,r.networkPriority=a.priority)}),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(r,n,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,p=Fe(r.simulcastCodecs.values()),f;f=yield p.next(),a=f.done,!a;h=!0)d=f.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(g){o={error:g}}finally{try{!h&&!a&&(c=p.return)&&(yield c.call(p))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(const t of this.simulcastCodecs.values())yield this.applyDegradationPreference(t.sender)})}applyDegradationPreference(e){return m(this,void 0,void 0,function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);const t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){return m(this,void 0,void 0,function*(){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},cg))})}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Ze(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,n=Fe(e);r=yield n.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ze(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield po(u.sender,u.encodings,l.qualities,this.senderLock,Ze(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return m(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield po(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return m(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((n,r)=>{var s;return Object.assign(Object.assign({},n),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&Ze(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?n.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Md()&&this.isInBackground&&this.source===w.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function po(i,e,t,n,r,s,a){return m(this,void 0,void 0,function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:i,qualities:t,senderEncodings:e}));try{const c=i.getParameters(),d=c.encodings;if(!d)return;if(d.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;r&&t.some(u=>u.enabled)&&t.forEach(u=>u.enabled=!0),d.forEach((u,h)=>{var p;let f=(p=u.rid)!==null&&p!==void 0?p:"";f===""&&(f="q");const g=Kd(f),b=t.find(k=>k.quality===g);b&&u.active!==b.enabled&&(l=!0,u.active=b.enabled,s.debug("setting layer ".concat(b.quality," to ").concat(u.active?"enabled":"disabled"),a),Wt()&&(b.enabled?(u.scaleResolutionDownBy=e[h].scaleResolutionDownBy,u.maxBitrate=e[h].maxBitrate,u.maxFrameRate=e[h].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))}),l&&(c.encodings=d,s.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield i.setParameters(c))}finally{o()}})}function Kd(i){switch(i){case"f":return xe.HIGH;case"h":return xe.MEDIUM;case"q":return xe.LOW;default:return xe.HIGH}}function mo(i,e,t,n){if(!t)return[new Tt({quality:xe.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const r=t[0].scalabilityMode,s=new zd(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let d=0;d<s.spatial;d+=1)a.push(new Tt({quality:Math.min(xe.HIGH,s.spatial-1)-d,width:Math.ceil(i/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let d=Kd((a=r.rid)!==null&&a!==void 0?a:"");return new Tt({quality:d,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const dg=2*1e3,Sr="leave-reconnect",lg=10*1e3,ug=3e4,hg=3,pg=3;var Oe;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Oe||(Oe={}));const go=64e3;class mg extends De.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ks.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Oe.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=B,this.reliableReceivedState=new Sm(ug),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>m(this,[n],void 0,function(r){var s=this;let a=r.channel;return(function*(){a&&s.dataChannels.adoptSubscriberChannel(a)&&s.log.debug("on data channel ".concat(a.id,", ").concat(a.label))})()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var r,s,a,o,c;const d=yield this.dataProcessLock.lock();try{const l=yield this.decodeDataMessage(n);if(!l)return;const u=Ce.fromBinary(l);if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((r=u.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((s=u.value)===null||s===void 0?void 0:s.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),p=vc.fromBinary(h.payload),f=new Ce({value:p.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=f.value)===null||o===void 0?void 0:o.case)==="user"&&fo(f,f.value.value),this.emit(P.DataPacketReceived,f,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&fo(u,u.value.value),this.emit(P.DataPacketReceived,u,G.NONE)}finally{d()}}),this.handleDataTrackMessage=n=>m(this,void 0,void 0,function*(){const r=yield this.decodeDataMessage(n);r&&this.emit("dataTrackPacketReceived",r)}),this.handleDataError=n=>{if(this._isClosed)return;const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&n instanceof RTCErrorEvent&&n.error){const s=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(s.message),{error:s,errorDetail:s.errorDetail,sctpCauseCode:s.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(r),{event:n})},this.handleDataChannelClose=n=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(W[n],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(n,r)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected")),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.emit(P.Disconnected),this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms"))},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}n===Sr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(P.TokenRefreshed,this.token),this.reconnectTimeout=Y.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,r)=>{this.pcState===Oe.Connected&&n();const s=()=>{this.off(P.Disconnected,a),n()},a=()=>{this.off(P.Restarted,s),r()};this.once(P.Restarted,s),this.once(P.Disconnected,a)}),this.onRtpMapAvailable=n=>{const r=new Map;n.forEach(s=>{const a=s.codec.toLowerCase();Od(a)&&r.set(s.payload,a)}),this.emit(P.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>m(this,void 0,void 0,function*(){!this.url||!(yield fetch(Vn(this.url),{method:"HEAD"}).then(n=>n.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===we.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===we.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(st.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>m(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Vn(this.url),{method:"HEAD"}),Te(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ve((t=e.loggerName)!==null&&t!==void 0?t:ae.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Hs(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new fe,this.dataProcessLock=new fe,this.dataChannels=new zm({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:n=>this.handleDataMessage(n),onDataTrackMessage:n=>this.handleDataTrackMessage(n),onDataError:n=>this.handleDataError(n),onChannelClose:n=>this.handleDataChannelClose(n)(),onBufferStatusChanged:(n,r)=>this.emit(P.DCBufferStatusChanged,r,n)}),this.client.onParticipantUpdate=n=>this.emit(P.ParticipantUpdate,n),this.client.onConnectionQuality=n=>{this.handleLocalConnectionQuality(n),this.emit(P.ConnectionQualityUpdate,n)},this.client.onRoomUpdate=n=>this.emit(P.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(P.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(P.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(P.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(P.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(P.SignalRequestResponse,n),this.client.onParticipantUpdate=n=>this.emit(P.ParticipantUpdate,n),this.client.onJoined=n=>this.emit(P.Joined,n)}get logContext(){var e,t,n,r,s,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,n,r){return m(this,arguments,void 0,function(s,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var u,h,p;d._isNewlyCreated=!1,d.url=s,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const f=!l&&Np();let g;if(f){d.pcManager||(yield d.configure(),d.applyInitialPublisherLayout());const S=yield(u=d.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();S&&(g=Nt(S.offer,S.offerId))}if(c?.aborted)throw N.cancelled("Connection aborted");if(!l&&d.shouldFailOnV1Path)throw d.shouldFailOnV1Path=!1,N.serviceNotFound("Simulated v1 path failure","v0-rtc");const b=yield d.client.join(s,a,o,c,l,g);d._isClosed=!1,d.latestJoinResponse=b,d.participantSid=(h=b.participant)===null||h===void 0?void 0:h.sid,d.subscriberPrimary=b.subscriberPrimary,f?(p=d.pcManager)===null||p===void 0||p.updateConfiguration(d.makeRTCConfiguration(b)):(d.pcManager||(yield d.configure(b,!l),l||d.applyInitialPublisherLayout()),(!d.subscriberPrimary||b.fastPublish)&&d.negotiate().catch(S=>{d.log.error(S)})),d.registerOnLineListener(),d.clientConfiguration=b.clientConfiguration,d.emit(P.SignalConnected,b);let k=b.serverInfo;return k||(k={version:b.serverVersion,region:b.serverRegion}),d.log.info("connected to Livekit Server ".concat(Object.entries(k).map(S=>{let M=x(S,2),v=M[0],T=M[1];return"".concat(v,": ").concat(T)}).join(", "))),{joinResponse:b,serverInfo:k}}catch(f){if(f instanceof N){if(f.reason===Q.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts)),d.joinAttempts<d.maxJoinAttempts)return d.join(s,a,o,c,l)}else if(f.reason===Q.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(f.message," – Retrying")),d.pcManager&&(d.pcManager.onStateChange=void 0,yield d.cleanupPeerConnections()),d.join(s,a,o,c,!0)}throw f}})()})}close(e){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(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(e)}finally{t()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;this.dataChannels.teardown(),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return m(this,void 0,void 0,function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(const t of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[t].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ut("a track with the same ID has already been published");return new Promise((t,n)=>{const r=Y.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(N.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{Y.clearTimeout(r),t(s)},reject:()=>{Y.clearTimeout(r),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.dataChannelForKind(W.RELIABLE,!0))===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return m(this,void 0,void 0,function*(){var n;if(!(this.pcManager&&this.pcManager.currentState!==Z.NEW)){if(e){this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new ro(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{const r=this.makeRTCConfiguration();this.pcManager=new ro("publisher-only",this.loggerOptions,r)}this.emit(P.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=(r,s)=>{this.client.sendOffer(r,s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,a)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),r===Z.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===Z.CONNECTED){const d=this.pcState===Oe.New;this.pcState=Oe.Connected,d&&this.emit(P.Connected,this.latestJoinResponse)}else r===Z.FAILED&&(this.pcState===Oe.Connected||this.pcState===Oe.Reconnecting)&&(this.pcState=Oe.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?st.RR_SUBSCRIBER_FAILED:st.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===we.RECONNECTING,c=[Z.FAILED,Z.CLOSING,Z.CLOSED].includes(r);o&&c&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(P.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>m(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}const n=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(P.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(P.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(P.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(P.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",st.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{var t;switch(this.log.info("client leave request received (action=".concat(e?.action,")"),{reason:e?.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(P.ServerRegionsReported,e.regions)),e.action){case Xt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close("server leave: ".concat((t=Ne[e.reason])!==null&&t!==void 0?t:e.reason));break;case Xt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Sr);break;case Xt.RESUME:this.handleDisconnect(Sr)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled||this.frameMetadataWorker&&!Wn())&&Fs()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),n.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ln.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),Qe()||this.addMediaSections(hg,pg)}addMediaSections(e,t){var n,r,s;const a={direction:"recvonly"};for(let c=0;c<e;c++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",a);const o=((r=this.pcManager)===null||r===void 0?void 0:r.mode)==="publisher-only";for(let c=0;c<t;c++){const d=(s=this.pcManager)===null||s===void 0?void 0:s.addPublisherTransceiverOfKind("video",a);if(o&&d){const l=vp(d);this.log.debug("dependency descriptor negotiated for received video",{negotiated:l})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return m(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,n){return m(this,void 0,void 0,function*(){let r;if(es())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(ts())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new ee("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return m(this,void 0,void 0,function*(){let s;if(es())s=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(ts())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new ee("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,n),s})}get frameMetadataWorker(){var e,t;return(t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer)===null||t===void 0?void 0:t.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,r,s;const a=this.frameMetadataWorker;if(!a||!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled)return;const o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,c=Ci(o);if(Wn()){c&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Hn((s=this.options.frameMetadata)!==null&&s!==void 0?s:this.options.packetTrailer)||!("createEncodedStreams"in e)){c&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const d=e.createEncodedStreams(),l=d.readable,u=d.writable;c?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:u,packetTrailer:o}},[l,u]):l.pipeTo(u)}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),mt(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return n&&(s.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,n,r){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("publisher is closed");return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;const t=e.updates.find(n=>n.participantSid===this.participantSid);t&&(t.quality===Jt.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=Y.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==Oe.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",st.RR_PUBLISHER_FAILED))},lg))}clearLostQualityTimeout(){this.lostQualityTimeout&&(Y.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return(t=(e=this.pcManager)===null||e===void 0?void 0:e.publisher.getSenders().some(n=>!!n.track&&n.track.readyState==="live"))!==null&&t!==void 0?t:!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:st.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,r;if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}this.clearLostQualityTimeout(),(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ln.DISABLED||((r=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&r!==void 0?r:Z.NEW)===Z.NEW)&&(this.fullReconnectOnNext=!0);const s=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let a=!1;try{this.attemptingReconnect=!0,s?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),a=!0}catch(o){this.reconnectAttempts+=1;let c=!0;o instanceof ee?(this.log.debug("received unrecoverable error",{error:o}),c=!1):(s||!(o instanceof Gt))&&(this.fullReconnectOnNext=!0),c?this.handleDisconnect("reconnect",st.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(P.Disconnected),yield this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms")))}finally{this.attemptingReconnect=!1,a&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",{error:t})}return null}restartConnection(e){return m(this,void 0,void 0,function*(){var t,n,r;try{if(!this.url||!this.token)throw new ee("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(P.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"),new Gt;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof N&&a.reason===Q.NotAllowed?new ee("could not reconnect, token might be expired"):new Gt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==we.CONNECTED)throw new Gt("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(s){const a=yield(n=this.regionStrategy)===null||n===void 0?void 0:n.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return m(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new ee("could not reconnect, url or token not saved");if(!this.pcManager)throw new ee("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(P.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,{error:r})),r instanceof N&&r.reason===Q.NotAllowed?new ee("could not reconnect, token might be expired"):r instanceof N&&r.reason===Q.LeaveRequest?r:new Gt(s)}if(this.emit(P.SignalResumed),t){const r=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==we.CONNECTED)throw new Gt("Signal connection got severed during reconnect");this.client.setReconnected();const n=this.dataChannelForKind(W.RELIABLE);n?.readyState==="open"&&n.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(r=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:r}))}),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new ee("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Oe.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Te(dg),!this.pcManager)throw new ee("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Oe.Connected}catch(e){throw this.pcState=Oe.Disconnected,N.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new Ce({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new Ui({requestId:t})}});yield this.sendDataPacket(n,W.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){var n,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=Hp(e);if(o){const c=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new fc({encryptedValue:c.payload,iv:c.iv,keyIndex:c.keyIndex})}}}t===W.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const s=e.toBinary(),a=Math.min((r=(n=this.pcManager)===null||n===void 0?void 0:n.getMaxPublisherMessageSize())!==null&&r!==void 0?r:go,go);if(typeof a<"u"&&a!==0&&s.byteLength>a)throw new Zh("cannot publish data packet larger than ".concat(a," bytes (got ").concat(s.byteLength,")"));t===W.RELIABLE?yield this.reliableChannel.send(s,e.sequence):yield this.lossyChannel.send(s)})}sendDataTrackFrame(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(W.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(W.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return m(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!n.pcManager)throw new ee("PC manager is closed");const a=r?n.pcManager.subscriber:n.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw N.internal("".concat(o," connection not set"));let c=!1;if(!r&&!n.dataChannelForKind(t,r)&&(n.createDataChannels(),c=!0),!c&&!r&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate().catch(u=>{n.log.error(u)}),n.dataChannelForKind(t,r)?.readyState==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=n.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield Te(50)}throw N.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;const e=this.pcManager.currentState;return![Z.CONNECTING,Z.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===Z.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn("transport stuck in connecting state",this.logContext),!1):!0}negotiate(){return m(this,void 0,void 0,function*(){return new Ee((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new wt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();const n=new AbortController,r=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new wt("cannot negotiate on closed engine")),this.on(P.Closing,r),this.on(P.Restarting,r),this.pcManager.publisher.off(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(s){if(n.signal.aborted){e();return}s instanceof wt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",st.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(P.Closing,r),this.off(P.Restarting,r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const c=this.pcManager.publisher.getLocalDescription(),d=this.pcManager.publisher.getRemoteDescription(),l=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getRemoteDescription(),u=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),h=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,p=new Array,f=new Array;e.forEach(g=>{g.isDesired!==h&&p.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Ds({answer:this.pcManager.mode==="publisher-only"?d?Nt({sdp:d.sdp,type:d.type}):void 0:u?Nt({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?c?Nt({sdp:c.sdp,type:c.type}):void 0:l?Nt({sdp:l.sdp,type:l.type}):void 0,subscription:new qi({trackSids:p,subscribe:!h,participantTracks:[]}),publishTracks:cp(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,b)=>new Fc({publisherSid:b,lastSeq:g})),publishDataTracks:n.map(g=>new Es({info:Ei.toProtobuf(g)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(n,r)=>{n?.id!==void 0&&n.id!==null&&e.push(new Bc({label:n.label,id:n.id,target:r}))};return t(this.dataChannelForKind(W.LOSSY),He.PUBLISHER),t(this.dataChannelForKind(W.RELIABLE),He.PUBLISHER),t(this.dataChannelForKind(W.LOSSY,!0),He.SUBSCRIBER),t(this.dataChannelForKind(W.RELIABLE,!0),He.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Y.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Me()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Me()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){const r=Object.entries(this.midToTrackId).find(s=>x(s,1)[0]===n);if(r)return r[1]}}}function fo(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}const $n=ve(ae.Region),ls=5e3,gg=3e4;class z{static fetchRegionSettings(e,t,n){return m(this,void 0,void 0,function*(){const r=yield z.fetchLock.lock();try{const s=yield fetch("".concat(fg(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(s.ok){const a=Op(s.headers),o=a?a*1e3:ls;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?N.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):N.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof N?s:n?.aborted?N.cancelled("Region fetching was aborted"):N.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,n){return m(this,void 0,void 0,function*(){const r=z.settingsTimeouts.get(e.hostname);clearTimeout(r),z.settingsTimeouts.set(e.hostname,setTimeout(()=>m(this,void 0,void 0,function*(){try{const s=yield z.fetchRegionSettings(e,t);z.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof N&&s.reason===Q.NotAllowed){$n.debug("token is not valid, cancelling auto region refresh");return}$n.debug("auto refetching of region settings failed",{error:s}),z.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){z.cache.set(e.hostname,n),z.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=z.settingsTimeouts.get(e);t&&(clearTimeout(t),z.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=z.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const n=z.connectionTrackers.get(e);n&&n.connectionCount===0&&($n.debug("stopping region refetch after disconnect delay",{hostname:e}),z.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},gg))}static cancelCleanup(e){const t=z.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=z.connectionTrackers.get(e);t||(t={connectionCount:0},z.connectionTrackers.set(e,t)),t.connectionCount++,z.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=z.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&z.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const n=this.getServerUrl(),r=z.cache.get(n.hostname);z.scheduleRefetch(this.serverUrl,this.token,(t=r?.maxAgeInMs)!==null&&t!==void 0?t:ls)}isCloud(){return un(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){return z.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=z.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),z.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(n.length>0){const r=n[0];return this.attemptedRegions.push(r),$n.info("switching to region: ".concat(r.region),{region:r.region}),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){z.updateCachedRegionSettings(this.serverUrl,this.token,e)}}z.cache=new Map;z.settingsTimeouts=new Map;z.connectionTrackers=new Map;z.fetchLock=new fe;function fg(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}function wr(){return new CompressionStream("deflate-raw")}function Gd(){return new DecompressionStream("deflate-raw")}function vo(i,e){return m(this,void 0,void 0,function*(){const t=new DecompressionStream("deflate-raw"),n=t.writable.getWriter();return n.write(i).catch(()=>{}),n.close().catch(()=>{}),Jd(t.readable,e)})}function Jd(i,e){return m(this,void 0,void 0,function*(){const t=i.getReader(),n=[];let r=0;for(;;){const o=yield t.read(),c=o.done,d=o.value;if(c)break;if(n.push(d),r+=d.byteLength,typeof e=="number"&&r>e)throw yield t.cancel(),new le("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),ie.PayloadTooLarge)}const s=new Uint8Array(r);let a=0;for(const o of n)s.set(o,a),a+=o.byteLength;return s})}const xt=15e3,vg=5e9;class Qd{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new le("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ie.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new le("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ie.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class yo extends Qd{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){var n;try{const r=this.signal;if(r?.aborted)throw r.reason;const s=yield new Promise((a,o)=>{if(r){const c=()=>o(r.reason);r.addEventListener("abort",c,{once:!0}),e.read().then(a,o).finally(()=>{r.removeEventListener("abort",c)})}else e.read().then(a,o)});return s.done?(this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((n=this.onProgress)===null||n===void 0||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(s.value),{done:!1,value:s.value.content})}catch(r){throw t(),r}}),return(){return m(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=Fe(c),u;u=yield l.next(),n=u.done,!n;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!d&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)})()})}}class bo extends Qd{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=At(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8"),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){var s;try{if(n?.aborted)throw n.reason;const a=yield new Promise((o,c)=>{if(n){const d=()=>c(n.reason);n.addEventListener("abort",d,{once:!0}),e.read().then(o,c).finally(()=>{n.removeEventListener("abort",d)})}else e.read().then(o,c)});if(a.done)return this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((s=this.onProgress)===null||s===void 0||s.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(a.value);let o;try{o=t.decode(a.value.content)}catch(c){throw new le("Cannot decode datastream chunk ".concat(a.value.chunkIndex," as text: ").concat(c),ie.DecodeFailed)}return{done:!1,value:o}}}catch(a){throw r(),a}}),return(){return m(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=Fe(c),u;u=yield l.next(),n=u.done,!n;d=!0)a=u.value,d=!1,o+=a}catch(h){r={error:h}}finally{try{!d&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o})()})}}class yg{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vg;this.log=B,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const n=t.packet,r=t.encryptionType;this.handleDataStreamPacket(n,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new le('A text stream handler for topic "'.concat(e,'" has already been set.'),ie.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new le('A byte stream handler for topic "'.concat(e,'" has already been set.'),ie.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){const a=new le("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ie.AbnormalEnd);for(const o of n){var r=x(o,2);const c=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(c)}for(const o of t){var s=x(o,2);const c=s[0];s[1].controller.error(a),this.textStreamControllers.delete(c)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}handleStreamHeader(e,t,n){var r;switch(e.contentHeader.case){case"byteHeader":{const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:At(e.timestamp),attributes:e.attributes,encryptionType:n};let c;switch(e.compression){case ke.DEFLATE_RAW:if(!Ct()){B.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}c=!0;break;case ke.NONE:c=!1;break;default:B.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const d=e.inlineContent;if(typeof d<"u"){s(new yo(o,ko(e.streamId,c?vo(d,this.maxPayloadByteLength):d),At(e.totalLength)),{identity:t});return}const l=new ReadableStream({start:u=>{if(a=u,this.byteStreamControllers.has(e.streamId))throw new le("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ie.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new yo(o,c?Tg(l,e.streamId,this.maxPayloadByteLength):l,At(e.totalLength)),{identity:t});return}case"textHeader":{const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};let c;switch(e.compression){case ke.DEFLATE_RAW:if(!Ct()){B.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}c=!0;break;case ke.NONE:c=!1;break;default:B.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const d=e.inlineContent;if(typeof d<"u"){const u=c?vo(d,this.maxPayloadByteLength):d;s(new bo(o,ko(e.streamId,u),At(e.totalLength)),{identity:t});return}const l=new ReadableStream({start:u=>{if(a=u,this.textStreamControllers.has(e.streamId))throw new le("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ie.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new bo(o,c?Sg(l,e.streamId,this.maxPayloadByteLength):l,At(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ie.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),ie.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ie.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new le("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ie.AbnormalEnd)):n.controller.close()),this.textStreamControllers.delete(e.streamId));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new le("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),ie.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new le("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ie.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}function ko(i,e){return new ReadableStream({start:t=>m(this,void 0,void 0,function*(){try{const n=yield e;t.enqueue(new ht({streamId:i,chunkIndex:BigInt(0),content:n})),t.close()}catch(n){t.error(n)}})})}function Yd(i){let e=-1;return new TransformStream({transform:(t,n)=>{const r=At(t.chunkIndex);if(r<=e){B.warn("ignoring duplicate chunk ".concat(r," for compressed data stream ").concat(i," (last processed: ").concat(e,")"));return}if(r>e+1)throw new le("Missing chunk(s) ".concat(e+1,"..").concat(r-1," for compressed data stream ").concat(i," - cannot continue decompressing"),ie.Incomplete);e=r,n.enqueue(t)}})}function $d(){return new TransformStream({transform:(i,e)=>{e.enqueue(i.content)}})}function bg(i){let e=0;return new TransformStream({transform:(t,n)=>{t.byteLength>0&&(n.enqueue(new ht({streamId:i,chunkIndex:Je(e),content:t})),e+=1)}})}function kg(i){const e=new TextDecoder("utf-8"),t=new TextEncoder;let n=0;const r=s=>{try{return s?e.decode(s,{stream:!0}):e.decode()}catch(a){throw new le("Cannot decode compressed data stream ".concat(i," as text: ").concat(a),ie.DecodeFailed)}};return new TransformStream({transform:(s,a)=>{const o=r(s);o.length>0&&(a.enqueue(new ht({streamId:i,chunkIndex:Je(n),content:t.encode(o)})),n+=1)},flush:s=>{const a=r();a.length>0&&(s.enqueue(new ht({streamId:i,chunkIndex:Je(n),content:t.encode(a)})),n+=1)}})}function Tg(i,e,t){return i.pipeThrough(Yd(e)).pipeThrough($d()).pipeThrough(Gd()).pipeThrough(Xd(e,t)).pipeThrough(bg(e))}function Sg(i,e,t){return i.pipeThrough(Yd(e)).pipeThrough($d()).pipeThrough(Gd()).pipeThrough(Xd(e,t)).pipeThrough(kg(e))}function Xd(i,e){let t=0;return new TransformStream({transform:(n,r)=>{if(t+=n.byteLength,t>e)throw new le("Data stream ".concat(i," exceeds the maximum payload size of ").concat(e," bytes"),ie.PayloadTooLarge);r.enqueue(n)}})}class Zd{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class wg extends Zd{}class Cg extends Zd{}function Cr(i,e,t){var n;return new Fi({streamId:i.id,mimeType:i.mimeType,topic:i.topic,timestamp:Je(i.timestamp),totalLength:Je(i.size),attributes:i.attributes,compression:(n=t?.compression)!==null&&n!==void 0?n:ke.NONE,inlineContent:t?.inlineContent,contentHeader:{case:"textHeader",value:new Ic({version:e?.version,attachedStreamIds:i.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Nr.UPDATE:Nr.CREATE})}})}function Xn(i,e){var t;return new Fi({streamId:i.id,mimeType:i.mimeType,topic:i.topic,timestamp:Je(i.timestamp),totalLength:Je(i.size),attributes:i.attributes,compression:(t=e?.compression)!==null&&t!==void 0?t:ke.NONE,inlineContent:e?.inlineContent,contentHeader:{case:"byteHeader",value:new _c({name:i.name})}})}function Mt(i,e){return new Ce({destinationIdentities:e,value:{case:"streamHeader",value:i}})}const Eg=new TextEncoder;class Rg{constructor(e,t,n,r,s){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=s}setupEngine(e){this.engine=e}sendText(e,t){return m(this,void 0,void 0,function*(){var n,r,s,a,o;const c=crypto.randomUUID(),d=Eg.encode(e),l=d.byteLength,u=(n=t?.compress)!==null&&n!==void 0?n:!0;let h={id:c,mimeType:"text/plain",timestamp:Date.now(),topic:(r=t?.topic)!==null&&r!==void 0?r:"",size:l,attributes:t?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?G.GCM:G.NONE},p=u&&Ct()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?_i.fromStream(pi(d).pipeThrough(wr())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let S=d,M=ke.NONE;if(p){const C=yield p.collect();C.byteLength<d.byteLength&&(S=C,M=ke.DEFLATE_RAW)}const v=Cr(h,void 0,{compression:M,inlineContent:S}),T=Mt(v,t?.destinationIdentities);if(T.toBinary().byteLength<=xt)return yield this.engine.sendDataPacket(T,W.RELIABLE),(a=t?.onProgress)===null||a===void 0||a.call(t,1),h}const f=(o=t?.attachments)===null||o===void 0?void 0:o.map(()=>crypto.randomUUID()),g=f?f.length+1:1,b=new Array(g).fill(0),k=(S,M)=>{var v;b[M]=S,(v=t?.onProgress)===null||v===void 0||v.call(t,b.reduce((T,C)=>T+C,0)/g)};if(p){h.attachedStreamIds=f;const S=Cr(h,void 0,{compression:ke.DEFLATE_RAW}),M=Mt(S,t?.destinationIdentities);yield this.sendChunkedByteStream(M,c,t?.destinationIdentities,p.stream().pipeThrough(Er(d.length,v=>k(v,0)))),d.length===0&&k(1,0)}else{const S=yield this.streamText({streamId:c,totalSize:l,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:f,attributes:t?.attributes});yield S.write(e),k(1,0),yield S.close(),h=S.info}return t?.attachments&&f&&(yield Promise.all(t.attachments.map((S,M)=>m(this,void 0,void 0,function*(){return this._sendFile(f[M],S,{topic:t.topic,mimeType:S.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:v=>{k(v,M+1)}})})))),h})}sendBytes(e,t){return m(this,void 0,void 0,function*(){var n,r,s,a,o,c,d;const l=crypto.randomUUID(),u=t?.destinationIdentities,h=(n=t?.compress)!==null&&n!==void 0?n:!0,p={id:l,name:(r=t?.name)!==null&&r!==void 0?r:"unknown",mimeType:(s=t?.mimeType)!==null&&s!==void 0?s:"application/octet-stream",timestamp:Date.now(),topic:(a=t?.topic)!==null&&a!==void 0?a:"",size:e.byteLength,attributes:t?.attributes,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?G.GCM:G.NONE},f=Er(e.length,t?.onProgress);let g=h&&Ct()&&this.allRecipientsSupportV2(u)&&this.allRecipientsSupportCompression(u)?_i.fromStream(pi(e).pipeThrough(f).pipeThrough(wr())):null;if(this.allRecipientsSupportV2(u)){let M=e,v=ke.NONE;if(g){const O=yield g.collect();O.byteLength<e.byteLength&&(M=O,v=ke.DEFLATE_RAW)}const T=Xn(p,{compression:v,inlineContent:M}),C=Mt(T,u);if(C.toBinary().byteLength<=xt)return yield this.engine.sendDataPacket(C,W.RELIABLE),(c=t?.onProgress)===null||c===void 0||c.call(t,1),p}const b=Xn(p,{compression:g?ke.DEFLATE_RAW:ke.NONE}),k=Mt(b,u),S=g?g.stream():pi(e).pipeThrough(f);return yield this.sendChunkedByteStream(k,l,u,S),e.length===0&&((d=t?.onProgress)===null||d===void 0||d.call(t,1)),p})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(t=>this.getRemoteParticipantClientProtocol(t)>=wd)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(t=>this.getRemoteParticipantCapabilities(t).includes(Fn.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,n,r){return m(this,void 0,void 0,function*(){var s,a,o,c;const d=this.engine;yield Rr(d,e);let l=0;try{for(var u=!0,h=Fe(Ap(r,xt)),p;p=yield h.next(),s=p.done,!s;u=!0){c=p.value,u=!1;const f=c,g=new Ce({destinationIdentities:n,value:{case:"streamChunk",value:new ht({content:f,streamId:t,chunkIndex:Je(l)})}});yield d.sendDataPacket(g,W.RELIABLE),l+=1}}catch(f){a={error:f}}finally{try{!u&&!s&&(o=h.return)&&(yield o.call(h))}finally{if(a)throw a.error}}yield Pr(t,n,d)})}streamText(e){return m(this,void 0,void 0,function*(){var t,n,r;const s=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e?.destinationIdentities,o={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?G.GCM:G.NONE,attachedStreamIds:e?.attachedStreamIds},c=Cr(o,e),d=Mt(c,a);yield Rr(this.engine,d);let l=0;const u=this.engine,h=new WritableStream({write(g){return m(this,void 0,void 0,function*(){for(const b of Dp(g,xt)){const k=new ht({content:b,streamId:s,chunkIndex:Je(l)}),S=new Ce({destinationIdentities:a,value:{case:"streamChunk",value:k}});yield u.sendDataPacket(S,W.RELIABLE),l+=1}})},close(){return m(this,void 0,void 0,function*(){yield Pr(s,a,u)})},abort(g){console.log("Sink error:",g)}});let p=()=>m(this,void 0,void 0,function*(){yield f.close()});u.once(P.Closing,p);const f=new wg(h,o,()=>this.engine.off(P.Closing,p));return f})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var r,s,a,o,c;const d=n?.destinationIdentities,l=((r=n?.compress)!==null&&r!==void 0?r:!0)&&Ct()&&this.allRecipientsSupportV2(d)&&this.allRecipientsSupportCompression(d),u={id:e,name:t.name,mimeType:(s=n?.mimeType)!==null&&s!==void 0?s:t.type,topic:(a=n?.topic)!==null&&a!==void 0?a:"",timestamp:Date.now(),size:t.size,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?G.GCM:G.NONE},h=Xn(u,{compression:l?ke.DEFLATE_RAW:ke.NONE}),p=Mt(h,d),f=t.stream().pipeThrough(Er(t.size,n?.onProgress)),g=l?f.pipeThrough(wr()):f;return yield this.sendChunkedByteStream(p,e,d,g),t.size===0&&((c=n?.onProgress)===null||c===void 0||c.call(n,1)),u})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,r,s,a;const o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e?.destinationIdentities,d={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(r=e?.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(s=e?.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?G.GCM:G.NONE},l=Xn(d),u=Mt(l,c);yield Rr(this.engine,u);let h=0;const p=new fe,f=this.engine,g=this.log,b=new WritableStream({write(k){return m(this,void 0,void 0,function*(){const S=yield p.lock();let M=0;try{for(;M<k.byteLength;){const v=k.slice(M,M+xt),T=new Ce({destinationIdentities:c,value:{case:"streamChunk",value:new ht({content:v,streamId:o,chunkIndex:Je(h)})}});yield f.sendDataPacket(T,W.RELIABLE),h+=1,M+=v.byteLength}}finally{S()}})},close(){return m(this,void 0,void 0,function*(){yield Pr(o,c,f)})},abort(k){g.error("Sink error:",k)}});return new Cg(b,d)})}}class _i{constructor(e){this.state=e}static fromStream(e){return new _i({type:"stream",stream:e})}collect(){return m(this,void 0,void 0,function*(){switch(this.state.type){case"stream":const e=yield Jd(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return pi(this.state.bytes)}}}function Er(i,e){let t=0;return new TransformStream({transform(n,r){t+=n.byteLength,e&&typeof i=="number"&&i>0&&e(Math.min(t/i,1)),r.enqueue(n)}})}function Rr(i,e){return m(this,void 0,void 0,function*(){if(e.toBinary().byteLength>xt)throw new le("data stream header exceeds the ".concat(xt,"-byte limit; reduce attribute size"),ie.HeaderTooLarge);yield i.sendDataPacket(e,W.RELIABLE)})}function Pr(i,e,t){return m(this,void 0,void 0,function*(){const n=new Ce({destinationIdentities:e,value:{case:"streamTrailer",value:new ws({streamId:i})}});yield t.sendDataPacket(n,W.RELIABLE)})}function el(i){if(i.length===0)return new AbortController().signal;if(i.length===1)return i[0];for(const r of i)if(r.aborted)return r;const e=new AbortController,t=Array(i.length),n=()=>{for(const r of t)r()};return i.forEach((r,s)=>{const a=()=>{e.abort(r.reason),n()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function tl(i){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(i," ms"),"TimeoutError"))},i),e.signal}const se=1,rt=2,To=4,Pg=8,So=0,wo=12,Co=5,Ig=7,Eo=3,_g=3,Ro=2,Po=1,Io=0,_o=3,Zn=2,Mo=2,Mg=1,Dg=0;var ot;(function(i){i[i.TooShort=0]="TooShort",i[i.HeaderOverrun=1]="HeaderOverrun",i[i.MissingExtWords=2]="MissingExtWords",i[i.UnsupportedVersion=3]="UnsupportedVersion",i[i.InvalidHandle=4]="InvalidHandle",i[i.MalformedExt=5]="MalformedExt"})(ot||(ot={}));class Se extends Be{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=ot[t]}static tooShort(){return new Se("Too short to contain a valid header",ot.TooShort)}static headerOverrun(){return new Se("Header exceeds total packet length",ot.HeaderOverrun)}static missingExtWords(){return new Se("Extension word indicator is missing",ot.MissingExtWords)}static unsupportedVersion(e){return new Se("Unsupported version ".concat(e),ot.UnsupportedVersion)}static invalidHandle(e){return new Se("invalid track handle: ".concat(e.message),ot.InvalidHandle,{cause:e})}static malformedExt(e){return new Se("Extension with tag ".concat(e," is malformed"),ot.MalformedExt)}}var An;(function(i){i[i.TooSmallForHeader=0]="TooSmallForHeader",i[i.TooSmallForPayload=1]="TooSmallForPayload"})(An||(An={}));class zn extends Be{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=An[t]}static tooSmallForHeader(){return new zn("Buffer cannot fit header",An.TooSmallForHeader)}static tooSmallForPayload(){return new zn("Buffer cannot fit payload",An.TooSmallForPayload)}}class zi{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(r," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var pn;(function(i){i[i.UserTimestamp=2]="UserTimestamp",i[i.E2ee=1]="E2ee"})(pn||(pn={}));class nl extends zi{}class ze extends nl{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return se+se+ze.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,ze.tag),t+=se,e.setUint8(t,ze.lengthBytes),t+=se,e.setBigUint64(t,this.timestamp),t+=Pg;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:ze.tag,lengthBytes:ze.lengthBytes,timestamp:this.timestamp}}}ze.tag=pn.UserTimestamp;ze.lengthBytes=8;class Ke extends nl{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return se+se+Ke.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Ke.tag),t+=se,e.setUint8(t,Ke.lengthBytes),t+=se,e.setUint8(t,this.keyIndex),t+=se;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=se;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:Ke.tag,lengthBytes:Ke.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}Ke.tag=pn.E2ee;Ke.lengthBytes=13;class cn extends zi{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){const r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){const r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){const t=Ws(e);let n,r,s=0;for(;t.byteLength-s>=se+se;){const a=t.getUint8(s);s+=se;const o=t.getUint8(s);if(s+=se,a!==Dg)switch(a){case pn.UserTimestamp:if(t.byteLength-s<ze.lengthBytes)throw Se.malformedExt(a);n=new ze(t.getBigUint64(s)),s+=o;break;case pn.E2ee:if(t.byteLength-s<Ke.lengthBytes)throw Se.malformedExt(a);const c=t.getUint8(s),d=new Uint8Array(12);for(let l=0;l<d.length;l+=1){let u=s;u+=se,u+=l*se,d[l]=t.getUint8(u)}r=new Ke(c,d),s+=o;break;default:if(t.byteLength-s<o)throw Se.malformedExt(a);s+=o;break}}return[new cn({userTimestamp:n,e2ee:r}),t.byteLength]}toJSON(){var e,t,n,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(n=this.e2ee)===null||n===void 0?void 0:n.toJSON())!==null&&r!==void 0?r:null}}}const il={from(i){return{payload:i.payload,extensions:new cn({userTimestamp:i.userTimestamp?new ze(i.userTimestamp):void 0})}},lossyIntoFrame(i){var e;return{payload:i.payload,userTimestamp:(e=i.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},rl=Symbol.for("lk.track"),sl=Symbol.for("lk.data-track");class al{constructor(e,t,n){this.trackSymbol=rl,this.isLocal=!1,this.typeSymbol=sl,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),n=x(t,2),r=n[0];return n[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Kn extends zi{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=(t=e.extensions)!==null&&t!==void 0?t:new cn}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((Zn+e)/4),n=t*4-Zn-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:n}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes;let r=wo;return t>0&&(r+=Zn+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw zn.tooSmallForHeader();let t=So<<Co,n;switch(this.marker){case te.Inter:n=Io;break;case te.Final:n=Po;break;case te.Start:n=Ro;break;case te.Single:n=_o;break}t|=n<<Eo;const r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<Mo);let c=0;if(e.setUint8(c,t),c+=se,e.setUint8(c,0),c+=se,e.setUint16(c,this.trackHandle),c+=rt,e.setUint16(c,this.sequence.value),c+=rt,e.setUint16(c,this.frameNumber.value),c+=rt,e.setUint32(c,this.timestamp.asTicks()),c+=To,s>0){const l=a-1;e.setUint16(c,l),c+=rt;const u=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+c));c+=u;for(let h=0;h<o;h+=1)e.setUint8(c,0),c+=se}const d=this.toBinaryLengthBytes();if(c!==d)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(c," bytes but expected length was ").concat(d," bytes"));return d}static fromBinary(e){const t=Ws(e);if(t.byteLength<wo)throw Se.tooShort();let n=0;const r=t.getUint8(n);n+=se;const s=r>>Co&Ig;if(s>So)throw Se.unsupportedVersion(s);let a;switch(r>>Eo&_g){case Ro:a=te.Start;break;case Po:a=te.Final;break;case _o:a=te.Single;break;case Io:default:a=te.Inter;break}const o=(r>>Mo&Mg)>0;n+=se;let c;try{c=em.fromNumber(t.getUint16(n))}catch(p){throw p instanceof hn&&(p.isReason(Bt.Reserved)||p.isReason(Bt.TooLarge))?Se.invalidHandle(p):p}n+=rt;const d=Ge.u16(t.getUint16(n));n+=rt;const l=Ge.u16(t.getUint16(n));n+=rt;const u=an.fromRtpTicks(t.getUint32(n));n+=To;let h=new cn;if(o){if(t.byteLength-n<rt)throw Se.missingExtWords();let p=t.getUint16(n);n+=rt;let f=4*(p+1)-Zn;if(n+f>t.byteLength)throw Se.headerOverrun();let g=new DataView(t.buffer,t.byteOffset+n,f);const b=cn.fromBinary(g),k=x(b,2),S=k[0],M=k[1];h=S,n+=M}return[new Kn({marker:a,trackHandle:c,sequence:d,frameNumber:l,timestamp:u,extensions:h}),n]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var te;(function(i){i[i.Start=0]="Start",i[i.Inter=1]="Inter",i[i.Final=2]="Final",i[i.Single=3]="Single"})(te||(te={}));class Ki extends zi{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw zn.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=se;const r=this.toBinaryLengthBytes();if(t!==r)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(r," bytes"));return r}static fromBinary(e){const t=Ws(e),n=Kn.fromBinary(t),r=x(n,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new Ki(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const Ir=ve(ae.DataTracks);class et extends Be{constructor(e,t,n,r){super(19,"Frame ".concat(n," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Lt[t],this.frameNumber=n}static interrupted(e,t){return new et("Interrupted by the start of a new frame ".concat(t),Lt.Interrupted,e)}static unknownFrame(e){return new et("Initial packet was never received.",Lt.UnknownFrame,e)}static bufferFull(e){return new et("Reorder buffer is full.",Lt.BufferFull,e)}static incomplete(e,t,n){return new et("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),Lt.Incomplete,e)}}var Lt;(function(i){i[i.Interrupted=0]="Interrupted",i[i.UnknownFrame=1]="UnknownFrame",i[i.BufferFull=2]="BufferFull",i[i.Incomplete=3]="Incomplete"})(Lt||(Lt={}));class Gi{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case te.Single:return this.frameFromSingle(e,t);case te.Start:return this.beginPartial(e,t);case te.Inter:case te.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==te.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const r=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;if(this.partials.size>=r){const s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t?.throwOnInterruption)throw et.interrupted(s,e.header.frameNumber.value);Ir.warn("Data track frame ".concat(s," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var n;if(e.header.marker!==te.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;for(;this.partials.size>=o;){const c=this.peekOldestPartialFrameNumber();if(typeof c!="number")break;if(this.partials.delete(c),t?.throwOnInterruption)throw et.interrupted(c,s);Ir.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(c," to make room for new frame ").concat(s,"."))}return this.partials.set(s,a),null}pushToPartial(e){if(e.header.marker!==te.Inter&&e.header.marker!==te.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),et.unknownFrame(t);if(n.payloads.size>=Gi.MAX_BUFFER_PACKETS)throw this.partials.delete(t),et.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Ir.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===te.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const r=t.payloads.size;let s=0;for(const d of t.payloads.values())s+=d.length;const a=new Uint8Array(s);let o=t.startSequence.clone(),c=0;for(;;){const d=t.payloads.get(o.value);if(!d)break;t.payloads.delete(o.value);const l=a.length-c;if(d.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(d.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(d,c),c+=d.length,o.value!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),et.incomplete(e,r,n-t.startSequence.value+1)}}Gi.MAX_BUFFER_PACKETS=128;var Ut;(function(i){i[i.Unpublished=0]="Unpublished",i[i.Timeout=1]="Timeout",i[i.Disconnected=2]="Disconnected",i[i.Cancelled=4]="Cancelled"})(Ut||(Ut={}));class Ie extends Be{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Ut[t]}static unpublished(){return new Ie("The track has been unpublished and is no longer available",Ut.Unpublished)}static timeout(){return new Ie("Request to subscribe to data track timed-out",Ut.Timeout)}static disconnected(){return new Ie("Cannot subscribe to data track when disconnected",Ut.Disconnected)}static cancelled(){return new Ie("Subscription to data track cancelled by caller",Ut.Cancelled)}}const _r=ve(ae.DataTracks);class Ag{constructor(e){var t,n;const r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const s=new Gi;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(n=e.pipelineOptions)!==null&&n!==void 0?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return m(this,void 0,void 0,function*(){const t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return _r.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return m(this,void 0,void 0,function*(){var t,n;const r=this.e2eeManager;if(!r)return e;const s=(n=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&n!==void 0?n:null;if(!s)return _r.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return _r.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const ce=ve(ae.DataTracks),Og=1e4,Ng=16;class xg extends De.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const n=this.descriptors.get(e);if(!n){ce.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}n.pipelineOptions=t,n.subscription.type==="active"&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ng,r=null;const s=new be,a=this.descriptors.get(e),o=()=>{t?.removeEventListener("abort",d)},c=()=>{if(o(),!r){ce.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!a||this.descriptors.get(a.info.sid)!==a){ce.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(a.subscription.type!=="active"){ce.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},d=()=>{var l;r&&(a?.subscription.type==="active"&&a.subscription.streamControllers.delete(r),r.error(Ie.cancelled()),(l=s.reject)===null||l===void 0||l.call(s,Ie.cancelled()),c())};return[new ReadableStream({start:l=>{r=l,this.subscribeRequest(e,t).then(()=>m(this,void 0,void 0,function*(){var u,h,p;if(!a||this.descriptors.get(a.info.sid)!==a){ce.error("Unknown track ".concat(e));const f=Ie.disconnected();l.error(f),(u=s.reject)===null||u===void 0||u.call(s,f);return}if(a.subscription.type!=="active"){ce.error("Subscription for track ".concat(e," is not active"));const f=Ie.disconnected();l.error(f),(h=s.reject)===null||h===void 0||h.call(s,f);return}if(t?.aborted){d();return}t?.addEventListener("abort",d),a.subscription.streamControllers.set(l,o),(p=s.resolve)===null||p===void 0||p.call(s)})).catch(u=>{var h;l.error(u),(h=s.reject)===null||h===void 0||h.call(s,u)})},cancel:()=>{c()}},new CountQueuingStrategy({highWaterMark:n})),s.promise]}subscribeRequest(e,t){return m(this,void 0,void 0,function*(){const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");const r=(s,a,o)=>m(this,void 0,void 0,function*(){if(s.subscription.type==="active")return;if(s.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(s.subscription.type));const c=el([a,o].filter(u=>typeof u<"u")),d=new be;s.subscription.completionFuture.promise.then(()=>{var u;return(u=d.resolve)===null||u===void 0?void 0:u.call(d)}).catch(u=>{var h;return(h=d.reject)===null||h===void 0?void 0:h.call(d,u)});const l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,o?.aborted){s.subscription.cancel();return}if(s.subscription.pendingRequestCount<=0){s.subscription.cancel();return}(u=d.reject)===null||u===void 0||u.call(d,Ie.cancelled())}};c.aborted&&l(),c.addEventListener("abort",l),yield d.promise,c.removeEventListener("abort",l)});switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new be,pendingRequestCount:1,cancel:()=>{var a,o;const c=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),c.type==="pending"&&((o=(a=c.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?Ie.timeout():Ie.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const s=tl(Og);yield r(n,t,s);return}case"pending":{n.subscription.pendingRequestCount+=1,yield r(n,t);return}case"active":return}})}querySubscribed(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type==="active").map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){var t;const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if(n.subscription.type!=="active"){ce.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=n.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(n.subscription.streamControllers,e);const r=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var n=x(r,2);const s=n[0],a=n[1];a();try{s.close()}catch(o){ce.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return m(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const s of e.entries()){var n=x(s,2);const a=n[0],o=n[1],c=new Set;for(const d of o)c.add(d.sid),!this.descriptors.has(d.sid)&&(this.handleSidReassigned(a,d)||(yield this.handleTrackPublished(a,d)));t.set(a,c)}for(const s of t.entries()){var r=x(s,2);const a=r[0],o=r[1];let c=Array.from(this.descriptors.entries()).filter(d=>{let l=x(d,2);return l[0],l[1].publisherIdentity===a}).map(d=>x(d,1)[0]).filter(d=>!o.has(d));for(const d of c)this.handleTrackUnpublished(d)}})}queryPublications(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return m(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){ce.error("Existing descriptor for track ".concat(t.sid));return}let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);const r=new al(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleSidReassigned(e,t){const n=Array.from(this.descriptors.entries()).find(u=>{let h=x(u,2);h[0];let p=h[1];return p.publisherIdentity===e&&p.info.pubHandle===t.pubHandle});if(!n)return!1;const r=x(n,2),s=r[0],a=r[1],o=a.info,c=o.name,d=o.usesE2ee;if(c!==t.name||d!==t.usesE2ee)return ce.warn("Info mismatch for ".concat(s,", treating as new publication")),!1;const l=t.sid;if(ce.debug("SID reassigned: ".concat(s," -> ").concat(l)),!this.descriptors.delete(s))return!1;switch(a.info.sid=l,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:l,subscribe:!0});break}return a.subscription.type==="active"&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){ce.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=x(n,2);const r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var n,r;const s=this.descriptors.get(t);if(!s){ce.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{ce.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(s.subscription.subcriptionHandle),s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{ce.debug("data track subscription activated",{sid:t,handle:e});const a=new Ag({info:s.info,publisherIdentity:s.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:s.pipelineOptions}),o=s.subscription;s.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)===null||r===void 0||r.call(n)}}}packetReceived(e){return m(this,void 0,void 0,function*(){let t;try{var n=Ki.fromBinary(e),r=x(n,1);t=r[0]}catch(c){ce.error("Failed to deserialize packet: ".concat(c));return}const s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){ce.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(s);if(!a){ce.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){ce.warn("Received packet for track ".concat(s," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const c of a.subscription.streamControllers.keys()){if(c.desiredSize!==null&&c.desiredSize<=0){ce.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(c.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const d=il.lossyIntoFrame(o);c.enqueue(d)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=x(t,2);const n=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(const r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(n=(t=r.subscription.completionFuture).reject)===null||n===void 0||n.call(t,Ie.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(const n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type==="pending"&&((t=(e=n.subscription.completionFuture).reject)===null||t===void 0||t.call(e,Ie.disconnected())),n.subscription.type==="active"&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Ji extends Be{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Mi[t]}static mtuTooShort(){return new Ji("MTU is too short to send frame",Mi.MtuTooShort)}}var Mi;(function(i){i[i.MtuTooShort=0]="MtuTooShort"})(Mi||(Mi={}));class Js{constructor(e,t){this.sequence=Ge.u16(0),this.frameNumber=Ge.u16(0),this.clock=Ot.rtpStartingNow(an.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?te.Single:e===0?te.Start:e===t-1?te.Final:te.Inter}*packetize(e,t){var n;const r=this.frameNumber.getThenIncrement(),s={marker:te.Inter,trackHandle:this.handle,sequence:Ge.u16(0),frameNumber:r,timestamp:(n=t?.now)!==null&&n!==void 0?n:this.clock.now(),extensions:e.extensions},a=new Kn(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Ji.mtuTooShort();const o=this.mtuSizeBytes-a,c=Math.ceil(e.payload.byteLength/o);for(let l=0,u=0;u<e.payload.byteLength;d=[l+1,u+o],l=d[0],u=d[1],d){var d;const h=this.sequence.getThenIncrement(),p=new Kn(Object.assign(Object.assign({},s),{marker:Js.computeFrameMarker(l,c),sequence:h})),f=Math.min(o,e.payload.byteLength-u),g=new Uint8Array(e.payload.buffer,e.payload.byteOffset+u,f);yield new Ki(p,g)}}}var qe;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.DuplicateName=1]="DuplicateName",i[i.Timeout=2]="Timeout",i[i.LimitReached=3]="LimitReached",i[i.Disconnected=4]="Disconnected",i[i.Cancelled=5]="Cancelled",i[i.InvalidName=6]="InvalidName",i[i.Unknown=7]="Unknown"})(qe||(qe={}));class ue extends Be{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=qe[t],this.rawMessage=n?.rawMessage}static notAllowed(e){return new ue("Data track publishing unauthorized",qe.NotAllowed,{rawMessage:e})}static duplicateName(e){return new ue("Track name already taken",qe.DuplicateName,{rawMessage:e})}static invalidName(e){return new ue("Track name is invalid",qe.InvalidName,{rawMessage:e})}static timeout(){return new ue("Publish data track timed-out. Does the LiveKit server support data tracks?",qe.Timeout)}static limitReached(e){return new ue("Data track publication limit reached",qe.LimitReached,{rawMessage:e})}static unknown(e,t){return new ue("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),qe.Unknown)}static disconnected(){return new ue("Room disconnected",qe.Disconnected)}static cancelled(){return new ue("Publish data track cancelled by caller",qe.Cancelled)}}var On;(function(i){i[i.TrackUnpublished=0]="TrackUnpublished",i[i.Dropped=1]="Dropped"})(On||(On={}));class jt extends Be{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=On[t]}static trackUnpublished(){return new jt("Track is no longer published",On.TrackUnpublished)}static dropped(e){return new jt("Frame was dropped",On.Dropped,{cause:e})}}var Nn;(function(i){i[i.Packetizer=0]="Packetizer",i[i.Encryption=1]="Encryption"})(Nn||(Nn={}));class Gn extends Be{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Nn[t]}static packetizer(e){return new Gn("Error packetizing frame",Nn.Packetizer,{cause:e})}static encryption(e){return new Gn("Error encrypting frame",Nn.Encryption,{cause:e})}}class Qi{constructor(e,t){this.trackSymbol=rl,this.isLocal=!0,this.typeSymbol=sl,this.handle=null,this.log=B,this.flushedFuture=new be,this.isFlushed=!0,this.handleManagerReset=()=>{var n,r;(r=(n=this.flushedFuture).resolve)===null||r===void 0||r.call(n),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=n=>{var r,s;this.isFlushed=n.isFlushed,n.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new be)},this.options=e,this.manager=t,this.log=ve(ae.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const r=new Qi(e,t);return r.handle=n,r}get info(){const e=this.descriptor;if(e?.type==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return m(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw jt.trackUnpublished();const t=il.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return m(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return m(this,void 0,void 0,function*(){if(!this.handle){B.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class Yi{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Js(e.info.pubHandle,Yi.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Vc(this,arguments,function*(){const t=yield pt(this.encryptIfNeeded(e));try{yield pt(yield*Lh(Fe(this.packetizer.packetize(t))))}catch(n){throw n instanceof Ji?Gn.packetizer(n):n}})}encryptIfNeeded(e){return m(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw Gn.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new Ke(t.keyIndex,t.iv),e})}}Yi.TRANSPORT_MTU_BYTES=16e3;const Le=ve(ae.DataTracks),Do={pending(){return{type:"pending",completionFuture:new be}},active(i,e){return{type:"active",info:i,publishState:"published",pipeline:new Yi({info:i,e2eeManager:e}),unpublishingFuture:new be}}},Lg=1e4;class Qs extends De.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new tm,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new Qs;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return m(this,void 0,void 0,function*(){var n,r,s,a,o;const c=this.getDescriptor(e);if(c?.type!=="active"||c.publishState==="unpublished")throw jt.trackUnpublished();if(c.publishState==="republishing")throw jt.dropped("Data track republishing");try{try{for(var d=!0,l=Fe(c.pipeline.processFrame(t)),u;u=yield l.next(),n=u.done,!n;d=!0){a=u.value,d=!1;const h=a,p=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,p+1),p===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!d&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw jt.dropped(h)}})}handlePacketSendComplete(e){var t;let n=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;n<0&&(Le.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),n=0),this.inFlightPacketCounter.set(e,n),n===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return m(this,void 0,void 0,function*(){const n=this.handleAllocator.get();if(!n)throw ue.limitReached();const r=tl(Lg),s=t?el([t,r]):r;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const a=Do.pending();this.descriptors.set(n,a);const o=()=>{var c,d;const l=this.descriptors.get(n);if(!l){Le.warn("No descriptor for ".concat(n));return}this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),l.type==="pending"&&((d=(c=l.completionFuture).reject)===null||d===void 0||d.call(c,r.aborted?ue.timeout():ue.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>n)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:Qi.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type==="active").map(e=>e.info)}unpublishRequest(e){return m(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){Le.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Le.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,s,a;const o=this.descriptors.get(e);if(!o){Le.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const c=t.data;Le.debug("SFU accepted publish request for handle ".concat(e),{sid:c.sid});const d=c.usesE2ee?this.e2eeManager:null;this.descriptors.set(c.pubHandle,Do.active(c,d)),(r=(n=o.completionFuture).resolve)===null||r===void 0||r.call(n)}else Le.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){Le.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Le.warn("Republish failed for track ".concat(e));return}Le.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,n;const r=this.descriptors.get(e);if(!r){Le.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){Le.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(n=(t=r.unpublishingFuture).resolve)===null||n===void 0||n.call(t)}sfuWillRepublishTracks(){var e,t;for(const r of this.descriptors.entries()){var n=x(r,2);const s=n[0],a=n[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,ue.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return m(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(const s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,ue.disconnected());break;case"active":(r=(n=s.unpublishingFuture).resolve)===null||r===void 0||r.call(n),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class J extends Error{constructor(e,t,n,r){super(t),this.code=e,this.message=Ao(t,J.MAX_MESSAGE_BYTES),this.data=n?Ao(n,J.MAX_DATA_BYTES):void 0,typeof r?.cause<"u"&&(this.cause=r?.cause)}static fromProto(e){return new J(e.code,e.message,e.data)}toProto(){return new kc({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new J(J.ErrorCode[e],J.ErrorMessage[e],t,n)}}J.MAX_MESSAGE_BYTES=256;J.MAX_DATA_BYTES=15360;J.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};J.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 ol=15360,cl="lk.rpc_request",dl="lk.rpc_response";var ye;(function(i){i.RPC_REQUEST_ID="lk.rpc_request_id",i.RPC_REQUEST_METHOD="lk.rpc_request_method",i.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",i.RPC_REQUEST_VERSION="lk.rpc_request_version"})(ye||(ye={}));const Ug=1,ll=2;function Ys(i){return new TextEncoder().encode(i).length}function Ao(i,e){if(Ys(i)<=e)return i;let t=0,n=i.length;const r=new TextEncoder;for(;t<n;){const s=Math.floor((t+n+1)/2);r.encode(i.slice(0,s)).length<=e?t=s:n=s-1}return i.slice(0,t)}class Fg extends De.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,c=o===void 0?15e3:o;return(function*(){const d=n.getRemoteParticipantClientProtocol(r);if(Ys(a)>ol&&d<Gr)throw J.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const l=n.getServerVersion();if(l&&nt(l,"1.8.0")<0)throw J.builtIn("UNSUPPORTED_SERVER");const u=Math.max(c,8e3),h=crypto.randomUUID(),p=new be;let f=null;const g=setTimeout(()=>{var k;n.pendingAcks.delete(h),(k=p.reject)===null||k===void 0||k.call(p,J.builtIn("CONNECTION_TIMEOUT")),n.pendingResponses.delete(h),f!==null&&clearTimeout(f)},7e3);n.pendingAcks.set(h,{resolve:()=>{clearTimeout(g)},participantIdentity:r}),n.pendingResponses.set(h,{completionFuture:p,participantIdentity:r}),yield n.publishRpcRequest(r,h,s,a,u,d),f=setTimeout(()=>{var k;n.pendingResponses.delete(h),(k=p.reject)===null||k===void 0||k.call(p,J.builtIn("RESPONSE_TIMEOUT"))},c);const b=p.promise.finally(()=>{clearTimeout(f),n.pendingAcks.has(h)&&(n.log.warn("RPC response received before ack",h),n.pendingAcks.delete(h),clearTimeout(g))});return[h,b]})()})}publishRpcRequest(e,t,n,r,s,a){return m(this,void 0,void 0,function*(){if(a>=Gr){yield this.outgoingDataStreamManager.sendText(r,{topic:cl,destinationIdentities:[e],attributes:{[ye.RPC_REQUEST_ID]:t,[ye.RPC_REQUEST_METHOD]:n,[ye.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[ye.RPC_REQUEST_VERSION]:"".concat(ll)}});return}this.emit("sendDataPacket",{packet:new Ce({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcRequest",value:new Ts({id:t,method:n,payload:r,responseTimeoutMs:s,version:Ug})}})})})}handleIncomingDataStream(e,t,n){return m(this,void 0,void 0,function*(){const r=n[ye.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(ye.RPC_REQUEST_ID," not set."));return}const s=this.pendingResponses.get(r);if(s&&s.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(r," arrived from unexpected sender ").concat(t,", expected ").concat(s.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(r,J.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var n,r;const s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).resolve)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,r;const s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).reject)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var n=x(a,2);const o=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var r=x(a,2);const o=r[0];var s=r[1];const c=s.participantIdentity,d=s.completionFuture;c===e&&((t=d.reject)===null||t===void 0||t.call(d,J.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class Bg extends De.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return m(this,void 0,void 0,function*(){var n;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,J.builtIn("UNSUPPORTED_VERSION"));return}const r=this.rpcHandlers.get(t.method);if(!r){this.publishRpcResponsePacket(e,t.id,null,J.builtIn("UNSUPPORTED_METHOD"));return}let s;try{s=yield r({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof J?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=J.builtIn("APPLICATION_ERROR","Uncaught error: ".concat((n=a?.message)!==null&&n!==void 0?n:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,n){return m(this,void 0,void 0,function*(){const r=n[ye.RPC_REQUEST_ID],s=n[ye.RPC_REQUEST_METHOD],a=parseInt(n[ye.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[ye.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(ye.RPC_REQUEST_ID," / ").concat(ye.RPC_REQUEST_METHOD," / ").concat(ye.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(ye.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,r,null,J.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,r),o!==ll){this.publishRpcResponsePacket(t,r,null,J.builtIn("UNSUPPORTED_VERSION"));return}let c;try{c=yield e.readAll()}catch(u){this.log.warn("Error reading RPC request payload: ".concat(u)),this.publishRpcResponsePacket(t,r,null,J.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:u}));return}const d=this.rpcHandlers.get(s);if(!d){this.publishRpcResponsePacket(t,r,null,J.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield d({requestId:r,callerIdentity:t,payload:c,responseTimeout:a})}catch(u){let h;u instanceof J?h=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(s,". Returning APPLICATION_ERROR instead."),u),h=J.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,r,null,h);return}yield this.publishRpcResponse(t,r,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Ce({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcAck",value:new Ui({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit("sendDataPacket",{packet:new Ce({destinationIdentities:[e],kind:St.RELIABLE,value:{case:"rpcResponse",value:new Ss({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:n??""}})}})})}publishRpcResponse(e,t,n){return m(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Gr){yield this.outgoingDataStreamManager.sendText(n,{topic:dl,destinationIdentities:[e],attributes:{[ye.RPC_REQUEST_ID]:t}});return}if(Ys(n)>ol){this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),this.publishRpcResponsePacket(e,t,null,J.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,n,null)})}}class jg extends xd{constructor(e,t,n,r,s,a){super(e,t,w.Kind.Audio,n,a),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=Hi(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Qe()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Qe())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(ns(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&ns(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{n.connect(r),n=r}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(I.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(I.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.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 e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}class ct extends De.EventEmitter{constructor(e,t,n,r){var s;super(),this.metadataMuted=!1,this.encryption=G.NONE,this.log=B,this.handleMuted=()=>{this.emit(I.Muted)},this.handleUnmuted=()=>{this.emit(I.Unmuted)},this.log=ve((s=r?.loggerName)!==null&&s!==void 0?s:ae.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=w.Source.Unknown}setTrack(e){this.track&&(this.track.off(I.Muted,this.handleMuted),this.track.off(I.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(I.Muted,this.handleMuted),e.on(I.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),H(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==G.NONE}get audioTrack(){if(tt(this.track))return this.track}get videoTrack(){if(mt(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=w.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===w.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(ct||(ct={}));class us extends ct{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(I.Ended)},this.handleCpuConstrained=()=>{this.track&&mt(this.track)&&this.emit(I.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(I.Ended,this.handleTrackEnded),this.track.off(I.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(I.Ended,this.handleTrackEnded),e.on(I.CpuConstrained,this.handleCpuConstrained))}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 e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(tt(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(me.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(me.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(me.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(me.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(me.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(me.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function $i(i,e){return m(this,void 0,void 0,function*(){i??(i={});let t=!1;const n=Id(i),r=n.audioProcessor,s=n.videoProcessor,a=n.optionsWithoutProcessor;let o=a.audio,c=a.video;if(r&&typeof a.audio=="object"&&(a.audio.processor=r),s&&typeof a.video=="object"&&(a.video.processor=s),i.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const h=a.audio.deviceId;a.audio.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:h}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const h=a.video.deviceId;a.video.deviceId={exact:h},t=!0,c=Object.assign(Object.assign({},a.video),{deviceId:{ideal:h}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const d=Ed(a,jd,qd),l=Ls(d),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(ge.userMediaPromiseMap.set("audioinput",u),u.catch(()=>ge.userMediaPromiseMap.delete("audioinput"))),a.video&&(ge.userMediaPromiseMap.set("videoinput",u),u.catch(()=>ge.userMediaPromiseMap.delete("videoinput")));try{const h=yield u;return yield Promise.all(h.getTracks().map(p=>m(this,void 0,void 0,function*(){const f=p.kind==="audio";let g;const b=f?l.audio:l.video;typeof b!="boolean"&&(g=b);const k=p.getSettings().deviceId;g?.deviceId&&nn(g.deviceId)!==k?g.deviceId=k:g||(g={deviceId:k});const S=Xm(p,g,e);return S.kind===w.Kind.Video?S.source=w.Source.Camera:S.kind===w.Kind.Audio&&(S.source=w.Source.Microphone),S.mediaStream=h,tt(S)&&r?yield S.setProcessor(r):mt(S)&&s&&(yield S.setProcessor(s)),S})))}catch(h){if(!t)throw h;return $i(Object.assign(Object.assign({},i),{audio:o,video:c}),e)}})}function qg(i){return m(this,void 0,void 0,function*(){return(yield $i({audio:!1,video:!0}))[0]})}function ul(i){return m(this,void 0,void 0,function*(){return(yield $i({audio:i??!0,video:!1}))[0]})}var yt;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(yt||(yt={}));function Vg(i){switch(i){case Jt.EXCELLENT:return yt.Excellent;case Jt.GOOD:return yt.Good;case Jt.POOR:return yt.Poor;case Jt.LOST:return yt.Lost;default:return yt.Unknown}}class hl extends De.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Un.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===$t.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Un.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=yt.Unknown,this.log=B,this.loggerOptions=a,this.log=ve((c=a?.loggerName)!==null&&c!==void 0?c:ae.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const n of this.trackPublications){var t=x(n,2);const r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(const n of this.trackPublications){var t=x(n,2);const r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new be,this.once(D.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;return!(!((e=this.getTrackPublication(w.Source.Camera)?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;return!(!((e=this.getTrackPublication(w.Source.Microphone)?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(w.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===$t.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==$t.ACTIVE&&this.emit(D.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(D.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(D.ParticipantNameChanged,e)}_setAttributes(e){const t=lp(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(D.AttributesChanged,t)}setPermissions(e){var t,n,r,s,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(D.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(D.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Vg(e),t!==this._connectionQuality&&this.emit(D.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>tt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(I.Muted,()=>{this.emit(D.TrackMuted,e)}),e.on(I.Unmuted,()=>{this.emit(D.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case w.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case w.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Wg(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Lc({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class Hg extends hl{constructor(e,t,n,r,s,a,o,c){super(e,t,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=G.NONE,this.e2eeStateMutex=new fe,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new be)},this.handleReconnected=()=>{var d,l;(l=(d=this.reconnectFuture)===null||d===void 0?void 0:d.resolve)===null||l===void 0||l.call(d),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var d,l,u,h,p,f;this.reconnectFuture&&(this.reconnectFuture.promise.catch(g=>this.log.warn(g.message)),(l=(d=this.reconnectFuture)===null||d===void 0?void 0:d.reject)===null||l===void 0||l.call(d,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((h=(u=this.signalConnectedFuture).reject)===null||h===void 0||h.call(u,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(f=(p=this.activeAgentFuture)===null||p===void 0?void 0:p.reject)===null||f===void 0||f.call(p,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=d=>{var l,u;d.participant&&this.updateInfo(d.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new be),(u=(l=this.signalConnectedFuture).resolve)===null||u===void 0||u.call(l)},this.handleSignalRequestResponse=d=>{const l=d.requestId,u=d.reason,h=d.message,p=this.pendingSignalRequests.get(l);switch(p&&(u!==Dt.OK&&p.reject(new Oa(h,u)),this.pendingSignalRequests.delete(l)),d.request.case){case"publishDataTrack":{let f;switch(d.reason){case Dt.NOT_ALLOWED:f=ue.notAllowed(d.message);break;case Dt.DUPLICATE_NAME:f=ue.duplicateName(d.message);break;case Dt.INVALID_NAME:f=ue.invalidName(d.message);break;case Dt.LIMIT_EXCEEDED:f=ue.limitReached(d.message);break;default:f=ue.unknown(d.reason,d.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(d.request.value.pubHandle,{type:"error",error:f});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(d=>Wg(d)))},this.onTrackUnmuted=d=>{this.onTrackMuted(d,d.isUpstreamPaused)},this.onTrackMuted=(d,l)=>{if(l===void 0&&(l=!0),!d.sid){this.log.error("could not update mute status for unpublished track",H(d));return}this.engine.updateMuteStatus(d.sid,l)},this.onTrackUpstreamPaused=d=>{this.log.debug("upstream paused",H(d)),this.onTrackMuted(d,!0)},this.onTrackUpstreamResumed=d=>{this.log.debug("upstream resumed",H(d)),this.onTrackMuted(d,d.isMuted)},this.onTrackFeatureUpdate=d=>{const l=this.audioTrackPublications.get(d.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(d.sid));return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(d,l)=>{this.log.debug("track cpu constrained",H(l)),this.emit(D.LocalTrackCpuConstrained,d,l)},this.handleSubscribedQualityUpdate=d=>m(this,void 0,void 0,function*(){var l,u,h,p,f;if(!(!((f=this.roomOptions)===null||f===void 0)&&f.dynacast))return;const g=this.videoTrackPublications.get(d.trackSid);if(!g){this.log.warn("received subscribed quality update for unknown track",{trackSid:d.trackSid});return}if(!g.videoTrack)return;const b=yield g.videoTrack.setPublishingCodecs(d.subscribedCodecs);try{for(var k=!0,S=Fe(b),M;M=yield S.next(),l=M.done,!l;k=!0){p=M.value,k=!1;const v=p;sp(v)&&(this.log.debug("publish ".concat(v," for ").concat(g.videoTrack.sid),H(g)),yield this.publishAdditionalCodecForTrack(g.videoTrack,v,g.options))}}catch(v){u={error:v}}finally{try{!k&&!l&&(h=S.return)&&(yield h.call(S))}finally{if(u)throw u.error}}}),this.handleLocalTrackUnpublished=d=>{const l=this.trackPublications.get(d.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",{trackSid:d.trackSid});return}this.unpublishTrack(l.track)},this.handleTrackEnded=d=>m(this,void 0,void 0,function*(){if(d.source===w.Source.ScreenShare||d.source===w.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",H(d)),this.unpublishTrack(d);else if(d.isUserProvided)yield d.mute();else if(at(d)||Ye(d))try{if(Me())try{const l=yield navigator?.permissions.query({name:d.source===w.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(d.source),H(d)),l.onchange=()=>{l.state!=="denied"&&(d.isMuted||d.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}d.isMuted||(this.log.debug("track ended, attempting to use a different device",H(d)),at(d)?yield d.restartTrack({deviceId:"default"}):yield d.restartTrack())}catch{this.log.warn("could not restart track, muting instead",H(d)),yield d.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=s,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=c}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==G.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(n,r)=>{const s=this.trackPublications.get(n);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let r=t.metadata,s=t.name,a=t.attributes;return(function*(){return new Ee((o,c)=>m(n,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=r??this.metadata)!==null&&d!==void 0?d:"",(l=s??this.name)!==null&&l!==void 0?l:"",a),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:f=>{c(f),u=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-p<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(f=>{let g=x(f,2),b=g[0],k=g[1];return this.attributes[b]===k||k===""&&!this.attributes[b]}))){this.pendingSignalRequests.delete(h),o();return}yield Te(50)}c(new Oa("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(w.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(w.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(w.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?G.GCM:G.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(n=>n.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return m(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let u;if(this.pendingPublishing.has(e)){const h=yield this.waitForPendingPublicationOfSource(e);return h||this.log.info("waiting for pending publication promise timed out",{source:e}),yield h?.unmute(),h}this.pendingPublishing.add(e);try{switch(e){case w.Source.Camera:u=yield this.createTracks({video:(s=n)!==null&&s!==void 0?s:!0});break;case w.Source.Microphone:u=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case w.Source.ScreenShare:u=yield this.createScreenTracks(Object.assign({},n));break;default:throw new ut(e)}}catch(h){throw u?.forEach(p=>{p.stop()}),h instanceof Error&&this.emit(D.MediaDevicesError,h,Zr(e)),this.pendingPublishing.delete(e),h}for(const h of u){const p=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===w.Source.Microphone&&tt(h)&&p.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),h.startPreConnectBuffer())}try{const h=[];for(const f of u)this.log.info("publishing track",H(f)),h.push(this.publishTrack(f,r));const p=yield Promise.all(h);var c=x(p,1);o=c[0]}catch(h){throw u?.forEach(p=>{p.stop()}),h}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",{source:e})),o&&o.track)if(e===w.Source.ScreenShare){const u=[this.unpublishTrack(o.track)],h=this.getTrackPublication(w.Source.ScreenShareAudio);h&&h.track&&u.push(this.unpublishTrack(h.track));var d=yield Promise.all(u),l=x(d,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(w.Source.Camera)||this.pendingPublishing.has(w.Source.Microphone))){this.pendingPublishing.add(w.Source.Camera),this.pendingPublishing.add(w.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(w.Source.Camera),this.pendingPublishing.delete(w.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const r=Ed(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield $i(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(tt(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=w.Source.Microphone,this.emit(D.AudioStreamAcquired)),mt(s)&&(this.cameraError=void 0,s.source=w.Source.Camera),s))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ns("getDisplayMedia not supported");e.resolution===void 0&&!kp()&&(e.resolution=xs.h1080fps30.resolution);const t=op(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new ut("no video track found");const s=new Ii(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=w.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(n.getAudioTracks().length>0){this.emit(D.AudioStreamAcquired);const o=new Ri(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=w.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,n)=>{const r=()=>{clearTimeout(o),this.engine.off(P.Restarted,s),this.engine.off(P.Closing,a)},s=()=>{r(),t()},a=()=>{r(),n(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),n(new Error("timed out waiting for engine restart"))},e);this.engine.once(P.Restarted,s),this.engine.once(P.Closing,a)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return(function*(){var c,d,l,u;at(n)&&n.setAudioContext(s.audioContext),yield(c=s.reconnectFuture)===null||c===void 0?void 0:c.promise,s.republishPromise&&!a&&(yield s.republishPromise),rn(n)&&s.pendingPublishPromises.has(n)&&(yield s.pendingPublishPromises.get(n));let h;if(n instanceof MediaStreamTrack)h=n.getConstraints();else{h=n.constraints;let S;switch(n.source){case w.Source.Microphone:S="audioinput";break;case w.Source.Camera:S="videoinput"}S&&s.activeDeviceMap.has(S)&&(h=Object.assign(Object.assign({},h),{deviceId:s.activeDeviceMap.get(S)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Ri(n,h,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":n=new Ii(n,h,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new ut("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let p;if(s.trackPublications.forEach(S=>{S.track&&S.track===n&&(p=S)}),p)return s.log.warn("track has already been published, skipping",H(p)),p;const f=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,b=(d=f.forceStereo)!==null&&d!==void 0?d:g;b&&(f.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",H(n)),f.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=f.dtx)!==null&&l!==void 0||(f.dtx=!1),(u=f.red)!==null&&u!==void 0||(f.red=!1)),!Sp()&&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"),f.simulcast=!1),f.source&&(n.source=f.source);const k=new Promise((S,M)=>m(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==we.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:H(n)});let v=!1;const T=setTimeout(()=>{v=!0,n.stop(),M(new Aa("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(T),v)return;const C=yield this.publish(n,f,b);S(C)}else try{const v=yield this.publish(n,f,b);S(v)}catch(v){M(v)}}catch(v){M(v)}}));s.pendingPublishPromises.set(n,k);try{return yield k}catch(S){if(!o&&S instanceof wt)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:S}),s.pendingPublishPromises.delete(n),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(n,r,a,!0);throw S}finally{s.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new be),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",H(e)),!1;const t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(s=>up(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",H(e)),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var r,s,a,o,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(e))throw new Aa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>rn(e)&&A.source===e.source)&&e.source!==w.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),H(e)),t.stopMicTrackOnMute&&tt(e)&&(e.stopOnMute=!0),e.source===w.Source.ScreenShare&&Wt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!gp()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!fp()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=cs),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>t.videoCodec===In(A.mime))||(t.videoCodec=In(this.enabledPublishVideoCodecs[0].mime)));const f=t.videoCodec;e.on(I.Muted,this.onTrackMuted),e.on(I.Unmuted,this.onTrackUnmuted),e.on(I.Ended,this.handleTrackEnded),e.on(I.UpstreamPaused,this.onTrackUpstreamPaused),e.on(I.UpstreamResumed,this.onTrackUpstreamResumed),e.on(I.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=[],b=!(!((r=t.dtx)!==null&&r!==void 0)||r),k=e.getSourceTrackSettings();k.autoGainControl&&g.push(me.TF_AUTO_GAIN_CONTROL),k.echoCancellation&&g.push(me.TF_ECHO_CANCELLATION),k.noiseSuppression&&g.push(me.TF_NOISE_SUPPRESSION),k.channelCount&&k.channelCount>1&&g.push(me.TF_STEREO),b&&g.push(me.TF_NO_DTX),at(e)&&e.hasPreConnectBuffer&&g.push(me.TF_PRECONNECT_BUFFER);const S=this.normalizeRequestedFrameMetadataOptions(e,t),M=new Bn({cid:e.mediaStreamTrack.id,name:t.name,type:w.kindToProto(e.kind),muted:e.isMuted,source:w.sourceToProto(e.source),disableDtx:b,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:g,packetTrailerFeatures:S});let v;if(e.kind===w.Kind.Video){let A;try{A=yield e.waitForDimensions()}catch{const j=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:jn.h720.resolution;A={width:j.width,height:j.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},H(e)),{dims:A}))}M.width=A.width,M.height=A.height,Ye(e)&&(Ze(f)&&(e.source===w.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",H(e)))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),M.simulcastCodecs=[new Lr({codec:f,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:cs}),t.backupCodec&&f!==t.backupCodec.codec&&M.encryption===G.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),M.simulcastCodecs.push(new Lr({codec:t.backupCodec.codec,cid:""})))),v=Pi(e.source===w.Source.ScreenShare,M.width,M.height,t),M.layers=mo(M.width,M.height,v,Ze(t.videoCodec))}else e.kind===w.Kind.Audio&&(v=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new ee("cannot publish track when not connected");const T=()=>m(this,void 0,void 0,function*(){var A,j,F,q;if(!this.engine.pcManager)throw new ee("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),Ye(e)&&(e.publishOptions=t),this.emit(D.LocalSenderCreated,e.sender,e),Ye(e)&&((A=t.degradationPreference)!==null&&A!==void 0||(t.degradationPreference=og(e)),e.setDegradationPreference(t.degradationPreference)),v){if(Wt()&&e.kind===w.Kind.Audio){let X;for(const he of this.engine.pcManager.publisher.getTransceivers())if(he.sender===e.sender){X=he;break}X&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:X,codec:"opus",maxbr:!((j=v[0])===null||j===void 0)&&j.maxBitrate?v[0].maxBitrate/1e3:0})}else if(e.codec&&Od(e.codec)){const X=Ze(e.codec)?(q=(F=v[0])===null||F===void 0?void 0:F.maxBitrate)!==null&&q!==void 0?q:0:v.reduce((he,it)=>{var Ae;return he+((Ae=it.maxBitrate)!==null&&Ae!==void 0?Ae:0)},0);X>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:M.cid,codec:e.codec,maxbr:X/1e3,isScreenShare:e.source===w.Source.ScreenShare})}}yield this.engine.negotiate()});let C;const O=new Promise((A,j)=>m(this,void 0,void 0,function*(){var F;try{C=yield this.engine.addTrack(M),A(C)}catch(q){if(e.sender&&!((F=this.engine.pcManager)===null||F===void 0)&&F.publisher){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(X){this.log.error(X)}yield this.engine.negotiate().catch(X=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},H(e)),{error:X}))})}j(q)}}));if(this.enabledPublishVideoCodecs.length>0&&S.length===0)C=(yield Promise.all([O,T()]))[0];else{C=yield O;let A;if(C.codecs.forEach(j=>{A===void 0&&(A=j.mimeType)}),A&&e.kind===w.Kind.Video){const j=In(A);j!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},H(e)),{codec:j})),t.videoCodec=j,v=Pi(e.source===w.Source.ScreenShare,M.width,M.height,t))}yield T()}const L=new us(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(L.on(I.CpuConstrained,A=>this.onTrackCpuConstrained(A,L)),L.options=t,e.sid=C.sid,Ye(e)&&(e.publishOptions=t,M.width&&M.height&&(e.lastEncodedDimensions={width:M.width,height:M.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:v,trackInfo:C}),Ye(e)?e.startMonitor(this.engine.client):at(e)&&e.startMonitor(),this.addTrackPublication(L),this.emit(D.LocalTrackPublished,L),at(e)&&C.audioFeatures.includes(me.TF_PRECONNECT_BUFFER)){const A=e.getPreConnectBuffer(),j=e.getPreConnectBufferMimeType();this.on(D.LocalTrackSubscribed,F=>{if(F.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",H(e)),e.stopPreConnectBuffer()}}),A&&new Promise((F,q)=>m(this,void 0,void 0,function*(){var X,he,it,Ae,ft,fn;try{this.log.debug("waiting for agent",H(e));const tr=setTimeout(()=>{q(new Error("agent not active within 10 seconds"))},1e4),Pl=yield this.waitUntilActiveAgentPresent();clearTimeout(tr),this.log.debug("sending preconnect buffer",H(e));const ta=yield this.streamBytes({name:"preconnect-buffer",mimeType:j,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Pl.identity],attributes:{trackId:L.trackSid,sampleRate:String((ft=k.sampleRate)!==null&&ft!==void 0?ft:"48000"),channels:String((fn=k.channelCount)!==null&&fn!==void 0?fn:"1")}});try{for(var pe=!0,_t=Fe(A),er;er=yield _t.next(),X=er.done,!X;pe=!0){Ae=er.value,pe=!1;const nr=Ae;yield ta.write(nr)}}catch(nr){he={error:nr}}finally{try{!pe&&!X&&(it=_t.return)&&(yield it.call(_t))}finally{if(he)throw he.error}}yield ta.close(),F()}catch(tr){q(tr)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",H(e))}).catch(F=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},H(e)),{error:F}))})}return L})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Hn((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;const r=(n=t.frameMetadata)!==null&&n!==void 0?n:t.packetTrailer;if(e.kind!==w.Kind.Video||!Ci(r))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),H(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const s=zp(r),a=Kp(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var r;if(this.encryptionType!==G.NONE)return;let s;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(s=p)}),!s)throw new ut("track is not published");if(!Ye(e))throw new ut("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),n),o=Hd(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",H(e));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=this.normalizeRequestedFrameMetadataOptions(e,a),l=new Bn({cid:c.mediaStreamTrack.id,type:w.kindToProto(e.kind),muted:e.isMuted,source:w.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:d,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=mo(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new ee("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:h})})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,r;if(rn(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",H(e)),yield l)}const s=this.getPublicationForTrack(e),a=s?H(s):void 0;if(this.log.info("unpublishing track",a),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=s.track,e.off(I.Muted,this.onTrackMuted),e.off(I.Unmuted,this.onTrackUnmuted),e.off(I.Ended,this.handleTrackEnded),e.off(I.UpstreamPaused,this.onTrackUpstreamPaused),e.off(I.UpstreamResumed,this.onTrackUpstreamResumed),e.off(I.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Z.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(c)}catch(l){this.log.warn(l),o=!0}if(Ye(e)){for(const l of e.simulcastCodecs){var d=x(l,2);const u=d[1];if(u.sender){try{o=this.engine.removeTrack(u.sender)}catch(h){this.log.warn(h),o=!0}u.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case w.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case w.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(D.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(t=>this.unpublishTrack(t)))).filter(t=>!!t)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Ee((s,a)=>m(n,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>m(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),r&&!d.isMuted&&d.source!==w.Source.ScreenShare&&d.source!==w.Source.ScreenShareAudio&&(at(d)||Ye(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",{track:c.trackSid}),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),s()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const s=r.reliable?W.RELIABLE:W.LOSSY,a=r.reliable?St.RELIABLE:St.LOSSY,o=r.destinationIdentities,c=r.topic;let d=new ks({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:c});const l=new Ce({kind:a,value:{case:"user",value:d}});yield n.engine.sendDataPacket(l,s)})()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new Ce({kind:St.RELIABLE,value:{case:"sipDtmf",value:new bc({code:e,digit:t})}});yield this.engine.sendDataPacket(n,W.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new Ce({value:{case:"chatMessage",value:new Si(Object.assign(Object.assign({},n),{timestamp:ne.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,W.RELIABLE),this.emit(D.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Ce({value:{case:"chatMessage",value:new Si(Object.assign(Object.assign({},n),{timestamp:ne.parse(n.timestamp),editTimestamp:ne.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,W.RELIABLE),this.emit(D.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let n=x(t,2);return n[0],n[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(n=s.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},H(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,n,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.call(t,e):(s=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||s===void 0||s.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new be),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const r=n.track;r&&(e instanceof MediaStreamTrack?(at(r)||Ye(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const n=Array.from(this.pendingPublishPromises.entries()).find(r=>x(r,1)[0].source===e);if(n)return n[1];yield Te(20)}})}publishDataTrack(e){return m(this,void 0,void 0,function*(){const t=new Qi(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class Oo extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class zg extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,r;super.set(e,t);const s=(n=this.pending)===null||n===void 0?void 0:n.get(e);if(s){for(const a of s)a.isResolved||(r=a.resolve)===null||r===void 0||r.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return m(this,void 0,void 0,function*(){const n=this.get(e);if(typeof n<"u")return n;if(t?.aborted)throw new Oo("The operation was aborted.",t.reason);const r=new be(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),s=this.pending.get(e);if(s?s.push(r):this.pending.set(e,[r]),t){const a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new Oo("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}}class Kg extends ct{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=s=>{this.setTrack(void 0),this.emit(I.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.visible=s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensionsAdaptiveStream=s,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new qi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Tc({participantSid:"",trackSids:[this.trackSid]})]});this.emit(I.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?ct.SubscriptionStatus.Unsubscribed:super.isSubscribed?ct.SubscriptionStatus.Subscribed:ct.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ct.PermissionStatus.Allowed:ct.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(mr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&mr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:xe.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(I.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(I.VisibilityChanged,this.handleVisibilityChange),r.off(I.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(I.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(I.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(I.VisibilityChanged,this.handleVisibilityChange),e.on(I.Ended,this.handleEnded),this.emit(I.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(I.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?I.Muted:I.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(I.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(I.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return mr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ac({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===w.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)xa(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const n=hp(this.trackInfo,this.requestedMaxQuality);n&&xa(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:xe.HIGH})),e.quality=xe.HIGH)}this.emit(I.UpdateSettings,e)}}class Di extends hl{static fromParticipantInfo(e,t,n,r){return new Di(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map(s=>{const a=Ei.from(s);return new al(a,r,{publisherIdentity:t.identity})}),t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,s,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Un.STANDARD,d=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:Sd,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,n||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new zg(d.map(h=>[h.info.name,h])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(I.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),H(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(I.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(I.SubscriptionPermissionChanged,t=>{this.emit(D.TrackSubscriptionPermissionChanged,e,t)}),e.on(I.SubscriptionStatusChanged,t=>{this.emit(D.TrackSubscriptionStatusChanged,e,t)}),e.on(I.Subscribed,t=>{this.emit(D.TrackSubscribed,t,e)}),e.on(I.Unsubscribed,t=>{this.emit(D.TrackUnsubscribed,t,e)}),e.on(I.SubscriptionFailed,t=>{this.emit(D.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:w.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:w.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(D.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),H(o))),this.emit(D.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new qs(e,t,r,s):d=new jg(e,t,r,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(n),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&rs(d)&&tt(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const c=w.kindFromProto(r.type);if(!c)return;o=new Kg(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),n.set(r.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==w.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:H(d),newTrack:H(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),H(r))),this.unpublishTrack(r.trackSid,!0))}),n.forEach(r=>{this.emit(D.TrackPublished,r)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case w.Kind.Audio:this.audioTrackPublications.delete(e);break;case w.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(D.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var r;tt(n.track)&&rs(n.track)&&t.push(n.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const n of this.dataTracks.entries()){var t=x(n,2);const r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var K;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(K||(K={}));const Gg=4*1e3,Jg=30*1e3;class mn extends De.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,r,s,a,o,c,d;if(super(),t=this,this.state=K.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new fe,this.isVideoPlaybackBlocked=!1,this.log=B,this.statsLog=B,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(l,u,h)=>m(this,void 0,void 0,function*(){var p;if(!yp())throw Qe()?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 f=yield this.disconnectLock.lock();if(this.state===K.Connected)return this.log.info("already connected to room ".concat(this.name)),f(),Promise.resolve();if(this.connectFuture)return f(),this.connectFuture.promise;this.setAndEmitConnectionState(K.Connecting),((p=this.regionUrlProvider)===null||p===void 0?void 0:p.getServerUrl().toString())!==Nd(l)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),un(new URL(l))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new z(l,u):this.regionUrlProvider.updateToken(u),this.regionUrlProvider.fetchRegionSettings().then(k=>{var S;(S=this.regionUrlProvider)===null||S===void 0||S.setServerReportedRegions(k)}).catch(k=>{this.log.warn("could not fetch region settings",{error:k})}));const g=(k,S,M)=>m(this,void 0,void 0,function*(){var v,T;this.abortController&&this.abortController.abort();const C=new AbortController;this.abortController=C,f?.();try{if(yield sn.getInstance().getBackOffPromise(l),C.signal.aborted)throw N.cancelled("Connection attempt aborted");yield this.attemptConnection(M??l,u,h,C),this.abortController=void 0,k()}catch(O){if(this.regionUrlProvider&&O instanceof N&&O.reason!==Q.Cancelled&&O.reason!==Q.NotAllowed){let L=null;try{this.log.debug("Fetching next region"),L=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(A){if(A instanceof N&&(A.status===401||A.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),S(A);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(O.reason)&&(this.log.debug("Adding failed connection attempt to back off"),sn.getInstance().addFailedConnectionAttempt(l)),L&&!(!((T=this.abortController)===null||T===void 0)&&T.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(O.message,". Retrying with another region: ").concat(L)),this.recreateEngine(!0),yield g(k,S,L)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ja(O)),S(O))}else{let L=Ne.UNKNOWN_REASON;O instanceof N&&(L=ja(O)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,L),S(O)}}}),b=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new be((k,S)=>{g(k,S,b)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(l,u,h,p,f,g)=>m(this,void 0,void 0,function*(){const b=yield h.join(l,u,{autoSubscribe:p.autoSubscribe,adaptiveStream:typeof f.adaptiveStream=="object"?!0:f.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(f),maxRetries:p.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:p.websocketTimeout},g.signal,!f.singlePeerConnection),k=b.joinResponse,S=b.serverInfo;if(this.serverInfo=S,!S.version)throw new Xh("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),f.dynacast=!1),k}),this.applyJoinResponse=l=>{const u=l.participant;if(this.localParticipant.sid=u.sid,this.localParticipant.identity=u.identity,this.localParticipant.setEnabledPublishCodecs(l.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(l.sifTrailer)}catch(h){this.log.error(h instanceof Error?h.message:"Could not set SifTrailer",{error:h})}this.handleParticipantUpdates([u,...l.otherParticipants]),l.room&&this.handleRoomUpdate(l.room)},this.attemptConnection=(l,u,h,p)=>m(this,void 0,void 0,function*(){var f,g;this.state===K.Reconnecting||this.isResuming||!((f=this.engine)===null||f===void 0)&&f.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((g=this.regionUrlProvider)===null||g===void 0)&&g.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ks),h),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const b=yield this.connectSignal(l,u,this.engine,this.connOptions,this.options,p);this.applyJoinResponse(b),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(b){yield this.engine.close(),this.recreateEngine();const k=p.signal.aborted?N.cancelled("Signal connection aborted"):N.serverUnreachable("could not establish signal connection");throw b instanceof Error&&(k.message="".concat(k.message,": ").concat(b.message)),b instanceof N&&(k.reason=b.reason,k.status=b.status),this.log.debug("error trying to establish signal connection",{error:b}),k}if(p.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),N.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,p)}catch(b){throw yield this.engine.close(),this.recreateEngine(),b}Me()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Me()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(K.Connected),this.emit(E.Connected),sn.getInstance().resetFailedConnectionAttempts(l),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var l=arguments.length,u=new Array(l),h=0;h<l;h++)u[h]=arguments[h];return m(t,[...u],void 0,function(){var p=this;let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var g,b,k;const S=yield p.disconnectLock.lock();try{if(p.state===K.Disconnected){p.log.debug("already disconnected");return}if(p.log.info("disconnect from room"),p.state===K.Connecting||p.state===K.Reconnecting||p.isResuming){const M="Abort connection attempt due to user initiated disconnect";p.log.warn(M),(g=p.abortController)===null||g===void 0||g.abort(M),(k=(b=p.connectFuture)===null||b===void 0?void 0:b.reject)===null||k===void 0||k.call(b,N.cancelled("Client initiated disconnect")),p.connectFuture=void 0}p.engine&&(p.engine.client.isDisconnected||(yield p.engine.client.sendLeave()),yield p.engine.close()),p.handleDisconnect(f,Ne.CLIENT_INITIATED),p.engine=void 0}finally{S()}})()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const l=[],u=Re();if(u&&u.os==="iOS"){const h="livekit-dummy-audio-el";let p=document.getElementById(h);if(!p){p=document.createElement("audio"),p.id=h,p.autoplay=!0,p.hidden=!0;const f=pr();f.enabled=!0;const g=new MediaStream([f]);p.srcObject=g,document.addEventListener("visibilitychange",()=>{p&&(p.srcObject=document.hidden?null:g,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(p),this.once(E.Disconnected,()=>{p?.remove(),p=null})}l.push(p)}this.remoteParticipants.forEach(h=>{h.audioTrackPublications.forEach(p=>{p.track&&p.track.attachedElements.forEach(f=>{l.push(f)})})});try{yield Promise.all([this.acquireAudioContext(),...l.map(h=>(this.options.webAudioMix||(h.muted=!1),h.play()))]),this.handleAudioPlaybackStarted()}catch(h){throw this.handleAudioPlaybackFailed(h),h}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const l=[];for(const u of this.remoteParticipants.values())u.videoTrackPublications.forEach(h=>{var p;(p=h.track)===null||p===void 0||p.attachedElements.forEach(f=>{l.includes(f)||l.push(f)})});yield Promise.all(l.map(u=>u.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(u=>{u.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const l of this.remoteParticipants.values())this.handleParticipantDisconnected(l.identity,l);this.setAndEmitConnectionState(K.Reconnecting)&&this.emit(E.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=l=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(l.serverRegion),{region:l.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(l);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(u){this.log.error("error trying to re-publish tracks after reconnection",{error:u})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:l.serverRegion})}catch{return}this.setAndEmitConnectionState(K.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=l=>{var u;for(const p of l){if(p.identity===this.localParticipant.identity){this.localParticipant.updateInfo(p);continue}p.identity===""&&(p.identity=(u=this.sidToIdentity.get(p.sid))!==null&&u!==void 0?u:"");let f=this.remoteParticipants.get(p.identity);p.state===$t.DISCONNECTED?this.handleParticipantDisconnected(p.identity,f,p.disconnectReason===Ne.UNKNOWN_REASON?void 0:p.disconnectReason):this.getOrCreateParticipant(p.identity,p)}const h=new Map(l.filter(p=>p.identity!==this.localParticipant.identity).map(p=>[p.identity,p.dataTracks.map(f=>Ei.from(f))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(h)},this.handleActiveSpeakersUpdate=l=>{const u=[],h={};l.forEach(p=>{if(h[p.sid]=!0,p.sid===this.localParticipant.sid)this.localParticipant.audioLevel=p.level,this.localParticipant.setIsSpeaking(!0),u.push(this.localParticipant);else{const f=this.getRemoteParticipantBySid(p.sid);f&&(f.audioLevel=p.level,f.setIsSpeaking(!0),u.push(f))}}),h[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(p=>{h[p.sid]||(p.audioLevel=0,p.setIsSpeaking(!1))}),this.activeSpeakers=u,this.emitWhenConnected(E.ActiveSpeakersChanged,u)},this.handleSpeakersChanged=l=>{const u=new Map;this.activeSpeakers.forEach(p=>{const f=this.remoteParticipants.get(p.identity);f&&f.sid!==p.sid||u.set(p.sid,p)}),l.forEach(p=>{let f=this.getRemoteParticipantBySid(p.sid);p.sid===this.localParticipant.sid&&(f=this.localParticipant),f&&(f.audioLevel=p.level,f.setIsSpeaking(p.active),p.active?u.set(p.sid,f):u.delete(p.sid))});const h=Array.from(u.values());h.sort((p,f)=>f.audioLevel-p.audioLevel),this.activeSpeakers=h,this.emitWhenConnected(E.ActiveSpeakersChanged,h)},this.handleStreamStateUpdate=l=>{l.streamStates.forEach(u=>{const h=this.getRemoteParticipantBySid(u.participantSid);if(!h)return;const p=h.getTrackPublicationBySid(u.trackSid);if(!p||!p.track)return;const f=w.streamStateFromProto(u.state),g=p.track.streamState;p.track.setStreamState(f),f!==g&&(h.emit(D.TrackStreamStateChanged,p,p.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,p,p.track.streamState,h))})},this.handleSubscriptionPermissionUpdate=l=>{const u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);h&&h.setAllowed(l.allowed)},this.handleSubscriptionError=l=>{this.cancelPendingTrackAdded(l.trackSid);const u=Array.from(this.remoteParticipants.values()).find(p=>p.trackPublications.has(l.trackSid));if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);h&&h.setSubscriptionError(l.err)},this.handleDataPacket=(l,u)=>{const h=this.remoteParticipants.get(l.participantIdentity);if(l.value.case==="user")this.handleUserPacket(h,l.value.value,l.kind,u);else if(l.value.case==="transcription")this.handleTranscription(h,l.value.value);else if(l.value.case==="sipDtmf")this.handleSipDtmf(h,l.value.value);else if(l.value.case==="chatMessage")this.handleChatMessage(h,l.value.value);else if(l.value.case==="metrics")this.handleMetrics(l.value.value,h);else if(l.value.case==="streamHeader"||l.value.case==="streamChunk"||l.value.case==="streamTrailer")this.handleDataStream(l,u);else if(l.value.case==="rpcRequest"){const p=l.value.value;this.rpcServerManager.handleIncomingRpcRequest(l.participantIdentity,p)}else if(l.value.case==="rpcResponse"){const p=l.value.value;switch(p.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(p.requestId,p.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(p.requestId,J.fromProto(p.value.value));break;default:this.log.warn("Unknown rpcResponse.value.case: ".concat(p.value.case),this.logContext);break}}else l.value.case==="rpcAck"&&this.rpcClientManager.handleIncomingRpcAck(l.value.value.requestId)},this.handleUserPacket=(l,u,h,p)=>{this.emit(E.DataReceived,u.payload,l,h,u.topic,p),l?.emit(D.DataReceived,u.payload,h,p)},this.handleSipDtmf=(l,u)=>{this.emit(E.SipDTMFReceived,u,l),l?.emit(D.SipDTMFReceived,u)},this.handleTranscription=(l,u)=>{const h=u.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(u.transcribedParticipantIdentity),p=h?.trackPublications.get(u.trackId),f=Pp(u,this.transcriptionReceivedTimes);p?.emit(I.TranscriptionReceived,f),h?.emit(D.TranscriptionReceived,f,p),this.emit(E.TranscriptionReceived,f,h,p)},this.handleChatMessage=(l,u)=>{const h=Ip(u);this.emit(E.ChatMessage,h,l)},this.handleMetrics=(l,u)=>{this.emit(E.MetricsReceived,l,u)},this.handleDataStream=(l,u)=>{this.incomingDataStreamManager.handleDataStreamPacket(l,u)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=l=>{this.log.warn("could not playback audio",{error:l}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var l;((l=Re())===null||l===void 0?void 0:l.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=l=>{const u=this.roomInfo;this.roomInfo=l,u&&u.metadata!==l.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,l.metadata),u?.activeRecording!==l.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,l.activeRecording)},this.handleConnectionQualityUpdate=l=>{l.updates.forEach(u=>{if(u.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(u.quality);return}const h=this.getRemoteParticipantBySid(u.participantSid);h&&h.setConnectionQuality(u.quality)})},this.getRemoteParticipantClientProtocol=l=>{var u,h;return(h=(u=this.remoteParticipants.get(l))===null||u===void 0?void 0:u.clientProtocol)!==null&&h!==void 0?h:Sd},this.getRemoteParticipantCapabilities=l=>{var u,h;return(h=(u=this.remoteParticipants.get(l))===null||u===void 0?void 0:u.capabilities)!==null&&h!==void 0?h:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.logWebRTCStats=()=>m(this,void 0,void 0,function*(){var l,u,h,p;const f=(l=this.engine)===null||l===void 0?void 0:l.pcManager;if(f)try{const g=yield Promise.all([f.publisher.getStats(),(u=f.subscriber)===null||u===void 0?void 0:u.getStats()]),b=x(g,2),k=b[0],S=b[1],M=k&&Qr(k),v=S&&Qr(S);this.statsLog.info("webrtc stats",{publisher:M?.connection,subscriber:v?.connection,inbound:[...(h=M?.inbound)!==null&&h!==void 0?h:[],...(p=v?.inbound)!==null&&p!==void 0?p:[]],outbound:M?.outbound})}catch(g){this.statsLog.debug("could not collect webrtc stats",{error:g})}}),this.onLocalParticipantMetadataChanged=l=>{this.emit(E.ParticipantMetadataChanged,l,this.localParticipant)},this.onLocalParticipantNameChanged=l=>{this.emit(E.ParticipantNameChanged,l,this.localParticipant)},this.onLocalAttributesChanged=l=>{this.emit(E.ParticipantAttributesChanged,l,this.localParticipant)},this.onLocalTrackMuted=l=>{this.emit(E.TrackMuted,l,this.localParticipant)},this.onLocalTrackUnmuted=l=>{this.emit(E.TrackUnmuted,l,this.localParticipant)},this.onTrackProcessorUpdate=l=>{var u;(u=l?.onPublish)===null||u===void 0||u.call(l,this)},this.onLocalTrackPublished=l=>m(this,void 0,void 0,function*(){var u,h,p,f,g,b;(u=l.track)===null||u===void 0||u.on(I.TrackProcessorUpdate,this.onTrackProcessorUpdate),(h=l.track)===null||h===void 0||h.on(I.Restarted,this.onLocalTrackRestarted),(g=(f=(p=l.track)===null||p===void 0?void 0:p.getProcessor())===null||f===void 0?void 0:f.onPublish)===null||g===void 0||g.call(f,this),this.emit(E.LocalTrackPublished,l,this.localParticipant),at(l.track)&&(yield l.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,l);const k=yield(b=l.track)===null||b===void 0?void 0:b.getDeviceId(!1),S=Zr(l.source);S&&k&&k!==this.localParticipant.activeDeviceMap.get(S)&&(this.localParticipant.activeDeviceMap.set(S,k),this.emit(E.ActiveDeviceChanged,S,k))}),this.onLocalTrackUnpublished=l=>{var u,h;(u=l.track)===null||u===void 0||u.off(I.TrackProcessorUpdate,this.onTrackProcessorUpdate),(h=l.track)===null||h===void 0||h.off(I.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,l,this.localParticipant)},this.onLocalTrackRestarted=l=>m(this,void 0,void 0,function*(){const u=yield l.getDeviceId(!1),h=Zr(l.source);h&&u&&u!==this.localParticipant.activeDeviceMap.get(h)&&(this.log.debug("local track restarted, setting ".concat(h," ").concat(u," active")),this.localParticipant.activeDeviceMap.set(h,u),this.emit(E.ActiveDeviceChanged,h,u))}),this.onLocalConnectionQualityChanged=l=>{this.emit(E.ConnectionQualityChanged,l,this.localParticipant)},this.onMediaDevicesError=(l,u)=>{this.emit(E.MediaDevicesError,l,u)},this.onLocalParticipantPermissionsChanged=l=>{this.emit(E.ParticipantPermissionsChanged,l,this.localParticipant)},this.onLocalChatMessageSent=l=>{this.emit(E.ChatMessage,l,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Um),e),this.log=ve((n=this.options.loggerName)!==null&&n!==void 0?n:ae.Room,()=>this.logContext),this.statsLog=ve(ae.Stats,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},jd),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},qd),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Lm),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new yg((r=this.options.dataStream)===null||r===void 0?void 0:r.maxPayloadByteLength),this.outgoingDataStreamManager=new Rg(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new xg({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",l=>{this.engine.client.sendUpdateDataSubscription(l.sid,l.subscribe)}).on("trackPublished",l=>{var u;l.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(E.DataTrackPublished,l.track),(u=this.remoteParticipants.get(l.track.publisherIdentity))===null||u===void 0||u.addRemoteDataTrack(l.track))}).on("trackUnpublished",l=>{var u;l.publisherIdentity!==this.localParticipant.identity&&(this.emit(E.DataTrackUnpublished,l.sid),(u=this.remoteParticipants.get(l.publisherIdentity))===null||u===void 0||u.removeRemoteDataTrack(l.sid))}),this.outgoingDataTrackManager=new Qs({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on("sfuPublishRequest",l=>{this.engine.client.sendPublishDataTrackRequest(l.handle,l.name,l.usesE2ee)}).on("sfuUnpublishRequest",l=>{this.engine.client.sendUnPublishDataTrackRequest(l.handle)}).on("trackPublished",l=>{this.emit(E.LocalDataTrackPublished,l.track)}).on("trackUnpublished",l=>{this.emit(E.LocalDataTrackUnpublished,l.sid)}).on("packetAvailable",l=>{let u=l.handle,h=l.bytes;this.engine.sendDataTrackFrame(h).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(u))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Fg(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var l,u;return(u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0?void 0:u.version}),this.rpcClientManager.on("sendDataPacket",l=>{let u=l.packet;var h;(h=this.engine)===null||h===void 0||h.sendDataPacket(u,W.RELIABLE)}),this.rpcServerManager=new Bg(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",l=>{let u=l.packet;var h;(h=this.engine)===null||h===void 0||h.sendDataPacket(u,W.RELIABLE)}),this.disconnectLock=new fe,this.localParticipant=new Hg("","",this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.outgoingDataTrackManager.updateE2eeManager((a=this.e2eeManager)!==null&&a!==void 0?a:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",nn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",nn(this.options.audioCaptureDefaults.deviceId)),!((o=this.options.audioOutput)===null||o===void 0)&&o.deviceId&&this.switchActiveDevice("audiooutput",nn(this.options.audioOutput.deviceId)).catch(l=>this.log.warn("Could not set audio output: ".concat(l.message))),Me()){const l=new AbortController;let u;if(mn.cleanupRegistry){const h=new WeakRef(this);u=()=>{const p=h.deref();p&&p.handleDeviceChange()},mn.cleanupRegistry.register(this,()=>{l.abort()})}else u=this.handleDeviceChange;(d=(c=navigator.mediaDevices)===null||c===void 0?void 0:c.addEventListener)===null||d===void 0||d.call(c,"devicechange",u,{signal:l.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{t()}})}setupE2EE(){var e,t;const n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new Jp(r,n),this.e2eeManager.on(bt.ParticipantEncryptionStatusChanged,(s,a)=>{Mp(a)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(bt.EncryptionError,(s,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(E.EncryptionError,s,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new $p(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,n;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:(t=this.localParticipant)===null||t===void 0?void 0:t.identity,participantID:(n=this.localParticipant)===null||n===void 0?void 0:n.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===K.Disconnected?Ee.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?Ee.resolve(this.roomInfo.sid):new Ee((e,t)=>{const n=r=>{r.sid!==""&&(this.engine.off(P.RoomUpdate,n),e(r.sid))};this.engine.on(P.RoomUpdate,n),this.once(E.Disconnected,()=>{this.engine.off(P.RoomUpdate,n),t(new ee("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new mg(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(K.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(K.Connected)&&this.emit(E.Reconnected),this.emitBufferedEvents()}).on(P.SignalResumed,()=>{(this.state===K.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(P.Restarting,this.handleRestarting).on(P.Restarted,this.handleRestarted).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(K.Reconnecting)&&this.emit(E.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(E.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(P.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==G.NONE}})}).on(P.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."));return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(P.DataTrackSubscriberHandles,e=>{const t=new Map(Object.entries(e.subHandles).map(n=>{let r=x(n,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(P.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(P.Joined,e=>{const t=new Map(e.otherParticipants.map(n=>[n.identity,n.dataTracks.map(r=>Ei.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(P.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(P.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:ls})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>m(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ge.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===K.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(un(new URL(e))&&t){this.regionUrlProvider=new z(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===K.Disconnected&&(this.regionUrl=n,yield fetch(Vn(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(Vn(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let n=()=>m(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":r=new $e({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new $e({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new $e({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new $e({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new $e({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new $e({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 $e({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Vi({reason:Ne.CLIENT_INITIATED,action:Xt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new $e({scenario:{case:"subscriberBandwidth",value:Je(t)}});break;case"leave-full-reconnect":r=new $e({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,p;let f=!0,g=!1;const b=a?{exact:r}:r;if(n==="audioinput"){g=s.localParticipant.audioTrackPublications.size===0;const k=(o=s.getActiveDevice(n))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=b;const S=Array.from(s.localParticipant.audioTrackPublications.values()).filter(v=>v.source===w.Source.Microphone);try{f=(yield Promise.all(S.map(v=>{var T;return(T=v.audioTrack)===null||T===void 0?void 0:T.setDeviceId(b)}))).every(v=>v===!0)}catch(v){throw s.options.audioCaptureDefaults.deviceId=k,v}const M=S.some(v=>{var T,C;return(C=(T=v.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});f&&M&&(g=!0)}else if(n==="videoinput"){g=s.localParticipant.videoTrackPublications.size===0;const k=(c=s.getActiveDevice(n))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const S=Array.from(s.localParticipant.videoTrackPublications.values()).filter(v=>v.source===w.Source.Camera);try{f=(yield Promise.all(S.map(v=>{var T;return(T=v.videoTrack)===null||T===void 0?void 0:T.setDeviceId(b)}))).every(v=>v===!0)}catch(v){throw s.options.videoCaptureDefaults.deviceId=k,v}const M=S.some(v=>{var T,C;return(C=(T=v.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});f&&M&&(g=!0)}else if(n==="audiooutput"){if(g=!0,!ns()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");s.options.webAudioMix&&(r=(d=yield ge.getInstance().normalizeDeviceId("audiooutput",r))!==null&&d!==void 0?d:""),(l=(p=s.options).audioOutput)!==null&&l!==void 0||(p.audioOutput={});const k=(u=s.getActiveDevice(n))!==null&&u!==void 0?u: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(S=>S.setAudioOutput({deviceId:r})))}catch(S){throw s.options.audioOutput.deviceId=k,S}}return g&&(s.localParticipant.activeDeviceMap.set(n,r),s.emit(E.ActiveDeviceChanged,n,r)),f})()})}setupLocalParticipantEvents(){this.localParticipant.on(D.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(D.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(D.AttributesChanged,this.onLocalAttributesChanged).on(D.TrackMuted,this.onLocalTrackMuted).on(D.TrackUnmuted,this.onLocalTrackUnmuted).on(D.LocalTrackPublished,this.onLocalTrackPublished).on(D.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(D.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(D.MediaDevicesError,this.onMediaDevicesError).on(D.AudioStreamAcquired,this.startAudio).on(D.ChatMessage,this.onLocalChatMessageSent).on(D.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){var r,s;if([K.Connecting,K.Reconnecting].includes(this.state)){const p=qa(e,t);this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(b=>b.id)});const f=()=>{g(),this.onTrackAdded(e,t,n)},g=()=>{if(this.off(E.Reconnected,f),this.off(E.Connected,f),this.off(E.Disconnected,g),p){const b=this.pendingTrackAddedCallbacks.get(p);b?.delete(g),b?.size===0&&this.pendingTrackAddedCallbacks.delete(p)}};if(this.once(E.Reconnected,f),this.once(E.Connected,f),this.once(E.Disconnected,g),p){const b=(r=this.pendingTrackAddedCallbacks.get(p))!==null&&r!==void 0?r:new Set;b.add(g),this.pendingTrackAddedCallbacks.set(p,b)}return}if(this.state===K.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const a=_d(t.id),o=a[0],c=a[1];let d=(s=qa(e,t))!==null&&s!==void 0?s:e.id;if(o===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const l=Array.from(this.remoteParticipants.values()).find(p=>p.sid===o);if(!l){o.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o));return}if(!d.startsWith("TR")){const p=this.engine.getTrackIdForReceiver(n);if(!p){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(o));return}d=p}d.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(o,", streamId: ").concat(c,", trackId: ").concat(d),{remoteParticipantID:o,streamId:c,trackId:d});let u;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?u=this.options.adaptiveStream:u={});const h=l.addSubscribedMediaTrack(e,d,t,n,u);h?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))===null||t===void 0||t.forEach(n=>n())}handleLocalTrackSubscribed(e){const t=()=>this.localParticipant.getTrackPublications().find(c=>c.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});const r=1e4;let s;const a=c=>{c.trackSid===e&&(o(),this.emitLocalTrackSubscribed(c))},o=()=>{clearTimeout(s),this.localParticipant.off(D.LocalTrackPublished,a),this.off(E.Disconnected,o)};this.localParticipant.on(D.LocalTrackPublished,a),this.once(E.Disconnected,o),s=setTimeout(()=>{o();const c=t();c?this.emitLocalTrackSubscribed(c):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},r)}emitLocalTrackSubscribed(e){this.localParticipant.emit(D.LocalTrackSubscribed,e),this.emitWhenConnected(E.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==K.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(a=>{s.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var a,o,c;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((a=s.track)===null||a===void 0||a.detach(),(o=s.track)===null||o===void 0||o.stop()):(c=s.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(D.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(D.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(D.AttributesChanged,this.onLocalAttributesChanged).off(D.TrackMuted,this.onLocalTrackMuted).off(D.TrackUnmuted,this.onLocalTrackUnmuted).off(D.LocalTrackPublished,this.onLocalTrackPublished).off(D.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(D.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(D.MediaDevicesError,this.onMediaDevicesError).off(D.AudioStreamAcquired,this.startAudio).off(D.ChatMessage,this.onLocalChatMessageSent).off(D.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),Me()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||r===void 0||r.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(K.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t,n){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t,n),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return m(this,void 0,void 0,function*(){var e,t,n;const r=ge.getInstance().previousDevices,s=yield ge.getInstance().getDevices(void 0,!1),a=Re();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of s){const d=r.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=ap(c),l=this.localParticipant.getTrackPublication(d);if(l&&!((e=l.track)===null||e===void 0)&&e.isUserProvided)continue;const u=s.filter(p=>p.kind===c),h=this.getActiveDevice(c);if(h===((t=r.filter(p=>p.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!qn()||c==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!qn())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Pd())!==null&&e!==void 0?e: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(),Te(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(E.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let r;return t?r=Di.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new Di(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message))),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,n),n.on(D.TrackPublished,r=>{this.emitWhenConnected(E.TrackPublished,r,n)}).on(D.TrackSubscribed,(r,s)=>{r.kind===w.Kind.Audio?(r.on(I.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(I.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===w.Kind.Video&&(r.on(I.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(I.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(E.TrackSubscribed,r,s,n)}).on(D.TrackUnpublished,r=>{this.cancelPendingTrackAdded(r.trackSid),this.emit(E.TrackUnpublished,r,n)}).on(D.TrackUnsubscribed,(r,s)=>{this.emit(E.TrackUnsubscribed,r,s,n)}).on(D.TrackMuted,r=>{this.emitWhenConnected(E.TrackMuted,r,n)}).on(D.TrackUnmuted,r=>{this.emitWhenConnected(E.TrackUnmuted,r,n)}).on(D.ParticipantMetadataChanged,r=>{this.emitWhenConnected(E.ParticipantMetadataChanged,r,n)}).on(D.ParticipantNameChanged,r=>{this.emitWhenConnected(E.ParticipantNameChanged,r,n)}).on(D.AttributesChanged,r=>{this.emitWhenConnected(E.ParticipantAttributesChanged,r,n)}).on(D.ConnectionQualityChanged,r=>{this.emitWhenConnected(E.ConnectionQualityChanged,r,n)}).on(D.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,r,n)}).on(D.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,r,s,n)}).on(D.TrackSubscriptionFailed,(r,s)=>{this.emit(E.TrackSubscriptionFailed,r,n,s)}).on(D.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,r,s,n)}).on(D.Active,()=>{this.emitWhenConnected(E.ParticipantActive,n),n.kind===Un.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&_p(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;const n=[];return(Hn((t=e.frameMetadata)!==null&&t!==void 0?t:e.packetTrailer)||this.e2eeManager)&&n.push(Fn.CAP_PACKET_TRAILER),Ct()&&n.push(Fn.CAP_COMPRESSION_DEFLATE_RAW),n}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(cl,(e,t)=>m(this,[e,t],void 0,function(n,r){var s=this;let a=r.identity;return(function*(){var o;const c=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(n,a,c)})()})),this.incomingDataStreamManager.registerTextStreamHandler(dl,(e,t)=>m(this,[e,t],void 0,function(n,r){var s=this;let a=r.identity;return(function*(){var o;const c=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(n,a,c)})()}))}setStatsLogging(e){e?this.statsLogInterval||(this.statsLogInterval=Y.setInterval(()=>{this.logWebRTCStats()},Jg)):this.statsLogInterval&&(Y.clearInterval(this.statsLogInterval),this.statsLogInterval=void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Y.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ne.STATE_MISMATCH)))):e=0},Gg)}clearConnectionReconcile(){this.connectionReconcileInterval&&Y.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===K.Connected),this.setStatsLogging(e===K.Connected),this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=x(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(this.state===K.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===K.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n,r,s;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new xi({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ne.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Vt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(K.Connected),a.video){const c=new us(w.Kind.Video,new Qt({source:de.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:We.AUDIO,name:"video-dummy"}),new Ii(a.useRealTracks&&!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Ba(160*((n=o.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(c),this.localParticipant.emit(D.LocalTrackPublished,c)}if(a.audio){const c=new us(w.Kind.Audio,new Qt({source:de.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:We.AUDIO}),new Ri(a.useRealTracks&&!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:pr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(D.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new Vt({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:$t.ACTIVE,tracks:[],joinedAt:ne.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=Ba(160*((s=o.aspectRatios[c%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),h=new Qt({source:de.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:We.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=pr(),h=new Qt({source:de.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:We.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const s=pl(n).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:s}),this.log.debug("room event ".concat(e),{event:e,args:s})}return super.emit(e,...n)}}mn.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(i=>{i()});function pl(i){return i.map(e=>{if(e)return Array.isArray(e)?pl(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ve;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Ve||(Ve={}));class It extends De.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ve.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new mn(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==Ve.IDLE)throw Error("check is running already");this.setStatus(Ve.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Ve.SKIPPED&&this.setStatus(this.isSuccess()?Ve.SUCCESS:Ve.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===K.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==K.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ve.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(n)return;yield Te(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Qg extends It{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new z(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(n.has(a))continue;n.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,o=1e6/a,c="A".repeat(a),d=Date.now();for(let p=0;p<o;p++)yield s.write(c);yield s.close();const l=Date.now(),u=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:r,rtt:1e4,duration:l-d};return u?.forEach(p=>{p.type==="candidate-pair"&&p.nominated&&(h.rtt=p.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const Mr=1e4;class Yg extends It{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Mr/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Mr/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,n.fillStyle="hsl(".concat(r,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const a=t.captureStream(30).getVideoTracks()[0],o=(yield this.room.localParticipant.publishTrack(a,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,c={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},d=setInterval(()=>m(this,void 0,void 0,function*(){(yield o.getRTCStatsReport())?.forEach(u=>{u.type==="outbound-rtp"?(c.packetsSent=u.packetsSent,c.qualityLimitationDurations=u.qualityLimitationDurations,c.bitrateTotal+=u.targetBitrate,c.count++):u.type==="remote-inbound-rtp"&&(c.packetsLost=u.packetsLost,c.rttTotal+=u.roundTripTime,c.jitterTotal+=u.jitter)})}),1e3);return yield new Promise(l=>setTimeout(l,Mr)),clearInterval(d),a.stop(),t.remove(),yield this.disconnect(),c})}}class $g extends It{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield ul();if(yield Rd(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="audio"||!a.kind&&a.mediaType==="audio")&&(s=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class Xg extends It{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield qg();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(r=>{n.onplay=()=>{setTimeout(()=>{var s,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:n.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const p=d.getContext("2d");p.drawImage(n,0,0);const f=p.getImageData(0,0,d.width,d.height).data;let g=!0;for(let b=0;b<f.length;b+=4)if(f[b]!==0||f[b+1]!==0||f[b+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},n.play()}),t.getTracks().forEach(r=>r.stop()),n.remove()})}}class Zg extends It{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,r=!1,s;const a=new Promise(d=>{setTimeout(d,5e3),s=d}),o=()=>{n=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,n){if(!r||t.state!==K.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 ef extends It{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;un(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new z(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new Hs,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of s.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.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(d=>setTimeout(d,0)))})}}class tf extends It{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var n;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){const o=new RTCIceCandidate(s);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(nf(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}r&&r(s,a)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),B.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function nf(i){const e=i.split(".");if(e.length===4){if(e[0]==="10"||e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class rf extends It{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new Hs,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(un(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const o=yield new z(this.url,this.token).getNextBestRegionUrl();o&&(s=yield r.join(o,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}s?(this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===wc.Cloud&&!((t=s.serverInfo)===null||t===void 0)&&t.region&&this.appendMessage("LiveKit Cloud: ".concat((n=s.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class bv extends De.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Ve.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Ve.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};n.on("update",r);const s=yield n.run();return n.off("update",r),s})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(rf)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(tf)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(ef)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Zg)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck($g)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Xg)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yg);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Qg)})}}new TextEncoder;new TextDecoder;class Pe extends Error{constructor(e,t){var n;super(e,t),U(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}}U(Pe,"code","ERR_JOSE_GENERIC");class sf extends Pe{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:r,payload:t}}),U(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),U(this,"claim",void 0),U(this,"reason",void 0),U(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}}U(sf,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class af extends Pe{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:r,payload:t}}),U(this,"code","ERR_JWT_EXPIRED"),U(this,"claim",void 0),U(this,"reason",void 0),U(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}}U(af,"code","ERR_JWT_EXPIRED");class of extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}U(of,"code","ERR_JOSE_ALG_NOT_ALLOWED");class cf extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JOSE_NOT_SUPPORTED")}}U(cf,"code","ERR_JOSE_NOT_SUPPORTED");class df extends Pe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),U(this,"code","ERR_JWE_DECRYPTION_FAILED")}}U(df,"code","ERR_JWE_DECRYPTION_FAILED");class lf extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JWE_INVALID")}}U(lf,"code","ERR_JWE_INVALID");class uf extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JWS_INVALID")}}U(uf,"code","ERR_JWS_INVALID");class hf extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JWT_INVALID")}}U(hf,"code","ERR_JWT_INVALID");class pf extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JWK_INVALID")}}U(pf,"code","ERR_JWK_INVALID");class mf extends Pe{constructor(){super(...arguments),U(this,"code","ERR_JWKS_INVALID")}}U(mf,"code","ERR_JWKS_INVALID");class gf extends Pe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),U(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}U(gf,"code","ERR_JWKS_NO_MATCHING_KEY");class ff extends Pe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),U(this,Symbol.asyncIterator,void 0),U(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}U(ff,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class vf extends Pe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),U(this,"code","ERR_JWKS_TIMEOUT")}}U(vf,"code","ERR_JWKS_TIMEOUT");class yf extends Pe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),U(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}U(yf,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const ml="conversation_initiation_client_data";function gl(i){const e={type:ml};return i.overrides&&(e.conversation_config_override={agent:{prompt:i.overrides.agent?.prompt,first_message:i.overrides.agent?.firstMessage,language:i.overrides.agent?.language},tts:{voice_id:i.overrides.tts?.voiceId,speed:i.overrides.tts?.speed,stability:i.overrides.tts?.stability,similarity_boost:i.overrides.tts?.similarityBoost},...i.overrides.asr?.keywords!==void 0?{asr:{keywords:i.overrides.asr.keywords}}:{},conversation:{text_only:i.overrides.conversation?.textOnly}}),i.customLlmExtraBody&&(e.custom_llm_extra_body=i.customLlmExtraBody),i.dynamicVariables&&(e.dynamic_variables=i.dynamicVariables),i.userId&&(e.user_id=i.userId),e.source_info={source:vi.name,version:vi.version},i.toolMockConfig&&(e.tool_mock_config={mocking_strategy:i.toolMockConfig.mockingStrategy,mocked_tool_names:i.toolMockConfig.mockedToolNames,fallback_strategy:i.toolMockConfig.fallbackStrategy}),e}function $s(i){const e=new Uint8Array(i);return btoa(String.fromCharCode(...e))}function bf(i){const e=atob(i),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n.buffer}const ei={getVolume:()=>0,getByteFrequencyData:()=>{}},kf=100,Tf=8e3;function No(i,e,t){const n=i.length,r=t/2/n,s=Math.floor(kf/r),a=Math.min(Math.ceil(Tf/r),n),o=a-s,c=e.length;for(let d=0;d<c;d++){const l=d/c*o,u=s+Math.floor(l),h=Math.min(u+1,a-1),p=l-Math.floor(l);e[d]=Math.round(i[u]*(1-p)+i[h]*p)}}let fl;function Sf(i){fl=i}function wf(){return fl?.()??null}const Cf="wss://livekit.rtc.elevenlabs.io",Ef="https://api.elevenlabs.io",Rf=.01;function Pf(i){return i.replace(/^wss:\/\//,"https://")}class Xi extends Wo{constructor(e,t,n,r,s={}){super(s),_(this,"conversationId"),_(this,"inputFormat"),_(this,"outputFormat"),_(this,"room"),_(this,"isConnected",!1),_(this,"audioEventId",1),_(this,"outputDeviceId",null),_(this,"audioAdapter"),_(this,"workletPaths"),_(this,"inputAnalyser"),_(this,"inputVolumeProvider",ei),_(this,"outputAnalyser"),_(this,"outputVolumeProvider",ei),_(this,"_isMuted",!1),_(this,"input",{close:async()=>{if(this.isConnected)try{this.room.localParticipant.audioTrackPublications.forEach(a=>{a.track&&a.track.stop()})}catch(a){console.warn("Error stopping local tracks:",a)}},setDevice:async a=>{if(a?.sampleRate!==void 0||a?.format!==void 0||a?.preferHeadphonesForIosDevices!==void 0)throw new Error("WebRTC input device does not support sampleRate, format, or preferHeadphonesForIosDevices options");const o=a?.inputDeviceId;o&&await this.setAudioInputDevice(o)},setMuted:async a=>{if(!this.isConnected||!this.room.localParticipant){console.warn("Cannot set microphone muted: room not connected or no local participant");return}this._isMuted=a;const o=this.room.localParticipant.getTrackPublication(w.Source.Microphone);if(o?.track)try{a?await o.track.mute():await o.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!a)}else await this.room.localParticipant.setMicrophoneEnabled(!a);if(!a){const c=this.room.localParticipant.getTrackPublication(w.Source.Microphone)?.track;c&&this.setupInputAnalyser(c.mediaStreamTrack)}},isMuted:()=>this._isMuted,getAnalyser:()=>this.inputAnalyser,getVolume:()=>this._isMuted?0:this.inputVolumeProvider.getVolume(),getByteFrequencyData:a=>{if(this._isMuted){a.fill(0);return}this.inputVolumeProvider.getByteFrequencyData(a)}}),_(this,"output",{close:async()=>{},setDevice:async a=>{if(a?.sampleRate!==void 0||a?.format!==void 0)throw new Error("WebRTC output device does not support sampleRate or format options");const o=a?.outputDeviceId;o&&await this.setAudioOutputDevice(o)},setVolume:a=>{this.setAudioVolume(a)},interrupt:a=>{},getAnalyser:()=>this.outputAnalyser,getVolume:()=>this.outputVolumeProvider.getVolume(),getByteFrequencyData:a=>{this.outputVolumeProvider.getByteFrequencyData(a)}}),this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.audioAdapter=wf(),this.workletPaths=s.workletPaths,this.setupRoomEventListeners()}static async create(e){let t;if("conversationToken"in e&&e.conversationToken)t=e.conversationToken;else if("agentId"in e&&e.agentId)try{const{name:r,version:s}=vi,a=e.origin??Ef;let o=`${Pf(a)}/v1/convai/conversation/token?agent_id=${e.agentId}&source=${r}&version=${s}`;e.environment&&(o+=`&environment=${encodeURIComponent(e.environment)}`);const c=await fetch(o);if(!c.ok){const l=await Ho(c);throw new Error(`ElevenLabs API returned ${c.status} ${l}`)}const d=await c.json();if(!fi(d)||typeof d.token!="string")throw new Error("No conversation token received from API");if(t=d.token,!t)throw new Error("No conversation token received from API")}catch(r){let s=r instanceof Error?r.message:String(r);throw r instanceof Error&&r.message.includes("401")&&(s="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${e.agentId}: ${s}`)}else throw new Error("Either conversationToken or agentId is required for WebRTC connection");const n=new mn;try{const r=`room_${Date.now()}`,s=gi("pcm_48000"),a=gi("pcm_48000"),o=new Xi(n,r,s,a,e),c=e.livekitUrl||Cf,d=e.textOnly?Promise.resolve():new Promise((p,f)=>{n.once(E.SignalConnected,()=>{o.enableMicrophone(e.inputDeviceId).then(()=>p()).catch(f)})}),l=e.webRtc?.iceTransportPolicy;await n.connect(c,t,{rtcConfig:l?{iceTransportPolicy:l}:void 0}),await new Promise(p=>{if(o.isConnected)p();else{const f=()=>{n.off(E.Connected,f),p()};n.on(E.Connected,f)}}),await d;const u=n.localParticipant.getTrackPublication(w.Source.Microphone)?.track;u&&o.setupInputAnalyser(u.mediaStreamTrack),n.name&&(o.conversationId=n.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||n.name);const h=gl(e);return o.debug({type:ml,message:h}),await o.sendRequiredMessage(h),o}catch(r){throw await n.disconnect(),r}}setupRoomEventListeners(){this.room.on(E.Connected,()=>{this.isConnected=!0}),this.room.on(E.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:"agent",context:{type:"close",reason:e?.toString()}})}),this.room.on(E.ConnectionStateChanged,e=>{e===K.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${e}`,context:{type:"connection_state_changed"}}))}),this.room.on(E.DataReceived,(e,t)=>{try{const n=JSON.parse(new TextDecoder().decode(e));if(n.type==="audio"){yi(n)&&this.handleMessage(n);return}yi(n)?this.handleMessage(n):console.warn("Invalid socket event received:",n)}catch(n){console.warn("Failed to parse incoming data message:",n),console.warn("Raw payload:",new TextDecoder().decode(e))}}),this.room.on(E.TrackSubscribed,async(e,t,n)=>{if(e.kind===w.Kind.Audio&&n.identity.includes("agent")){const r=e;this.audioAdapter&&(await this.audioAdapter.attachRemoteTrack(r,this.outputDeviceId),await this.setupAudioCapture(r),this.onDebug?.({type:"audio_element_ready"}))}}),this.room.on(E.ActiveSpeakersChanged,async e=>{e.length>0?this.updateMode(e[0].identity.startsWith("agent")?"speaking":"listening"):this.updateMode("listening")}),this.room.on(E.ParticipantDisconnected,e=>{e.identity?.startsWith("agent")&&this.disconnect({reason:"agent",context:{type:"close",reason:"agent disconnected"}})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioAdapter?.cleanup(),this.inputAnalyser=void 0,this.outputAnalyser=void 0,this.inputVolumeProvider=ei,this.outputVolumeProvider=ei,this.room.disconnect()}}async sendMessage(e){if(!this.isConnected||!this.room.localParticipant){console.warn("Cannot send message: room not connected or no local participant");return}if(!("user_audio_chunk"in e)){this.handleOutgoingMessage(e);try{await this.publishMessage(e)}catch(t){this.debug({type:"send_message_error",message:{message:e,error:t}}),console.error("Failed to send message via WebRTC:",t)}}}async sendRequiredMessage(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot send message: room not connected or no local participant");this.handleOutgoingMessage(e),await this.publishMessage(e)}async publishMessage(e){const t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}getRoom(){return this.room}setupInputAnalyser(e){if(this.audioAdapter)try{const t=this.audioAdapter.setupInputAnalysis(e);this.inputVolumeProvider=t.volumeProvider,this.inputAnalyser=t.analyser}catch(t){console.warn("[ConversationalAI] Failed to set up input volume analyser:",t)}}setInputVolumeProvider(e){this.inputVolumeProvider=e}setOutputVolumeProvider(e){this.outputVolumeProvider=e}async setupAudioCapture(e){if(this.audioAdapter)try{const t=(r,s)=>{if(s>Rf){const a=$s(r),o=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:a,event_id:o}})}},n=await this.audioAdapter.setupOutputAnalysis(e,this.outputFormat,t,this.workletPaths);this.outputVolumeProvider=n.volumeProvider,this.outputAnalyser=n.analyser}catch(t){console.warn("Failed to set up audio capture:",t)}}setAudioVolume(e){this.audioAdapter?.setVolume(e)}async setAudioOutputDevice(e){if(!this.audioAdapter)throw new Error("Cannot set output device: no audio adapter available on this platform");await this.audioAdapter.setOutputDevice(e),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");const t=await this.createMicrophoneTrack(e);try{const n=this.room.localParticipant.getTrackPublication(w.Source.Microphone);n?.track&&await this.room.localParticipant.unpublishTrack(n.track),this._isMuted&&await t.mute(),await this.room.localParticipant.publishTrack(t,{name:"microphone",source:w.Source.Microphone})}catch(n){console.error("Failed to change input device:",n);const r=this.room.localParticipant.getTrackPublication(w.Source.Microphone);if(r?.track!==t&&t.stop(),!r?.track)try{await this.room.localParticipant.setMicrophoneEnabled(!this._isMuted);const s=this.room.localParticipant.getTrackPublication(w.Source.Microphone)?.track;s&&this.setupInputAnalyser(s.mediaStreamTrack)}catch(s){console.error("Failed to recover microphone after device switch error:",s)}throw n}this.setupInputAnalyser(t.mediaStreamTrack)}async enableMicrophone(e){if(!e){await this.room.localParticipant.setMicrophoneEnabled(!0);return}const t=await this.createMicrophoneTrack(e);try{await this.room.localParticipant.publishTrack(t,{name:"microphone",source:w.Source.Microphone})}catch(n){throw t.stop(),n}}createMicrophoneTrack(e){return ul({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}})}}const If='Import the platform-specific entry point (e.g. @elevenlabs/client via the "browser" export).';let _f=If;function vl(i){return new Error(`No ${i} registered. ${_f}`)}let hs;function Mf(i){hs=i}function Df(){if(hs)return hs;throw vl("voice session setup strategy")}function Af(i){if(!(i instanceof Xi))throw new Error(`setupWebRTCSession requires a WebRTCConnection. Received: ${i?.constructor?.name??typeof i}`);return{connection:i,input:i.input,output:i.output,playbackEventTarget:null,detach:async()=>{}}}const ti=new Map;function Of(i,e){return e?`${i} ${e}`:i}function Xs(i,e){return async(t,n)=>{const r=Of(i,n),s=ti.get(r);if(s)return t.addModule(s);if(n)try{await t.addModule(n),ti.set(r,n);return}catch(c){throw new Error(`Failed to load the ${i} worklet module from path: ${n}. Error: ${c}`)}const a=new Blob([e],{type:"application/javascript"}),o=URL.createObjectURL(a);try{await t.addModule(o),ti.set(r,o);return}catch{URL.revokeObjectURL(o)}try{const c=`data:application/javascript;base64,${btoa(e)}`;await t.addModule(c),ti.set(r,c)}catch{throw new Error(`Failed to load the ${i} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const Nf=Xs("audioConcatProcessor",`/*
40
+ * ulaw decoding logic taken from the wavefile library
41
+ * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
42
+ * USED BY @elevenlabs/client
43
+ */
44
+
45
+ const decodeTable = [0, 132, 396, 924, 1980, 4092, 8316, 16764];
46
+
47
+ function decodeSample(muLawSample) {
48
+ let sign;
49
+ let exponent;
50
+ let mantissa;
51
+ let sample;
52
+ muLawSample = ~muLawSample;
53
+ sign = muLawSample & 0x80;
54
+ exponent = (muLawSample >> 4) & 0x07;
55
+ mantissa = muLawSample & 0x0f;
56
+ sample = decodeTable[exponent] + (mantissa << (exponent + 3));
57
+ if (sign !== 0) sample = -sample;
58
+
59
+ return sample;
60
+ }
61
+
62
+ class AudioConcatProcessor extends AudioWorkletProcessor {
63
+ constructor() {
64
+ super();
65
+ this.buffers = []; // Initialize an empty buffer
66
+ this.cursor = 0;
67
+ this.currentBuffer = null;
68
+ this.wasInterrupted = false;
69
+ this.finished = false;
70
+
71
+ this.port.onmessage = ({ data }) => {
72
+ switch (data.type) {
73
+ case "setFormat":
74
+ this.format = data.format;
75
+ if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {
76
+ globalThis.LibSampleRate.create(
77
+ 1,
78
+ data.sampleRate,
79
+ sampleRate
80
+ ).then(resampler => {
81
+ this.resampler = resampler;
82
+ });
83
+ }
84
+ break;
85
+ case "buffer":
86
+ this.wasInterrupted = false;
87
+ this.buffers.push(
88
+ this.format === "ulaw"
89
+ ? new Uint8Array(data.buffer)
90
+ : new Int16Array(data.buffer)
91
+ );
92
+ break;
93
+ case "interrupt":
94
+ this.wasInterrupted = true;
95
+ break;
96
+ case "clearInterrupted":
97
+ if (this.wasInterrupted) {
98
+ this.wasInterrupted = false;
99
+ this.buffers = [];
100
+ this.currentBuffer = null;
101
+ }
102
+ }
103
+ };
104
+ }
105
+ process(_, outputs) {
106
+ let finished = false;
107
+ const output = outputs[0][0];
108
+ for (let i = 0; i < output.length; i++) {
109
+ if (!this.currentBuffer) {
110
+ if (this.buffers.length === 0) {
111
+ finished = true;
112
+ break;
113
+ }
114
+ this.currentBuffer = this.buffers.shift();
115
+ if (this.resampler) {
116
+ this.currentBuffer = this.resampler.full(this.currentBuffer);
117
+ }
118
+ this.cursor = 0;
119
+ }
120
+
121
+ let value = this.currentBuffer[this.cursor];
122
+ if (this.format === "ulaw") {
123
+ value = decodeSample(value);
124
+ }
125
+ output[i] = value / 32768;
126
+ this.cursor++;
127
+
128
+ if (this.cursor >= this.currentBuffer.length) {
129
+ this.currentBuffer = null;
130
+ }
131
+ }
132
+
133
+ if (this.finished !== finished) {
134
+ this.finished = finished;
135
+ this.port.postMessage({ type: "process", finished });
136
+ }
137
+
138
+ return true; // Continue processing
139
+ }
140
+ }
141
+
142
+ registerProcessor("audioConcatProcessor", AudioConcatProcessor);
143
+ `),xf="https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js";async function yl(i,e){const t=e||xf;await i.audioWorklet.addModule(t)}function Lf(i){if(i.length===0)return 0;let e=0;for(let t=0;t<i.length;t++)e+=i[t]/255;return e/=i.length,e<0?0:e>1?1:e}function Ai(i,e){const t=i.frequencyBinCount;let n,r;return{getVolume(){return n??(n=new Uint8Array(t)),r??(r=new Uint8Array(t)),i.getByteFrequencyData(n),No(n,r,e),Lf(r)},getByteFrequencyData(s){n??(n=new Uint8Array(t)),i.getByteFrequencyData(n),No(n,s,e)}}}function gn(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function Uf(){return/android/i.test(navigator.userAgent)}function Ff({sampleRate:i,format:e,worklet:t,audioElement:n}){if(!gn())return;const r=Math.floor(i*100/1e3),s=e==="ulaw"?new Uint8Array(r).fill(255):new Int16Array(r);t.port.postMessage({type:"buffer",buffer:s.buffer}),n.play().catch(()=>{})}class Zs{constructor(e,t,n,r,s){_(this,"context"),_(this,"analyser"),_(this,"gain"),_(this,"worklet"),_(this,"audioElement"),_(this,"volume",1),_(this,"interrupted",!1),_(this,"interruptTimeout",null),_(this,"volumeProvider"),this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=s,this.worklet.port.start(),this.volumeProvider=Ai(t,e.sampleRate)}static async create({sampleRate:e,format:t,outputDeviceId:n,workletPaths:r,libsampleratePath:s,audioContext:a}){let o=a??null,c=null;try{const d=navigator.mediaDevices.getSupportedConstraints().sampleRate;o||(o=new AudioContext(d?{sampleRate:e}:{}));const l=o.createAnalyser(),u=o.createGain();c=new Audio,c.src="",c.load(),c.autoplay=!0,c.style.display="none",document.body.appendChild(c);const h=o.createMediaStreamDestination();c.srcObject=h.stream,u.connect(l),l.connect(h),(!d||o.sampleRate!==e)&&(o.sampleRate!==e&&console.warn(`[ConversationalAI] Sample rate ${e} not available, resampling to ${o.sampleRate}`),await yl(o,s)),await Nf(o.audioWorklet,r?.audioConcatProcessor);const p=new AudioWorkletNode(o,"audioConcatProcessor");return p.port.postMessage({type:"setFormat",format:t,sampleRate:e}),p.connect(u),await o.resume(),Ff({sampleRate:e,format:t,worklet:p,audioElement:c}),n&&c.setSinkId&&await c.setSinkId(n),new Zs(o,l,u,p,c)}catch(d){throw c?.parentNode&&c.parentNode.removeChild(c),c?.pause(),o&&o.state!=="closed"&&await o.close(),d}}getAnalyser(){return this.analyser}getVolume(){return this.volumeProvider.getVolume()}getByteFrequencyData(e){this.volumeProvider.getByteFrequencyData(e)}addListener(e){this.worklet.port.addEventListener("message",e)}removeListener(e){this.worklet.port.removeEventListener("message",e)}setVolume(e){this.volume=e,this.gain.gain.value=e}playAudio(e){this.gain.gain.cancelScheduledValues(this.context.currentTime),this.gain.gain.value=this.volume,this.interruptTimeout&&(clearTimeout(this.interruptTimeout),this.interruptTimeout=null),this.worklet.port.postMessage({type:"clearInterrupted"}),this.worklet.port.postMessage({type:"buffer",buffer:e})}interrupt(e=2e3){this.interrupted=!0,this.interruptTimeout&&(clearTimeout(this.interruptTimeout),this.interruptTimeout=null),this.worklet.port.postMessage({type:"interrupt"}),this.gain.gain.exponentialRampToValueAtTime(1e-4,this.context.currentTime+e/1e3),this.interruptTimeout=setTimeout(()=>{this.interrupted=!1,this.gain.gain.value=this.volume,this.worklet.port.postMessage({type:"clearInterrupted"}),this.interruptTimeout=null},e)}async setDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");const t=e?.outputDeviceId;await this.audioElement.setSinkId(t||"")}async close(){this.interruptTimeout&&(clearTimeout(this.interruptTimeout),this.interruptTimeout=null),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}const bl=Xs("rawAudioProcessor",`/*
144
+ * ulaw encoding logic taken from the wavefile library
145
+ * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
146
+ * USED BY @elevenlabs/client
147
+ */
148
+
149
+ const BIAS = 0x84;
150
+ const CLIP = 32635;
151
+ const encodeTable = [
152
+ 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
153
+ 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
154
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
155
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
156
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
157
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
158
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
159
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
160
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
161
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
162
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
163
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
164
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
165
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
166
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
167
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
168
+ ];
169
+
170
+ function encodeSample(sample) {
171
+ let sign;
172
+ let exponent;
173
+ let mantissa;
174
+ let muLawSample;
175
+ sign = (sample >> 8) & 0x80;
176
+ if (sign !== 0) sample = -sample;
177
+ sample = sample + BIAS;
178
+ if (sample > CLIP) sample = CLIP;
179
+ exponent = encodeTable[(sample>>7) & 0xFF];
180
+ mantissa = (sample >> (exponent+3)) & 0x0F;
181
+ muLawSample = ~(sign | (exponent << 4) | mantissa);
182
+
183
+ return muLawSample;
184
+ }
185
+
186
+ class RawAudioProcessor extends AudioWorkletProcessor {
187
+ constructor() {
188
+ super();
189
+
190
+ this.port.onmessage = ({ data }) => {
191
+ switch (data.type) {
192
+ case "setFormat":
193
+ this.isMuted = false;
194
+ this.buffer = []; // Initialize an empty buffer
195
+ const chunkDurationMs = data.chunkDurationMs ?? 25;
196
+ this.bufferSize = Math.max(
197
+ 1,
198
+ Math.round((data.sampleRate * chunkDurationMs) / 1000)
199
+ );
200
+ this.format = data.format;
201
+
202
+ if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) {
203
+ globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => {
204
+ this.resampler = resampler;
205
+ });
206
+ }
207
+ break;
208
+ case "setMuted":
209
+ this.isMuted = data.isMuted;
210
+ break;
211
+ }
212
+ };
213
+ }
214
+ process(inputs) {
215
+ if (!this.buffer) {
216
+ return true;
217
+ }
218
+
219
+ const input = inputs[0]; // Get the first input node
220
+ if (input.length > 0) {
221
+ let channelData = input[0]; // Get the first channel's data
222
+
223
+ // Resample the audio if necessary
224
+ if (this.resampler) {
225
+ channelData = this.resampler.full(channelData);
226
+ }
227
+
228
+ // Add channel data to the buffer
229
+ this.buffer.push(...channelData);
230
+ // Get max volume
231
+ let sum = 0.0;
232
+ for (let i = 0; i < channelData.length; i++) {
233
+ sum += channelData[i] * channelData[i];
234
+ }
235
+ const maxVolume = Math.sqrt(sum / channelData.length);
236
+ // Check if buffer size has reached or exceeded the threshold
237
+ if (this.buffer.length >= this.bufferSize) {
238
+ const float32Array = this.isMuted
239
+ ? new Float32Array(this.buffer.length)
240
+ : new Float32Array(this.buffer);
241
+
242
+ let encodedArray = this.format === "ulaw"
243
+ ? new Uint8Array(float32Array.length)
244
+ : new Int16Array(float32Array.length);
245
+
246
+ // Iterate through the Float32Array and convert each sample to PCM16
247
+ for (let i = 0; i < float32Array.length; i++) {
248
+ // Clamp the value to the range [-1, 1]
249
+ let sample = Math.max(-1, Math.min(1, float32Array[i]));
250
+
251
+ // Scale the sample to the range [-32768, 32767]
252
+ let value = sample < 0 ? sample * 32768 : sample * 32767;
253
+ if (this.format === "ulaw") {
254
+ value = encodeSample(Math.round(value));
255
+ }
256
+
257
+ encodedArray[i] = value;
258
+ }
259
+
260
+ // Send the buffered data to the main script
261
+ this.port.postMessage([encodedArray, maxVolume]);
262
+
263
+ // Clear the buffer after sending
264
+ this.buffer = [];
265
+ }
266
+ }
267
+ return true; // Continue processing
268
+ }
269
+ }
270
+ registerProcessor("rawAudioProcessor", RawAudioProcessor);
271
+ `),Bf=25,xo={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class xn{constructor(e,t,n,r,s,a,o=console.error){_(this,"context"),_(this,"analyser"),_(this,"worklet"),_(this,"inputStream"),_(this,"mediaStreamSource"),_(this,"permissions"),_(this,"onError"),_(this,"muted",!1),_(this,"volumeProvider"),_(this,"settingInput",!1),_(this,"handlePermissionsChange",()=>{if(this.permissions.state==="denied")this.onError("Microphone permission denied");else if(!this.settingInput){const[c]=this.inputStream.getAudioTracks(),{deviceId:d}=c?.getSettings()??{};this.setDevice({inputDeviceId:d}).catch(l=>{this.onError("Failed to reset input device after permission change:",l)})}}),this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=s,this.permissions=a,this.onError=o,this.permissions.addEventListener("change",this.handlePermissionsChange),this.worklet.port.start(),this.volumeProvider=Ai(t,e.sampleRate)}static async create({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:s,libsampleratePath:a,onError:o,inputChunkDurationMs:c=Bf}){let d=null,l=null;try{const u={sampleRate:{ideal:e},...xo};if(gn()&&n){const S=(await window.navigator.mediaDevices.enumerateDevices()).find(M=>M.kind==="audioinput"&&["airpod","headphone","earphone"].find(v=>M.label.toLowerCase().includes(v)));S&&(u.deviceId={ideal:S.deviceId})}r&&(u.deviceId=xn.getDeviceIdConstraint(r));const h=navigator.mediaDevices.getSupportedConstraints().sampleRate;d=new window.AudioContext(h?{sampleRate:e}:{});const p=d.createAnalyser();h||await yl(d,a),await bl(d.audioWorklet,s?.rawAudioProcessor);const f={voiceIsolation:!0,...u};l=await navigator.mediaDevices.getUserMedia({audio:f});const g=d.createMediaStreamSource(l),b=new AudioWorkletNode(d,"rawAudioProcessor");b.port.postMessage({type:"setFormat",format:t,sampleRate:e,chunkDurationMs:c}),g.connect(p),p.connect(b),await d.resume();const k=await navigator.permissions.query({name:"microphone"});return new xn(d,p,b,l,g,k,o)}catch(u){throw l?.getTracks().forEach(h=>{h.stop()}),d?.close(),u}}static getDeviceIdConstraint(e){if(e)return gn()?{ideal:e}:{exact:e}}getAnalyser(){return this.analyser}getVolume(){return this.muted?0:this.volumeProvider.getVolume()}getByteFrequencyData(e){if(this.muted){e.fill(0);return}this.volumeProvider.getByteFrequencyData(e)}isMuted(){return this.muted}addListener(e){this.worklet.port.addEventListener("message",e)}removeListener(e){this.worklet.port.removeEventListener("message",e)}forgetInputStreamAndSource(){for(const e of this.inputStream.getTracks())e.stop();this.mediaStreamSource.disconnect()}async close(){this.forgetInputStreamAndSource(),this.permissions.removeEventListener("change",this.handlePermissionsChange),await this.context.close()}async setMuted(e){this.muted=e,this.worklet.port.postMessage({type:"setMuted",isMuted:e})}async setDevice(e){try{if(this.settingInput)throw new Error("Input device is already being set");this.settingInput=!0;const t=e?.inputDeviceId,n={...xo};t&&(n.deviceId=xn.getDeviceIdConstraint(t));const r={voiceIsolation:!0,...n},s=await navigator.mediaDevices.getUserMedia({audio:r});this.forgetInputStreamAndSource(),this.inputStream=s,this.mediaStreamSource=this.context.createMediaStreamSource(s),this.mediaStreamSource.connect(this.analyser)}catch(t){throw this.onError("Failed to switch input device:",t),t}finally{this.settingInput=!1}}}const jf="enclave_setup_config";function Lo(i){return{url:i.url,...i.hmacSecret!==void 0?{hmac_secret:i.hmacSecret}:{}}}function qf(i){const e={type:jf,agent_config_dict:i.agentConfig??null,override_agent_config_list:i.agentConfigOverrides??null,tools_config_list:i.tools??null,prompt_knowledge_base:i.promptKnowledgeBase??null};return i.bedrockInferenceProfile!==void 0&&(e.bedrock_inference_profile=i.bedrockInferenceProfile),i.postCallTranscriptionWebhook&&(e.post_call_transcription_webhook=Lo(i.postCallTranscriptionWebhook)),i.postCallAudioWebhook&&(e.post_call_audio_webhook=Lo(i.postCallAudioWebhook)),e}const Vf="convai",Wf="wss://api.elevenlabs.io",Hf="/v1/convai/conversation?agent_id=";class Zi extends Wo{constructor(e,t,n,r){super(),_(this,"socket"),_(this,"conversationId"),_(this,"inputFormat"),_(this,"outputFormat"),_(this,"outputListeners",new Set),_(this,"pendingAudioEvents",[]),this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener("error",s=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:{type:s.type}}),0)}),this.socket.addEventListener("close",s=>{const a=s.code,o=s.reason||void 0,c={type:s.type,code:a,reason:o};this.disconnect(a===1e3?{reason:"agent",context:c,closeCode:a,closeReason:o}:{reason:"error",message:o||"The connection was closed by the server.",context:c,closeCode:a,closeReason:o})}),this.socket.addEventListener("message",s=>{try{const a=JSON.parse(s.data);if(!yi(a)){this.debug({type:"invalid_event",message:"Received invalid socket event",data:s.data});return}this.handleMessage(a)}catch(a){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:a instanceof Error?a.message:String(a),data:s.data})}})}static async create(e){let t=null;try{let n,r;const{name:s,version:a}=vi;if(e.orchestrator)n=e.orchestrator.url;else{const p=e.origin??Wf;if(e.signedUrl){const f=e.signedUrl.includes("?")?"&":"?";n=`${e.signedUrl}${f}source=${s}&version=${a}`}else n=`${p}${Hf}${e.agentId}&source=${s}&version=${a}`;e.environment&&(n+=`&environment=${encodeURIComponent(e.environment)}`),r=[Vf],e.authorization&&r.push(`bearer.${e.authorization}`)}t=new WebSocket(n,r);const o=await new Promise((p,f)=>{t.addEventListener("open",()=>{e.orchestrator&&t?.send(JSON.stringify(qf(e.orchestrator)));const g=gl(e);t?.send(JSON.stringify(g))},{once:!0}),t.addEventListener("error",g=>{setTimeout(()=>f(new ia("The connection was closed due to a socket error.")),0)}),t.addEventListener("close",g=>{const b=g.reason||(g.code===1e3?"Connection closed normally before session could be established.":"Connection closed unexpectedly before session could be established.");f(new ia(b,{closeCode:g.code,closeReason:g.reason||void 0}))}),t.addEventListener("message",g=>{const b=JSON.parse(g.data);yi(b)&&(b.type==="conversation_initiation_metadata"?p(b.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:c,agent_output_audio_format:d,user_input_audio_format:l}=o,u=gi(l??"pcm_16000"),h=gi(d);return new Zi(t,c,u,h)}catch(n){throw t?.close(),n}}close(){this.pendingAudioEvents=[],this.socket.close(1e3,"User ended conversation")}sendMessage(e){this.handleOutgoingMessage(e),this.socket.send(JSON.stringify(e))}addListener(e){const t=this.outputListeners.size>0;if(this.outputListeners.add(e),t||this.pendingAudioEvents.length===0)return;const n=this.pendingAudioEvents;this.pendingAudioEvents=[];for(const r of n)e(r)}removeListener(e){this.outputListeners.delete(e)}handleMessage(e){if(super.handleMessage(e),e.type==="audio"&&e.audio_event.audio_base_64){const t={audio_base_64:e.audio_event.audio_base_64};if(this.outputListeners.size===0){this.pendingAudioEvents.push(t);return}this.outputListeners.forEach(n=>n(t))}}}function zf(i,e){const t=n=>{const r=n.data[0];e.sendMessage({user_audio_chunk:$s(r.buffer)})};return i.addListener(t),()=>{i.removeListener(t)}}function Kf(i,e){const t=n=>{e.playAudio(bf(n.audio_base_64))};return i.addListener(t),()=>{i.removeListener(t)}}function Gf(i){const e="signedUrl"in i&&i.signedUrl,t="orchestrator"in i&&i.orchestrator;if(e&&i.connectionType==="webrtc")throw new Error("signedUrl only supports websocket connections. Remove connectionType or set it to 'websocket'.");if(t&&i.connectionType==="webrtc")throw new Error("Orchestrator sessions only support websocket connections. Remove connectionType or set it to 'websocket'.");if(t&&(e||"conversationToken"in i&&i.conversationToken||i.authorization))throw new Error("The orchestrator option cannot be combined with signedUrl, conversationToken or authorization.");return i.connectionType?i.connectionType:"conversationToken"in i&&i.conversationToken?"webrtc":e||t||i.textOnly?"websocket":"webrtc"}async function kl(i){const e=Gf(i);switch(e){case"websocket":return Zi.create(i);case"webrtc":return Xi.create(i);default:throw new Error(`Unknown connection type: ${e}`)}}const Jf={default:0,android:3e3};function Tl(i,e="default"){const t=i??Jf;return e==="android"?t.android??t.default:e==="ios"?t.ios??t.default:t.default}async function Sl(i){i>0&&await new Promise(e=>setTimeout(e,i))}const Qf=3e4,Yf=["touchstart","touchend","click"];let qt=null,Ft=null,Uo=!1;function $f(i){const e=i.createBuffer(1,1,22050),t=i.createBufferSource();t.buffer=e,t.connect(i.destination),t.start(0),i.resume().catch(()=>{})}function Xf(){Ft&&clearTimeout(Ft),Ft=setTimeout(()=>{Ft=null,ps()},Qf)}function wl(){Ft&&(clearTimeout(Ft),Ft=null)}function Zf(){if(!gn()||qt)return;const i=new AudioContext;$f(i),qt=i,Xf()}function ev(){if(!gn()||Uo||typeof document>"u")return;Uo=!0;const i=()=>{Zf()};for(const e of Yf)document.addEventListener(e,i,!0)}function tv(){const i=qt;return qt=null,wl(),i}function ps(){qt&&(qt.close().catch(()=>{}),qt=null,wl())}function nv(){return Uf()?"android":gn()?"ios":"default"}async function Fo(){if("wakeLock"in navigator)try{return await navigator.wakeLock.request("screen")}catch{}return null}async function iv(i,e,t){const[n,r]=await Promise.all([xn.create({...e.inputFormat,preferHeadphonesForIosDevices:i.preferHeadphonesForIosDevices,inputDeviceId:i.inputDeviceId,inputChunkDurationMs:i.inputChunkDurationMs,workletPaths:i.workletPaths,libsampleratePath:i.libsampleratePath}),Zs.create({...e.outputFormat,outputDeviceId:i.outputDeviceId,workletPaths:i.workletPaths,audioContext:t??void 0})]),s=zf(n,e),a=Kf(e,r);return{input:n,output:r,playbackEventTarget:r,detach:async()=>{s(),a()}}}async function rv(i){const e=i.useWakeLock??!0;let t=null,n=null,r=null;try{e&&(t=await Fo()),n=await navigator.mediaDevices.getUserMedia({audio:!0});const s=nv();await Sl(Tl(i.connectionDelay,s));const a=await kl(i);let o;try{a instanceof Zi?(r=tv(),o={connection:a,...await iv(i,a,r)},r=null):(ps(),o=Af(a))}catch(l){throw await r?.close().catch(()=>{}),r=null,a.close(),l}if(n){for(const l of n.getTracks())l.stop();n=null}let c=null;t&&(c=()=>{document.visibilityState==="visible"&&t?.released&&Fo().then(l=>{t=l})},document.addEventListener("visibilitychange",c));const d=o.detach;return{...o,detach:async()=>{await d(),c&&document.removeEventListener("visibilitychange",c);try{await t?.release(),t=null}catch{}}}}catch(s){if(n)for(const a of n.getTracks())a.stop();try{await t?.release(),t=null}catch{}throw ps(),s}}Mf(rv);class sv{constructor(){_(this,"audioElements",[]),_(this,"inputAudioContext",null),_(this,"audioCaptureContext",null)}async attachRemoteTrack(e,t){const n=e.attach();if(n.autoplay=!0,n.controls=!1,t&&n.setSinkId)try{await n.setSinkId(t)}catch(r){console.warn("Failed to set output device for new audio element:",r)}n.style.display="none",document.body.appendChild(n),this.audioElements.push(n)}setupInputAnalysis(e){this.inputAudioContext&&(this.inputAudioContext.close().catch(()=>{}),this.inputAudioContext=null);const t=new AudioContext,n=t.createAnalyser();return t.createMediaStreamSource(new MediaStream([e])).connect(n),this.inputAudioContext=t,{volumeProvider:Ai(n,t.sampleRate),analyser:n}}async setupOutputAnalysis(e,t,n,r){this.audioCaptureContext&&(this.audioCaptureContext.close().catch(()=>{}),this.audioCaptureContext=null);const s=new AudioContext;this.audioCaptureContext=s;const a=s.createAnalyser();a.fftSize=2048,a.smoothingTimeConstant=.8;const o=new MediaStream([e.mediaStreamTrack]),c=s.createMediaStreamSource(o),d=Ai(a,s.sampleRate);await bl(s.audioWorklet,r?.rawAudioProcessor);const l=new AudioWorkletNode(s,"rawAudioProcessor");return l.port.postMessage({type:"setFormat",format:t.format,sampleRate:t.sampleRate}),l.port.onmessage=u=>{const[h,p]=u.data;n(h.buffer,p)},c.connect(a),a.connect(l),{volumeProvider:d,analyser:a}}setVolume(e){for(const t of this.audioElements)t.volume=e}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await Promise.all(this.audioElements.map(async t=>{try{await t.setSinkId(e)}catch(n){throw console.error("Failed to set sink ID for audio element:",n),n}}))}cleanup(){this.inputAudioContext&&(this.inputAudioContext.close().catch(e=>{console.warn("Error closing input audio context:",e)}),this.inputAudioContext=null),this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null);for(const e of this.audioElements)e.remove();this.audioElements=[]}}let ms=null;function av(i){ms=i}function ov(){if(!ms)throw vl("Scribe microphone implementation");return ms}const cv=Xs("scribeAudioProcessor",`/*
272
+ * Scribe Audio Processor for converting microphone audio to PCM16 format
273
+ * Supports resampling for browsers like Firefox that don't support
274
+ * AudioContext sample rate constraints.
275
+ * USED BY @elevenlabs/client
276
+ */
277
+
278
+ class ScribeAudioProcessor extends AudioWorkletProcessor {
279
+ constructor() {
280
+ super();
281
+ this.buffer = [];
282
+ this.bufferSize = 4096; // Buffer size for optimal chunk transmission
283
+
284
+ // Resampling state
285
+ this.inputSampleRate = null;
286
+ this.outputSampleRate = null;
287
+ this.resampleRatio = 1;
288
+ this.lastSample = 0;
289
+ this.resampleAccumulator = 0;
290
+
291
+ this.port.onmessage = ({ data }) => {
292
+ if (data.type === "configure") {
293
+ this.inputSampleRate = data.inputSampleRate;
294
+ this.outputSampleRate = data.outputSampleRate;
295
+ if (this.inputSampleRate && this.outputSampleRate) {
296
+ this.resampleRatio = this.inputSampleRate / this.outputSampleRate;
297
+ }
298
+ }
299
+ };
300
+ }
301
+
302
+ // Linear interpolation resampling
303
+ resample(inputData) {
304
+ if (this.resampleRatio === 1 || !this.inputSampleRate) {
305
+ return inputData;
306
+ }
307
+
308
+ const outputSamples = [];
309
+
310
+ for (let i = 0; i < inputData.length; i++) {
311
+ const currentSample = inputData[i];
312
+
313
+ // Generate output samples using linear interpolation
314
+ while (this.resampleAccumulator < 1) {
315
+ const interpolated =
316
+ this.lastSample +
317
+ (currentSample - this.lastSample) * this.resampleAccumulator;
318
+ outputSamples.push(interpolated);
319
+ this.resampleAccumulator += this.resampleRatio;
320
+ }
321
+
322
+ this.resampleAccumulator -= 1;
323
+ this.lastSample = currentSample;
324
+ }
325
+
326
+ return new Float32Array(outputSamples);
327
+ }
328
+
329
+ process(inputs) {
330
+ const input = inputs[0];
331
+ if (input.length > 0) {
332
+ let channelData = input[0]; // Get first channel (mono)
333
+
334
+ // Resample if needed (for Firefox and other browsers that don't
335
+ // support AudioContext sample rate constraints)
336
+ if (this.resampleRatio !== 1) {
337
+ channelData = this.resample(channelData);
338
+ }
339
+
340
+ // Add incoming audio to buffer
341
+ for (let i = 0; i < channelData.length; i++) {
342
+ this.buffer.push(channelData[i]);
343
+ }
344
+
345
+ // When buffer reaches threshold, convert and send
346
+ if (this.buffer.length >= this.bufferSize) {
347
+ const float32Array = new Float32Array(this.buffer);
348
+ const int16Array = new Int16Array(float32Array.length);
349
+
350
+ // Convert Float32 [-1, 1] to Int16 [-32768, 32767]
351
+ for (let i = 0; i < float32Array.length; i++) {
352
+ // Clamp the value to prevent overflow
353
+ const sample = Math.max(-1, Math.min(1, float32Array[i]));
354
+ // Scale to PCM16 range
355
+ int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767;
356
+ }
357
+
358
+ // Send to main thread as transferable ArrayBuffer
359
+ this.port.postMessage(
360
+ {
361
+ audioData: int16Array.buffer
362
+ },
363
+ [int16Array.buffer]
364
+ );
365
+
366
+ // Clear buffer
367
+ this.buffer = [];
368
+ }
369
+ }
370
+
371
+ return true; // Continue processing
372
+ }
373
+ }
374
+
375
+ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
376
+
377
+ `),Dr=16e3,dv=async(i,e)=>{let t,n,r,s;const a=()=>{for(const o of t?.getTracks()??[])o.stop();r?.disconnect(),s?.disconnect(),n?.close()};try{t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:i.deviceId,echoCancellation:i.echoCancellation??!0,noiseSuppression:i.noiseSuppression??!0,autoGainControl:i.autoGainControl??!0,channelCount:i.channelCount??1,sampleRate:{ideal:Dr}}});const[o]=t.getAudioTracks(),c=o?.getSettings().sampleRate;return n=new AudioContext(c?{sampleRate:c}:{}),await cv(n.audioWorklet,i.workletPaths?.scribeAudioProcessor),r=n.createMediaStreamSource(t),s=new AudioWorkletNode(n,"scribeAudioProcessor"),n.sampleRate!==Dr&&s.port.postMessage({type:"configure",inputSampleRate:n.sampleRate,outputSampleRate:Dr}),s.port.onmessage=d=>{e($s(d.data.audioData))},r.connect(s),n.state==="suspended"&&await n.resume(),{mediaStreamTrack:o,cleanup:a}}catch(o){throw a(),o}},lv="https://api.elevenlabs.io";async function uv({conversationId:i,origin:e,file:t,filename:n}){const r=(e??lv).replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://"),s=n??("name"in t&&typeof t.name=="string"?t.name:`upload.${(t.type||"image/png").split("/").pop()?.split("+")[0]}`),a=new FormData;a.append("file",t,s);const o=await fetch(`${r}/v1/convai/conversations/${i}/files`,{method:"POST",body:a});if(!o.ok){const l=await Ho(o);throw new Error(`Upload failed: ${o.status} ${l}`)}const c=await o.json();Ml(c,"Upload response is not a JSON object");const{file_id:d}=c;if(typeof d!="string"||!d)throw new Error("Upload response is missing a valid file_id");return{fileId:d}}const Bo={reason:"agent",context:{type:"end_call",reason:"Agent ended the call"}};function Cl(i){const{textOnly:e}=i.overrides?.conversation??{},{textOnly:t}=i;return typeof t=="boolean"?(typeof e=="boolean"&&t!==e&&console.warn(`Conflicting textOnly options provided: ${t} via options.textOnly (will be used) and ${e} via options.overrides.conversation.textOnly (will be ignored)`),t):typeof e=="boolean"?e:void 0}class Oi{constructor(e,t){_(this,"options"),_(this,"connection"),_(this,"lastInterruptTimestamp",0),_(this,"mode","listening"),_(this,"status","connecting"),_(this,"volume",1),_(this,"currentEventId",1),_(this,"canSendFeedback",!1),_(this,"mcpApprovals",new Map),_(this,"endSessionWithDetails",async n=>{if(!(this.status!=="connected"&&this.status!=="connecting")){this.updateStatus("disconnecting");for(const r of this.mcpApprovals.keys())this.markMCPApprovalStale(r);try{await this.handleEndSession()}finally{this.updateStatus("disconnected"),this.options.onDisconnect&&this.options.onDisconnect(n)}}}),_(this,"onMessage",async n=>{switch(this.options.onIncomingEvent?.(n),n.type){case"interruption":{this.handleInterruption(n);return}case"agent_response":{this.handleAgentResponse(n);return}case"agent_response_correction":{this.handleAgentResponseCorrection(n);return}case"user_transcript":{this.handleUserTranscript(n);return}case"internal_tentative_agent_response":{this.handleTentativeAgentResponse(n);return}case"client_tool_call":{try{await this.handleClientToolCall(n)}catch(r){this.onError(`Unexpected error in client tool call handling: ${r instanceof Error?r.message:String(r)}`,{clientToolName:n.client_tool_call.tool_name,toolCallId:n.client_tool_call.tool_call_id})}return}case"audio":{this.handleAudio(n);return}case"vad_score":{this.handleVadScore(n);return}case"ping":{this.connection.sendMessage({type:"pong",event_id:n.ping_event.event_id}),this.handlePing(n);return}case"context_usage":{this.handleContextUsage(n);return}case"mcp_tool_call":{try{await this.handleMCPToolCall(n)}catch(r){this.onError(`Unexpected error in MCP tool call handling: ${r instanceof Error?r.message:String(r)}`,{toolCallId:n.mcp_tool_call.tool_call_id,toolName:n.mcp_tool_call.tool_name})}return}case"mcp_connection_status":{this.handleMCPConnectionStatus(n);return}case"agent_tool_request":{this.handleAgentToolRequest(n);return}case"agent_tool_response":{this.handleAgentToolResponse(n);return}case"agent_tool_response_full_payload":{this.handleAgentToolResponseFullPayload(n);return}case"conversation_initiation_metadata":{this.handleConversationMetadata(n);return}case"asr_initiation_metadata":{this.handleAsrInitiationMetadata(n);return}case"agent_chat_response_part":{this.handleAgentChatResponsePart(n);return}case"agent_reasoning_response_part":{this.handleAgentReasoningResponsePart(n);return}case"rich_content":{this.handleRichContent(n);return}case"guardrail_triggered":{this.handleGuardrailTriggered(n);return}case"error":{this.handleErrorEvent(n);return}case"agent_typing":{this.handleAgentTyping(n);return}case"external_agent_connected":{this.handleExternalAgentConnected(n);return}case"external_agent_disconnected":{this.handleExternalAgentDisconnected(n);return}default:{this.options.onDebug&&this.options.onDebug(n);return}}}),_(this,"onOutgoingMessage",n=>{this.options.onOutgoingEvent?.(n)}),this.options=e,this.connection=t,this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(n=>this.updateMode(n)),this.connection.onOutgoingMessage(this.onOutgoingMessage)}static getFullOptions(e){const t=Cl(e);return{clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{},onAgentResponseCorrection:()=>{},onAgentTyping:()=>{},onExternalAgentConnected:()=>{},onExternalAgentDisconnected:()=>{},onPing:()=>{},...e,textOnly:t,overrides:{...e.overrides,conversation:{...e.overrides?.conversation,textOnly:t}}}}markConnected(){this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}),this.updateCanSendFeedback())}updateCanSendFeedback(){const e=this.status==="connected";this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.currentEventId=e.agent_response_event.event_id,this.options.onMessage&&this.options.onMessage({source:"ai",role:"agent",message:e.agent_response_event.agent_response,event_id:e.agent_response_event.event_id})}handleAgentResponseCorrection(e){this.options.onAgentResponseCorrection&&this.options.onAgentResponseCorrection(e.agent_response_correction_event)}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",role:"user",message:e.user_transcription_event.user_transcript,event_id:e.user_transcription_event.event_id})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}handlePing(e){this.options.onPing&&this.options.onPing(e.ping_event)}handleContextUsage(e){this.options.onContextUsage&&this.options.onContextUsage(e.context_usage_event)}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{const t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??"Client tool execution successful.",n=typeof t=="object"?JSON.stringify(t):String(t);this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall){this.options.onUnhandledClientToolCall(e.client_tool_call);return}this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}async handleMCPToolCall(e){const t=e.mcp_tool_call;if(this.options.onMCPToolCall&&this.options.onMCPToolCall(t),t.state!=="awaiting_approval"){this.markMCPApprovalStale(t.tool_call_id);return}const n=this.options.onMCPToolApprovalRequest;if(!n)return;if(this.status==="disconnecting"||this.status==="disconnected"){this.onError(`Ignored an approval request for MCP tool call ${t.tool_call_id}, which arrived after the session ended`,this.mcpApprovalErrorContext(t));return}if(this.mcpApprovals.has(t.tool_call_id)){this.onError(`Ignored a repeated approval request for MCP tool call ${t.tool_call_id}, which has already been handled`,this.mcpApprovalErrorContext(t));return}const r={state:"pending",controller:new AbortController};this.mcpApprovals.set(t.tool_call_id,r);let s;try{s=await n(t,{signal:r.controller.signal})}catch(a){this.onError(`MCP tool approval handler failed: ${a?.message}`,this.mcpApprovalErrorContext(t)),this.settleMCPApproval(t,!1);return}if(typeof s!="boolean"){this.onError(`MCP tool approval handler must resolve to a boolean, received ${typeof s}`,this.mcpApprovalErrorContext(t)),this.settleMCPApproval(t,!1);return}this.settleMCPApproval(t,s)}settleMCPApproval(e,t){const n=this.mcpApprovals.get(e.tool_call_id);if(!n||n.state!=="pending"){this.onError(`Discarded an approval decision for MCP tool call ${e.tool_call_id}, which is no longer awaiting approval`,this.mcpApprovalErrorContext(e));return}n.state="settled",this.sendMCPToolApprovalResult(e.tool_call_id,t)}markMCPApprovalStale(e){const t=this.mcpApprovals.get(e);!t||t.state!=="pending"||(t.state="stale",t.controller.abort())}mcpApprovalErrorContext(e){return{toolCallId:e.tool_call_id,toolName:e.tool_name,serviceId:e.service_id}}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name==="end_call"&&this.endSessionWithDetails(Bo).catch(t=>{this.onError("Failed to end session after agent end_call",t)}),this.options.onAgentToolResponse?.(e.agent_tool_response)}handleAgentToolResponseFullPayload(e){e.agent_tool_response_full_payload.tool_name==="end_call"&&this.endSessionWithDetails(Bo).catch(t=>{this.onError("Failed to end session after agent end_call",t)}),this.options.onAgentToolResponse?.(e.agent_tool_response_full_payload)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleAgentReasoningResponsePart(e){this.options.onAgentReasoningResponsePart&&this.options.onAgentReasoningResponsePart(e.reasoning_response_part)}handleRichContent(e){this.options.onRichContent&&this.options.onRichContent(e.rich_content)}handleGuardrailTriggered(e){this.options.onGuardrailTriggered&&this.options.onGuardrailTriggered()}handleAgentTyping(e){this.options.onAgentTyping&&this.options.onAgentTyping(e.agent_typing_event)}handleExternalAgentConnected(e){this.options.onExternalAgentConnected&&this.options.onExternalAgentConnected()}handleExternalAgentDisconnected(e){this.options.onExternalAgentDisconnected&&this.options.onExternalAgentDisconnected()}handleErrorEvent(e){const t=e.error_event,n=t?.error_type,r=t?.message||t?.reason||"Unknown error";if(n==="max_duration_exceeded"){this.endSessionWithDetails({reason:"error",message:r,context:{type:"max_duration_exceeded"}}).catch(s=>{this.onError("Failed to end session after max_duration_exceeded",s)});return}this.onError(`Server error: ${r}`,{errorType:n,code:t?.code,debugMessage:t?.debug_message,details:t?.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}sendFeedback(e,t){if(!this.canSendFeedback){console.warn("Cannot send feedback: the conversation is not connected.");return}this.connection.sendMessage({type:"feedback",score:e!==null?e?"like":"dislike":null,event_id:t??this.currentEventId})}sendContextualUpdate(e,t){this.connection.sendMessage({type:"contextual_update",text:e,...t?.contextId?{context_id:t.contextId}:{}})}sendUserMessage(e,t){this.connection.sendMessage({type:"user_message",text:e,rich_content_id:t?.richContentId??void 0})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:t})}sendMultimodalMessage(e){const t=(e.fileIds?.length?e.fileIds:e.fileId?[e.fileId]:[]).map(n=>({type:"file_input",file_id:n}));this.connection.sendMessage({type:"multimodal_message",text:e.text?{type:"user_message",text:e.text}:void 0,file:t[0],files:t.length?t:void 0})}async uploadFile(e){if(this.options.orchestrator)throw new Error("uploadFile is not supported for self-hosted orchestrator sessions.");return uv({conversationId:this.connection.conversationId,origin:this.options.origin,file:e})}}function hv(){const i=["fetch","WebSocket","TextEncoder","TextDecoder","URL","btoa","atob"];for(const e of i)if(typeof globalThis[e]>"u")throw new Error(`${e} is not available in this environment.`)}const jo=new Uint8Array(0);class ea extends Oi{constructor(){super(...arguments),_(this,"type","text")}setVolume(){throw new Error("setVolume is not supported in text conversations")}setMicMuted(){throw new Error("setMicMuted is not supported in text conversations")}getInputByteFrequencyData(){return jo}getOutputByteFrequencyData(){return jo}getInputVolume(){return 0}getOutputVolume(){return 0}static async startSession(e){const t=Oi.getFullOptions(e);t.onStatusChange&&t.onStatusChange({status:"connecting"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1}),t.onModeChange&&t.onModeChange({mode:"listening"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1});let n=null,r=null;try{return await Sl(Tl(t.connectionDelay)),n=await kl(t),r=new ea(t,n),t.onConversationCreated?.(r),r.markConnected(),t.onConnect?.({conversationId:n.conversationId}),r}catch(s){throw r?await r.endSession().catch(()=>{}):(t.onStatusChange?.({status:"disconnected"}),n?.close()),s}}}const El=class mi extends Oi{constructor(e,t,n,r,s,a){super(e,t),_(this,"input"),_(this,"output"),_(this,"playbackEventTarget"),_(this,"cleanUp"),_(this,"type","voice"),_(this,"inputFrequencyData"),_(this,"outputFrequencyData"),_(this,"handlePlaybackEvent",o=>{o.data.type==="process"&&this.updateMode(o.data.finished?"listening":"speaking")}),_(this,"setVolume",({volume:o})=>{const c=Number.isFinite(o)?Math.min(1,Math.max(0,o)):1;this.volume=c,this.output.setVolume(c)}),this.input=n,this.output=r,this.playbackEventTarget=s,this.cleanUp=a,s?.addListener(this.handlePlaybackEvent)}static async startSession(e){const t=Oi.getFullOptions(e);t.onStatusChange&&t.onStatusChange({status:"connecting"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1});let n=null,r=null;try{return r=await Df()(t),n=new mi(t,r.connection,r.input,r.output,r.playbackEventTarget,r.detach),t.onConversationCreated?.(n),n.markConnected(),t.onConnect?.({conversationId:r.connection.conversationId}),n}catch(s){throw n?await n.endSession().catch(()=>{}):(r&&await r.detach().catch(()=>{}),t.onStatusChange?.({status:"disconnected"})),s}}async handleEndSession(){this.playbackEventTarget?.removeListener(this.handlePlaybackEvent),this.playbackEventTarget=null,await this.cleanUp(),await super.handleEndSession(),await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.updateMode("listening"),this.output.interrupt()}handleAudio(e){super.handleAudio(e),e.audio_event.alignment&&this.options.onAudioAlignment&&this.options.onAudioAlignment(e.audio_event.alignment),this.lastInterruptTimestamp<=e.audio_event.event_id&&(e.audio_event.audio_base_64&&this.options.onAudio?.(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(e){this.input.setMuted(e).catch(t=>{this.options.onError?.("Failed to set input muted state",t)})}getInputByteFrequencyData(){return this.inputFrequencyData??(this.inputFrequencyData=new Uint8Array(mi.FREQUENCY_BIN_COUNT)),this.input.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.outputFrequencyData??(this.outputFrequencyData=new Uint8Array(mi.FREQUENCY_BIN_COUNT)),this.output.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData}getInputVolume(){return this.input.getVolume()}getOutputVolume(){return this.output.getVolume()}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{await this.input.setDevice({inputDeviceId:r,sampleRate:e,format:t,preferHeadphonesForIosDevices:n})}catch(s){throw console.error("Error changing input device",s),s}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{await this.output.setDevice({outputDeviceId:n,sampleRate:e,format:t})}catch(r){throw console.error("Error changing output device",r),r}}};_(El,"FREQUENCY_BIN_COUNT",1024);let pv=El;const mv="https://api.elevenlabs.io";function kv(i,e,t=mv){const n={};return typeof e=="boolean"?n.feedback=e?"like":"dislike":(n.rating=e.rating,n.comment=e.comment),fetch(`${t}/v1/convai/conversations/${i}/feedback`,{method:"POST",body:JSON.stringify(n),headers:{"Content-Type":"application/json"}})}class gv{constructor(){_(this,"listeners",new Map)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);n&&n.add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(r=>{r(...t)})}}function fv(i){return typeof i=="object"&&i!==null&&"message_type"in i&&"error"in i&&typeof i.message_type=="string"&&typeof i.error=="string"?i:{message_type:"error",error:i instanceof Error?i.message:String(i)}}var V;(function(i){i.SESSION_STARTED="session_started",i.PARTIAL_TRANSCRIPT="partial_transcript",i.FINAL_TRANSCRIPT="final_transcript",i.FINAL_TRANSCRIPT_WITH_TIMESTAMPS="final_transcript_with_timestamps",i.COMMITTED_TRANSCRIPT="committed_transcript",i.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",i.COMMITTED_TRANSCRIPT_ENTITIES="committed_transcript_entities",i.AUTH_ERROR="auth_error",i.ERROR="error",i.OPEN="open",i.CLOSE="close",i.QUOTA_EXCEEDED="quota_exceeded",i.COMMIT_THROTTLED="commit_throttled",i.TRANSCRIBER_ERROR="transcriber_error",i.UNACCEPTED_TERMS="unaccepted_terms",i.RATE_LIMITED="rate_limited",i.INPUT_ERROR="input_error",i.INVALID_REQUEST="invalid_request",i.QUEUE_OVERFLOW="queue_overflow",i.RESOURCE_EXHAUSTED="resource_exhausted",i.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",i.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",i.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"})(V||(V={}));class vv{constructor(e){_(this,"websocket",null),_(this,"eventEmitter",new gv),_(this,"currentSampleRate",16e3),_(this,"_muted",!1),_(this,"_closed",!1),_(this,"_audioCleanup"),_(this,"_mediaStreamTrack"),this.currentSampleRate=e}get isMuted(){return this._muted}getMediaStreamTrackForMute(e){if(!this._mediaStreamTrack)throw new Error(`Cannot ${e} audio without an active microphone MediaStreamTrack. mute() and unmute() are only supported for microphone connections.`);return this._mediaStreamTrack}mute(){const e=this.getMediaStreamTrackForMute("mute");this._muted=!0,e.enabled=!1}unmute(){const e=this.getMediaStreamTrackForMute("unmute");this._muted=!1,e.enabled=!0}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(V.OPEN):this.websocket.addEventListener("open",()=>{this.eventEmitter.emit(V.OPEN)}),this.websocket.addEventListener("message",t=>{try{const n=JSON.parse(t.data);switch(n.message_type){case"session_started":this.eventEmitter.emit(V.SESSION_STARTED,n);break;case"partial_transcript":this.eventEmitter.emit(V.PARTIAL_TRANSCRIPT,n);break;case"final_transcript":this.eventEmitter.emit(V.FINAL_TRANSCRIPT,n);break;case"final_transcript_with_timestamps":this.eventEmitter.emit(V.FINAL_TRANSCRIPT_WITH_TIMESTAMPS,n);break;case"committed_transcript":this.eventEmitter.emit(V.COMMITTED_TRANSCRIPT,n);break;case"committed_transcript_with_timestamps":this.eventEmitter.emit(V.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,n);break;case"committed_transcript_entities":this.eventEmitter.emit(V.COMMITTED_TRANSCRIPT_ENTITIES,n);break;case"auth_error":this.eventEmitter.emit(V.AUTH_ERROR,n),this.eventEmitter.emit(V.ERROR,n);break;case"quota_exceeded":this.eventEmitter.emit(V.QUOTA_EXCEEDED,n),this.eventEmitter.emit(V.ERROR,n);break;case"commit_throttled":this.eventEmitter.emit(V.COMMIT_THROTTLED,n),this.eventEmitter.emit(V.ERROR,n);break;case"transcriber_error":this.eventEmitter.emit(V.TRANSCRIBER_ERROR,n),this.eventEmitter.emit(V.ERROR,n);break;case"unaccepted_terms":this.eventEmitter.emit(V.UNACCEPTED_TERMS,n),this.eventEmitter.emit(V.ERROR,n);break;case"rate_limited":this.eventEmitter.emit(V.RATE_LIMITED,n),this.eventEmitter.emit(V.ERROR,n);break;case"input_error":this.eventEmitter.emit(V.INPUT_ERROR,n),this.eventEmitter.emit(V.ERROR,n);break;case"invalid_request":this.eventEmitter.emit(V.INVALID_REQUEST,n),this.eventEmitter.emit(V.ERROR,n);break;case"queue_overflow":this.eventEmitter.emit(V.QUEUE_OVERFLOW,n),this.eventEmitter.emit(V.ERROR,n);break;case"resource_exhausted":this.eventEmitter.emit(V.RESOURCE_EXHAUSTED,n),this.eventEmitter.emit(V.ERROR,n);break;case"session_time_limit_exceeded":this.eventEmitter.emit(V.SESSION_TIME_LIMIT_EXCEEDED,n),this.eventEmitter.emit(V.ERROR,n);break;case"chunk_size_exceeded":this.eventEmitter.emit(V.CHUNK_SIZE_EXCEEDED,n),this.eventEmitter.emit(V.ERROR,n);break;case"insufficient_audio_activity":this.eventEmitter.emit(V.INSUFFICIENT_AUDIO_ACTIVITY,n),this.eventEmitter.emit(V.ERROR,n);break;case"error":this.eventEmitter.emit(V.ERROR,n);break;default:console.warn("Unknown message type:",n)}}catch(n){console.error("Failed to parse WebSocket message:",n,t.data),this._emitError(new Error(`Failed to parse message: ${n}`))}}),this.websocket.addEventListener("error",t=>{this._closed||(console.error("WebSocket error:",t),this._emitError(new Error("WebSocket error")))}),this.websocket.addEventListener("close",t=>{const n=this._closed;if(this._closed=!0,!n&&(console.log(`WebSocket closed: code=${t.code}, reason="${t.reason}", wasClean=${t.wasClean}`),!t.wasClean||t.code!==1e3&&t.code!==1005)){const r=`WebSocket closed unexpectedly: ${t.code} - ${t.reason||"No reason provided"}`;console.error(r),this._emitError(new Error(r))}this._audioCleanup&&(this._audioCleanup(),this._audioCleanup=void 0),this.eventEmitter.emit(V.CLOSE,t)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}_emitError(e){this.eventEmitter.emit(V.ERROR,fv(e))}send(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");const t={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:e.commit??!1,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(t))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");const e={message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate};this.websocket.send(JSON.stringify(e))}close(){this._closed=!0,this._audioCleanup&&(this._audioCleanup(),this._audioCleanup=void 0),this.websocket&&this.websocket.close(1e3,"User ended session")}}var qo;(function(i){i.PCM_8000="pcm_8000",i.PCM_16000="pcm_16000",i.PCM_22050="pcm_22050",i.PCM_24000="pcm_24000",i.PCM_44100="pcm_44100",i.PCM_48000="pcm_48000",i.ULAW_8000="ulaw_8000"})(qo||(qo={}));var Vo;(function(i){i.MANUAL="manual",i.VAD="vad"})(Vo||(Vo={}));const Rl=class En{static getWebSocketUri(e=En.DEFAULT_BASE_URI){return`${e}/v1/speech-to-text/realtime`}static buildWebSocketUri(e){const t=En.getWebSocketUri(e.baseUri),n=new URLSearchParams;if(n.append("model_id",e.modelId),n.append("token",e.token),e.commitStrategy!==void 0&&n.append("commit_strategy",e.commitStrategy),e.audioFormat!==void 0&&n.append("audio_format",e.audioFormat),e.vadSilenceThresholdSecs!==void 0){if(e.vadSilenceThresholdSecs<.3||e.vadSilenceThresholdSecs>3)throw new Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");n.append("vad_silence_threshold_secs",e.vadSilenceThresholdSecs.toString())}if(e.vadThreshold!==void 0){if(e.vadThreshold<.1||e.vadThreshold>.9)throw new Error("vadThreshold must be between 0.1 and 0.9");n.append("vad_threshold",e.vadThreshold.toString())}if(e.minSpeechDurationMs!==void 0){if(e.minSpeechDurationMs<50||e.minSpeechDurationMs>2e3)throw new Error("minSpeechDurationMs must be between 50 and 2000");n.append("min_speech_duration_ms",e.minSpeechDurationMs.toString())}if(e.minSilenceDurationMs!==void 0){if(e.minSilenceDurationMs<50||e.minSilenceDurationMs>2e3)throw new Error("minSilenceDurationMs must be between 50 and 2000");n.append("min_silence_duration_ms",e.minSilenceDurationMs.toString())}if(e.languageCode!==void 0&&n.append("language_code",e.languageCode),e.secondaryLanguages!==void 0)for(const s of e.secondaryLanguages)n.append("secondary_languages",s);if(e.includeTimestamps!==void 0&&n.append("include_timestamps",e.includeTimestamps?"true":"false"),e.includeLanguageDetection!==void 0&&n.append("include_language_detection",e.includeLanguageDetection?"true":"false"),e.keyterms!==void 0)for(const s of e.keyterms)n.append("keyterms",s);if(e.noVerbatim!==void 0&&n.append("no_verbatim",e.noVerbatim?"true":"false"),e.entityDetection!==void 0){const s=Array.isArray(e.entityDetection)?e.entityDetection:[e.entityDetection];for(const a of s)n.append("entity_detection",a)}e.filterBackgroundAudio!==void 0&&n.append("filter_background_audio",e.filterBackgroundAudio?"true":"false"),e.enableLogging!==void 0&&n.append("enable_logging",e.enableLogging?"true":"false");const r=n.toString();return r?`${t}?${r}`:t}static connect(e){if(!e.modelId)throw new Error("modelId is required");const t="microphone"in e&&e.microphone?16e3:e.sampleRate,n=new vv(t),r=En.buildWebSocketUri(e),s=new WebSocket(r);return"microphone"in e&&e.microphone&&s.addEventListener("open",()=>{En.streamFromMicrophone(e,n)}),n.setWebSocket(s),n}static async streamFromMicrophone(e,t){try{const n=await ov()(e.microphone??{},r=>{t._closed||t.send({audioBase64:r})});t._mediaStreamTrack=n.mediaStreamTrack,t._audioCleanup=n.cleanup,t._closed&&(n.cleanup(),t._audioCleanup=void 0)}catch(n){console.error("Failed to start microphone streaming:",n),t._emitError(n),t.close()}}};_(Rl,"DEFAULT_BASE_URI","wss://api.elevenlabs.io");let Tv=Rl;const Sv={async startSession(i){return hv(),Cl(i)?ea.startSession(i):pv.startSession(i)}};ev();Sf(()=>new sv);av(dv);export{qo as AudioFormat,Vo as CommitStrategy,Sv as Conversation,Bf as DEFAULT_INPUT_CHUNK_DURATION_MS,vv as RealtimeConnection,V as RealtimeEvents,Tv as Scribe,ia as SessionConnectionError,ea as TextConversation,pv as VoiceConversation,Xi as WebRTCConnection,Zi as WebSocketConnection,kl as createConnection,kv as postOverallFeedback};