livekit-client 2.15.6 → 2.15.8

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 (173) hide show
  1. package/dist/livekit-client.e2ee.worker.js +1 -1
  2. package/dist/livekit-client.e2ee.worker.js.map +1 -1
  3. package/dist/livekit-client.e2ee.worker.mjs +253 -118
  4. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  5. package/dist/livekit-client.esm.mjs +1892 -153
  6. package/dist/livekit-client.esm.mjs.map +1 -1
  7. package/dist/livekit-client.umd.js +1 -1
  8. package/dist/livekit-client.umd.js.map +1 -1
  9. package/dist/src/connectionHelper/checks/publishVideo.d.ts.map +1 -1
  10. package/dist/src/e2ee/E2eeManager.d.ts +16 -2
  11. package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
  12. package/dist/src/e2ee/types.d.ts +35 -1
  13. package/dist/src/e2ee/types.d.ts.map +1 -1
  14. package/dist/src/e2ee/utils.d.ts +2 -0
  15. package/dist/src/e2ee/utils.d.ts.map +1 -1
  16. package/dist/src/e2ee/worker/DataCryptor.d.ts +15 -0
  17. package/dist/src/e2ee/worker/DataCryptor.d.ts.map +1 -0
  18. package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts +3 -2
  19. package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts.map +1 -1
  20. package/dist/src/e2ee/worker/sifPayload.d.ts +6 -6
  21. package/dist/src/e2ee/worker/sifPayload.d.ts.map +1 -1
  22. package/dist/src/index.d.ts +5 -3
  23. package/dist/src/index.d.ts.map +1 -1
  24. package/dist/src/logger.d.ts +1 -0
  25. package/dist/src/logger.d.ts.map +1 -1
  26. package/dist/src/options.d.ts +4 -2
  27. package/dist/src/options.d.ts.map +1 -1
  28. package/dist/src/room/PCTransport.d.ts.map +1 -1
  29. package/dist/src/room/RTCEngine.d.ts +5 -2
  30. package/dist/src/room/RTCEngine.d.ts.map +1 -1
  31. package/dist/src/room/Room.d.ts +3 -2
  32. package/dist/src/room/Room.d.ts.map +1 -1
  33. package/dist/src/room/data-stream/incoming/IncomingDataStreamManager.d.ts +2 -2
  34. package/dist/src/room/data-stream/incoming/IncomingDataStreamManager.d.ts.map +1 -1
  35. package/dist/src/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts.map +1 -1
  36. package/dist/src/room/errors.d.ts +2 -1
  37. package/dist/src/room/errors.d.ts.map +1 -1
  38. package/dist/src/room/participant/LocalParticipant.d.ts +1 -3
  39. package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
  40. package/dist/src/room/participant/Participant.d.ts +2 -2
  41. package/dist/src/room/participant/Participant.d.ts.map +1 -1
  42. package/dist/src/room/token-source/TokenSource.d.ts +70 -0
  43. package/dist/src/room/token-source/TokenSource.d.ts.map +1 -0
  44. package/dist/src/room/token-source/types.d.ts +68 -0
  45. package/dist/src/room/token-source/types.d.ts.map +1 -0
  46. package/dist/src/room/token-source/utils.d.ts +5 -0
  47. package/dist/src/room/token-source/utils.d.ts.map +1 -0
  48. package/dist/src/room/track/LocalTrack.d.ts +1 -1
  49. package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
  50. package/dist/src/room/track/options.d.ts +7 -3
  51. package/dist/src/room/track/options.d.ts.map +1 -1
  52. package/dist/src/room/track/utils.d.ts.map +1 -1
  53. package/dist/src/room/types.d.ts +1 -0
  54. package/dist/src/room/types.d.ts.map +1 -1
  55. package/dist/src/room/utils.d.ts +2 -1
  56. package/dist/src/room/utils.d.ts.map +1 -1
  57. package/dist/src/utils/camelToSnakeCase.d.ts +8 -0
  58. package/dist/src/utils/camelToSnakeCase.d.ts.map +1 -0
  59. package/dist/ts4.2/{src/e2ee → e2ee}/E2eeManager.d.ts +16 -2
  60. package/dist/ts4.2/{src/e2ee → e2ee}/types.d.ts +35 -1
  61. package/dist/ts4.2/{src/e2ee → e2ee}/utils.d.ts +3 -0
  62. package/dist/ts4.2/e2ee/worker/DataCryptor.d.ts +15 -0
  63. package/dist/ts4.2/{src/e2ee → e2ee}/worker/ParticipantKeyHandler.d.ts +3 -2
  64. package/dist/ts4.2/{src/e2ee → e2ee}/worker/sifPayload.d.ts +6 -6
  65. package/dist/ts4.2/{src/index.d.ts → index.d.ts} +5 -3
  66. package/dist/ts4.2/{src/logger.d.ts → logger.d.ts} +1 -0
  67. package/dist/ts4.2/{src/options.d.ts → options.d.ts} +4 -2
  68. package/dist/ts4.2/{src/room → room}/RTCEngine.d.ts +5 -2
  69. package/dist/ts4.2/{src/room → room}/Room.d.ts +3 -2
  70. package/dist/ts4.2/{src/room → room}/data-stream/incoming/IncomingDataStreamManager.d.ts +2 -1
  71. package/dist/ts4.2/{src/room → room}/errors.d.ts +2 -1
  72. package/dist/ts4.2/{src/room → room}/participant/LocalParticipant.d.ts +1 -3
  73. package/dist/ts4.2/{src/room → room}/participant/Participant.d.ts +2 -2
  74. package/dist/ts4.2/room/token-source/TokenSource.d.ts +71 -0
  75. package/dist/ts4.2/room/token-source/types.d.ts +68 -0
  76. package/dist/ts4.2/room/token-source/utils.d.ts +5 -0
  77. package/dist/ts4.2/{src/room → room}/track/LocalTrack.d.ts +1 -1
  78. package/dist/ts4.2/{src/room → room}/track/options.d.ts +10 -3
  79. package/dist/ts4.2/{src/room → room}/types.d.ts +1 -0
  80. package/dist/ts4.2/{src/room → room}/utils.d.ts +2 -1
  81. package/dist/ts4.2/utils/camelToSnakeCase.d.ts +8 -0
  82. package/package.json +14 -12
  83. package/src/connectionHelper/checks/publishVideo.ts +5 -0
  84. package/src/e2ee/E2eeManager.ts +94 -2
  85. package/src/e2ee/types.ts +44 -1
  86. package/src/e2ee/utils.ts +16 -0
  87. package/src/e2ee/worker/DataCryptor.test.ts +271 -0
  88. package/src/e2ee/worker/DataCryptor.ts +147 -0
  89. package/src/e2ee/worker/ParticipantKeyHandler.ts +4 -3
  90. package/src/e2ee/worker/e2ee.worker.ts +47 -0
  91. package/src/e2ee/worker/sifPayload.ts +10 -6
  92. package/src/index.ts +14 -1
  93. package/src/logger.ts +1 -0
  94. package/src/options.ts +8 -2
  95. package/src/room/PCTransport.ts +14 -5
  96. package/src/room/RTCEngine.ts +55 -6
  97. package/src/room/Room.ts +39 -17
  98. package/src/room/data-stream/incoming/IncomingDataStreamManager.ts +64 -17
  99. package/src/room/data-stream/outgoing/OutgoingDataStreamManager.ts +7 -0
  100. package/src/room/errors.ts +3 -0
  101. package/src/room/participant/LocalParticipant.ts +17 -29
  102. package/src/room/participant/Participant.ts +6 -1
  103. package/src/room/token-source/TokenSource.ts +285 -0
  104. package/src/room/token-source/types.ts +84 -0
  105. package/src/room/token-source/utils.ts +35 -0
  106. package/src/room/track/LocalAudioTrack.ts +1 -1
  107. package/src/room/track/LocalTrack.ts +1 -1
  108. package/src/room/track/options.ts +12 -4
  109. package/src/room/track/utils.ts +10 -2
  110. package/src/room/types.ts +1 -0
  111. package/src/room/utils.ts +8 -4
  112. package/src/utils/camelToSnakeCase.ts +16 -0
  113. /package/dist/ts4.2/{src/api → api}/SignalClient.d.ts +0 -0
  114. /package/dist/ts4.2/{src/api → api}/utils.d.ts +0 -0
  115. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/ConnectionCheck.d.ts +0 -0
  116. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/Checker.d.ts +0 -0
  117. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/cloudRegion.d.ts +0 -0
  118. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/connectionProtocol.d.ts +0 -0
  119. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/publishAudio.d.ts +0 -0
  120. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/publishVideo.d.ts +0 -0
  121. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/reconnect.d.ts +0 -0
  122. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/turn.d.ts +0 -0
  123. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/webrtc.d.ts +0 -0
  124. /package/dist/ts4.2/{src/connectionHelper → connectionHelper}/checks/websocket.d.ts +0 -0
  125. /package/dist/ts4.2/{src/e2ee → e2ee}/KeyProvider.d.ts +0 -0
  126. /package/dist/ts4.2/{src/e2ee → e2ee}/constants.d.ts +0 -0
  127. /package/dist/ts4.2/{src/e2ee → e2ee}/errors.d.ts +0 -0
  128. /package/dist/ts4.2/{src/e2ee → e2ee}/events.d.ts +0 -0
  129. /package/dist/ts4.2/{src/e2ee → e2ee}/index.d.ts +0 -0
  130. /package/dist/ts4.2/{src/e2ee → e2ee}/worker/FrameCryptor.d.ts +0 -0
  131. /package/dist/ts4.2/{src/e2ee → e2ee}/worker/e2ee.worker.d.ts +0 -0
  132. /package/dist/ts4.2/{src/e2ee → e2ee}/worker/naluUtils.d.ts +0 -0
  133. /package/dist/ts4.2/{src/room → room}/DefaultReconnectPolicy.d.ts +0 -0
  134. /package/dist/ts4.2/{src/room → room}/DeviceManager.d.ts +0 -0
  135. /package/dist/ts4.2/{src/room → room}/PCTransport.d.ts +0 -0
  136. /package/dist/ts4.2/{src/room → room}/PCTransportManager.d.ts +0 -0
  137. /package/dist/ts4.2/{src/room → room}/ReconnectPolicy.d.ts +0 -0
  138. /package/dist/ts4.2/{src/room → room}/RegionUrlProvider.d.ts +0 -0
  139. /package/dist/ts4.2/{src/room → room}/attribute-typings.d.ts +0 -0
  140. /package/dist/ts4.2/{src/room → room}/data-stream/incoming/StreamReader.d.ts +0 -0
  141. /package/dist/ts4.2/{src/room → room}/data-stream/outgoing/OutgoingDataStreamManager.d.ts +0 -0
  142. /package/dist/ts4.2/{src/room → room}/data-stream/outgoing/StreamWriter.d.ts +0 -0
  143. /package/dist/ts4.2/{src/room → room}/defaults.d.ts +0 -0
  144. /package/dist/ts4.2/{src/room → room}/events.d.ts +0 -0
  145. /package/dist/ts4.2/{src/room → room}/participant/ParticipantTrackPermission.d.ts +0 -0
  146. /package/dist/ts4.2/{src/room → room}/participant/RemoteParticipant.d.ts +0 -0
  147. /package/dist/ts4.2/{src/room → room}/participant/publishUtils.d.ts +0 -0
  148. /package/dist/ts4.2/{src/room → room}/rpc.d.ts +0 -0
  149. /package/dist/ts4.2/{src/room → room}/stats.d.ts +0 -0
  150. /package/dist/ts4.2/{src/room → room}/timers.d.ts +0 -0
  151. /package/dist/ts4.2/{src/room → room}/track/LocalAudioTrack.d.ts +0 -0
  152. /package/dist/ts4.2/{src/room → room}/track/LocalTrackPublication.d.ts +0 -0
  153. /package/dist/ts4.2/{src/room → room}/track/LocalVideoTrack.d.ts +0 -0
  154. /package/dist/ts4.2/{src/room → room}/track/RemoteAudioTrack.d.ts +0 -0
  155. /package/dist/ts4.2/{src/room → room}/track/RemoteTrack.d.ts +0 -0
  156. /package/dist/ts4.2/{src/room → room}/track/RemoteTrackPublication.d.ts +0 -0
  157. /package/dist/ts4.2/{src/room → room}/track/RemoteVideoTrack.d.ts +0 -0
  158. /package/dist/ts4.2/{src/room → room}/track/Track.d.ts +0 -0
  159. /package/dist/ts4.2/{src/room → room}/track/TrackPublication.d.ts +0 -0
  160. /package/dist/ts4.2/{src/room → room}/track/create.d.ts +0 -0
  161. /package/dist/ts4.2/{src/room → room}/track/facingMode.d.ts +0 -0
  162. /package/dist/ts4.2/{src/room → room}/track/processor/types.d.ts +0 -0
  163. /package/dist/ts4.2/{src/room → room}/track/record.d.ts +0 -0
  164. /package/dist/ts4.2/{src/room → room}/track/types.d.ts +0 -0
  165. /package/dist/ts4.2/{src/room → room}/track/utils.d.ts +0 -0
  166. /package/dist/ts4.2/{src/test → test}/MockMediaStreamTrack.d.ts +0 -0
  167. /package/dist/ts4.2/{src/test → test}/mocks.d.ts +0 -0
  168. /package/dist/ts4.2/{src/utils → utils}/AsyncQueue.d.ts +0 -0
  169. /package/dist/ts4.2/{src/utils → utils}/browserParser.d.ts +0 -0
  170. /package/dist/ts4.2/{src/utils → utils}/cloneDeep.d.ts +0 -0
  171. /package/dist/ts4.2/{src/utils → utils}/dataPacketBuffer.d.ts +0 -0
  172. /package/dist/ts4.2/{src/utils → utils}/ttlmap.d.ts +0 -0
  173. /package/dist/ts4.2/{src/version.d.ts → version.d.ts} +0 -0
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var i=Object.defineProperty,n=(e,t,n)=>((e,t,n)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class s{constructor(){n(this,"_locking"),n(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}}function r(e,t){if(!e)throw new Error(t)}const o=34028234663852886e22,a=-34028234663852886e22,c=4294967295,d=2147483647,l=-2147483648;function u(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>d||e<l)throw new Error("invalid int 32: "+e)}function h(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>c||e<0)throw new Error("invalid uint 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>o||e<a))throw new Error("invalid float 32: "+e)}const m=Symbol("@bufbuild/protobuf/enum-type");function g(e){const t=e[m];return r(t,"missing enum type on enum object"),t}function v(e,t,i,n){e[m]=f(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function f(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const e of t){const t=b(e);r.push(t),n[e.name]=t,s[e.no]=t}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function k(e,t,i){const n={};for(const e of t){const t=b(e);n[t.localName]=t.no,n[t.no]=t.localName}return v(n,e,t),n}function b(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class y{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function T(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,0==(128&i))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,0==(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function C(e,t,i){for(let n=0;n<28;n+=7){const s=e>>>n,r=!(s>>>7==0&&0==t),o=255&(r?128|s:s);if(i.push(o),!r)return}const n=e>>>28&15|(7&t)<<4,s=!(t>>3==0);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const S=4294967296;function E(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=S&&(s+=n/S|0,n%=S)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?R(n,s):P(n,s)}function w(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(S*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+I(r)+I(s)}function P(e,t){return{lo:0|e,hi:0|t}}function R(e,t){return t=~t,e?e=1+~e:t+=1,P(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function O(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function D(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const x=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>r(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>r(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),E(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),E(e)),dec:(e,t)=>function(e,t){let i=P(e,t);const n=2147483648&i.hi;n&&(i=R(i.lo,i.hi));const s=w(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>w(e,t)}}();var M,A,_;function N(e,t,i){if(t===i)return!0;if(e==M.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return t==i}return!1}function L(e,t){switch(e){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return 0==t?x.zero:"0";case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}function U(e,t){switch(e){case M.BOOL:return!1===t;case M.STRING:return""===t;case M.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(M||(M={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(A||(A={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(_||(_={}));class j{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].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(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),O(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),O(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=x.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=x.enc(e);return C(t.lo,t.hi,this.buf),this}sint64(e){let t=x.enc(e),i=t.hi>>31;return C(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=x.uEnc(e);return C(t.lo,t.hi,this.buf),this}}class F{constructor(e,t){this.varint64=T,this.uint32=D,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case _.Varint:for(;128&this.buf[this.pos++];);break;case _.Bit64:this.pos+=4;case _.Bit32:this.pos+=4;break;case _.LengthDelimited:let i=this.uint32();this.pos+=i;break;case _.StartGroup:for(;;){const[e,i]=this.tag();if(i===_.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return x.dec(...this.varint64())}uint64(){return x.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,x.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return x.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return x.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 B(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return L(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let V="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),q=[];for(let e=0;e<V.length;e++)q[V[e].charCodeAt(0)]=e;q["-".charCodeAt(0)]=V.indexOf("+"),q["_".charCodeAt(0)]=V.indexOf("/");const K={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let t=0;t<e.length;t++){if(i=q[e.charCodeAt(t)],void 0===i)switch(e[t]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=V[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=V[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=V[s|t>>6],i+=V[63&t],n=0}return n&&(i+=V[s],i+="=",1==n&&(i+="=")),i}};function H(e,t,i){z(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=B(t);for(const e of s)t.runtime.bin.readField(r,n.readerFactory(e.data),t.field,e.wireType,n);return o()}function W(e,t,i,n){z(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(G(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function G(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function z(e,t){r(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function J(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!U(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function Q(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?L(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(y.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function X(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}M.DOUBLE,M.FLOAT,M.INT64,M.UINT64,M.INT32,M.UINT32,M.BOOL,M.STRING,M.BYTES;const Z={ignoreUnknownFields:!1},$={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ee(e){return e?Object.assign(Object.assign({},Z),e):Z}function te(e){return e?Object.assign(Object.assign({},$),e):$}const ie=Symbol(),ne=Symbol();function se(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function re(e,t,i,n,s){let o=i.localName;if(i.repeated){if(r("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(t)));const a=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=ce(i.T,e,n.ignoreUnknownFields,!0);t!==ne&&a.push(t);break;case"scalar":try{a.push(ae(i.T,e,i.L,!0))}catch(t){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(e));throw t instanceof Error&&t.message.length>0&&(n+=": ".concat(t.message)),new Error(n)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(t)));const r=e[o];for(const[e,o]of Object.entries(t)){if(null===o)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let a;try{a=oe(i.K,e)}catch(e){let n="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}switch(i.V.kind){case"message":r[a]=i.V.T.fromJson(o,n);break;case"enum":const e=ce(i.V.T,o,n.ignoreUnknownFields,!0);e!==ne&&(r[a]=e);break;case"scalar":try{r[a]=ae(i.V.T,o,A.BIGINT,!0)}catch(e){let n="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:o},o="value"),i.kind){case"message":const r=i.T;if(null===t&&"google.protobuf.Value"!=r.typeName)return;let a=e[o];Y(a)?a.fromJson(t,n):(e[o]=a=r.fromJson(t,n),r.fieldWrapper&&!i.oneof&&(e[o]=r.fieldWrapper.unwrapField(a)));break;case"enum":const c=ce(i.T,t,n.ignoreUnknownFields,!1);switch(c){case ie:Q(i,e);break;case ne:break;default:e[o]=c}break;case"scalar":try{const n=ae(i.T,t,i.L,!1);if(n===ie)Q(i,e);else e[o]=n}catch(e){let n="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(se(t));throw e instanceof Error&&e.message.length>0&&(n+=": ".concat(e.message)),new Error(n)}}}function oe(e,t){if(e===M.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ae(e,t,A.BIGINT,!0).toString()}function ae(e,t,i,n){if(null===t)return n?L(e,i):ie;switch(e){case M.DOUBLE:case M.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==M.FLOAT&&p(n),n;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==M.UINT32||e==M.FIXED32?h(s):u(s),s;case M.INT64:case M.SFIXED64:case M.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=x.parse(t);return i?r.toString():r;case M.FIXED64:case M.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=x.uParse(t);return i?o.toString():o;case M.BOOL:if("boolean"!=typeof t)break;return t;case M.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case M.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return K.dec(t)}throw new Error}function ce(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:ie;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return ne}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(se(t)))}function de(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function le(e,t,i){if("map"==e.kind){r("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,i]of s)n[t.toString()]=he(e.V.T,i);break;case"message":for(const[e,t]of s)n[e.toString()]=t.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=ue(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){r(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(he(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(ue(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return he(e.T,t);case"enum":return ue(e.T,t,i.enumAsInteger);case"message":return X(e.T,t).toJson(i)}}function ue(e,t,i){var n;if(r("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function he(e,t){switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:case M.FIXED32:case M.UINT32:return r("number"==typeof t),t;case M.FLOAT:case M.DOUBLE:return r("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case M.STRING:return r("string"==typeof t),t;case M.BOOL:return r("boolean"==typeof t),t;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return r("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case M.BYTES:return r(t instanceof Uint8Array),K.enc(t)}}const pe=Symbol("@bufbuild/protobuf/unknown-fields"),me={readUnknownFields:!0,readerFactory:e=>new F(e)},ge={writeUnknownFields:!0,writerFactory:()=>new j};function ve(e){return e?Object.assign(Object.assign({},me),e):me}function fe(e){return e?Object.assign(Object.assign({},ge),e):ge}function ke(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?M.INT32:i.T;let c=Te;if("scalar"==i.kind&&i.L>0&&(c=ye),r){let i=e[o];if(n==_.LengthDelimited&&a!=M.STRING&&a!=M.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(be(t,new d,s,i)):Y(e[o])?be(t,e[o],s,i):(e[o]=be(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=Te(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Te(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=be(t,new e.V.T,i,void 0)}}}void 0===r&&(r=L(e.K,A.BIGINT));"string"!=typeof r&&"number"!=typeof r&&(r=r.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=L(e.V.T,A.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function be(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function ye(e,t){const i=Te(e,t);return"bigint"==typeof i?i.toString():i}function Te(e,t){switch(t){case M.STRING:return e.string();case M.BOOL:return e.bool();case M.DOUBLE:return e.double();case M.FLOAT:return e.float();case M.INT32:return e.int32();case M.INT64:return e.int64();case M.UINT64:return e.uint64();case M.FIXED64:return e.fixed64();case M.BYTES:return e.bytes();case M.FIXED32:return e.fixed32();case M.SFIXED32:return e.sfixed32();case M.SFIXED64:return e.sfixed64();case M.SINT64:return e.sint64();case M.UINT32:return e.uint32();case M.SINT32:return e.sint32()}}function Ce(e,t,i,n){r(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?M.INT32:e.T;if(s)if(r(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,_.LengthDelimited).fork();let[,s]=Pe(t);for(let t=0;t<n.length;t++)e[s](n[t]);e.join()}(i,o,e.no,t);else for(const n of t)we(i,o,e.no,n);else we(i,o,e.no,t);break;case"message":if(s){r(Array.isArray(t));for(const s of t)Ee(i,n,e,s)}else Ee(i,n,e,t);break;case"map":r("object"==typeof t&&null!=t);for(const[s,r]of Object.entries(t))Se(i,n,e,s,r)}}function Se(e,t,i,n,s){e.tag(i.no,_.LengthDelimited),e.fork();let o=n;switch(i.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:o=Number.parseInt(n);break;case M.BOOL:r("true"==n||"false"==n),o="true"==n}switch(we(e,i.K,1,o),i.V.kind){case"scalar":we(e,i.V.T,2,s);break;case"enum":we(e,M.INT32,2,s);break;case"message":r(void 0!==s),e.tag(2,_.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Ee(e,t,i,n){const s=X(i.T,n);i.delimited?e.tag(i.no,_.StartGroup).raw(s.toBinary(t)).tag(i.no,_.EndGroup):e.tag(i.no,_.LengthDelimited).bytes(s.toBinary(t))}function we(e,t,i,n){r(void 0!==n);let[s,o]=Pe(t);e.tag(i,s)[o](n)}function Pe(e){let t=_.Varint;switch(e){case M.BYTES:case M.STRING:t=_.LengthDelimited;break;case M.DOUBLE:case M.FIXED64:case M.SFIXED64:t=_.Bit64;break;case M.FIXED32:case M.SFIXED32:case M.FLOAT:t=_.Bit32}return[t,M[e].toLowerCase()]}function Re(e){if(void 0===e)return e;if(Y(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ie(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Oe{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function De(e,t){const i=Me(e);return t?i:Ue(Le(i))}const xe=Me;function Me(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const Ae=new Set(["constructor","toString","toJSON","valueOf"]),_e=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ne=e=>"".concat(e,"$"),Le=e=>_e.has(e)?Ne(e):e,Ue=e=>Ae.has(e)?Ne(e):e;class je{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=De(e,!1)}addField(e){r(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const Fe=(Be=e=>new Oe(e,(e=>function(e,t){var i,n,s,r,o,a;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=De(t.name,void 0!==t.oneof),e.jsonName=null!==(i=t.jsonName)&&void 0!==i?i:xe(t.name),e.repeated=null!==(n=t.repeated)&&void 0!==n&&n,"scalar"==t.kind&&(e.L=null!==(s=t.L)&&void 0!==s?s:A.BIGINT),e.delimited=null!==(r=t.delimited)&&void 0!==r&&r,e.req=null!==(o=t.req)&&void 0!==o&&o,e.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=M.BYTES&&t.T!=M.STRING),void 0!==t.oneof){const i="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==i||(d=new je(i)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),Ve=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=L(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ee,makeWriteOptions:te,readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(se(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}re(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=B(s);re(e,a,s.field,i,s),W(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!J(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!de(s))continue}const i=le(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&G(e,o)){const i=H(e,o,t),s=le(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),n=e instanceof Error?e.message:String(e);throw new Error(t+(n.length>0?": ".concat(n):""))}return n},readScalar:(e,t,i)=>ae(e,t,null!=i?i:A.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||U(e,t)?he(e,t):void 0},debug:se},bin:{makeReadOptions:ve,makeWriteOptions:fe,listUnknownFields(e){var t;return null!==(t=e[pe])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[pe]},writeUnknownFields(e,t){const i=e[pe];if(i)for(const e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[pe])||(s[pe]=[]),s[pe].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=_.EndGroup);){const i=r.fields.find(a);if(i)ke(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=_.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:ke,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(J(s,e))Ce(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Ce(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:v,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!Y(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===M.BYTES&&(o=Ie(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===M.BYTES&&(a=n.repeated?a.map(Ie):Ie(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===M.BYTES)for(const[e,t]of Object.entries(r[i]))s[i][e]=Ie(t);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>Y(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Ie(e):s[i]=e:s[i]=Y(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>N(e.T,t,s[i])));case"enum":return n.every(((e,t)=>N(M.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=n,i=s;return e.T.fieldWrapper&&(void 0===t||Y(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===i||Y(i)||(i=e.T.fieldWrapper.wrapField(i))),e.T.equals(t,i);case"enum":return N(M.INT32,n,s);case"scalar":return N(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const r=e.findField(n.case);if(void 0===r)return!0;switch(r.kind){case"message":return r.T.equals(n.value,s.value);case"enum":return N(M.INT32,n.value,s.value);case"scalar":return N(r.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(r.kind));case"map":const o=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(n[e],s[e])));case"enum":return o.every((e=>N(M.INT32,n[e],s[e])));case"scalar":const i=e.V.T;return o.every((e=>N(i,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const i of t.fields.byMember()){const t=e[i.localName];let s;if(i.repeated)s=t.map(Re);else if("map"==i.kind){s=n[i.localName];for(const[e,i]of Object.entries(t))s[e]=Re(i)}else s="oneof"==i.kind?i.findField(t.case)?{case:t.case,value:Re(t.value)}:{case:void 0}:Re(t);n[i.localName]=s}for(const i of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,i.no,i.wireType,i.data);return i}}),{newFieldList:Be,initFields:Ve}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new y),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:k,makeEnumType:f,getEnumType:g,makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var Be,Ve;class qe extends y{constructor(e){super(),this.seconds=x.zero,this.nanos=0,Fe.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Fe.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=x.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return qe.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new qe({seconds:x.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new qe).fromBinary(e,t)}static fromJson(e,t){return(new qe).fromJson(e,t)}static fromJsonString(e,t){return(new qe).fromJsonString(e,t)}static equals(e,t){return Fe.util.equals(qe,e,t)}}qe.runtime=Fe,qe.typeName="google.protobuf.Timestamp",qe.fields=Fe.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Ke=Fe.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:qe},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:He,repeated:!0},{no:5,name:"events",kind:"message",T:Ge,repeated:!0}])),He=Fe.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:We,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),We=Fe.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:qe},{no:3,name:"value",kind:"scalar",T:2}])),Ge=Fe.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:qe},{no:7,name:"normalized_end_timestamp",kind:"message",T:qe,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),ze=Fe.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Je=Fe.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Qe=Fe.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"}]),Ye=Fe.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Xe=Fe.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ze=Fe.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),$e=Fe.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"}]),et=Fe.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"}]),tt=Fe.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),it=Fe.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"}]),nt=Fe.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:st,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:Nt}])),st=Fe.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),rt=Fe.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:Fe.getEnumType(Qe),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}])),ot=Fe.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:Fe.getEnumType(at)},{no:4,name:"tracks",kind:"message",T:ht,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:rt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Fe.getEnumType(ct)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Fe.getEnumType($e)},{no:18,name:"kind_details",kind:"enum",T:Fe.getEnumType(dt),repeated:!0}])),at=Fe.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ct=Fe.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),dt=Fe.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),lt=Fe.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),ut=Fe.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:pt,repeated:!0}])),ht=Fe.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Fe.getEnumType(Je)},{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:Fe.getEnumType(Qe)},{no:10,name:"layers",kind:"message",T:pt,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:ut,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:Fe.getEnumType(lt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Nt},{no:19,name:"audio_features",kind:"enum",T:Fe.getEnumType(it),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Fe.getEnumType(ze)}])),pt=Fe.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Fe.getEnumType(Ye)},{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}])),mt=Fe.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Fe.getEnumType(gt)},{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:kt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:vt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:bt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:yt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Ke,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Ct,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:St,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Et,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:wt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ft,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Bt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Vt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),gt=Fe.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),vt=Fe.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ft,repeated:!0}])),ft=Fe.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}])),kt=Fe.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}])),bt=Fe.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),yt=Fe.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:Tt,repeated:!0}])),Tt=Fe.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}])),Ct=Fe.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}])),St=Fe.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}])),Et=Fe.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),wt=Fe.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:Pt,oneof:"value"}])),Pt=Fe.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}])),Rt=Fe.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),It=Fe.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Fe.getEnumType(Ot)},{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}])),Ot=Fe.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Dt=Fe.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Fe.getEnumType(xt)},{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}])),xt=Fe.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"}]),Mt=Fe.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:At},{no:2,name:"screen",kind:"message",T:At},{no:3,name:"resume_connection",kind:"enum",T:Fe.getEnumType(Ze)},{no:4,name:"disabled_codecs",kind:"message",T:_t},{no:5,name:"force_relay",kind:"enum",T:Fe.getEnumType(Ze)}])),At=Fe.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Fe.getEnumType(Ze)}])),_t=Fe.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:st,repeated:!0},{no:2,name:"publish",kind:"message",T:st,repeated:!0}])),Nt=Fe.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Lt=Fe.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Ut=Fe.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Fe.getEnumType(Lt)},{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"}),jt=Fe.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Ft=Fe.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:Fe.getEnumType(lt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ut,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:jt,oneof:"content_header"}]),{localName:"DataStream_Header"}),Bt=Fe.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"}),Vt=Fe.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"}),qt=Fe.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Kt=Fe.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Ht=Fe.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Wt=Fe.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:ti,oneof:"message"},{no:2,name:"answer",kind:"message",T:ti,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Qt,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Jt,oneof:"message"},{no:5,name:"mute",kind:"message",T:Yt,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ni,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:si,oneof:"message"},{no:8,name:"leave",kind:"message",T:ai,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:di,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ci,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:wi,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ii,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:li,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Oi,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ri,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:oi,oneof:"message"}])),Gt=Fe.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Xt,oneof:"message"},{no:2,name:"answer",kind:"message",T:ti,oneof:"message"},{no:3,name:"offer",kind:"message",T:ti,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Qt,oneof:"message"},{no:5,name:"update",kind:"message",T:ii,oneof:"message"},{no:6,name:"track_published",kind:"message",T:$t,oneof:"message"},{no:8,name:"leave",kind:"message",T:ai,oneof:"message"},{no:9,name:"mute",kind:"message",T:Yt,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:hi,oneof:"message"},{no:11,name:"room_update",kind:"message",T:pi,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:gi,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:fi,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:yi,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Si,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ei,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Zt,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Di,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Ai,oneof:"message"},{no:22,name:"request_response",kind:"message",T:_i,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Li,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Ei,oneof:"message"}])),zt=Fe.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),Jt=Fe.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:Fe.getEnumType(Je)},{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:Fe.getEnumType(Qe)},{no:9,name:"layers",kind:"message",T:pt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:zt,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:Fe.getEnumType(lt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Fe.getEnumType(ze)},{no:17,name:"audio_features",kind:"enum",T:Fe.getEnumType(it),repeated:!0}])),Qt=Fe.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Fe.getEnumType(qt)},{no:3,name:"final",kind:"scalar",T:8}])),Yt=Fe.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Xt=Fe.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:nt},{no:2,name:"participant",kind:"message",T:ot},{no:3,name:"other_participants",kind:"message",T:ot,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ui,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:Mt},{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:It},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:st,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Zt=Fe.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:ui,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Mt},{no:3,name:"server_info",kind:"message",T:It},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),$t=Fe.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ht}])),ei=Fe.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),ti=Fe.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}])),ii=Fe.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:ot,repeated:!0}])),ni=Fe.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:Rt,repeated:!0}])),si=Fe.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:Fe.getEnumType(Ye)},{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}])),ri=Fe.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Fe.getEnumType(it),repeated:!0}])),oi=Fe.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}])),ai=Fe.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Fe.getEnumType($e)},{no:3,name:"action",kind:"enum",T:Fe.getEnumType(ci)},{no:4,name:"regions",kind:"message",T:xi}])),ci=Fe.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),di=Fe.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:pt,repeated:!0}])),li=Fe.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}])),ui=Fe.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}])),hi=Fe.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ft,repeated:!0}])),pi=Fe.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:nt}])),mi=Fe.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Fe.getEnumType(Xe)},{no:3,name:"score",kind:"scalar",T:2}])),gi=Fe.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:mi,repeated:!0}])),vi=Fe.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:Fe.getEnumType(Kt)}])),fi=Fe.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:vi,repeated:!0}])),ki=Fe.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Fe.getEnumType(Ye)},{no:2,name:"enabled",kind:"scalar",T:8}])),bi=Fe.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ki,repeated:!0}])),yi=Fe.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ki,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:bi,repeated:!0}])),Ti=Fe.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}])),Ci=Fe.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ti,repeated:!0}])),Si=Fe.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}])),Ei=Fe.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:nt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ot},{no:4,name:"other_participants",kind:"message",T:ot,repeated:!0}])),wi=Fe.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:ti},{no:2,name:"subscription",kind:"message",T:ni},{no:3,name:"publish_tracks",kind:"message",T:$t,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ri,repeated:!0},{no:5,name:"offer",kind:"message",T:ti},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Pi,repeated:!0}])),Pi=Fe.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),Ri=Fe.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:Fe.getEnumType(qt)}])),Ii=Fe.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:Fe.getEnumType(Ht),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"}])),Oi=Fe.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Di=Fe.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),xi=Fe.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:Mi,repeated:!0}])),Mi=Fe.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}])),Ai=Fe.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Fe.getEnumType(tt)}])),_i=Fe.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Fe.getEnumType(Ni)},{no:3,name:"message",kind:"scalar",T:9}])),Ni=Fe.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Li=Fe.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function Ui(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ji,Fi={exports:{}},Bi=Fi.exports;var Vi,qi,Ki=(ji||(ji=1,function(e){var t,i;t=Bi,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},e.exports?e.exports=i():t.log=i()}(Fi)),Fi.exports);e.LogLevel=void 0,(Vi=e.LogLevel||(e.LogLevel={}))[Vi.trace=0]="trace",Vi[Vi.debug=1]="debug",Vi[Vi.info=2]="info",Vi[Vi.warn=3]="warn",Vi[Vi.error=4]="error",Vi[Vi.silent=5]="silent",e.LoggerNames=void 0,(qi=e.LoggerNames||(e.LoggerNames={})).Default="livekit",qi.Room="livekit-room",qi.Participant="livekit-participant",qi.Track="livekit-track",qi.Publication="livekit-track-publication",qi.Engine="livekit-engine",qi.Signal="livekit-signal",qi.PCManager="livekit-pc-manager",qi.PCTransport="livekit-pc-transport",qi.E2EE="lk-e2ee";let Hi=Ki.getLogger("livekit");const Wi=Object.values(e.LoggerNames).map((e=>Ki.getLogger(e)));function Gi(e){const t=Ki.getLogger(e);return t.setDefaultLevel(Hi.getLevel()),t}Hi.setDefaultLevel(e.LogLevel.info);const zi=Ki.getLogger("lk-e2ee"),Ji=7e3,Qi=[0,300,1200,2700,4800,Ji,Ji,Ji,Ji,Ji];class Yi{constructor(e){this._retryDelays=void 0!==e?[...e]:Qi}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function Xi(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Zi(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function $i(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=Zi(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var en,tn={exports:{}};var nn=function(){if(en)return tn.exports;en=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}tn.exports=s,tn.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,s,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(o(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},tn.exports}();let sn=!0,rn=!0;function on(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function an(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function cn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(sn=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function dn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(rn=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function ln(){if("object"==typeof window){if(sn)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function un(e,t){rn&&console.warn(e+" is deprecated, please use "+t+" instead.")}function hn(e){return"[object Object]"===Object.prototype.toString.call(e)}function pn(e){return hn(e)?Object.keys(e).reduce((function(t,i){const n=hn(e[i]),s=n?pn(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function mn(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?mn(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{mn(e,e.get(t),i)}))})))}function gn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&mn(e,i,s)}))})),s}const vn=ln;function fn(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),vn("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return vn("chrome: "+JSON.stringify(e)),s(e)},r=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(r(e))))))}}}function kn(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function bn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else an(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function yn(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Tn(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>gn(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),an(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>gn(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Cn(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Sn(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Cn(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:r(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function En(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function wn(e,t){an(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Pn=Object.freeze({__proto__:null,fixNegotiationNeeded:wn,shimAddTrackRemoveTrack:Sn,shimAddTrackRemoveTrackWithNative:Cn,shimGetSendersWithDtmf:yn,shimGetUserMedia:fn,shimMediaStream:kn,shimOnTrack:bn,shimPeerConnection:En,shimSenderReceiverGetStats:Tn});function Rn(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){un("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function In(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function On(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function Dn(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function xn(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),an(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Mn(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){un("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function An(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function _n(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function Nn(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Ln(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function Un(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var jn=Object.freeze({__proto__:null,shimAddTransceiver:_n,shimCreateAnswer:Un,shimCreateOffer:Ln,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:Nn,shimGetUserMedia:Rn,shimOnTrack:In,shimPeerConnection:On,shimRTCDataChannel:An,shimReceiverGetStats:xn,shimRemoveStream:Mn,shimSenderGetStats:Dn});function Fn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function Bn(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function Vn(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function qn(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(Kn(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function Kn(e){return e&&void 0!==e.video?Object.assign({},e,{video:pn(e.video)}):e}function Hn(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(un("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Wn(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gn(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function zn(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Jn,Qn=Object.freeze({__proto__:null,shimAudioContext:zn,shimCallbacksAPI:Vn,shimConstraints:Kn,shimCreateOfferLegacy:Gn,shimGetUserMedia:qn,shimLocalStreamsAPI:Fn,shimRTCIceServerUrls:Hn,shimRemoteStreamsAPI:Bn,shimTrackEventTransceiver:Wn}),Yn={exports:{}};var Xn=(Jn||(Jn=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i=n[e].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let s=3;s<n.length;s++){const r=n[s],o=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const n=t.parseRtpMap(o),s=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=s.length?t.parseFmtp(s[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-1!==n.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(Yn)),Yn.exports),Zn=Ui(Xn),$n=t({__proto__:null,default:Zn},[Xn]);function es(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=Zn.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,an(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function ts(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||an(e,"icecandidate",(e=>{if(e.candidate){const t=Zn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function is(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Zn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Zn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=Zn.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function ns(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},an(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function ss(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function rs(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function os(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function as(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var cs=Object.freeze({__proto__:null,removeExtmapAllowMixed:rs,shimAddIceCandidateNullOrEmpty:os,shimConnectionState:ss,shimMaxMessageSize:is,shimParameterlessSetLocalDescription:as,shimRTCIceCandidate:es,shimRTCIceCandidateRelayProtocol:ts,shimSendThrowTypeError:ns});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=ln,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=parseInt(on(i.userAgent,/Firefox\/(\d+)\./,1));else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(on(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(on(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=on(i.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:n,commonShim:cs,extractVersion:on,disableLog:cn,disableWarnings:dn,sdp:$n};switch(n.browser){case"chrome":if(!Pn||!En||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Pn,os(e,n),as(e),fn(e,n),kn(e),En(e,n),bn(e),Sn(e,n),yn(e),Tn(e),wn(e,n),es(e),ts(e),ss(e),is(e,n),ns(e),rs(e,n);break;case"firefox":if(!jn||!On||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=jn,os(e,n),as(e),Rn(e,n),On(e,n),In(e),Mn(e),Dn(e),xn(e),An(e),_n(e),Nn(e),Ln(e),Un(e),es(e),ss(e),is(e,n),ns(e);break;case"safari":if(!Qn||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=Qn,os(e,n),as(e),Hn(e),Gn(e),Vn(e),Fn(e),Bn(e),Wn(e),qn(e),zn(e),es(e),ts(e),is(e,n),ns(e),rs(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const ds="AES-GCM",ls="lk_e2ee",us={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};var hs,ps;function ms(){return vs()||gs()}function gs(){return void 0!==window.RTCRtpScriptTransform}function vs(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function fs(e){return Xi(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function ks(e){return Xi(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function bs(e,t){const i=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:i,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:i,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(hs=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",hs.RatchetRequest="ratchetRequest",hs.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(ps=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",ps.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class ys extends nn.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t,i)=>{Hi.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},us),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,i,n){const s={key:t,participantIdentity:i,keyIndex:n};if(!this.options.sharedKey&&!i)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=i?i:"shared","-").concat(null!=n?n:0),s),this.emit(e.KeyProviderEvent.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,i){this.emit(e.KeyProviderEvent.RatchetRequest,t,i)}}class Ts extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Cs,Ss,Es,ws,Ps,Rs,Is,Os;e.ConnectionErrorReason=void 0,(Cs=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[Cs.NotAllowed=0]="NotAllowed",Cs[Cs.ServerUnreachable=1]="ServerUnreachable",Cs[Cs.InternalError=2]="InternalError",Cs[Cs.Cancelled=3]="Cancelled",Cs[Cs.LeaveRequest=4]="LeaveRequest",Cs[Cs.Timeout=5]="Timeout";class Ds extends Ts{constructor(t,i,n,s){super(1,t),this.name="ConnectionError",this.status=n,this.reason=i,this.context=s,this.reasonName=e.ConnectionErrorReason[i]}}class xs extends Ts{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ms extends Ts{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class As extends Ts{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class _s extends Ts{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ns extends Ts{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Ls extends Ts{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Us extends Ts{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:Ni[t]}}e.DataStreamErrorReason=void 0,(Ss=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[Ss.AlreadyOpened=0]="AlreadyOpened",Ss[Ss.AbnormalEnd=1]="AbnormalEnd",Ss[Ss.DecodeFailed=2]="DecodeFailed",Ss[Ss.LengthExceeded=3]="LengthExceeded",Ss[Ss.Incomplete=4]="Incomplete",Ss[Ss.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered";class js extends Ts{constructor(t,i){super(16,t),this.name="DataStreamError",this.reason=i,this.reasonName=e.DataStreamErrorReason[i]}}e.MediaDeviceFailure=void 0,(Es=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",Es.NotFound="NotFound",Es.DeviceInUse="DeviceInUse",Es.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={})),e.CryptorErrorReason=void 0,(ws=e.CryptorErrorReason||(e.CryptorErrorReason={}))[ws.InvalidKey=0]="InvalidKey",ws[ws.MissingKey=1]="MissingKey",ws[ws.InternalError=2]="InternalError";e.RoomEvent=void 0,(Ps=e.RoomEvent||(e.RoomEvent={})).Connected="connected",Ps.Reconnecting="reconnecting",Ps.SignalReconnecting="signalReconnecting",Ps.Reconnected="reconnected",Ps.Disconnected="disconnected",Ps.ConnectionStateChanged="connectionStateChanged",Ps.Moved="moved",Ps.MediaDevicesChanged="mediaDevicesChanged",Ps.ParticipantConnected="participantConnected",Ps.ParticipantDisconnected="participantDisconnected",Ps.TrackPublished="trackPublished",Ps.TrackSubscribed="trackSubscribed",Ps.TrackSubscriptionFailed="trackSubscriptionFailed",Ps.TrackUnpublished="trackUnpublished",Ps.TrackUnsubscribed="trackUnsubscribed",Ps.TrackMuted="trackMuted",Ps.TrackUnmuted="trackUnmuted",Ps.LocalTrackPublished="localTrackPublished",Ps.LocalTrackUnpublished="localTrackUnpublished",Ps.LocalAudioSilenceDetected="localAudioSilenceDetected",Ps.ActiveSpeakersChanged="activeSpeakersChanged",Ps.ParticipantMetadataChanged="participantMetadataChanged",Ps.ParticipantNameChanged="participantNameChanged",Ps.ParticipantAttributesChanged="participantAttributesChanged",Ps.ParticipantActive="participantActive",Ps.RoomMetadataChanged="roomMetadataChanged",Ps.DataReceived="dataReceived",Ps.SipDTMFReceived="sipDTMFReceived",Ps.TranscriptionReceived="transcriptionReceived",Ps.ConnectionQualityChanged="connectionQualityChanged",Ps.TrackStreamStateChanged="trackStreamStateChanged",Ps.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Ps.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Ps.AudioPlaybackStatusChanged="audioPlaybackChanged",Ps.VideoPlaybackStatusChanged="videoPlaybackChanged",Ps.MediaDevicesError="mediaDevicesError",Ps.ParticipantPermissionsChanged="participantPermissionsChanged",Ps.SignalConnected="signalConnected",Ps.RecordingStatusChanged="recordingStatusChanged",Ps.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Ps.EncryptionError="encryptionError",Ps.DCBufferStatusChanged="dcBufferStatusChanged",Ps.ActiveDeviceChanged="activeDeviceChanged",Ps.ChatMessage="chatMessage",Ps.LocalTrackSubscribed="localTrackSubscribed",Ps.MetricsReceived="metricsReceived",e.ParticipantEvent=void 0,(Rs=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",Rs.TrackSubscribed="trackSubscribed",Rs.TrackSubscriptionFailed="trackSubscriptionFailed",Rs.TrackUnpublished="trackUnpublished",Rs.TrackUnsubscribed="trackUnsubscribed",Rs.TrackMuted="trackMuted",Rs.TrackUnmuted="trackUnmuted",Rs.LocalTrackPublished="localTrackPublished",Rs.LocalTrackUnpublished="localTrackUnpublished",Rs.LocalTrackCpuConstrained="localTrackCpuConstrained",Rs.LocalSenderCreated="localSenderCreated",Rs.ParticipantMetadataChanged="participantMetadataChanged",Rs.ParticipantNameChanged="participantNameChanged",Rs.DataReceived="dataReceived",Rs.SipDTMFReceived="sipDTMFReceived",Rs.TranscriptionReceived="transcriptionReceived",Rs.IsSpeakingChanged="isSpeakingChanged",Rs.ConnectionQualityChanged="connectionQualityChanged",Rs.TrackStreamStateChanged="trackStreamStateChanged",Rs.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Rs.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Rs.TrackCpuConstrained="trackCpuConstrained",Rs.MediaDevicesError="mediaDevicesError",Rs.AudioStreamAcquired="audioStreamAcquired",Rs.ParticipantPermissionsChanged="participantPermissionsChanged",Rs.PCTrackAdded="pcTrackAdded",Rs.AttributesChanged="attributesChanged",Rs.LocalTrackSubscribed="localTrackSubscribed",Rs.ChatMessage="chatMessage",Rs.Active="active",e.EngineEvent=void 0,(Is=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",Is.Connected="connected",Is.Disconnected="disconnected",Is.Resuming="resuming",Is.Resumed="resumed",Is.Restarting="restarting",Is.Restarted="restarted",Is.SignalResumed="signalResumed",Is.SignalRestarted="signalRestarted",Is.Closing="closing",Is.MediaTrackAdded="mediaTrackAdded",Is.ActiveSpeakersUpdate="activeSpeakersUpdate",Is.DataPacketReceived="dataPacketReceived",Is.RTPVideoMapUpdate="rtpVideoMapUpdate",Is.DCBufferStatusChanged="dcBufferStatusChanged",Is.ParticipantUpdate="participantUpdate",Is.RoomUpdate="roomUpdate",Is.SpeakersChanged="speakersChanged",Is.StreamStateChanged="streamStateChanged",Is.ConnectionQualityUpdate="connectionQualityUpdate",Is.SubscriptionError="subscriptionError",Is.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Is.RemoteMute="remoteMute",Is.SubscribedQualityUpdate="subscribedQualityUpdate",Is.LocalTrackUnpublished="localTrackUnpublished",Is.LocalTrackSubscribed="localTrackSubscribed",Is.Offline="offline",Is.SignalRequestResponse="signalRequestResponse",Is.SignalConnected="signalConnected",Is.RoomMoved="roomMoved",e.TrackEvent=void 0,(Os=e.TrackEvent||(e.TrackEvent={})).Message="message",Os.Muted="muted",Os.Unmuted="unmuted",Os.Restarted="restarted",Os.Ended="ended",Os.Subscribed="subscribed",Os.Unsubscribed="unsubscribed",Os.CpuConstrained="cpuConstrained",Os.UpdateSettings="updateSettings",Os.UpdateSubscription="updateSubscription",Os.AudioPlaybackStarted="audioPlaybackStarted",Os.AudioPlaybackFailed="audioPlaybackFailed",Os.AudioSilenceDetected="audioSilenceDetected",Os.VisibilityChanged="visibilityChanged",Os.VideoDimensionsChanged="videoDimensionsChanged",Os.VideoPlaybackStarted="videoPlaybackStarted",Os.VideoPlaybackFailed="videoPlaybackFailed",Os.ElementAttached="elementAttached",Os.ElementDetached="elementDetached",Os.UpstreamPaused="upstreamPaused",Os.UpstreamResumed="upstreamResumed",Os.SubscriptionPermissionChanged="subscriptionPermissionChanged",Os.SubscriptionStatusChanged="subscriptionStatusChanged",Os.SubscriptionFailed="subscriptionFailed",Os.TrackProcessorUpdate="trackProcessorUpdate",Os.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Os.TranscriptionReceived="transcriptionReceived",Os.TimeSyncUpdate="timeSyncUpdate",Os.PreConnectBufferFlushed="preConnectBufferFlushed";const Fs=/version\/(\d+(\.?_?\d+)+)/i;let Bs;function Vs(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===Bs||t){const e=qs.find((e=>{let{test:t}=e;return t.test(i)}));Bs=null==e?void 0:e.describe(i)}return Bs}const qs=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ks(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Hs(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ks(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Hs(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ks(Fs,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Hs(e)})}];function Ks(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function Hs(e){return e.includes("mac os")?Ks(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const Ws="2.15.6";class Gs{}Gs.setTimeout=function(){return setTimeout(...arguments)},Gs.setInterval=function(){return setInterval(...arguments)},Gs.clearTimeout=function(){return clearTimeout(...arguments)},Gs.clearInterval=function(){return clearInterval(...arguments)};const zs=[];e.VideoQuality=void 0,function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(e.VideoQuality||(e.VideoQuality={}));class Js extends nn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Js.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Hi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Gi(null!==(s=n.loggerName)&&void 0!==s?s:e.LoggerNames.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=i,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=Js.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ao(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let i="audio";this.kind===Js.Kind.Video&&(i="video"),0===this.attachedElements.length&&this.kind===Js.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===i&&(zs.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&zs.splice(zs.indexOf(t),1)),t||(t=document.createElement(i))),this.attachedElements.includes(t)||this.attachedElements.push(t),Qs(this.mediaStreamTrack,t);const n=t.srcObject.getTracks(),s=n.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(s?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((i=>{"NotAllowedError"===i.name?this.emit(s?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,i):"AbortError"===i.name?Hi.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Hi.warn("could not playback ".concat(s?"audio":"video"),i),s&&t&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===i.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Ys(this.mediaStreamTrack,t);const i=this.attachedElements.indexOf(t);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const i=[];return this.attachedElements.forEach((t=>{Ys(this.mediaStreamTrack,t),i.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],i}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Gi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),zs.forEach((e=>{e.parentElement||(t=!1)})),t&&zs.push(e)}}handleAppVisibilityChanged(){return Xi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Js.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){br()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){br()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Qs(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),gr()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(gr()||mr())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Ys(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t,i,n;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(i=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(n=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Je.AUDIO;case t.Video:return Je.VIDEO;default:return Je.DATA}},e.kindFromProto=function(e){switch(e){case Je.AUDIO:return t.Audio;case Je.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case i.Camera:return Qe.CAMERA;case i.Microphone:return Qe.MICROPHONE;case i.ScreenShare:return Qe.SCREEN_SHARE;case i.ScreenShareAudio:return Qe.SCREEN_SHARE_AUDIO;default:return Qe.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Qe.CAMERA:return i.Camera;case Qe.MICROPHONE:return i.Microphone;case Qe.SCREEN_SHARE:return i.ScreenShare;case Qe.SCREEN_SHARE_AUDIO:return i.ScreenShareAudio;default:return i.Unknown}},e.streamStateFromProto=function(e){switch(e){case Kt.ACTIVE:return n.Active;case Kt.PAUSED:return n.Paused;default:return n.Unknown}}}(Js||(Js={}));class Xs{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Zs=["vp8","h264"],$s=["vp8","h264","vp9","av1","h265"];function er(e){return!!Zs.find((t=>t===e))}var tr;e.BackupCodecPolicy=void 0,function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(e.BackupCodecPolicy||(e.BackupCodecPolicy={})),e.AudioPresets=void 0,(tr=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},tr.speech={maxBitrate:24e3},tr.music={maxBitrate:48e3},tr.musicStereo={maxBitrate:64e3},tr.musicHighQuality={maxBitrate:96e3},tr.musicHighQualityStereo={maxBitrate:128e3};const ir={h90:new Xs(160,90,9e4,20),h180:new Xs(320,180,16e4,20),h216:new Xs(384,216,18e4,20),h360:new Xs(640,360,45e4,20),h540:new Xs(960,540,8e5,25),h720:new Xs(1280,720,17e5,30),h1080:new Xs(1920,1080,3e6,30),h1440:new Xs(2560,1440,5e6,30),h2160:new Xs(3840,2160,8e6,30)},nr={h120:new Xs(160,120,7e4,20),h180:new Xs(240,180,125e3,20),h240:new Xs(320,240,14e4,20),h360:new Xs(480,360,33e4,20),h480:new Xs(640,480,5e5,20),h540:new Xs(720,540,6e5,25),h720:new Xs(960,720,13e5,30),h1080:new Xs(1440,1080,23e5,30),h1440:new Xs(1920,1440,38e5,30)},sr={h360fps3:new Xs(640,360,2e5,3,"medium"),h360fps15:new Xs(640,360,4e5,15,"medium"),h720fps5:new Xs(1280,720,8e5,5,"medium"),h720fps15:new Xs(1280,720,15e5,15,"medium"),h720fps30:new Xs(1280,720,2e6,30,"medium"),h1080fps15:new Xs(1920,1080,25e5,15,"medium"),h1080fps30:new Xs(1920,1080,5e6,30,"medium"),original:new Xs(0,0,7e6,30,"medium")},rr="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function or(e){return Xi(this,void 0,void 0,(function*(){return new Promise((t=>Gs.setTimeout(t,e)))}))}function ar(){return"addTransceiver"in RTCPeerConnection.prototype}function cr(){return"addTrack"in RTCPeerConnection.prototype}function dr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(gr()||mr())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}function lr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(mr())return!1;if(gr()){const e=Vs();if((null==e?void 0:e.version)&&wr(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&wr(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}function ur(e){return"av1"===e||"vp9"===e}function hr(e){return!(!document||vr())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function pr(){return"undefined"!=typeof RTCPeerConnection&&(ar()||cr())}function mr(){var e;return"Firefox"===(null===(e=Vs())||void 0===e?void 0:e.name)}function gr(){var e;return"Safari"===(null===(e=Vs())||void 0===e?void 0:e.name)}function vr(){const e=Vs();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function fr(){const e=Vs();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&wr(e.osVersion,"17")>=0}function kr(){var e,t;return!!br()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function br(){return"undefined"!=typeof document}function yr(){return"ReactNative"==navigator.product}function Tr(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Cr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Sr(){if(!yr())return;let e=Cr();return e?e.platform:void 0}function Er(){if(br())return window.devicePixelRatio;if(yr()){let e=Cr();if(e)return e.devicePixelRatio}return 1}function wr(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let e=0;e<s;++e){const t=parseInt(i[e],10),r=parseInt(n[e],10);if(t>r)return 1;if(t<r)return-1;if(e===s-1&&t===r)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Pr(e){for(const t of e)t.target.handleResize(t)}function Rr(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Ir=null;const Or=()=>(Ir||(Ir=new ResizeObserver(Pr)),Ir);let Dr=null;const xr=()=>(Dr||(Dr=new IntersectionObserver(Rr,{root:null,rootMargin:"0px"})),Dr);let Mr,Ar;function _r(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}function Nr(){if(!Ar){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[Ar]=n.stream.getAudioTracks(),!Ar)throw Error("Could not get empty media stream audio track");Ar.enabled=!1}return Ar.clone()}class Lr{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,i)=>Xi(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function Ur(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function jr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Fr(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return $e.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return $e.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return $e.JOIN_FAILURE;default:return $e.UNKNOWN_REASON}}function Br(e){return void 0!==e?Number(e):void 0}function Vr(e){return void 0!==e?BigInt(e):void 0}function qr(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Kr(e){return!!e&&e.kind==Js.Kind.Audio}function Hr(e){return!!e&&e.kind==Js.Kind.Video}function Wr(e){return qr(e)&&Hr(e)}function Gr(e){return qr(e)&&Kr(e)}function zr(e){return!!e&&!e.isLocal}function Jr(e){return!!e&&!e.isLocal}function Qr(e){return zr(e)&&Hr(e)}function Yr(e){return e.isLocal}function Xr(e,t,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=co(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Zr(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Zr(h.video,i),null!==(s=(o=h.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Zr(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function $r(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,o=e.video;Object.keys(o).forEach((e=>{if("resolution"===e)Zr(s,o.resolution);else s[e]=o[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function eo(e){return Xi(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=to();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield or(t),n.getByteTimeDomainData(r);const o=r.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}()}))}function to(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Xi(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function io(e){return"audioinput"===e?Js.Source.Microphone:"videoinput"===e?Js.Source.Camera:Js.Source.Unknown}function no(e){return e===Js.Source.Microphone?"audioinput":e===Js.Source.Camera?"videoinput":void 0}function so(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=gr()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function ro(e){return e.split("/")[1].toLowerCase()}function oo(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new $t({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function ao(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?ao(e.track):{})}}function co(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function lo(e,t){return e.width*e.height<t.width*t.height}class uo extends nn.EventEmitter{constructor(t){super(),this.onWorkerMessage=t=>{var i,n;const{kind:s,data:r}=t.data;switch(s){case"error":Hi.error(r.error.message),this.emit(e.EncryptionEvent.EncryptionError,r.error);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(r.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,r.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex)}},this.onWorkerError=t=>{Hi.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1}setup(e){if(!ms())throw new xs("tried to setup end-to-end encryption on an unsupported browser");if(Hi.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:zi.getLevel()}};this.worker&&(Hi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Hi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Hi.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,i){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==lt.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(i=>{i===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==lt.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(e.RoomEvent.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");i.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>Xi(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!Hr(e.track)||!vr())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:ro(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)})),i.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?ro(i.mimeType):void 0)}}setupE2EESender(e,t){qr(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Hi.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Xi(this,void 0,void 0,(function*(){if(this.worker){if(gs()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(ls in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i,isReuse:ls in e}};this.worker.postMessage(o,[r,s])}e[ls]=!0}}))}handleSender(e,t,i){var n;if(!(ls in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(gs()){Hi.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{Hi.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[n.readable,n.writable])}e[ls]=!0}}}const ho="default";class po{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new po),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Xi(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=po.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){Hi.debug("awaiting getUserMedia promise");try{e?yield po.userMediaPromiseMap.get(e):yield Promise.all(po.userMediaPromiseMap.values())}catch(e){Hi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!gr()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return Xi(this,void 0,void 0,(function*(){if(t!==ho)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===ho));if(!s)return void Hi.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==ho&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;Hi.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?po.userMediaPromiseMap.has(e):po.userMediaPromiseMap.size>0}}var mo;po.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],po.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(mo||(mo={}));class go{constructor(){this.pendingTasks=new Map,this.taskMutex=new s,this.nextTaskIndex=0}run(e){return Xi(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:mo.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=mo.RUNNING,yield e()}finally{t.status=mo.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Xi(this,void 0,void 0,(function*(){return this.run((()=>Xi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function vo(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const fo=["syncState","trickle","offer","answer","simulate","leave"];var ko;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(ko||(ko={}));class bo{get currentState(){return this.state}get isDisconnected(){return this.state===ko.DISCONNECTING||this.state===ko.DISCONNECTED}get isEstablishingConnection(){return this.state===ko.CONNECTING||this.state===ko.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;this.rtt=0,this.state=ko.DISCONNECTED,this.log=Hi,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Gi(null!==(n=i.loggerName)&&void 0!==n?n:e.LoggerNames.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new go,this.queuedRequests=[],this.closingLock=new s,this.connectionLock=new s,this.state=ko.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return Xi(this,void 0,void 0,(function*(){this.state=ko.CONNECTING,this.options=i;return yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Xi(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=ko.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))}))}connect(t,i,n,s){this.connectOptions=n;const r=function(e,t,i){var n;const s=new URLSearchParams;s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid));s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",yr()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);i.adaptiveStream&&s.set("adaptive_stream","1");i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString());(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type);return s}(i,function(){var e;const t=new Dt({sdk:xt.JS,protocol:16,version:Ws});return yr()&&(t.os=null!==(e=Sr())&&void 0!==e?e:""),t}(),n),o=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),vo(i,"rtc")}(t,r),a=vo(new URL(jr(o)),"validate");return new Promise(((t,i)=>Xi(this,void 0,void 0,(function*(){const r=yield this.connectionLock.lock();try{const r=()=>Xi(this,void 0,void 0,(function*(){this.close(),clearTimeout(c),i(new Ds("room connection has been cancelled (signal)",e.ConnectionErrorReason.Cancelled))})),c=setTimeout((()=>{this.close(),i(new Ds("room connection has timed out (signal)",e.ConnectionErrorReason.ServerUnreachable))}),n.websocketTimeout);(null==s?void 0:s.aborted)&&r(),null==s||s.addEventListener("abort",r);const d=new URL(o);d.searchParams.has("access_token")&&d.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(d),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(c)},this.ws.onerror=t=>Xi(this,void 0,void 0,(function*(){if(this.state===ko.CONNECTED)this.handleWSError(t);else{this.state=ko.DISCONNECTED,clearTimeout(c);try{const n=yield fetch(a);if(n.status.toFixed(0).startsWith("4")){const t=yield n.text();i(new Ds(t,e.ConnectionErrorReason.NotAllowed,n.status))}else i(new Ds("Encountered unknown websocket error during connection: ".concat(t.toString()),e.ConnectionErrorReason.InternalError,n.status))}catch(t){i(new Ds(t instanceof Error?t.message:"server was not reachable",e.ConnectionErrorReason.ServerUnreachable))}}})),this.ws.onmessage=o=>Xi(this,void 0,void 0,(function*(){var a,c,d;let l;if("string"==typeof o.data){const e=JSON.parse(o.data);l=Gt.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(o.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof o.data),this.logContext);l=Gt.fromBinary(new Uint8Array(o.data))}if(this.state!==ko.CONNECTED){let o=!1;if("join"===(null===(a=l.message)||void 0===a?void 0:a.case)?(this.state=ko.CONNECTED,null==s||s.removeEventListener("abort",r),this.pingTimeoutDuration=l.message.value.pingTimeout,this.pingIntervalDuration=l.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),t(l.message.value)):this.state===ko.RECONNECTING&&"leave"!==l.message.case?(this.state=ko.CONNECTED,null==s||s.removeEventListener("abort",r),this.startPingInterval(),"reconnect"===(null===(c=l.message)||void 0===c?void 0:c.case)?t(l.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),t(void 0),o=!0)):this.isEstablishingConnection&&"leave"===l.message.case?i(new Ds("Received leave request while trying to (re)connect",e.ConnectionErrorReason.LeaveRequest,void 0,l.message.value.reason)):n.reconnect||i(new Ds("did not receive join response, got ".concat(null===(d=l.message)||void 0===d?void 0:d.case," instead"),e.ConnectionErrorReason.InternalError)),!o)return}this.signalLatency&&(yield or(this.signalLatency)),this.handleSignalResponse(l)})),this.ws.onclose=t=>{this.isEstablishingConnection&&i(new Ds("Websocket got closed during a (re)connection attempt",e.ConnectionErrorReason.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:t.reason,code:t.code,wasClean:t.wasClean,state:this.state})),this.handleOnClose(t.reason)}}finally{r()}}))))}close(){return Xi(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ko.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,or(250)])),e.ws=void 0}}finally{t&&(e.state=ko.DISCONNECTED),i()}}()}))}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:To(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:To(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Qt({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Yt({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Xi(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new li({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new di({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ci({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:x.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Oi({timestamp:x.parse(Date.now()),rtt:x.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ri({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ai({reason:$e.CLIENT_INITIATED,action:ci.DISCONNECT})})}sendRequest(e){return Xi(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=fo.indexOf(e.case)>=0;return Hi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===ko.RECONNECTING)return void t.queuedRequests.push((()=>Xi(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield or(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new Wt({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=yo(n.value);this.onAnswer&&this.onAnswer(e,n.value.id)}else if("offer"===n.case){const e=yo(n.value);this.onOffer&&this.onOffer(e,n.value.id)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Xi(this,void 0,void 0,(function*(){if(this.state===ko.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Gs.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Gs.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Gs.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Gs.clearInterval(this.pingInterval)}}function yo(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function To(e,t){return new ti({sdp:e.sdp,type:e.type,id:t})}class Co{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class So{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[n,s]of i.entries())t.push(e(s,n,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var Eo,wo,Po,Ro,Io,Oo={},Do={},xo={exports:{}};function Mo(){if(Eo)return xo.exports;Eo=1;var e=xo.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),xo.exports}function Ao(){return wo||(wo=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Mo(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(Do)),Do}function _o(){if(Ro)return Po;Ro=1;var e=Mo(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var o=t.names[r];t.name?s.push(n[t.name][o]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Po=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var o=i.outerOrder||s,a=i.innerOrder||r,c=[];return o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},Po}var No=function(){if(Io)return Oo;Io=1;var e=Ao(),t=_o(),i=Mo();return Oo.grammar=i,Oo.write=t,Oo.parse=e.parse,Oo.parseParams=e.parseParams,Oo.parseFmtpConfig=e.parseFmtpConfig,Oo.parsePayloads=e.parsePayloads,Oo.parseRemoteCandidates=e.parseRemoteCandidates,Oo.parseImageAttributes=e.parseImageAttributes,Oo.parseSimulcastStreamList=e.parseSimulcastStreamList,Oo}();function Lo(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),i=this;return new Promise((function(n,s){var c=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var n=e.apply(i,t);a&&a(n),l.forEach((function(e){return(0,e.resolve)(n)})),l=[]}}),u()),c){var h=e.apply(i,t);return a&&a(h),n(h)}l.push({resolve:n,reject:s})}))};return h.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}const Uo="negotiationStarted",jo="negotiationComplete",Fo="rtpVideoPayloadTypes";class Bo extends nn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;super(),this.log=Hi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Lo((e=>Xi(this,void 0,void 0,(function*(){this.emit(Uo);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Gi(null!==(n=i.loggerName)&&void 0!==n?n:e.LoggerNames.PCTransport),this.loggerOptions=i,this.config=t,this._pc=this.createPC(),this.offerLock=new s}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Xi(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return Xi(this,void 0,void 0,(function*(){var i;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=No.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const t=No.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),n=No.write(t)}if(yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(jo),e.sdp)){No.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Fo,e.rtp)}))}return!0}))}createAndSendOffer(e){return Xi(this,void 0,void 0,(function*(){var t;const i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=this.latestOfferId+1;this.latestOfferId=i;const n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const s=No.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(s.media.forEach((e=>{qo(e),"audio"===e.type?Vo(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(ur(t.codec)&&!gr()&&this.ensureVideoDDExtensionForSVC(e,s),"av1"!==t.codec)return!0;const n=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0}))})),this.latestOfferId>i)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));yield this.setMungedSDP(n,No.write(s)),this.onOffer(n,this.latestOfferId)}finally{i()}}))}createAndSetAnswer(){return Xi(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=No.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{qo(e),"audio"===e.type&&Vo(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,No.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new _s("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 _s("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Xi(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return Xi(this,void 0,void 0,(function*(){if(t){const n=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let n="unknown error";t instanceof Error?n=t.message:"string"==typeof t&&(n=t);const s={error:n,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new Ns(n)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===rr)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:rr})}}}function Vo(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function qo(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const Ko="vp8",Ho={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:sr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ko,backupCodec:!0,preConnectBuffer:!1},Wo={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Go={deviceId:{ideal:"default"},resolution:ir.h720.resolution},zo={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Yi,disconnectOnPageLeave:!0,webAudioMix:!1},Jo={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Qo;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(Qo||(Qo={}));class Yo{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,i,n){var r;this.peerConnectionTimeout=Jo.peerConnectionTimeout,this.log=Hi,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=Qo.CONNECTED:i.some((e=>"failed"===e))?this.state=Qo.FAILED:i.some((e=>"connecting"===e))?this.state=Qo.CONNECTING:i.every((e=>"closed"===e))?this.state=Qo.CLOSED:i.some((e=>"closed"===e))?this.state=Qo.CLOSING:i.every((e=>"new"===e))&&(this.state=Qo.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(Qo[t]," to ").concat(Qo[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Gi(null!==(r=n.loggerName)&&void 0!==r?r:e.LoggerNames.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!i,this.isSubscriberConnectionRequired=i,this.publisher=new Bo(t,n),this.subscriber=new Bo(t,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,qt.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,qt.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=Qo.NEW,this.connectionLock=new s,this.remoteOfferLock=new s}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return Xi(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return Xi(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Xi(this,void 0,void 0,(function*(){t===qt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Xi(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const i=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{i()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Xi(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return Xi(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Xi(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(Uo,(()=>{e.signal.aborted||this.publisher.once(jo,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===qt.PUBLISHER||e===qt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(t,i){return Xi(this,arguments,void 0,(function(t,i){var n=this;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==t.getConnectionState())return new Promise(((t,r)=>Xi(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),Gs.clearTimeout(o),r(new Ds("room connection has been cancelled",e.ConnectionErrorReason.Cancelled))};(null==i?void 0:i.signal.aborted)&&n(),null==i||i.signal.addEventListener("abort",n);const o=Gs.setTimeout((()=>{null==i||i.signal.removeEventListener("abort",n),r(new Ds("could not establish pc connection",e.ConnectionErrorReason.InternalError))}),s);for(;this.state!==Qo.CONNECTED;)if(yield or(50),null==i?void 0:i.signal.aborted)return void r(new Ds("room connection has been cancelled",e.ConnectionErrorReason.Cancelled));Gs.clearTimeout(o),null==i||i.signal.removeEventListener("abort",n),t()}))))}()}))}}class Xo extends Error{constructor(e,t,i){super(t),this.code=e,this.message=$o(t,Xo.MAX_MESSAGE_BYTES),this.data=i?$o(i,Xo.MAX_DATA_BYTES):void 0}static fromProto(e){return new Xo(e.code,e.message,e.data)}toProto(){return new Pt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Xo(Xo.ErrorCode[e],Xo.ErrorMessage[e],t)}}Xo.MAX_MESSAGE_BYTES=256,Xo.MAX_DATA_BYTES=15360,Xo.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},Xo.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"};function Zo(e){return(new TextEncoder).encode(e).length}function $o(e,t){if(Zo(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}const ea=2e3;function ta(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}const ia="undefined"!=typeof MediaRecorder;const na=ia?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class sa extends na{constructor(e,t){if(!ia)throw new Error("MediaRecorder is not available in this environment");let i,n;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),null==n||n.close(),n=void 0},r=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",r),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>Xi(this,void 0,void 0,(function*(){let i;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();i=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");i=t.data.byteArray}void 0!==n&&e.enqueue(i)})),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",r)}}class ra extends Js{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,i,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,i,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Lo((()=>Xi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Xi(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(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new s,this.pauseUpstreamLock=new s,this.trackChangeLock=new s,this.trackChangeLock.lock().then((e=>Xi(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Js.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Xi(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Ys(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Qs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Qs(null!=n?n:e,t)})))}))}waitForDimensions(){return Xi(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===Js.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=Vs())||void 0===i?void 0:i.os)&&(yield or(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield or(50)}throw new Ms("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Xi(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ur(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Ur(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Xi(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Js.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===Js.Kind.Audio?"audioinput":"videoinput";return t?po.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Xi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Xi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Xi(this,void 0,void 0,(function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ms("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}}))}restart(t){return Xi(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const{deviceId:i,facingMode:n}=t,s=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const r={audio:!1,video:!1};this.kind===Js.Kind.Video?r.video=!i&&!n||{deviceId:i,facingMode:n}:r.audio=!i||Object.assign({deviceId:i},s),this.attachedElements.forEach((e=>{Ys(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const o=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return this.kind===Js.Kind.Video&&(yield o.applyConstraints(s)),o.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(o),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{i()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Xi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),kr()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Xi(this,void 0,void 0,(function*(){var t;const i=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const i=Vs();if("Safari"===(null==i?void 0:i.name)&&wr(i.version,"12.0")<0)throw new xs("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{i()}}))}resumeUpstream(){return Xi(this,void 0,void 0,(function*(){var t;const i=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{i()}}))}getRTCStatsReport(){return Xi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){return Xi(this,arguments,void 0,(function(t){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s;const r=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const r=document.createElement(i.kind),o={kind:i.kind,track:i._mediaStreamTrack,element:r,audioContext:i.audioContext};if(yield t.init(o),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),"unknown"===i.kind)throw TypeError("cannot set processor on track of unknown kind");if(Qs(i._mediaStreamTrack,r),r.muted=!0,r.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:e})),setTimeout((()=>{r.play().catch((e=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:e}))}))}),100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:e}))})),i.processor=t,i.processorElement=r,i.processor.processedTrack){for(const e of i.attachedElements)e!==i.processorElement&&n&&(Ys(i._mediaStreamTrack,e),Qs(i.processor.processedTrack,e));yield null===(s=i.sender)||void 0===s?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(e.TrackEvent.TrackProcessorUpdate,i.processor)}finally{r()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Xi(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}}()}))}internalStopProcessor(){return Xi(this,arguments,void 0,(function(){var t=this;let i=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,s;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(n=t.processor.processedTrack)||void 0===n||n.stop(),yield t.processor.destroy(),t.processor=void 0,i||(null===(s=t.processorElement)||void 0===s||s.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(ia)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new sa(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout((()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()}),1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class oa extends ra{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,i){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(t,Js.Kind.Audio,i,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Xi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=ta(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,it.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,it.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Xi(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===Js.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 Xi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Ur(this._constraints.deviceId);return this.source!==Js.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Xi(this,void 0,void 0,(function*(){let t;if(e){const i=$r({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Xi(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){br()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ea)))}setProcessor(t){return Xi(this,void 0,void 0,(function*(){var i;const n=yield this.trackChangeLock.lock();try{if(!yr()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const n={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(n),this.processor=t,this.processor.processedTrack&&(yield null===(i=this.sender)||void 0===i?void 0:i.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(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{n()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Xi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Xi(this,void 0,void 0,(function*(){const t=yield eo(this);return t&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const aa=Object.values(ir),ca=Object.values(nr),da=Object.values(sr),la=[ir.h180,ir.h360],ua=[nr.h180,nr.h360],ha=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var i,n;return new Xs(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,e.encoding.priority)})),pa=["q","h","f"];function ma(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return da;const n=t>i?t/i:i/t;if(Math.abs(n-16/9)<Math.abs(n-4/3))return aa;return ca}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let e=0;e<s.length;e+=1){const t=s[e];if(r=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),Hi.debug("using video encoding",o));const l=o.maxFramerate,u=new Xs(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&ur(d)){const e=new ka(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=Vs();if(vr()||yr()||"Chrome"===(null==i?void 0:i.name)&&wr(null==i?void 0:i.version,"113")<0){const n="h"==e.suffix?2:3,s=function(e){return e||(e=Vs()),"Safari"===(null==e?void 0:e.name)&&wr(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&wr(e.osVersion,"18.3")>0}(i);for(let i=0;i<e.spatial;i+=1)t.push({rid:pa[2-i],maxBitrate:o.maxBitrate/Math.pow(n,i),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,i):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Hi.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(s=fa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:ga(e,u):null!==(r=fa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:ga(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return va(t,i,[e,h,u],l);if(n>=480)return va(t,i,[e,u],l)}return va(t,i,[u])}function ga(e,t){if(e)return ha(t);const{width:i,height:n}=t,s=i>n?i/n:n/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?la:ua}function va(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=pa.length)return;const o=Math.min(e,t),a={rid:pa[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=mr()||0===r;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),yr()&&"ios"===Sr()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,Hi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Hi.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function fa(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class ka{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class ba extends ra{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,i){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0;super(t,Js.Kind.Video,i,n,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Xi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const i=new Map(t.map((e=>[e.rid,e]))),n=t.some((e=>"cpu"===e.qualityLimitationReason));if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;i.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=ta(t,s)})),this._currentBitrate=e}this.prevStats=i})),this.senderLock=new s}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!br())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ea))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Xi(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=$i(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Xi(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=$i(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(e){i={error:e}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Xi(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!==Js.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 Xi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Js.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Xi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(t){const i=[];for(let n=e.VideoQuality.LOW;n<=e.VideoQuality.HIGH;n+=1)i.push(new ki({quality:n,enabled:n<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(ur(this.codec),i)}restartTrack(e){return Xi(this,void 0,void 0,(function*(){var t,i,n,s,r;let o;if(e){const t=$r({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var a,c=!0,d=$i(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){i={error:e}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Xi(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=$i(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(e){r={error:e}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return Xi(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Xi(this,void 0,void 0,(function*(){var t,i,n,s,r,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(ur(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=$i(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield ya(t.sender,t.encodings,e.qualities,this.senderLock,ur(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(ur(e.codec),e.qualities)}}catch(e){r={error:e}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e,t){return Xi(this,void 0,void 0,(function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield ya(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Xi(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 e=this.sender.getParameters();e.encodings=e.encodings.map(((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&ur(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Xi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),kr()&&this.isInBackground&&this.source===Js.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function ya(e,t,i,n,s,r,o){return Xi(this,void 0,void 0,(function*(){const a=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length)return void r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){i.some((e=>e.enabled))&&i.forEach((e=>e.enabled=!0))}a.forEach(((e,n)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=Ta(a),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,r.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),mr()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(n.encodings=a,r.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}}))}function Ta(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Ca(t,i,n,s){if(!n)return[new pt({quality:e.VideoQuality.HIGH,width:t,height:i,bitrate:0,ssrc:0})];if(s){const s=n[0].scalabilityMode,r=new ka(s),o=[],a="h"==r.suffix?1.5:2,c="h"==r.suffix?2:3;for(let s=0;s<r.spatial;s+=1)o.push(new pt({quality:Math.min(e.VideoQuality.HIGH,r.spatial-1)-s,width:Math.ceil(t/Math.pow(a,s)),height:Math.ceil(i/Math.pow(a,s)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(c,s)):0,ssrc:0}));return o}return n.map((e=>{var n,s,r;const o=null!==(n=e.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Ta(null!==(s=e.rid)&&void 0!==s?s:"");return new pt({quality:a,width:Math.ceil(t/o),height:Math.ceil(i/o),bitrate:null!==(r=e.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Sa="_lossy",Ea="_reliable",wa="leave-reconnect";var Pa;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Pa||(Pa={}));class Ra extends nn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var i;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Jo.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Pa.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Hi,this.reliableDataSequence=1,this.reliableMessageBuffer=new Co,this.reliableReceivedState=new So(3e4),this.handleDataChannel=e=>Xi(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Ea)t.reliableDCSub=i;else{if(i.label!==Sa)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=t=>Xi(this,void 0,void 0,(function*(){var i,n;const s=yield this.dataProcessLock.lock();try{let s;if(t.data instanceof ArrayBuffer)s=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));s=yield t.data.arrayBuffer()}const r=mt.fromBinary(new Uint8Array(s));if(r.sequence>0&&""!==r.participantSid){const e=this.reliableReceivedState.get(r.participantSid);if(e&&r.sequence<=e)return;this.reliableReceivedState.set(r.participantSid,r.sequence)}"speaker"===(null===(i=r.value)||void 0===i?void 0:i.case)?this.emit(e.EngineEvent.ActiveSpeakersUpdate,r.value.value.speakers):("user"===(null===(n=r.value)||void 0===n?void 0:n.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(r,r.value.value),this.emit(e.EngineEvent.DataPacketReceived,r))}finally{s()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?gt.LOSSY:gt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let r=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==r?(t===wa&&(r=0),this.log.debug("reconnecting in ".concat(r,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Gs.setTimeout((()=>this.attemptReconnect(i).finally((()=>this.reconnectTimeout=void 0))),r)):n(s)},this.waitForRestarted=()=>new Promise(((t,i)=>{this.pcState===Pa.Connected&&t();const n=()=>{this.off(e.EngineEvent.Disconnected,s),t()},s=()=>{this.off(e.EngineEvent.Restarted,n),i()};this.once(e.EngineEvent.Restarted,n),this.once(e.EngineEvent.Disconnected,s)})),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);void 0!==i&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(e.EngineEvent.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return e===gt.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ko.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(et.RR_SIGNAL_DISCONNECTED))},this.log=Gi(null!==(i=t.loggerName)&&void 0!==i?i:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new bo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new s,this.dataProcessLock=new s,this.dcBufferStatus=new Map([[gt.LOSSY,!0],[gt.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t)}get logContext(){var e,t,i,n,s,r;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:this.participantSid}}join(t,i,n,s){return Xi(this,void 0,void 0,(function*(){this.url=t,this.token=i,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(t,i,n,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),this.subscriberPrimary&&!r.fastPublish||this.negotiate(),this.clientConfiguration=r.clientConfiguration,this.emit(e.EngineEvent.SignalConnected,r),r}catch(r){if(r instanceof Ds&&r.reason===e.ConnectionErrorReason.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(t,i,n,s);throw r}}))}close(){return Xi(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Xi(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Co,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupClient(){return Xi(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new Ms("a track with the same ID has already been published");return new Promise(((i,n)=>{const s=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],n(new Ds("publication of local track timed out, no response from server",e.ConnectionErrorReason.Timeout))}),1e4);this.pendingTrackResolvers[t.cid]={resolve:e=>{clearTimeout(s),i(e)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Xi(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){return Xi(this,void 0,void 0,(function*(){var i,n;if(this.pcManager&&this.pcManager.currentState!==Qo.NEW)return;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const s=this.makeRTCConfiguration(t);var r;this.pcManager=new Yo(s,t.subscriberPrimary,this.loggerOptions),this.emit(e.EngineEvent.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(i,n,s)=>Xi(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(i),this.logContext),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),i===Qo.CONNECTED){const i=this.pcState===Pa.New;this.pcState=Pa.Connected,i&&this.emit(e.EngineEvent.Connected,t)}else i===Qo.FAILED&&this.pcState===Pa.Connected&&(this.pcState=Pa.Disconnected,this.handleDisconnect("peerconnection failed","failed"===s?et.RR_SUBSCRIBER_FAILED:et.RR_PUBLISHER_FAILED));const r=this.client.isDisconnected||this.client.currentState===ko.RECONNECTING,o=[Qo.FAILED,Qo.CLOSING,Qo.CLOSED].includes(i);r&&o&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(r=null===(n=t.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>Xi(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>Xi(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,i)=>{this.emit(e.EngineEvent.RemoteMute,t,i)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var i;this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(e.EngineEvent.RoomMoved,t)},this.client.onClose=()=>{this.handleDisconnect("signal",et.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(t.regions)),t.action){case ci.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case ci.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wa);break;case ci.RESUME:this.handleDisconnect(wa)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ze.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Sa,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ea,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return Xi(this,void 0,void 0,(function*(){if(ar()){return yield this.createTransceiverRTCRtpSender(e,t,i)}if(cr()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new _s("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Xi(this,void 0,void 0,(function*(){if(ar())return this.createSimulcastTransceiverSender(e,t,i,n);if(cr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new _s("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Xi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _s("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),Hr(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};i&&(s.sendEncodings=i);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Xi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _s("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return Xi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _s("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return Xi(this,void 0,void 0,(function*(){var i,n,s;if(!this._isClosed)if(this.attemptingReconnect)Hi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(i=this.clientConfiguration)||void 0===i?void 0:i.resumeConnection)!==Ze.DISABLED&&(null!==(s=null===(n=this.pcManager)||void 0===n?void 0:n.currentState)&&void 0!==s?s:Qo.NEW)!==Qo.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let i=!0;t instanceof _s?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),i=!1):t instanceof Ia||(this.fullReconnectOnNext=!0),i?this.handleDisconnect("reconnect",et.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(t){return Xi(this,void 0,void 0,(function*(){var i,n,s;try{if(!this.url||!this.token)throw new _s("could not reconnect, url or token not saved");let n;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ia;n=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(t){if(t instanceof Ds&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new _s("could not reconnect, token might be expired");throw new Ia}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==ko.CONNECTED)throw new Ia("Signal connection got severed during reconnect");null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),e}}))}resumeConnection(t){return Xi(this,void 0,void 0,(function*(){var i;if(!this.url||!this.token)throw new _s("could not reconnect, url or token not saved");if(!this.pcManager)throw new _s("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let i="";if(t instanceof Error&&(i=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof Ds&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new _s("could not reconnect, token might be expired");if(t instanceof Ds&&t.reason===e.ConnectionErrorReason.LeaveRequest)throw t;throw new Ia(i)}if(this.emit(e.EngineEvent.SignalResumed),n){const e=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==ko.CONNECTED)throw new Ia("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(i=this.reliableDC)||void 0===i?void 0:i.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return Xi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new _s("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Xi(this,void 0,void 0,(function*(){this.pcState=Pa.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield or(2e3),!this.pcManager)throw new _s("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Pa.Connected}catch(t){throw this.pcState=Pa.Disconnected,new Ds("could not establish PC connection, ".concat(t.message),e.ConnectionErrorReason.InternalError)}}))}publishRpcResponse(e,t,i,n){return Xi(this,void 0,void 0,(function*(){const s=new mt({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcResponse",value:new wt({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,gt.RELIABLE)}))}publishRpcAck(e,t){return Xi(this,void 0,void 0,(function*(){const i=new mt({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcAck",value:new Et({requestId:t})}});yield this.sendDataPacket(i,gt.RELIABLE)}))}sendDataPacket(e,t){return Xi(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(t),t===gt.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===gt.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)}))}resendReliableMessagesForResume(e){return Xi(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(gt.RELIABLE);const t=this.dataChannelForKind(gt.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(gt.RELIABLE)}))}waitForBufferStatusLow(t){return new Promise(((i,n)=>Xi(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))i();else{const s=()=>n("Engine closed");for(this.once(e.EngineEvent.Closing,s);!this.dcBufferStatus.get(t);)yield or(10);this.off(e.EngineEvent.Closing,s),i()}}))))}ensureDataTransportConnected(t){return Xi(this,arguments,void 0,(function(t){var i=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new _s("PC manager is closed");const r=n?i.pcManager.subscriber:i.pcManager.publisher,o=n?"Subscriber":"Publisher";if(!r)throw new Ds("".concat(o," connection not set"),e.ConnectionErrorReason.InternalError);let a=!1;n||i.dataChannelForKind(t,n)||(i.createDataChannels(),a=!0),a||n||i.pcManager.publisher.isICEConnected||"checking"===i.pcManager.publisher.getICEConnectionState()||(a=!0),a&&i.negotiate();const c=i.dataChannelForKind(t,n);if("open"===(null==c?void 0:c.readyState))return;const d=(new Date).getTime()+i.peerConnectionTimeout;for(;(new Date).getTime()<d;){if(r.isICEConnected&&"open"===(null===(s=i.dataChannelForKind(t,n))||void 0===s?void 0:s.readyState))return;yield or(50)}throw new Ds("could not establish ".concat(o," connection, state: ").concat(r.getICEConnectionState()),e.ConnectionErrorReason.InternalError)}()}))}ensurePublisherConnected(e){return Xi(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===Qo.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return Xi(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Xi(this,void 0,void 0,(function*(){if(!this.pcManager)return void i(new Ns("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&i("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,s),this.pcManager.publisher.once(Fo,(t=>{const i=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();var n;n=t,$s.includes(n)&&i.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,i)}));try{yield this.pcManager.negotiate(n),t()}catch(e){e instanceof Ns&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",et.RR_UNKNOWN),i(e)}finally{this.off(e.EngineEvent.Closing,s)}}))))}))}dataChannelForKind(e,t){if(t){if(e===gt.LOSSY)return this.lossyDCSub;if(e===gt.RELIABLE)return this.reliableDCSub}else{if(e===gt.LOSSY)return this.lossyDC;if(e===gt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new wi({answer:s?To({sdp:s.sdp,type:s.type}):void 0,offer:r?To({sdp:r.sdp,type:r.type}):void 0,subscription:new ni({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:oo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new Pi({publisherSid:t,lastSeq:e})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ri({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(gt.LOSSY),qt.PUBLISHER),t(this.dataChannelForKind(gt.RELIABLE),qt.PUBLISHER),t(this.dataChannelForKind(gt.LOSSY,!0),qt.SUBSCRIBER),t(this.dataChannelForKind(gt.RELIABLE,!0),qt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Gs.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){br()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){br()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Ia extends Error{}class Oa{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Tr(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Xi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),Hi.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(t){return Xi(this,void 0,void 0,(function*(){const i=yield fetch("".concat((n=this.serverUrl,"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:t});var n;if(i.ok){const e=yield i.json();return this.lastUpdateAt=Date.now(),e}throw new Ds("Could not fetch region settings: ".concat(i.statusText),401===i.status?e.ConnectionErrorReason.NotAllowed:e.ConnectionErrorReason.InternalError,i.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class Da{get info(){return this._info}validateBytesReceived(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(t&&this.bytesReceived<this.totalByteSize)throw new js("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new js("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,i,n){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=n}}class xa extends Da{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Lr,i=null,n=null;if(this.signal){const e=this.signal;n=()=>{var i;null===(i=t.reject)||void 0===i||i.call(t,e.reason)},e.addEventListener("abort",n),i=e}const s=()=>{e.releaseLock(),i&&n&&i.removeEventListener("abort",n),this.signal=void 0};return{next:()=>Xi(this,void 0,void 0,(function*(){var i,n;try{const{done:s,value:r}=yield Promise.race([e.read(),t.promise,null!==(n=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==n?n:new Promise((()=>{}))]);return s?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r),{done:!1,value:r.content})}catch(e){throw s(),e}})),return(){return Xi(this,void 0,void 0,(function*(){return s(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Xi(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,r;let o=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=$i(a);!(i=(c=yield l.next()).done);d=!0){r=c.value,d=!1;const e=r;o.add(e)}}catch(e){n={error:e}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return Array.from(o)}()}))}}class Ma extends Da{constructor(e,t,i,n){super(e,t,i,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Br(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const t=this.reader.getReader(),i=new TextDecoder("utf-8",{fatal:!0});let n=new Lr,s=null,r=null;if(this.signal){const e=this.signal;r=()=>{var t;null===(t=n.reject)||void 0===t||t.call(n,e.reason)},e.addEventListener("abort",r),s=e}const o=()=>{t.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>Xi(this,void 0,void 0,(function*(){var s,r;try{const{done:o,value:a}=yield Promise.race([t.read(),n.promise,null!==(r=null===(s=this.outOfBandFailureRejectingFuture)||void 0===s?void 0:s.promise)&&void 0!==r?r:new Promise((()=>{}))]);if(o)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let t;this.handleChunkReceived(a);try{t=i.decode(a.content)}catch(t){throw new js("Cannot decode datastream chunk ".concat(a.chunkIndex," as text: ").concat(t),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(e){throw o(),e}})),return(){return Xi(this,void 0,void 0,(function*(){return o(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Xi(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i,n,s,r;let o="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=$i(a);!(i=(c=yield l.next()).done);d=!0){r=c.value,d=!1;o+=r}}catch(e){n={error:e}}finally{try{d||i||!(s=l.return)||(yield s.call(l))}finally{if(n)throw n.error}}return o}()}))}}class Aa{constructor(){this.log=Hi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(t,i){if(this.textStreamHandlers.has(t))throw new js('A text stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,i)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(t,i){if(this.byteStreamHandlers.has(t))throw new js('A byte stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,i)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(t){var i,n,s,r;const o=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),a=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(o.length>0||a.length>0){const c=new js("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const[e,t]of a)null===(n=(i=t.outOfBandFailureRejectingFuture).reject)||void 0===n||n.call(i,c),this.byteStreamControllers.delete(e);for(const[e,t]of o)null===(r=(s=t.outOfBandFailureRejectingFuture).reject)||void 0===r||r.call(s,c),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e){return Xi(this,void 0,void 0,(function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}))}handleStreamHeader(t,i){return Xi(this,void 0,void 0,(function*(){var n;if("byteHeader"===t.contentHeader.case){const s=this.byteStreamHandlers.get(t.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let r;const o=new Lr,a={id:t.streamId,name:null!==(n=t.contentHeader.value.name)&&void 0!==n?n:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Br(t.timestamp),attributes:t.attributes},c=new ReadableStream({start:n=>{if(r=n,this.textStreamControllers.has(t.streamId))throw new js("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:a,controller:r,startTime:Date.now(),sendingParticipantIdentity:i,outOfBandFailureRejectingFuture:o})}});s(new xa(a,c,Br(t.totalLength),o),{identity:i})}else if("textHeader"===t.contentHeader.case){const n=this.textStreamHandlers.get(t.topic);if(!n)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let s;const r=new Lr,o={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes},a=new ReadableStream({start:n=>{if(s=n,this.textStreamControllers.has(t.streamId))throw new js("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:o,controller:s,startTime:Date.now(),sendingParticipantIdentity:i,outOfBandFailureRejectingFuture:r})}});n(new Ma(o,a,Br(t.totalLength),r),{identity:i})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class _a{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Xi(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class Na extends _a{}class La extends _a{}class Ua{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Xi(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),o=new Array(r?r.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;const s=o.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map(((e,i)=>Xi(this,void 0,void 0,(function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))))),c.info}))}streamText(t){return Xi(this,void 0,void 0,(function*(){var i,n;const s=null!==(i=null==t?void 0:t.streamId)&&void 0!==i?i:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(n=null==t?void 0:t.topic)&&void 0!==n?n:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes},o=new Ft({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Vr(r.timestamp),totalLength:Vr(null==t?void 0:t.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Ut({version:null==t?void 0:t.version,attachedStreamIds:null==t?void 0:t.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?Lt.UPDATE:Lt.CREATE})}}),a=null==t?void 0:t.destinationIdentities,c=new mt({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,gt.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Xi(this,void 0,void 0,(function*(){for(const t of function(e,t){const i=[];let n=(new TextEncoder).encode(e);for(;n.length>t;){let e=t;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,15e3)){yield l.waitForBufferStatusLow(gt.RELIABLE);const e=new Bt({content:t,streamId:s,chunkIndex:Vr(d)}),i=new mt({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(i,gt.RELIABLE),d+=1}}))},close(){return Xi(this,void 0,void 0,(function*(){const e=new Vt({streamId:s}),t=new mt({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,gt.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let h=()=>Xi(this,void 0,void 0,(function*(){yield p.close()}));l.once(e.EngineEvent.Closing,h);const p=new Na(u,r,(()=>this.engine.off(e.EngineEvent.Closing,h)));return p}))}sendFile(e,t){return Xi(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return Xi(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return Xi(this,void 0,void 0,(function*(){var t,i,n,r,o;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:a,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown"},l=new Ft({totalLength:Vr(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:Vr(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new jt({name:d.name})}}),u=new mt({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,gt.RELIABLE);let h=0;const p=new s,m=this.engine,g=this.log,v=new WritableStream({write(e){return Xi(this,void 0,void 0,(function*(){const t=yield p.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield m.waitForBufferStatusLow(gt.RELIABLE);const n=new mt({destinationIdentities:c,value:{case:"streamChunk",value:new Bt({content:t,streamId:a,chunkIndex:Vr(h)})}});yield m.sendDataPacket(n,gt.RELIABLE),h+=1,i+=t.byteLength}}finally{t()}}))},close(){return Xi(this,void 0,void 0,(function*(){const e=new Vt({streamId:a}),t=new mt({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,gt.RELIABLE)}))},abort(e){g.error("Sink error:",e)}});return new La(v,d)}))}}class ja extends Js{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const i=n=>{n.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",i),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",i)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Xi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),ea)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var i;this.timeSyncHandle=requestAnimationFrame((()=>t()));const n=null===(i=this.receiver)||void 0===i?void 0:i.getSynchronizationSources()[0];if(n){const{timestamp:t,rtpTimestamp:i}=n;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}};t()}}class Fa extends ja{constructor(e,t,i,n,s,r){super(e,t,Js.Kind.Audio,i,r),this.monitorReceiver=()=>Xi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ta(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;yr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(yr())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Xi(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(hr(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&hr(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,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(t,i){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(i.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{n.connect(e),n=e})),this.gainNode=t.createGain(),n.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Xi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Ba extends ja{constructor(e,t,i,n,s){super(e,t,Js.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Xi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=ta(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Lo((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===Js.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Ys(this._mediaStreamTrack,t):Qs(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new Va(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Xi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Xi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var i,n;const s=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),r=!(null!==(n=null===(i=this.adaptiveStreamSettings)||void 0===i?void 0:i.pauseVideoInBackground)&&void 0!==n&&!n)&&this.isInBackground,o=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!r||o;(this.lastVisible!==a||t)&&(!a&&Date.now()-s<100?Gs.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,i;let n=0,s=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,i=e.height()*r;t+i>n+s&&(n=t,s=i)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===n&&(null===(i=this.lastDimensions)||void 0===i?void 0:i.height)===s||(this.lastDimensions={width:n,height:s},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return Er();if(!t){return Er()>2?2:1}return t}}class Va{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=qa(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=qa(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=qa(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Ka(e),this.isPiP=br()&&qa(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Ka(this.element),this.isPiP=qa(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,xr().observe(this.element),Or().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=xr())||void 0===e||e.unobserve(this.element),null===(t=Or())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function qa(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Ka(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function Ka(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class Ha extends nn.EventEmitter{constructor(t,i,n,s){var r;super(),this.metadataMuted=!1,this.encryption=lt.NONE,this.log=Hi,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Gi(null!==(r=null==s?void 0:s.loggerName)&&void 0!==r?r:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=i,this.trackName=n,this.source=Js.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ao(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==lt.NONE}get audioTrack(){if(Kr(this.track))return this.track}get videoTrack(){if(Hr(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Js.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Js.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(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(Ha||(Ha={}));class Wa extends Ha{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,i,n,s){super(t,i.sid,i.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&Hr(this.track)&&this.emit(e.TrackEvent.CpuConstrained,this.track)},this.updateInfo(i),this.setTrack(n)}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),this.track.off(e.TrackEvent.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.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 Xi(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Xi(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Xi(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Xi(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Kr(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(it.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(it.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(it.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(it.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(it.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(it.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function Ga(e,t){return Xi(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=co(e);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),!0===r.video?r.video={deviceId:"default"}:"object"!=typeof r.video||r.video.deviceId||(r.video.deviceId="default");const c=Xr(r,Wo,Go),d=$r(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(po.userMediaPromiseMap.set("audioinput",l),l.catch((()=>po.userMediaPromiseMap.delete("audioinput")))),r.video&&(po.userMediaPromiseMap.set("videoinput",l),l.catch((()=>po.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>Xi(this,void 0,void 0,(function*(){const r="audio"===i.kind;let o,a=r?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=i.getSettings().deviceId;(null==o?void 0:o.deviceId)&&Ur(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new oa(e,t,!1,void 0,i);case"video":return new ba(e,t,!1,i);default:throw new Ms("unsupported track type: ".concat(e.kind))}}(i,o,t);return h.kind===Js.Kind.Video?h.source=Js.Source.Camera:h.kind===Js.Kind.Audio&&(h.source=Js.Source.Microphone),h.mediaStream=e,Kr(h)&&n?yield h.setProcessor(n):Hr(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(n){if(!i)throw n;return Ga(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}}))}function za(e){return Xi(this,void 0,void 0,(function*(){return(yield Ga({audio:!1,video:null==e||e}))[0]}))}function Ja(e){return Xi(this,void 0,void 0,(function*(){return(yield Ga({audio:null==e||e,video:!1}))[0]}))}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class Qa extends nn.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===ct.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===at.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,i,n,s,r,o){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ct.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=Hi,this.log=Gi(null!==(c=null==o?void 0:o.loggerName)&&void 0!==c?c:e.LoggerNames.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=t,this.identity=i,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Lr,this.once(e.ParticipantEvent.Active,(()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(Js.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Js.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Js.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(t){var i;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version)&&(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===at.ACTIVE&&(null===(i=this.participantInfo)||void 0===i?void 0:i.state)!==at.ACTIVE&&this.emit(e.ParticipantEvent.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const i=this.metadata!==t,n=this.metadata;this.metadata=t,i&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,n)}_setName(t){const i=this.name!==t;this.name=t,i&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const i=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,t);this._attributes=t,Object.keys(i).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,i)}setPermissions(t){var i,n,s,r,o,a;const c=this.permissions,d=t.canPublish!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublish)||t.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||t.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||t.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||t.recorder!==(null===(o=this.permissions)||void 0===o?void 0:o.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||t.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=t,d&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,c),d}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const i=this._connectionQuality;this._connectionQuality=function(t){switch(t){case Xe.EXCELLENT:return e.ConnectionQuality.Excellent;case Xe.GOOD:return e.ConnectionQuality.Good;case Xe.POOR:return e.ConnectionQuality.Poor;case Xe.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),i!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>Kr(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const i=t;switch(i.track&&(i.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case Js.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case Js.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Ya extends Qa{constructor(t,i,n,s,r,o){super(t,i,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=lt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Lr)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,s,r;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(r=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Lr),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==Ni.OK&&s.reject(new Us(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=Xo.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ti({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ao(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ao(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ao(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(t,i)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ao(i))),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,i)},this.handleSubscribedQualityUpdate=e=>Xi(this,void 0,void 0,(function*(){var t,i,n,s,r;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const o=this.videoTrackPublications.get(e.trackSid);if(!o)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!o.videoTrack)return;const a=yield o.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=$i(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;er(e)&&(this.log.debug("publish ".concat(e," for ").concat(o.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ao(o))),yield this.publishAdditionalCodecForTrack(o.videoTrack,e,o.options))}}catch(e){i={error:e}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Xi(this,void 0,void 0,(function*(){if(e.source===Js.Source.ScreenShare||e.source===Js.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ao(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Gr(e)||Wr(e))try{if(br())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Js.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),ao(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ao(e))),Gr(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ao(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==lt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){var i;this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),(null===(i=this.signalConnectedFuture)||void 0===i?void 0:i.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalConnected,this.handleSignalConnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Xi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Xi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Xi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Xi(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>Xi(t,void 0,void 0,(function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield or(50)}r(new Us("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&r(e)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(Js.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(Js.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(Js.Source.ScreenShare,e,t,i)}setPermissions(t){const i=this.permissions,n=super.setPermissions(t);return n&&i&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,i),n}setE2EEEnabled(e){return Xi(this,void 0,void 0,(function*(){this.encryptionType=e?lt.GCM:lt.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,i,n,s){return Xi(this,void 0,void 0,(function*(){var r,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:i})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(t);if(i)if(a)yield a.unmute();else{let i;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case Js.Source.Camera:i=yield this.createTracks({video:null===(r=n)||void 0===r||r});break;case Js.Source.Microphone:i=yield this.createTracks({audio:null===(o=n)||void 0===o||o});break;case Js.Source.ScreenShare:i=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Ms(t)}}catch(n){throw null==i||i.forEach((e=>{e.stop()})),n instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,n,no(t)),this.pendingPublishing.delete(t),n}for(const e of i){const i=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);t===Js.Source.Microphone&&Kr(e)&&i.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),e.startPreConnectBuffer())}try{const e=[];for(const t of i)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ao(t))),e.push(this.publishTrack(t,s));const t=yield Promise.all(e);[a]=t}catch(e){throw null==i||i.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(t)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(t)&&(a=yield this.waitForPendingPublicationOfSource(t),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),a&&a.track)if(t===Js.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(Js.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Xi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Js.Source.Camera)&&!this.pendingPublishing.has(Js.Source.Microphone)){this.pendingPublishing.add(Js.Source.Camera),this.pendingPublishing.add(Js.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(Js.Source.Camera),this.pendingPublishing.delete(Js.Source.Microphone)}}}))}createTracks(t){return Xi(this,void 0,void 0,(function*(){var i,n;null!=t||(t={});const s=Xr(t,null===(i=this.roomOptions)||void 0===i?void 0:i.audioCaptureDefaults,null===(n=this.roomOptions)||void 0===n?void 0:n.videoCaptureDefaults);try{const t=yield Ga(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(Kr(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=Js.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),Hr(t)&&(this.cameraError=void 0,t.source=Js.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return Xi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new xs("getDisplayMedia not supported");void 0!==t.resolution||fr()||(t.resolution=sr.h1080fps30.resolution);const i=so(t),n=yield navigator.mediaDevices.getDisplayMedia(i),s=n.getVideoTracks();if(0===s.length)throw new Ms("no video track found");const r=new ba(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Js.Source.ScreenShare,t.contentHint&&(r.mediaStreamTrack.contentHint=t.contentHint);const o=[r];if(n.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new oa(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=Js.Source.ScreenShareAudio,o.push(t)}return o}))}publishTrack(e,t){return Xi(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return Xi(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(Gr(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),qr(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case Js.Source.Microphone:t="audioinput";break;case Js.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new oa(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new ba(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new Ms("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),ao(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),ao(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=t.dtx)&&void 0!==o||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=Vs(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&wr(e.osVersion,t)>=0)||"Safari"===e.name&&wr(e.version,t)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>Xi(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==ko.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ao(e)}));const i=setTimeout((()=>{n(new Ls("publishing rejected as engine not connected within timeout",408))}),15e3);yield this.waitUntilEngineConnected(),clearTimeout(i);const s=yield this.publish(e,h,u);t(s)}else try{const i=yield this.publish(e,h,u);t(i)}catch(e){n(e)}}catch(e){n(e)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Lr),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ao(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case Qe.CAMERA:return Js.Source.Camera;case Qe.MICROPHONE:return Js.Source.Microphone;case Qe.SCREEN_SHARE:return Js.Source.ScreenShare;case Qe.SCREEN_SHARE_AUDIO:return Js.Source.ScreenShareAudio;default:return Js.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ao(e))),!1)}publish(t,i,n){return Xi(this,void 0,void 0,(function*(){var s,r,o,a,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(t))throw new Ls("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>qr(t)&&e.source===t.source))&&t.source!==Js.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),ao(t))),i.stopMicTrackOnMute&&Kr(t)&&(t.stopOnMute=!0),t.source===Js.Source.ScreenShare&&mr()&&(i.simulcast=!1),"av1"!==i.videoCodec||dr()||(i.videoCodec=void 0),"vp9"!==i.videoCodec||lr()||(i.videoCodec=void 0),void 0===i.videoCodec&&(i.videoCodec=Ko),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>i.videoCodec===ro(e.mime)))||(i.videoCodec=ro(this.enabledPublishVideoCodecs[0].mime)));const m=i.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=[],v=!(null===(s=i.dtx)||void 0===s||s),f=t.getSourceTrackSettings();f.autoGainControl&&g.push(it.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&g.push(it.TF_ECHO_CANCELLATION),f.noiseSuppression&&g.push(it.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&g.push(it.TF_STEREO),v&&g.push(it.TF_NO_DTX),Gr(t)&&t.hasPreConnectBuffer&&g.push(it.TF_PRECONNECT_BUFFER);const k=new Jt({cid:t.mediaStreamTrack.id,name:i.name,type:Js.kindToProto(t.kind),muted:t.isMuted,source:Js.sourceToProto(t.source),disableDtx:v,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(r=i.red)||void 0===r||r),stream:null==i?void 0:i.stream,backupCodecPolicy:null==i?void 0:i.backupCodecPolicy,audioFeatures:g});let b;if(t.kind===Js.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(i){const n=null!==(a=null===(o=this.roomOptions.videoCaptureDefaults)||void 0===o?void 0:o.resolution)&&void 0!==a?a:ir.h720.resolution;e={width:n.width,height:n.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ao(t)),{dims:e}))}k.width=e.width,k.height=e.height,Wr(t)&&(ur(m)&&(t.source===Js.Source.ScreenShare&&(i.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),ao(t))))),i.scalabilityMode=null!==(c=i.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),k.simulcastCodecs=[new zt({codec:m,cid:t.mediaStreamTrack.id})],!0===i.backupCodec&&(i.backupCodec={codec:Ko}),i.backupCodec&&m!==i.backupCodec.codec&&k.encryption===lt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new zt({codec:i.backupCodec.codec,cid:""})))),b=ma(t.source===Js.Source.ScreenShare,k.width,k.height,i),k.layers=Ca(k.width,k.height,b,ur(i.videoCodec))}else t.kind===Js.Kind.Audio&&(b=[{maxBitrate:null===(d=i.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=i.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=i.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new _s("cannot publish track when not connected");const y=()=>Xi(this,void 0,void 0,(function*(){var n,s,r;if(!this.engine.pcManager)throw new _s("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,i,b),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Wr(t)&&(null!==(n=i.degradationPreference)&&void 0!==n||(i.degradationPreference=function(e){return e.source===Js.Source.ScreenShare||e.constraints.height&&Ur(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(i.degradationPreference)),b)if(mr()&&t.kind===Js.Kind.Audio){let e;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===t.sender){e=i;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(s=b[0])||void 0===s?void 0:s.maxBitrate)?b[0].maxBitrate/1e3:0})}else t.codec&&ur(t.codec)&&(null===(r=b[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:t.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}));let T;const C=new Promise(((e,i)=>Xi(this,void 0,void 0,(function*(){var n;try{T=yield this.engine.addTrack(k),e(T)}catch(e){t.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),ao(t)),{error:e}))}))),i(e)}}))));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([C,y()]);T=e[0]}else{let e;if(T=yield C,T.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===Js.Kind.Video){const n=ro(e);n!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ao(t)),{codec:n})),i.videoCodec=n,b=ma(t.source===Js.Source.ScreenShare,k.width,k.height,i))}yield y()}const S=new Wa(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,S))),S.options=i,t.sid=T.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:T})),Wr(t)?t.startMonitor(this.engine.client):Gr(t)&&t.startMonitor(),this.addTrackPublication(S),this.emit(e.ParticipantEvent.LocalTrackPublished,S),Gr(t)&&T.audioFeatures.includes(it.TF_PRECONNECT_BUFFER)){const i=t.getPreConnectBuffer(),n=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===T.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ao(t))),t.stopPreConnectBuffer()}})),i){const e=new Promise(((e,s)=>Xi(this,void 0,void 0,(function*(){var r,o,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ao(t)));const m=setTimeout((()=>{s(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ao(t)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:n,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=$i(i);!(r=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){o={error:e}}finally{try{h||r||!(a=p.return)||(yield a.call(p))}finally{if(o)throw o.error}}yield v.close(),e()}catch(e){s(e)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ao(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ao(t)),{error:e}))}))}}return S}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Xi(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==lt.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new Ms("track is not published");if(!Wr(e))throw new Ms("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&Hi.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===Js.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),ma(e.source===Js.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ao(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Jt({cid:a.mediaStreamTrack.id,type:Js.kindToProto(e.kind),muted:e.isMuted,source:Js.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Ca(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new _s("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Xi(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(t,i){return Xi(this,void 0,void 0,(function*(){var n,s;if(qr(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ao(t))),yield e)}const r=this.getPublicationForTrack(t),o=r?ao(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));(t=r.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===i&&(i=null===(s=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===s||s),i?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Qo.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),Wr(t)){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(a=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Js.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Js.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,r),r.setTrack(void 0),a&&(yield this.engine.negotiate()),r}))}unpublishTracks(e){return Xi(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Xi(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>Xi(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>Xi(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===Js.Source.ScreenShare||t.source===Js.Source.ScreenShareAudio||!Gr(t)&&!Wr(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(e){s(e)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Xi(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?gt.RELIABLE:gt.LOSSY,s=i.destinationIdentities,r=i.topic,o=new mt({kind:n,value:{case:"user",value:new kt({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(o,n)}()}))}publishDtmf(e,t){return Xi(this,void 0,void 0,(function*(){const i=new mt({kind:gt.RELIABLE,value:{case:"sipDtmf",value:new bt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,gt.RELIABLE)}))}sendChatMessage(t,i){return Xi(this,void 0,void 0,(function*(){const n={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==i?void 0:i.attachments},s=new mt({value:{case:"chatMessage",value:new Ct(Object.assign(Object.assign({},n),{timestamp:x.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,gt.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,n),n}))}editChatMessage(t,i){return Xi(this,void 0,void 0,(function*(){const n=Object.assign(Object.assign({},i),{message:t,editTimestamp:Date.now()}),s=new mt({value:{case:"chatMessage",value:new Ct(Object.assign(Object.assign({},n),{timestamp:x.parse(n.timestamp),editTimestamp:x.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,gt.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,n),n}))}sendText(e,t){return Xi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return Xi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return Xi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return Xi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return Xi(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,o)=>Xi(t,void 0,void 0,(function*(){var t,a,c,d;if(Zo(s)>15360)return void o(Xo.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&wr(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(Xo.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),o(Xo.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),o(Xo.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return Xi(this,void 0,void 0,(function*(){const r=new mt({destinationIdentities:[e],kind:gt.RELIABLE,value:{case:"rpcRequest",value:new St({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,gt.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,Xo.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ao(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}setActiveAgent(e){var t,i,n,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(s=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Lr),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(Gr(n)||Wr(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return Xi(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield or(20)}}))}}class Xa extends Ha{constructor(t,i,n,s){super(t,i.sid,i.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(i)}setSubscribed(t){const i=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const s=new ni({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Rt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(i),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?Ha.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ha.SubscriptionStatus.Subscribed:Ha.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ha.PermissionStatus.Allowed:Ha.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}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,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)===e.height||(Qr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Qr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:e.VideoQuality.HIGH}setTrack(t){const i=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==t&&(s&&(s.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),s.off(e.TrackEvent.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,s)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(i))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const i=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):i!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const i=this.subscriptionStatus;t!==i&&this.emit(e.TrackEvent.SubscriptionStatusChanged,i,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Qr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new si({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Js.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(r){lo(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(i=this.trackInfo,n=this.requestedMaxQuality,null===(s=i.layers)||void 0===s?void 0:s.find((e=>e.quality===n)));e&&lo(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream;r?(t.width=Math.ceil(r.width),t.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:e.VideoQuality.HIGH})),t.quality=e.VideoQuality.HIGH)}var i,n,s;this.emit(e.TrackEvent.UpdateSettings,t)}}class Za extends Qa{static fromParticipantInfo(e,t,i){return new Za(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,o){super(t,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:ct.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ao(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,i)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,i)})),t.on(e.TrackEvent.Subscribed,(i=>{this.emit(e.ParticipantEvent.TrackSubscribed,i,t)})),t.on(e.TrackEvent.Unsubscribed,(i=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,i,t)})),t.on(e.TrackEvent.SubscriptionFailed,(i=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,i)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Js.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Js.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,i,n,s,r,o){let a=this.getTrackPublicationBySid(i);if(a||i.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===o?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:i})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i)):(void 0===o&&(o=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,i,n,s,r,o-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ao(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,i);let c;return c="video"===t.kind?new Ba(t,i,s,r):new Fa(t,i,s,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(n),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&zr(c)&&Kr(c)&&c.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const i=new Map,n=new Map;return t.tracks.forEach((e=>{var t,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const i=Js.kindFromProto(e.type);if(!i)return;r=new Xa(i,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),n.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));o&&r.source!==Js.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ao(o),newTrack:ao(r)})),this.addTrackPublication(r)}i.set(e.sid,r)})),this.trackPublications.forEach((e=>{i.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ao(e))),this.unpublishTrack(e.trackSid,!0))})),n.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,i){const n=this.trackPublications.get(t);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(t),n.kind){case Js.Kind.Audio:this.audioTrackPublications.delete(t);break;case Js.Kind.Video:this.videoTrackPublications.delete(t)}i&&this.emit(e.ParticipantEvent.TrackUnpublished,n)}setAudioOutput(e){return Xi(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;Kr(i.track)&&zr(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var $a;e.ConnectionState=void 0,($a=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",$a.Connecting="connecting",$a.Connected="connected",$a.Reconnecting="reconnecting",$a.SignalReconnecting="signalReconnecting";class ec extends nn.EventEmitter{constructor(t){var i,n,r,o;if(super(),i=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Hi,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(t,i,n)=>Xi(this,void 0,void 0,(function*(){var s;if(!pr())throw yr()?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 r=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Tr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Oa(t,i):this.regionUrlProvider.updateToken(i),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const o=(s,a,c)=>Xi(this,void 0,void 0,(function*(){var d,l;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==r||r();try{yield this.attemptConnection(null!=c?c:t,i,n,u),this.abortController=void 0,s()}catch(t){if(this.regionUrlProvider&&t instanceof Ds&&t.reason!==e.ConnectionErrorReason.Cancelled&&t.reason!==e.ConnectionErrorReason.NotAllowed){let i=null;try{i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(t){if(t instanceof Ds&&(401===t.status||t.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(t)}i&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield o(s,a,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Fr(t)),a(t))}else{let e=$e.UNKNOWN_REASON;t instanceof Ds&&(e=Fr(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(t)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Lr(((e,t)=>{o(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>Xi(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new As("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,i,n,s)=>Xi(this,void 0,void 0,(function*(){var r,o;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Jo),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(t,i,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const i=new Ds("could not establish signal connection",e.ConnectionErrorReason.ServerUnreachable);throw t instanceof Error&&(i.message="".concat(i.message,": ").concat(t.message)),t instanceof Ds&&(i.reason=t.reason,i.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),i}if(s.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Ds("Connection attempt aborted",e.ConnectionErrorReason.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}br()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),br()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return Xi(i,[...n],void 0,(function(){var t=this;let i=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,s,r,o;const a=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected",t.logContext);t.log.info("disconnect from room",Object.assign({},t.logContext)),(t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming)&&(t.log.warn("abort connection attempt",t.logContext),null===(n=t.abortController)||void 0===n||n.abort(),null===(r=null===(s=t.connectFuture)||void 0===s?void 0:s.reject)||void 0===r||r.call(s,new Ds("Client initiated disconnect",e.ConnectionErrorReason.Cancelled)),t.connectFuture=void 0),(null===(o=t.engine)||void 0===o?void 0:o.client.isDisconnected)||(yield t.engine.client.sendLeave()),t.engine&&(yield t.engine.close()),t.handleDisconnect(i,$e.CLIENT_INITIATED),t.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>Xi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Xi(this,void 0,void 0,(function*(){const t=[],i=Vs();if(i&&"iOS"===i.os){const i="livekit-dummy-audio-el";let n=document.getElementById(i);if(!n){n=document.createElement("audio"),n.id=i,n.autoplay=!0,n.hidden=!0;const t=Nr();t.enabled=!0;const s=new MediaStream([t]);n.srcObject=s,document.addEventListener("visibilitychange",(()=>{n&&(n.srcObject=document.hidden?null:s,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(n),this.once(e.RoomEvent.Disconnected,(()=>{null==n||n.remove(),n=null}))}t.push(n)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>Xi(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>Xi(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===at.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const i=[],n={};t.forEach((e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),i.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),i.push(t))}})),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleSpeakersChanged=t=>{const i=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||i.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?i.set(e.sid,t):i.delete(e.sid))}));const n=Array.from(i.values());n.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const i=this.getRemoteParticipantBySid(t.participantSid);if(!i)return;const n=i.getTrackPublicationBySid(t.trackSid);if(!n||!n.track)return;const s=Js.streamStateFromProto(t.state);n.track.setStreamState(s),s!==n.track.streamState&&(i.emit(e.ParticipantEvent.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,n,n.track.streamState,i))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(t,i,n)=>{this.emit(e.RoomEvent.DataReceived,i.payload,t,n,i.topic),null==t||t.emit(e.ParticipantEvent.DataReceived,i.payload,n)},this.handleSipDtmf=(t,i)=>{this.emit(e.RoomEvent.SipDTMFReceived,i,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,i)},this.handleTranscription=(t,i)=>{const n=i.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(i.transcribedParticipantIdentity),s=null==n?void 0:n.trackPublications.get(i.trackId),r=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(i,this.transcriptionReceivedTimes);null==s||s.emit(e.TrackEvent.TranscriptionReceived,r),null==n||n.emit(e.ParticipantEvent.TranscriptionReceived,r,s),this.emit(e.RoomEvent.TranscriptionReceived,r,n,s)},this.handleChatMessage=(t,i)=>{const n=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(i);this.emit(e.RoomEvent.ChatMessage,n,t)},this.handleMetrics=(t,i)=>{this.emit(e.RoomEvent.MetricsReceived,t,i)},this.handleDataStream=e=>{this.incomingDataStreamManager.handleDataStreamPacket(e)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Xi(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=Vs())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const i=this.roomInfo;this.roomInfo=t,i&&i.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==i?void 0:i.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>Xi(this,void 0,void 0,(function*(){var i,n,s,r,o,a;if(null===(i=t.track)||void 0===i||i.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=t.track)||void 0===n||n.on(e.TrackEvent.Restarted,this.onLocalTrackRestarted),null===(o=null===(r=null===(s=t.track)||void 0===s?void 0:s.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===o||o.call(r,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),Gr(t.track)){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const c=yield null===(a=t.track)||void 0===a?void 0:a.getDeviceId(!1),d=no(t.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,c),this.emit(e.RoomEvent.ActiveDeviceChanged,d,c))})),this.onLocalTrackUnpublished=t=>{var i,n;null===(i=t.track)||void 0===i||i.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=t.track)||void 0===n||n.off(e.TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>Xi(this,void 0,void 0,(function*(){const i=yield t.getDeviceId(!1),n=no(t.source);n&&i&&i!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug("local track restarted, setting ".concat(n," ").concat(i," active"),this.logContext),this.localParticipant.activeDeviceMap.set(n,i),this.emit(e.RoomEvent.ActiveDeviceChanged,n,i))})),this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,i)=>{this.emit(e.RoomEvent.MediaDevicesError,t,i)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(e.RoomEvent.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},zo),t),this.log=Gi(null!==(n=this.options.loggerName)&&void 0!==n?n:e.LoggerNames.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Wo),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Go),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ho),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Aa,this.outgoingDataStreamManager=new Ua(this.engine,this.log),this.disconnectLock=new s,this.localParticipant=new Ya("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ur(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ur(this.options.audioCaptureDefaults.deviceId)),(null===(r=this.options.audioOutput)||void 0===r?void 0:r.deviceId)&&this.switchActiveDevice("audiooutput",Ur(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),br()){const e=new AbortController;null===(o=navigator.mediaDevices)||void 0===o||o.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),ec.cleanupRegistry&&ec.cleanupRegistry.register(this,(()=>{e.abort()}))}}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){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)}setE2EEEnabled(e){return Xi(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var t;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new uo(this.options.e2ee),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,i)=>{Yr(i)&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,i)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Xi(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,i)=>{const n=i=>{""!==i.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,n),t(i.sid))};this.engine.on(e.EngineEvent.RoomUpdate,n),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,n),i("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ra(this.options),this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,i)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,i)})).on(e.EngineEvent.LocalTrackSubscribed,(t=>{const i=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:i}=e;return i===t}));i?(this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,i),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,i,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(e.EngineEvent.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(e.RoomEvent.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return po.getInstance().getDevices(e,t)}prepareConnection(t,i){return Xi(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(Tr(new URL(t))&&i){this.regionUrlProvider=new Oa(t,i);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=n,yield fetch(jr(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(jr(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Xi(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Ii({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Ii({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Ii({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Ii({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=()=>Xi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ii({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Xi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ii({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new Ii({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Xi(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new ai({reason:$e.CLIENT_INITIATED,action:ci.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Ii({scenario:{case:"subscriberBandwidth",value:Vr(t)}});break;case"leave-full-reconnect":i=new Ii({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,i){return Xi(this,arguments,void 0,(function(t,i){var n=this;let s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var r,o,a,c,d,l,u;let h=!0,p=!1;const m=s?{exact:i}:i;if("audioinput"===t){p=0===n.localParticipant.audioTrackPublications.size;const e=null!==(r=n.getActiveDevice(t))&&void 0!==r?r:n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=m;const i=Array.from(n.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Js.Source.Microphone));try{h=(yield Promise.all(i.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw n.options.audioCaptureDefaults.deviceId=e,t}const s=i.some((e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i}));h&&s&&(p=!0)}else if("videoinput"===t){p=0===n.localParticipant.videoTrackPublications.size;const e=null!==(o=n.getActiveDevice(t))&&void 0!==o?o:n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=m;const i=Array.from(n.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Js.Source.Camera));try{h=(yield Promise.all(i.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw n.options.videoCaptureDefaults.deviceId=e,t}const s=i.some((e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i}));h&&s&&(p=!0)}else if("audiooutput"===t){if(p=!0,!hr()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!("setSinkId"in n.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");n.options.webAudioMix&&(i=null!==(a=yield po.getInstance().normalizeDeviceId("audiooutput",i))&&void 0!==a?a:""),null!==(c=(u=n.options).audioOutput)&&void 0!==c||(u.audioOutput={});const e=null!==(d=n.getActiveDevice(t))&&void 0!==d?d:n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=i;try{n.options.webAudioMix&&(null===(l=n.audioContext)||void 0===l||l.setSinkId(i)),yield Promise.all(Array.from(n.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:i}))))}catch(t){throw n.options.audioOutput.deviceId=e,t}}return p&&(n.localParticipant.activeDeviceMap.set(t,i),n.emit(e.RoomEvent.ActiveDeviceChanged,t,i)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,i,n){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const s=()=>{this.onTrackAdded(t,i,n),r()},r=()=>{this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,r)};return this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),void this.once(e.RoomEvent.Disconnected,r)}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===t.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const s=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(i.id),r=s[0];let o=s[1],a=t.id;if(o&&o.startsWith("TR")&&(a=o),r===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===r));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const l=c.addSubscribedMediaTrack(t,a,i,n,d);(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],i=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var i,n,s;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop()):null===(s=e.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),br()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,i)}}}handleParticipantDisconnected(t,i){var n;this.remoteParticipants.delete(t),i&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),i.trackPublications.forEach((e=>{i.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,i),i.setDisconnected(),null===(n=this.localParticipant)||void 0===n||n.handleParticipantDisconnected(i.identity))}handleIncomingRpcRequest(e,t,i,n,s,r){return Xi(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,Xo.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,Xo.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});Zo(r)>15360?(a=Xo.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(e){e instanceof Xo?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=Xo.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}selectDefaultDevices(){return Xi(this,void 0,void 0,(function*(){var t,i,n;const s=po.getInstance().previousDevices,r=yield po.getInstance().getDevices(void 0,!1),o=Vs();if("Chrome"===(null==o?void 0:o.name)&&"iOS"!==o.os)for(let t of r){const i=s.find((e=>e.deviceId===t.deviceId));i&&""!==i.label&&i.kind===t.kind&&i.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,t.kind,t.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let e of a){const o=io(e),a=this.localParticipant.getTrackPublication(o);if(a&&(null===(t=a.track)||void 0===t?void 0:t.isUserProvided))continue;const c=r.filter((t=>t.kind===e)),d=this.getActiveDevice(e);d===(null===(i=s.filter((t=>t.kind===e))[0])||void 0===i?void 0:i.deviceId)&&c.length>0&&(null===(n=c[0])||void 0===n?void 0:n.deviceId)!==d?yield this.switchActiveDevice(e,c[0].deviceId):"audioinput"===e&&!vr()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&vr()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return Xi(this,void 0,void 0,(function*(){var t,i;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=to())&&void 0!==t?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),or(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const n="running"===(null===(i=this.audioContext)||void 0===i?void 0:i.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,n))}))}createParticipant(e,t){var i;let n;return n=t?Za.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new Za(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(t,i){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(i){e.updateInfo(i)&&this.sidToIdentity.set(i.sid,i.identity)}return e}const n=this.createParticipant(t,i);return this.remoteParticipants.set(t,n),this.sidToIdentity.set(i.sid,i.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,n),n.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,n)})).on(e.ParticipantEvent.TrackSubscribed,((t,i)=>{t.kind===Js.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===Js.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,i,n)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,n)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,i)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,i,n)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,n)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,n)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,n)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,n)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,n)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,n)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,n)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,i)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,i)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,i,n)})).on(e.ParticipantEvent.Active,(()=>{this.emitWhenConnected(e.RoomEvent.ParticipantActive,n),n.kind===ct.AGENT&&this.localParticipant.setActiveAgent(n)})),i&&n.updateInfo(i),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Jr(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Gs.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,$e.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Gs.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,n]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...n);return!1}simulateParticipants(t){return Xi(this,void 0,void 0,(function*(){var i,n;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new nt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:x.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ot({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),s.video){const t=new Wa(Js.Kind.Video,new ht({source:Qe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Je.AUDIO,name:"video-dummy"}),new ba(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:_r(160*(null!==(i=r.aspectRatios[0])&&void 0!==i?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(s.audio){const t=new Wa(Js.Kind.Audio,new ht({source:Qe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Je.AUDIO}),new oa(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Nr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<r.count-1;e+=1){let t=new ot({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:at.ACTIVE,tracks:[],joinedAt:x.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const s=_r(160*(null!==(n=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==n?n:1),160,!1,!0),o=new ht({source:Qe.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Je.AUDIO});i.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Nr(),n=new ht({source:Qe.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Je.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}}))}emit(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];if(t!==e.RoomEvent.ActiveSpeakersChanged&&t!==e.RoomEvent.TranscriptionReceived){const e=tc(n).filter((e=>void 0!==e));this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e}))}return super.emit(t,...n)}}function tc(e){return e.map((e=>{if(e)return Array.isArray(e)?tc(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}ec.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()}));var ic,nc=Object.freeze({__proto__:null,Convert:class{static toAgentAttributes(e){return JSON.parse(e)}static agentAttributesToJson(e){return JSON.stringify(e)}static toTranscriptionAttributes(e){return JSON.parse(e)}static transcriptionAttributesToJson(e){return JSON.stringify(e)}}});e.CheckStatus=void 0,(ic=e.CheckStatus||(e.CheckStatus={}))[ic.IDLE=0]="IDLE",ic[ic.RUNNING=1]="RUNNING",ic[ic.SKIPPED=2]="SKIPPED",ic[ic.SUCCESS=3]="SUCCESS",ic[ic.FAILED=4]="FAILED";class sc extends nn.EventEmitter{constructor(t,i){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.options={},this.url=t,this.token=i,this.name=this.constructor.name,this.room=new ec(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(t){return Xi(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(t){return Xi(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions)),this.room}))}disconnect(){return Xi(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(e.CheckStatus.SKIPPED)}switchProtocol(t){return Xi(this,void 0,void 0,(function*(){let i=!1,n=!1;if(this.room.on(e.RoomEvent.Reconnecting,(()=>{i=!0})),this.room.once(e.RoomEvent.Reconnected,(()=>{n=!0})),this.room.simulateScenario("force-".concat(t)),yield new Promise((e=>setTimeout(e,1e3))),!i)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield or(100)}throw new Error("Could not reconnect using ".concat(t," 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 null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class rc extends sc{get description(){return"Cloud regions"}perform(){return Xi(this,void 0,void 0,(function*(){const e=new Oa(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],i=new Set;for(let n=0;n<3;n++){const n=yield e.getNextBestRegionUrl();if(!n)break;if(i.has(n))continue;i.add(n);const s=yield this.checkCloudRegion(n);this.appendMessage("".concat(s.region," RTT: ").concat(s.rtt,"ms, duration: ").concat(s.duration,"ms")),t.push(s)}t.sort(((e,t)=>.5*(e.duration-t.duration)+.5*(e.rtt-t.rtt)));const n=t[0];this.bestStats=n,this.appendMessage("best Cloud region: ".concat(n.region))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return Xi(this,void 0,void 0,(function*(){var t,i;yield this.connect(e),"tcp"===this.options.protocol&&(yield this.switchProtocol("tcp"));const n=null===(t=this.room.serverInfo)||void 0===t?void 0:t.region;if(!n)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),r="A".repeat(1e3),o=Date.now();for(let e=0;e<1e3;e++)yield s.write(r);yield s.close();const a=Date.now(),c=yield null===(i=this.room.engine.pcManager)||void 0===i?void 0:i.publisher.getStats(),d={region:n,rtt:1e4,duration:a-o};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const oc=1e4;class ac extends sc{get description(){return"Connection via UDP vs TCP"}perform(){return Xi(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 i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/10*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/10*100).toFixed(2),"%"))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return Xi(this,void 0,void 0,(function*(){yield this.connect(),"tcp"===e?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let n=0;const s=()=>{n=(n+1)%360,i.fillStyle="hsl(".concat(n,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const r=t.captureStream(30).getVideoTracks()[0],o=(yield this.room.localParticipant.publishTrack(r,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,a={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},c=setInterval((()=>Xi(this,void 0,void 0,(function*(){const e=yield o.getRTCStatsReport();null==e||e.forEach((e=>{"outbound-rtp"===e.type?(a.packetsSent=e.packetsSent,a.qualityLimitationDurations=e.qualityLimitationDurations,a.bitrateTotal+=e.targetBitrate,a.count++):"remote-inbound-rtp"===e.type&&(a.packetsLost=e.packetsLost,a.rttTotal+=e.roundTripTime,a.jitterTotal+=e.jitter)}))}))),1e3);return yield new Promise((e=>setTimeout(e,oc))),clearInterval(c),r.stop(),t.remove(),yield this.disconnect(),a}))}}class cc extends sc{get description(){return"Can publish audio"}perform(){return Xi(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),i=yield Ja();if(yield eo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,3e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(s=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))}))}}class dc extends sc{get description(){return"Can publish video"}perform(){return Xi(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),i=yield za();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise((e=>setTimeout(e,5e3)));const n=yield null===(e=i.sender)||void 0===e?void 0:e.getStats();if(!n)throw new Error("Could not get RTCStats");let s=0;if(n.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(s+=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))}))}checkForVideo(e){return Xi(this,void 0,void 0,(function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,yield new Promise((t=>{i.onplay=()=>{setTimeout((()=>{var n,s,r,o;const a=document.createElement("canvas"),c=e.getSettings(),d=null!==(s=null!==(n=c.width)&&void 0!==n?n:i.videoWidth)&&void 0!==s?s:1280,l=null!==(o=null!==(r=c.height)&&void 0!==r?r:i.videoHeight)&&void 0!==o?o:720;a.width=d,a.height=l;const u=a.getContext("2d");u.drawImage(i,0,0);const h=u.getImageData(0,0,a.width,a.height).data;let p=!0;for(let e=0;e<h.length;e+=4)if(0!==h[e]||0!==h[e+1]||0!==h[e+2]){p=!1;break}p?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),t()}),1e3)},i.play()})),t.getTracks().forEach((e=>e.stop())),i.remove()}))}}class lc extends sc{get description(){return"Resuming connection after interruption"}perform(){return Xi(this,void 0,void 0,(function*(){var t;const i=yield this.connect();let n,s=!1,r=!1;const o=new Promise((e=>{setTimeout(e,5e3),n=e})),a=()=>{s=!0};i.on(e.RoomEvent.SignalReconnecting,a).on(e.RoomEvent.Reconnecting,a).on(e.RoomEvent.Reconnected,(()=>{r=!0,n(!0)})),null===(t=i.engine.client.ws)||void 0===t||t.close();const c=i.engine.client.onClose;if(c&&c(""),yield o,!s)throw new Error("Did not attempt to reconnect");if(!r||i.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class uc extends sc{get description(){return"Can connect via TURN"}perform(){return Xi(this,void 0,void 0,(function*(){var e,t;const i=new bo,n=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,r=!1,o=!1;for(let e of n.iceServers)for(let t of e.urls)t.startsWith("turn:")?(r=!0,o=!0):t.startsWith("turns:")&&(r=!0,o=!0,s=!0),t.startsWith("stun:")&&(o=!0);o?r&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||r?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class hc extends sc{get description(){return"Establishing WebRTC connection"}perform(){return Xi(this,void 0,void 0,(function*(){let t=!1,i=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(n,s)=>{if(n.candidate){const e=new RTCIceCandidate(n);let s="".concat(e.protocol," ").concat(e.address,":").concat(e.port," ").concat(e.type);e.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(e.address)?"tcp"===e.protocol&&"passive"===e.tcpType?(t=!0,s+=" (passive)"):"udp"===e.protocol&&(i=!0):s+=" (private)"),this.appendMessage(s)}e&&e(n,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),Hi.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),i||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class pc extends sc{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Xi(this,void 0,void 0,(function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let n=new bo;const s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),(null===(e=s.serverInfo)||void 0===e?void 0:e.edition)===Ot.Cloud&&(null===(t=s.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(i=s.serverInfo)||void 0===i?void 0:i.region)),yield n.close()}))}}class mc extends nn.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Xi(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),n=e=>{this.updateCheck(t,e)};i.on("update",n);const s=yield i.run();return i.off("update",n),s}))}checkWebsocket(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(pc)}))}checkWebRTC(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(hc)}))}checkTURN(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(uc)}))}checkReconnect(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(lc)}))}checkPublishAudio(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(cc)}))}checkPublishVideo(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(dc)}))}checkConnectionProtocol(){return Xi(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(ac);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return Xi(this,void 0,void 0,(function*(){return this.createAndRunCheck(rc)}))}}const gc=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),vc=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function fc(e){var t;const i=e.trim().toLowerCase();if(""!==i)return gc.has(i)?gc.get(i):null===(t=Array.from(vc.entries()).find((e=>{let[t]=e;return i.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ys,e.Checker=sc,e.ConnectionCheck=mc,e.ConnectionError=Ds,e.CriticalTimers=Gs,e.CryptorError=class extends Ts{constructor(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=i,this.participantIdentity=n}},e.DataPacket_Kind=gt,e.DataStreamError=js,e.DefaultReconnectPolicy=Yi,e.DeviceUnsupportedError=xs,e.DisconnectReason=$e,e.ExternalE2EEKeyProvider=class extends ys{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return Xi(this,void 0,void 0,(function*(){const t="string"==typeof e?yield fs(e):yield ks(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=Ts,e.LocalAudioTrack=oa,e.LocalParticipant=Ya,e.LocalTrack=ra,e.LocalTrackPublication=Wa,e.LocalTrackRecorder=sa,e.LocalVideoTrack=ba,e.Mutex=s,e.NegotiationError=Ns,e.Participant=Qa,e.ParticipantKind=ct,e.PublishDataError=class extends Ts{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}},e.PublishTrackError=Ls,e.RemoteAudioTrack=Fa,e.RemoteParticipant=Za,e.RemoteTrack=ja,e.RemoteTrackPublication=Xa,e.RemoteVideoTrack=Ba,e.Room=ec,e.RpcError=Xo,e.ScreenSharePresets=sr,e.SignalRequestError=Us,e.SubscriptionError=tt,e.Track=Js,e.TrackInvalidError=Ms,e.TrackPublication=Ha,e.TrackType=Je,e.UnexpectedConnectionState=_s,e.UnsupportedServer=As,e.VideoPreset=Xs,e.VideoPresets=ir,e.VideoPresets43=nr,e.attachToElement=Qs,e.attributes=nc,e.compareVersions=wr,e.createAudioAnalyser=function(e,t){const i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=to();if(!n)throw new Error("Audio Context not supported on this browser");const s=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,r=n.createMediaStreamSource(new MediaStream([s])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,r.connect(o);const a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>Xi(this,void 0,void 0,(function*(){yield n.close(),i.cloneTrack&&s.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=ks,e.createKeyMaterialFromString=fs,e.createLocalAudioTrack=Ja,e.createLocalScreenTracks=function(e){return Xi(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||fr()||(e.resolution=sr.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new xs("getDisplayMedia not supported");const t=so(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new Ms("no video track found");const s=new ba(n[0],void 0,!1);s.source=Js.Source.ScreenShare;const r=[s];if(i.getAudioTracks().length>0){const e=new oa(i.getAudioTracks()[0],void 0,!1);e.source=Js.Source.ScreenShareAudio,r.push(e)}return r}))},e.createLocalTracks=Ga,e.createLocalVideoTrack=za,e.deriveKeys=function(e,t){return Xi(this,void 0,void 0,(function*(){const i=bs(e.algorithm.name,t),n=yield crypto.subtle.deriveKey(i,e,{name:ds,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:n}}))},e.detachTrack=Ys,e.facingModeFromDeviceLabel=fc,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;const n=qr(e)?e.mediaStreamTrack:e,s=n.getSettings();let r={facingMode:null!==(i=t.defaultFacingMode)&&void 0!==i?i:"user",confidence:"low"};if("facingMode"in s){const e=s.facingMode;Hi.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(r={facingMode:e,confidence:"high"})}if(["low","medium"].includes(r.confidence)){Hi.trace("Try to get facing mode from device label: (".concat(n.label,")"));const e=fc(n.label);void 0!==e&&(r=e)}return r},e.getBrowser=Vs,e.getEmptyAudioStreamTrack=Nr,e.getEmptyVideoStreamTrack=function(){return Mr||(Mr=_r()),Mr.clone()},e.getLogger=Gi,e.importKey=function(e){return Xi(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:ds},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===i?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isAudioTrack=Kr,e.isBackupCodec=er,e.isBrowserSupported=pr,e.isE2EESupported=ms,e.isInsertableStreamSupported=vs,e.isLocalParticipant=Yr,e.isLocalTrack=qr,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=zr,e.isScriptTransformSupported=gs,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=Hr,e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var i=e.length,n=0;n<e.length;)i-n>=3&&!e[n]&&!e[n+1]&&3==e[n+2]?(t.push(e[n++]),t.push(e[n++]),n++):t.push(e[n++]);return new Uint8Array(t)},e.protocolVersion=16,e.ratchet=function(e,t){return Xi(this,void 0,void 0,(function*(){const i=bs(e.algorithm.name,t);return crypto.subtle.deriveBits(i,e,256)}))},e.setLogExtension=function(t,i){(i?[i]:Wi).forEach((i=>{const n=i.methodFactory;i.methodFactory=(i,s,r)=>{const o=n(i,s,r),a=e.LogLevel[i],c=a>=s&&a<e.LogLevel.silent;return(e,i)=>{i?o(e,i):o(e),c&&t(a,e,i)}},i.setLevel(i.getLevel())}))},e.setLogLevel=function(e,t){if(t)Ki.getLogger(t).setLevel(e);else for(const t of Wi)t.setLevel(e)},e.supportsAV1=dr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return ar()},e.supportsVP9=lr,e.version=Ws,e.videoCodecs=$s,e.writeRbsp=function(e){const t=[];for(var i=0,n=0;n<e.length;++n){var s=e[n];s<=3&&i>=2&&(t.push(3),i=0),t.push(s),0==s?++i:i=0}return new Uint8Array(t)}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LivekitClient={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var n=Object.defineProperty,i=(e,t,i)=>((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class s{constructor(){i(this,"_locking"),i(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}function o(e,t){if(!e)throw new Error(t)}const r=34028234663852886e22,a=-34028234663852886e22,c=4294967295,d=2147483647,l=-2147483648;function u(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>d||e<l)throw new Error("invalid int 32: "+e)}function h(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>c||e<0)throw new Error("invalid uint 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>r||e<a))throw new Error("invalid float 32: "+e)}const m=Symbol("@bufbuild/protobuf/enum-type");function g(e){const t=e[m];return o(t,"missing enum type on enum object"),t}function v(e,t,n,i){e[m]=f(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function f(e,t,n){const i=Object.create(null),s=Object.create(null),o=[];for(const e of t){const t=y(e);o.push(t),i[e.name]=t,s[e.no]=t}return{typeName:e,values:o,findName:e=>i[e],findNumber:e=>s[e]}}function k(e,t,n){const i={};for(const e of t){const t=y(e);i[t.localName]=t.no,i[t.no]=t.localName}return v(i,e,t),i}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class b{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().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,s=i.makeReadOptions(t);return i.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function T(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function C(e,t,n){for(let i=0;i<28;i+=7){const s=e>>>i,o=!(s>>>7==0&&0==t),r=255&(o?128|s:s);if(n.push(r),!o)return}const i=e>>>28&15|(7&t)<<4,s=!(t>>3==0);if(n.push(255&(s?128|i:i)),s){for(let e=3;e<31;e+=7){const i=t>>>e,s=!(i>>>7==0),o=255&(s?128|i:i);if(n.push(o),!s)return}n.push(t>>>31&1)}}const S=4294967296;function E(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,s=0;function o(t,o){const r=Number(e.slice(t,o));s*=n,i=i*n+r,i>=S&&(s+=i/S|0,i%=S)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?R(i,s):P(i,s)}function w(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(S*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let s=(16777215&e)+6777216*n+6710656*i,o=n+8147497*i,r=2*i;const a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(r+=Math.floor(o/a),o%=a),r.toString()+I(o)+I(s)}function P(e,t){return{lo:0|e,hi:0|t}}function R(e,t){return t=~t,e?e=1+~e:t+=1,P(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function O(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function _(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const D=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("int64 invalid: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<i)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>o(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>o(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),E(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),E(e)),dec:(e,t)=>function(e,t){let n=P(e,t);const i=2147483648&n.hi;i&&(n=R(n.lo,n.hi));const s=w(n.lo,n.hi);return i?"-"+s:s}(e,t),uDec:(e,t)=>w(e,t)}}();var M,x,A;function N(e,t,n){if(t===n)return!0;if(e==M.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return t==n}return!1}function L(e,t){switch(e){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return 0==t?D.zero:"0";case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}function U(e,t){switch(e){case M.BOOL:return!1===t;case M.STRING:return""===t;case M.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(M||(M={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(x||(x={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(A||(A={}));class j{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].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(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),O(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),O(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=D.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=D.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=D.enc(e);return C(t.lo,t.hi,this.buf),this}sint64(e){let t=D.enc(e),n=t.hi>>31;return C(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=D.uEnc(e);return C(t.lo,t.hi,this.buf),this}}class F{constructor(e,t){this.varint64=T,this.uint32=_,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=7&e;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 A.Varint:for(;128&this.buf[this.pos++];);break;case A.Bit64:this.pos+=4;case A.Bit32:this.pos+=4;break;case A.LengthDelimited:let n=this.uint32();this.pos+=n;break;case A.StartGroup:for(;;){const[e,n]=this.tag();if(n===A.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}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 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return D.dec(...this.varint64())}uint64(){return D.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,D.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return D.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return D.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 B(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return L(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let V="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),q=[];for(let e=0;e<V.length;e++)q[V[e].charCodeAt(0)]=e;q["-".charCodeAt(0)]=V.indexOf("+"),q["_".charCodeAt(0)]=V.indexOf("/");const K={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,i=new Uint8Array(t),s=0,o=0,r=0;for(let t=0;t<e.length;t++){if(n=q[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:r=n,o=1;break;case 1:i[s++]=r<<2|(48&n)>>4,r=n,o=2;break;case 2:i[s++]=(15&r)<<4|(60&n)>>2,r=n,o=3;break;case 3:i[s++]=(3&r)<<6|n,o=0}}if(1==o)throw Error("invalid base64 string.");return i.subarray(0,s)},enc(e){let t,n="",i=0,s=0;for(let o=0;o<e.length;o++)switch(t=e[o],i){case 0:n+=V[t>>2],s=(3&t)<<4,i=1;break;case 1:n+=V[s|t>>4],s=(15&t)<<2,i=2;break;case 2:n+=V[s|t>>6],n+=V[63&t],i=0}return i&&(n+=V[s],n+="=",1==i&&(n+="=")),n}};function W(e,t,n){J(t,e);const i=t.runtime.bin.makeReadOptions(n),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[o,r]=B(t);for(const e of s)t.runtime.bin.readField(o,i.readerFactory(e.data),t.field,e.wireType,i);return r()}function H(e,t,n,i){J(t,e);const s=t.runtime.bin.makeReadOptions(i),o=t.runtime.bin.makeWriteOptions(i);if(G(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const r=o.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,n,r,o);const c=s.readerFactory(r.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),i=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function G(e,t){const n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function J(e,t){o(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function z(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!U(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function Q(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?L(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(b.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function X(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}M.DOUBLE,M.FLOAT,M.INT64,M.UINT64,M.INT32,M.UINT32,M.BOOL,M.STRING,M.BYTES;const Z={ignoreUnknownFields:!1},$={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ee(e){return e?Object.assign(Object.assign({},Z),e):Z}function te(e){return e?Object.assign(Object.assign({},$),e):$}const ne=Symbol(),ie=Symbol();function se(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function oe(e,t,n,i,s){let r=n.localName;if(n.repeated){if(o("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(e)));switch(n.kind){case"message":a.push(n.T.fromJson(e,i));break;case"enum":const t=ce(n.T,e,i.ignoreUnknownFields,!0);t!==ie&&a.push(t);break;case"scalar":try{a.push(ae(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(t)));const o=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: map value null"));let a;try{a=re(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":o[a]=n.V.T.fromJson(r,i);break;case"enum":const e=ce(n.V.T,r,i.ignoreUnknownFields,!0);e!==ie&&(o[a]=e);break;case"scalar":try{o[a]=ae(n.V.T,r,x.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:r},r="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[r];Y(a)?a.fromJson(t,i):(e[r]=a=o.fromJson(t,i),o.fieldWrapper&&!n.oneof&&(e[r]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=ce(n.T,t,i.ignoreUnknownFields,!1);switch(c){case ne:Q(n,e);break;case ie:break;default:e[r]=c}break;case"scalar":try{const i=ae(n.T,t,n.L,!1);if(i===ne)Q(n,e);else e[r]=i}catch(e){let i="cannot decode field ".concat(s.typeName,".").concat(n.name," from JSON: ").concat(se(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function re(e,t){if(e===M.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ae(e,t,x.BIGINT,!0).toString()}function ae(e,t,n,i){if(null===t)return i?L(e,n):ne;switch(e){case M.DOUBLE:case M.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const i=Number(t);if(Number.isNaN(i))break;if(!Number.isFinite(i))break;return e==M.FLOAT&&p(i),i;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==M.UINT32||e==M.FIXED32?h(s):u(s),s;case M.INT64:case M.SFIXED64:case M.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=D.parse(t);return n?o.toString():o;case M.FIXED64:case M.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=D.uParse(t);return n?r.toString():r;case M.BOOL:if("boolean"!=typeof t)break;return t;case M.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case M.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return K.dec(t)}throw new Error}function ce(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:ne;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(void 0!==i)return i.no;if(n)return ie}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(se(t)))}function de(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function le(e,t,n){if("map"==e.kind){o("object"==typeof t&&null!=t);const i={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of s)i[t.toString()]=he(e.V.T,n);break;case"message":for(const[e,t]of s)i[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,o]of s)i[e.toString()]=ue(t,o,n.enumAsInteger)}return n.emitDefaultValues||s.length>0?i:void 0}if(e.repeated){o(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(he(e.T,t[n]));break;case"enum":for(let s=0;s<t.length;s++)i.push(ue(e.T,t[s],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)i.push(t[e].toJson(n))}return n.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return he(e.T,t);case"enum":return ue(e.T,t,n.enumAsInteger);case"message":return X(e.T,t).toJson(n)}}function ue(e,t,n){var i;if(o("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const s=e.findNumber(t);return null!==(i=null==s?void 0:s.name)&&void 0!==i?i:t}function he(e,t){switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:case M.FIXED32:case M.UINT32:return o("number"==typeof t),t;case M.FLOAT:case M.DOUBLE:return o("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case M.STRING:return o("string"==typeof t),t;case M.BOOL:return o("boolean"==typeof t),t;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return o("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case M.BYTES:return o(t instanceof Uint8Array),K.enc(t)}}const pe=Symbol("@bufbuild/protobuf/unknown-fields"),me={readUnknownFields:!0,readerFactory:e=>new F(e)},ge={writeUnknownFields:!0,writerFactory:()=>new j};function ve(e){return e?Object.assign(Object.assign({},me),e):me}function fe(e){return e?Object.assign(Object.assign({},ge),e):ge}function ke(e,t,n,i,s){let{repeated:o,localName:r}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=r&&delete e.value,e.case=r,r="value"),n.kind){case"scalar":case"enum":const a="enum"==n.kind?M.INT32:n.T;let c=Te;if("scalar"==n.kind&&n.L>0&&(c=be),o){let n=e[r];if(i==A.LengthDelimited&&a!=M.STRING&&a!=M.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,a))}else n.push(c(t,a))}else e[r]=c(t,a);break;case"message":const d=n.T;o?e[r].push(ye(t,new d,s,n)):Y(e[r])?ye(t,e[r],s,n):(e[r]=ye(t,new d,s,n),!d.fieldWrapper||n.oneof||n.repeated||(e[r]=d.fieldWrapper.unwrapField(e[r])));break;case"map":let[l,u]=function(e,t,n){const i=t.uint32(),s=t.pos+i;let o,r;for(;t.pos<s;){const[i]=t.tag();switch(i){case 1:o=Te(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=Te(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=ye(t,new e.V.T,n,void 0)}}}void 0===o&&(o=L(e.K,x.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===r)switch(e.V.kind){case"scalar":r=L(e.V.T,x.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[o,r]}(n,t,s);e[r][l]=u}}function ye(e,t,n,i){const s=t.getType().runtime.bin,o=null==i?void 0:i.delimited;return s.readMessage(t,e,o?i.no:e.uint32(),n,o),t}function be(e,t){const n=Te(e,t);return"bigint"==typeof n?n.toString():n}function Te(e,t){switch(t){case M.STRING:return e.string();case M.BOOL:return e.bool();case M.DOUBLE:return e.double();case M.FLOAT:return e.float();case M.INT32:return e.int32();case M.INT64:return e.int64();case M.UINT64:return e.uint64();case M.FIXED64:return e.fixed64();case M.BYTES:return e.bytes();case M.FIXED32:return e.fixed32();case M.SFIXED32:return e.sfixed32();case M.SFIXED64:return e.sfixed64();case M.SINT64:return e.sint64();case M.UINT32:return e.uint32();case M.SINT32:return e.sint32()}}function Ce(e,t,n,i){o(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?M.INT32:e.T;if(s)if(o(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,A.LengthDelimited).fork();let[,s]=Pe(t);for(let t=0;t<i.length;t++)e[s](i[t]);e.join()}(n,r,e.no,t);else for(const i of t)we(n,r,e.no,i);else we(n,r,e.no,t);break;case"message":if(s){o(Array.isArray(t));for(const s of t)Ee(n,i,e,s)}else Ee(n,i,e,t);break;case"map":o("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))Se(n,i,e,s,o)}}function Se(e,t,n,i,s){e.tag(n.no,A.LengthDelimited),e.fork();let r=i;switch(n.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:r=Number.parseInt(i);break;case M.BOOL:o("true"==i||"false"==i),r="true"==i}switch(we(e,n.K,1,r),n.V.kind){case"scalar":we(e,n.V.T,2,s);break;case"enum":we(e,M.INT32,2,s);break;case"message":o(void 0!==s),e.tag(2,A.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Ee(e,t,n,i){const s=X(n.T,i);n.delimited?e.tag(n.no,A.StartGroup).raw(s.toBinary(t)).tag(n.no,A.EndGroup):e.tag(n.no,A.LengthDelimited).bytes(s.toBinary(t))}function we(e,t,n,i){o(void 0!==i);let[s,r]=Pe(t);e.tag(n,s)[r](i)}function Pe(e){let t=A.Varint;switch(e){case M.BYTES:case M.STRING:t=A.LengthDelimited;break;case M.DOUBLE:case M.FIXED64:case M.SFIXED64:t=A.Bit64;break;case M.FIXED32:case M.SFIXED32:case M.FLOAT:t=A.Bit32}return[t,M[e].toLowerCase()]}function Re(e){if(void 0===e)return e;if(Y(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ie(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Oe{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function _e(e,t){const n=Me(e);return t?n:Ue(Le(n))}const De=Me;function Me(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let s=e.charAt(i);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),n.push(s)}}return n.join("")}const xe=new Set(["constructor","toString","toJSON","valueOf"]),Ae=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ne=e=>"".concat(e,"$"),Le=e=>Ae.has(e)?Ne(e):e,Ue=e=>xe.has(e)?Ne(e):e;class je{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=_e(e,!1)}addField(e){o(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const Fe=(Be=e=>new Oe(e,(e=>function(e,t){var n,i,s,o,r,a;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=_e(t.name,void 0!==t.oneof),e.jsonName=null!==(n=t.jsonName)&&void 0!==n?n:De(t.name),e.repeated=null!==(i=t.repeated)&&void 0!==i&&i,"scalar"==t.kind&&(e.L=null!==(s=t.L)&&void 0!==s?s:x.BIGINT),e.delimited=null!==(o=t.delimited)&&void 0!==o&&o,e.req=null!==(r=t.req)&&void 0!==r&&r,e.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=M.BYTES&&t.T!=M.STRING),void 0!==t.oneof){const n="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==n||(d=new je(n)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),Ve=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=L(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ee,makeWriteOptions:te,readMessage(e,t,n,i){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(se(t)));i=null!=i?i:new e;const s=new Map,o=n.typeRegistry;for(const[r,a]of Object.entries(t)){const t=e.fields.findJsonName(r);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const n=s.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(r,'"'));s.set(t.oneof,r)}oe(i,a,t,n,e)}else{let t=!1;if((null==o?void 0:o.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const s=o.findExtension(r.substring(1,r.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,o]=B(s);oe(e,a,s.field,n,s),H(i,s,o(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let s;try{for(s of n.fields.byNumber()){if(!z(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!de(s))continue}const n=le(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==n&&(i[t.useProtoFieldName?s.name:s.jsonName]=n)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const s of n.runtime.bin.listUnknownFields(e)){const r=o.findExtensionFor(n.typeName,s.no);if(r&&G(e,r)){const n=W(e,r,t),s=le(r.field,n,t);void 0!==s&&(i[r.field.jsonName]=s)}}}catch(e){const t=s?"cannot encode field ".concat(n.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>ae(e,t,null!=n?n:x.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||U(e,t)?he(e,t):void 0},debug:se},bin:{makeReadOptions:ve,makeWriteOptions:fe,listUnknownFields(e){var t;return null!==(t=e[pe])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[pe]},writeUnknownFields(e,t){const n=e[pe];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const s=e;Array.isArray(s[pe])||(s[pe]=[]),s[pe].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,s){const o=e.getType(),r=s?t.len:t.pos+n;let a,c;for(;t.pos<r&&([a,c]=t.tag(),!0!==s||c!=A.EndGroup);){const n=o.fields.find(a);if(n)ke(e,t,n,c,i);else{const n=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,n)}}if(s&&(c!=A.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:ke,writeMessage(e,t,n){const i=e.getType();for(const s of i.fields.byNumber())if(z(s,e))Ce(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,n);else if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){void 0!==t&&Ce(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:v,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,s=t,o=e;if(null!=o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let r=o[n].value;t&&"message"==t.kind&&!Y(r,t.T)?r=new t.T(r):t&&"scalar"===t.kind&&t.T===M.BYTES&&(r=Ie(r)),s[n]={case:e,value:r};break;case"scalar":case"enum":let a=o[n];i.T===M.BYTES&&(a=i.repeated?a.map(Ie):Ie(a)),s[n]=a;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===M.BYTES)for(const[e,t]of Object.entries(o[n]))s[n][e]=Ie(t);else Object.assign(s[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let i=o[n][t];e.fieldWrapper||(i=new e(i)),s[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)s[n]=o[n].map((e=>Y(e,c)?e:new c(e)));else{const e=o[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[n]=Ie(e):s[n]=e:s[n]=Y(e,c)?e:new c(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],s=n[e.localName];if(e.repeated){if(i.length!==s.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,s[n])));case"scalar":return i.every(((t,n)=>N(e.T,t,s[n])));case"enum":return i.every(((e,t)=>N(M.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=i,n=s;return e.T.fieldWrapper&&(void 0===t||Y(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||Y(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return N(M.INT32,i,s);case"scalar":return N(e.T,i,s);case"oneof":if(i.case!==s.case)return!1;const o=e.findField(i.case);if(void 0===o)return!0;switch(o.kind){case"message":return o.T.equals(i.value,s.value);case"enum":return N(M.INT32,i.value,s.value);case"scalar":return N(o.T,i.value,s.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const r=Object.keys(i).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return r.every((e=>t.equals(i[e],s[e])));case"enum":return r.every((e=>N(M.INT32,i[e],s[e])));case"scalar":const n=e.V.T;return r.every((e=>N(n,i[e],s[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let s;if(n.repeated)s=t.map(Re);else if("map"==n.kind){s=i[n.localName];for(const[e,n]of Object.entries(t))s[e]=Re(n)}else s="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Re(t.value)}:{case:void 0}:Re(t);i[n.localName]=s}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:Be,initFields:Ve}),makeMessageType(e,t,n){return function(e,t,n,i){var s;const o=null!==(s=null==i?void 0:i.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),r={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(r.prototype,new b),Object.assign(r,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new r).fromBinary(e,t),fromJson:(e,t)=>(new r).fromJson(e,t),fromJsonString:(e,t)=>(new r).fromJsonString(e,t),equals:(t,n)=>e.util.equals(r,t,n)}),r}(this,e,t,n)},makeEnum:k,makeEnumType:f,getEnumType:g,makeExtension(e,t,n){return function(e,t,n,i){let s;return{typeName:t,extendee:n,get field(){if(!s){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),s=e.util.newFieldList([n]).list()[0]}return s},runtime:e}}(this,e,t,n)}});var Be,Ve;class qe extends b{constructor(e){super(),this.seconds=D.zero,this.nanos=0,Fe.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Fe.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 i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>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=D.parse(i/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let n="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);n="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return qe.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new qe({seconds:D.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new qe).fromBinary(e,t)}static fromJson(e,t){return(new qe).fromJson(e,t)}static fromJsonString(e,t){return(new qe).fromJsonString(e,t)}static equals(e,t){return Fe.util.equals(qe,e,t)}}qe.runtime=Fe,qe.typeName="google.protobuf.Timestamp",qe.fields=Fe.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const Ke=Fe.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:qe},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:We,repeated:!0},{no:5,name:"events",kind:"message",T:Ge,repeated:!0}])),We=Fe.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:He,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),He=Fe.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:qe},{no:3,name:"value",kind:"scalar",T:2}])),Ge=Fe.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:qe},{no:7,name:"normalized_end_timestamp",kind:"message",T:qe,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Je=Fe.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),ze=Fe.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),Qe=Fe.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Ye=Fe.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Xe=Fe.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Ze=Fe.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"}]),$e=Fe.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),et=Fe.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),tt=Fe.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),nt=Fe.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"}]),it=Fe.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"}]),st=Fe.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ot=Fe.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"}]),rt=Fe.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:at,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:Vt}])),at=Fe.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),ct=Fe.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:Fe.getEnumType(Ze),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}])),dt=Fe.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:Fe.getEnumType(lt)},{no:4,name:"tracks",kind:"message",T:gt,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:ct},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Fe.getEnumType(ut)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Fe.getEnumType(nt)},{no:18,name:"kind_details",kind:"enum",T:Fe.getEnumType(ht),repeated:!0}])),lt=Fe.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ut=Fe.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),ht=Fe.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),pt=Fe.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),mt=Fe.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:vt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Fe.getEnumType(ft)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),gt=Fe.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Fe.getEnumType(Xe)},{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:Fe.getEnumType(Ze)},{no:10,name:"layers",kind:"message",T:vt,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:mt,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:Fe.getEnumType(pt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Vt},{no:19,name:"audio_features",kind:"enum",T:Fe.getEnumType(ot),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Fe.getEnumType(Ye)}])),vt=Fe.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Fe.getEnumType($e)},{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}])),ft=Fe.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"}]),kt=Fe.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Fe.getEnumType(yt)},{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:Et,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Ct,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:wt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Pt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Ke,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:It,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ot,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:_t,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Dt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ht,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Gt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Jt,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:bt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),yt=Fe.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),bt=Fe.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Fe.getEnumType(pt)},{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}])),Tt=Fe.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Et,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:It,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Ot,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:_t,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Dt,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Ht,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Gt,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Jt,oneof:"value"}])),Ct=Fe.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:St,repeated:!0}])),St=Fe.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}])),Et=Fe.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}])),wt=Fe.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Pt=Fe.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:Rt,repeated:!0}])),Rt=Fe.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}])),It=Fe.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}])),Ot=Fe.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}])),_t=Fe.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Dt=Fe.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:Mt,oneof:"value"}])),Mt=Fe.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}])),xt=Fe.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),At=Fe.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Fe.getEnumType(Nt)},{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}])),Nt=Fe.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Lt=Fe.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Fe.getEnumType(Ut)},{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}])),Ut=Fe.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"}]),jt=Fe.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ft},{no:2,name:"screen",kind:"message",T:Ft},{no:3,name:"resume_connection",kind:"enum",T:Fe.getEnumType(tt)},{no:4,name:"disabled_codecs",kind:"message",T:Bt},{no:5,name:"force_relay",kind:"enum",T:Fe.getEnumType(tt)}])),Ft=Fe.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Fe.getEnumType(tt)}])),Bt=Fe.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:at,repeated:!0},{no:2,name:"publish",kind:"message",T:at,repeated:!0}])),Vt=Fe.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),qt=Fe.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Kt=Fe.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Fe.getEnumType(qt)},{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"}),Wt=Fe.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Ht=Fe.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:Fe.getEnumType(pt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Kt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Wt,oneof:"content_header"}]),{localName:"DataStream_Header"}),Gt=Fe.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"}),Jt=Fe.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"}),zt=Fe.makeMessageType("livekit.WebhookConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9}])),Qt=Fe.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Yt=Fe.makeMessageType("livekit.RoomAgentDispatch",(()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}])),Xt=Fe.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),Zt=Fe.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),$t=Fe.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),en=Fe.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),tn=Fe.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"}]),nn=Fe.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),sn=Fe.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),on=Fe.makeMessageType("livekit.RoomCompositeEgressRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:Fe.getEnumType(nn)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:rn,oneof:"output"},{no:7,name:"stream",kind:"message",T:mn,oneof:"output"},{no:10,name:"segments",kind:"message",T:an,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Fe.getEnumType(sn),oneof:"options"},{no:9,name:"advanced",kind:"message",T:gn,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:rn,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:mn,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:an,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:cn,repeated:!0},{no:16,name:"webhooks",kind:"message",T:zt,repeated:!0}])),rn=Fe.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Fe.getEnumType(Xt)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:dn,oneof:"output"},{no:4,name:"gcp",kind:"message",T:ln,oneof:"output"},{no:5,name:"azure",kind:"message",T:un,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:hn,oneof:"output"}])),an=Fe.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Fe.getEnumType(Zt)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:Fe.getEnumType($t)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:dn,oneof:"output"},{no:6,name:"gcp",kind:"message",T:ln,oneof:"output"},{no:7,name:"azure",kind:"message",T:un,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:hn,oneof:"output"}])),cn=Fe.makeMessageType("livekit.ImageOutput",(()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:Fe.getEnumType(en)},{no:6,name:"image_codec",kind:"enum",T:Fe.getEnumType(Qe)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:dn,oneof:"output"},{no:9,name:"gcp",kind:"message",T:ln,oneof:"output"},{no:10,name:"azure",kind:"message",T:un,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:hn,oneof:"output"}])),dn=Fe.makeMessageType("livekit.S3Upload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:pn}])),ln=Fe.makeMessageType("livekit.GCPUpload",(()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:pn}])),un=Fe.makeMessageType("livekit.AzureBlobUpload",(()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}])),hn=Fe.makeMessageType("livekit.AliOSSUpload",(()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}])),pn=Fe.makeMessageType("livekit.ProxyConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}])),mn=Fe.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Fe.getEnumType(tn)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),gn=Fe.makeMessageType("livekit.EncodingOptions",(()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:Fe.getEnumType(Je)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:Fe.getEnumType(ze)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}])),vn=Fe.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Fe.getEnumType(sn),oneof:"options"},{no:2,name:"advanced",kind:"message",T:gn,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:rn,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:an,repeated:!0}])),fn=Fe.makeMessageType("livekit.AutoTrackEgress",(()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:dn,oneof:"output"},{no:3,name:"gcp",kind:"message",T:ln,oneof:"output"},{no:4,name:"azure",kind:"message",T:un,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:hn,oneof:"output"}])),kn=Fe.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:on},{no:3,name:"participant",kind:"message",T:vn},{no:2,name:"tracks",kind:"message",T:fn}])),yn=Fe.makeMessageType("livekit.RoomConfiguration",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:kn},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:Yt,repeated:!0}])),bn=Fe.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Tn=Fe.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Cn=Fe.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Sn=Fe.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:xn,oneof:"message"},{no:2,name:"answer",kind:"message",T:xn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Rn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Pn,oneof:"message"},{no:5,name:"mute",kind:"message",T:In,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Nn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ln,oneof:"message"},{no:8,name:"leave",kind:"message",T:Fn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Vn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ti,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:si,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ai,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:qn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:ci,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Un,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:jn,oneof:"message"}])),En=Fe.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:On,oneof:"message"},{no:2,name:"answer",kind:"message",T:xn,oneof:"message"},{no:3,name:"offer",kind:"message",T:xn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Rn,oneof:"message"},{no:5,name:"update",kind:"message",T:An,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Dn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Fn,oneof:"message"},{no:9,name:"mute",kind:"message",T:In,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Wn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Hn,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Jn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Qn,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Zn,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ni,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Mn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:_n,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:di,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:hi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:pi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:gi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:ii,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:vi,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:$n,oneof:"message"}])),wn=Fe.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:vt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Fe.getEnumType(ft)}])),Pn=Fe.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:Fe.getEnumType(Xe)},{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:Fe.getEnumType(Ze)},{no:9,name:"layers",kind:"message",T:vt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:wn,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:Fe.getEnumType(pt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Fe.getEnumType(Ye)},{no:17,name:"audio_features",kind:"enum",T:Fe.getEnumType(ot),repeated:!0}])),Rn=Fe.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Fe.getEnumType(bn)},{no:3,name:"final",kind:"scalar",T:8}])),In=Fe.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),On=Fe.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:rt},{no:2,name:"participant",kind:"message",T:dt},{no:3,name:"other_participants",kind:"message",T:dt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Kn,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:jt},{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:At},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:at,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),_n=Fe.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Kn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:jt},{no:3,name:"server_info",kind:"message",T:At},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),Dn=Fe.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:gt}])),Mn=Fe.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),xn=Fe.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}])),An=Fe.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:dt,repeated:!0}])),Nn=Fe.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:xt,repeated:!0}])),Ln=Fe.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:Fe.getEnumType($e)},{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}])),Un=Fe.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Fe.getEnumType(ot),repeated:!0}])),jn=Fe.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}])),Fn=Fe.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Fe.getEnumType(nt)},{no:3,name:"action",kind:"enum",T:Fe.getEnumType(Bn)},{no:4,name:"regions",kind:"message",T:li}])),Bn=Fe.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Vn=Fe.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:vt,repeated:!0}])),qn=Fe.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}])),Kn=Fe.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}])),Wn=Fe.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:St,repeated:!0}])),Hn=Fe.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:rt}])),Gn=Fe.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Fe.getEnumType(et)},{no:3,name:"score",kind:"scalar",T:2}])),Jn=Fe.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Gn,repeated:!0}])),zn=Fe.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:Fe.getEnumType(Tn)}])),Qn=Fe.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:zn,repeated:!0}])),Yn=Fe.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Fe.getEnumType($e)},{no:2,name:"enabled",kind:"scalar",T:8}])),Xn=Fe.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Yn,repeated:!0}])),Zn=Fe.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Yn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Xn,repeated:!0}])),$n=Fe.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Qt,repeated:!0}])),ei=Fe.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}])),ti=Fe.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:ei,repeated:!0}])),ni=Fe.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}])),ii=Fe.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:rt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:dt},{no:4,name:"other_participants",kind:"message",T:dt,repeated:!0}])),si=Fe.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:xn},{no:2,name:"subscription",kind:"message",T:Nn},{no:3,name:"publish_tracks",kind:"message",T:Dn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ri,repeated:!0},{no:5,name:"offer",kind:"message",T:xn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:oi,repeated:!0}])),oi=Fe.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),ri=Fe.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:Fe.getEnumType(bn)}])),ai=Fe.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:Fe.getEnumType(Cn),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"}])),ci=Fe.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),di=Fe.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),li=Fe.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:ui,repeated:!0}])),ui=Fe.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}])),hi=Fe.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Fe.getEnumType(st)}])),pi=Fe.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Fe.getEnumType(mi)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Rn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Pn,oneof:"request"},{no:6,name:"mute",kind:"message",T:In,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:qn,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Un,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:jn,oneof:"request"}])),mi=Fe.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"}]),gi=Fe.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),vi=Fe.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),fi=Fe.makeMessageType("livekit.TokenSourceRequest",(()=>[{no:1,name:"room_name",kind:"scalar",T:9,opt:!0},{no:2,name:"participant_name",kind:"scalar",T:9,opt:!0},{no:3,name:"participant_identity",kind:"scalar",T:9,opt:!0},{no:4,name:"participant_metadata",kind:"scalar",T:9,opt:!0},{no:5,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:6,name:"room_config",kind:"message",T:yn,opt:!0}])),ki=Fe.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));function yi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var bi,Ti={exports:{}},Ci=Ti.exports;var Si,Ei,wi=(bi||(bi=1,function(e){var t,n;t=Ci,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function r(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),s=0;s<i.length;s++){var o=i[s];this[o]=s<n?e:this.methodFactory(o,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(i,s,o){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?a:void 0!==console[i]?r(console,i):void 0!==console.log?r(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var r,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),s=n.indexOf(i+"=");-1!==s&&(e=/^([^;]+)/.exec(n.slice(s+i.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=n||l,u.getLevel=function(){return null!=d?d:null!=a?a:r},u.setLevel=function(e,n){return d=m(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(o!==u&&(r=m(o.getLevel())),c.call(u),o===u)for(var e in s)s[e].rebuild()},r=m(o?o.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(o=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,o.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=h),o},o.getLoggers=function(){return s},o.default=o,o},e.exports?e.exports=n():t.log=n()}(Ti)),Ti.exports);e.LogLevel=void 0,(Si=e.LogLevel||(e.LogLevel={}))[Si.trace=0]="trace",Si[Si.debug=1]="debug",Si[Si.info=2]="info",Si[Si.warn=3]="warn",Si[Si.error=4]="error",Si[Si.silent=5]="silent",e.LoggerNames=void 0,(Ei=e.LoggerNames||(e.LoggerNames={})).Default="livekit",Ei.Room="livekit-room",Ei.TokenSource="livekit-token-source",Ei.Participant="livekit-participant",Ei.Track="livekit-track",Ei.Publication="livekit-track-publication",Ei.Engine="livekit-engine",Ei.Signal="livekit-signal",Ei.PCManager="livekit-pc-manager",Ei.PCTransport="livekit-pc-transport",Ei.E2EE="lk-e2ee";let Pi=wi.getLogger("livekit");const Ri=Object.values(e.LoggerNames).map((e=>wi.getLogger(e)));function Ii(e){const t=wi.getLogger(e);return t.setDefaultLevel(Pi.getLevel()),t}Pi.setDefaultLevel(e.LogLevel.info);const Oi=wi.getLogger("lk-e2ee"),_i=7e3,Di=[0,300,1200,2700,4800,_i,_i,_i,_i,_i];class Mi{constructor(e){this._retryDelays=void 0!==e?[...e]:Di}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function xi(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function Ai(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}function Ni(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Li(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Ni(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,s){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,s,(t=e[n](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var Ui,ji={exports:{}};var Fi=function(){if(Ui)return ji.exports;Ui=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}ji.exports=s,ji.exports.once=function(e,t){return new Promise((function(n,i){function s(n){e.removeListener(t,o),i(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),n([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,n)}(e,s,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var s,o,c,d;if(r(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),c=o[t]),void 0===c)c=o[t]=n,++e._eventsCount;else if("function"==typeof c?c=o[t]=i?[n,c]:[c,n]:i?c.unshift(n):c.push(n),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=d.bind(i);return s.listener=n,i.wrapFn=s,s}function u(e,t,n){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?n?[s.listener||s]:[s]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function m(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(o){i.once&&e.removeEventListener(t,s),n(o)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var s="error"===e,o=this._events;if(void 0!==o)s=s&&void 0===o.error;else if(!s)return!1;if(s){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,l=p(c,d);for(i=0;i<d;++i)n(l[i],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return r(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,i,s,o,a;if(r(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var s,o=Object.keys(n);for(i=0;i<o.length;++i)"removeListener"!==(s=o[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},ji.exports}();let Bi=!0,Vi=!0;function qi(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function Ki(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return s.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),s.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Wi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Bi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Hi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Vi=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Gi(){if("object"==typeof window){if(Bi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Ji(e,t){Vi&&console.warn(e+" is deprecated, please use "+t+" instead.")}function zi(e){return"[object Object]"===Object.prototype.toString.call(e)}function Qi(e){return zi(e)?Object.keys(e).reduce((function(t,n){const i=zi(e[n]),s=i?Qi(e[n]):e[n],o=i&&!Object.keys(s).length;return void 0===s||o?t:Object.assign(t,{[n]:s})}),{}):e}function Yi(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?Yi(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{Yi(e,e.get(t),n)}))})))}function Xi(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((n=>{n.type===i&&n.trackId===t.id&&Yi(e,n,s)}))})),s}const Zi=Gi;function $i(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const s=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[s("min",n)]=i.ideal,t.optional.push(e),e={},e[s("max",n)]=i.ideal,t.optional.push(e)):(e[s("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const r=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{let r=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!r&&n.length&&t.includes("back")&&(r=n[n.length-1]),r&&(e.video.deviceId=o.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=i(e.video),Zi("chrome: "+JSON.stringify(e)),s(e)}))}e.video=i(e.video)}return Zi("chrome: "+JSON.stringify(e)),s(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){s(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return s(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function es(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ts(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const s=new Event("track");s.track=n.track,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const s=new Event("track");s.track=n,s.receiver=i,s.transceiver={receiver:i},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Ki(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function ns(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let s=n.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function is(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Xi(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Ki(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Xi(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ss(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function os(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ss(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];n=n.replace(new RegExp(s.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[n.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],s=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),r.apply(this,arguments)):r.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function rs(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function as(e,t){Ki(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var cs=Object.freeze({__proto__:null,fixNegotiationNeeded:as,shimAddTrackRemoveTrack:os,shimAddTrackRemoveTrackWithNative:ss,shimGetSendersWithDtmf:ns,shimGetUserMedia:$i,shimMediaStream:es,shimOnTrack:ts,shimPeerConnection:rs,shimSenderReceiverGetStats:is});function ds(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Ji("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function ls(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function us(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,s,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(s,o)}}function hs(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ps(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Ki(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ms(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Ji("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function gs(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function vs(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function fs(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ks(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function ys(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var bs=Object.freeze({__proto__:null,shimAddTransceiver:vs,shimCreateAnswer:ys,shimCreateOffer:ks,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:fs,shimGetUserMedia:ds,shimOnTrack:ls,shimPeerConnection:us,shimRTCDataChannel:gs,shimReceiverGetStats:ps,shimRemoveStream:ms,shimSenderGetStats:hs});function Ts(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach((e=>{n.includes(e.track)&&this.removeTrack(e)}))})}}function Cs(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function Ss(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,s=t.setLocalDescription,o=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function Es(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(ws(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function ws(e){return e&&void 0!==e.video?Object.assign({},e,{video:Qi(e.video)}):e}function Ps(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];void 0===i.urls&&i.url?(Ji("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Rs(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Is(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Os(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var _s,Ds=Object.freeze({__proto__:null,shimAudioContext:Os,shimCallbacksAPI:Ss,shimConstraints:ws,shimCreateOfferLegacy:Is,shimGetUserMedia:Es,shimLocalStreamsAPI:Ts,shimRTCIceServerUrls:Ps,shimRemoteStreamsAPI:Cs,shimTrackEventTransceiver:Rs}),Ms={exports:{}};var xs=(_s||(_s=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],s=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let s=3;s<i.length;s++){const o=i[s],r=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(r){const i=t.parseRtpMap(r),s=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(i.parameters=s.length?t.parseFmtp(s[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let s=0;return n.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(i+="a=maxptime:"+s+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),s=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=r.length>0&&r[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),n.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=0===s.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(n=s[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let s;i.length>0&&(s=parseInt(i[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:s}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let s;const o=void 0!==n?n:2;return s=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+s+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"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]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(Ms)),Ms.exports),As=yi(xs),Ns=t({__proto__:null,default:As},[xs]);function Ls(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const n=new t(e),i=As.parseCandidate(e.candidate);for(const e in i)e in n||Object.defineProperty(n,e,{value:i[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Ki(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Us(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Ki(e,"icecandidate",(e=>{if(e.candidate){const t=As.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function js(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=As.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=As.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const s=As.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?i=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let s;s=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>s}),this._sctp=o}return n.apply(this,arguments)}}function Fs(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],s=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},Ki(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Bs(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function Vs(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function qs(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ks(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var Ws=Object.freeze({__proto__:null,removeExtmapAllowMixed:Vs,shimAddIceCandidateNullOrEmpty:qs,shimConnectionState:Bs,shimMaxMessageSize:js,shimParameterlessSetLocalDescription:Ks,shimRTCIceCandidate:Ls,shimRTCIceCandidateRelayProtocol:Us,shimSendThrowTypeError:Fs});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Gi,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(qi(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(qi(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(qi(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=qi(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),s={browserDetails:i,commonShim:Ws,extractVersion:qi,disableLog:Wi,disableWarnings:Hi,sdp:Ns};switch(i.browser){case"chrome":if(!cs||!rs||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=cs,qs(e,i),Ks(e),$i(e,i),es(e),rs(e,i),ts(e),os(e,i),ns(e),is(e),as(e,i),Ls(e),Us(e),Bs(e),js(e,i),Fs(e),Vs(e,i);break;case"firefox":if(!bs||!us||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=bs,qs(e,i),Ks(e),ds(e,i),us(e,i),ls(e),ms(e),hs(e),ps(e),gs(e),vs(e),fs(e),ks(e),ys(e),Ls(e),Bs(e),js(e,i),Fs(e);break;case"safari":if(!Ds||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=Ds,qs(e,i),Ks(e),Ps(e),Is(e),Ss(e),Ts(e),Cs(e),Rs(e),Es(e),Os(e),Ls(e),Us(e),js(e,i),Fs(e),Vs(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Hs="AES-GCM",Gs="lk_e2ee",Js={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};var zs,Qs;function Ys(){return Zs()||Xs()}function Xs(){return void 0!==window.RTCRtpScriptTransform}function Zs(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function $s(e){return Ai(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function eo(e){return Ai(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function to(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(zs=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",zs.RatchetRequest="ratchetRequest",zs.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Qs=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Qs.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";function no(e){var t,n,i,s,o;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"speaker"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"transcription"!==(null===(s=e.value)||void 0===s?void 0:s.case)&&"encryptedPacket"!==(null===(o=e.value)||void 0===o?void 0:o.case))return new Tt({value:e.value})}class io extends Fi.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t,n)=>{Pi.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Js),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const s={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),s),this.emit(e.KeyProviderEvent.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}class so extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var oo,ro,ao,co,lo,uo,ho,po;e.ConnectionErrorReason=void 0,(oo=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[oo.NotAllowed=0]="NotAllowed",oo[oo.ServerUnreachable=1]="ServerUnreachable",oo[oo.InternalError=2]="InternalError",oo[oo.Cancelled=3]="Cancelled",oo[oo.LeaveRequest=4]="LeaveRequest",oo[oo.Timeout=5]="Timeout";class mo extends so{constructor(t,n,i,s){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=s,this.reasonName=e.ConnectionErrorReason[n]}}class go extends so{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class vo extends so{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class fo extends so{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class ko extends so{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class yo extends so{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class bo extends so{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class To extends so{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:mi[t]}}e.DataStreamErrorReason=void 0,(ro=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[ro.AlreadyOpened=0]="AlreadyOpened",ro[ro.AbnormalEnd=1]="AbnormalEnd",ro[ro.DecodeFailed=2]="DecodeFailed",ro[ro.LengthExceeded=3]="LengthExceeded",ro[ro.Incomplete=4]="Incomplete",ro[ro.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",ro[ro.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class Co extends so{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}e.MediaDeviceFailure=void 0,(ao=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",ao.NotFound="NotFound",ao.DeviceInUse="DeviceInUse",ao.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={})),e.CryptorErrorReason=void 0,(co=e.CryptorErrorReason||(e.CryptorErrorReason={}))[co.InvalidKey=0]="InvalidKey",co[co.MissingKey=1]="MissingKey",co[co.InternalError=2]="InternalError";e.RoomEvent=void 0,(lo=e.RoomEvent||(e.RoomEvent={})).Connected="connected",lo.Reconnecting="reconnecting",lo.SignalReconnecting="signalReconnecting",lo.Reconnected="reconnected",lo.Disconnected="disconnected",lo.ConnectionStateChanged="connectionStateChanged",lo.Moved="moved",lo.MediaDevicesChanged="mediaDevicesChanged",lo.ParticipantConnected="participantConnected",lo.ParticipantDisconnected="participantDisconnected",lo.TrackPublished="trackPublished",lo.TrackSubscribed="trackSubscribed",lo.TrackSubscriptionFailed="trackSubscriptionFailed",lo.TrackUnpublished="trackUnpublished",lo.TrackUnsubscribed="trackUnsubscribed",lo.TrackMuted="trackMuted",lo.TrackUnmuted="trackUnmuted",lo.LocalTrackPublished="localTrackPublished",lo.LocalTrackUnpublished="localTrackUnpublished",lo.LocalAudioSilenceDetected="localAudioSilenceDetected",lo.ActiveSpeakersChanged="activeSpeakersChanged",lo.ParticipantMetadataChanged="participantMetadataChanged",lo.ParticipantNameChanged="participantNameChanged",lo.ParticipantAttributesChanged="participantAttributesChanged",lo.ParticipantActive="participantActive",lo.RoomMetadataChanged="roomMetadataChanged",lo.DataReceived="dataReceived",lo.SipDTMFReceived="sipDTMFReceived",lo.TranscriptionReceived="transcriptionReceived",lo.ConnectionQualityChanged="connectionQualityChanged",lo.TrackStreamStateChanged="trackStreamStateChanged",lo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",lo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",lo.AudioPlaybackStatusChanged="audioPlaybackChanged",lo.VideoPlaybackStatusChanged="videoPlaybackChanged",lo.MediaDevicesError="mediaDevicesError",lo.ParticipantPermissionsChanged="participantPermissionsChanged",lo.SignalConnected="signalConnected",lo.RecordingStatusChanged="recordingStatusChanged",lo.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",lo.EncryptionError="encryptionError",lo.DCBufferStatusChanged="dcBufferStatusChanged",lo.ActiveDeviceChanged="activeDeviceChanged",lo.ChatMessage="chatMessage",lo.LocalTrackSubscribed="localTrackSubscribed",lo.MetricsReceived="metricsReceived",e.ParticipantEvent=void 0,(uo=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",uo.TrackSubscribed="trackSubscribed",uo.TrackSubscriptionFailed="trackSubscriptionFailed",uo.TrackUnpublished="trackUnpublished",uo.TrackUnsubscribed="trackUnsubscribed",uo.TrackMuted="trackMuted",uo.TrackUnmuted="trackUnmuted",uo.LocalTrackPublished="localTrackPublished",uo.LocalTrackUnpublished="localTrackUnpublished",uo.LocalTrackCpuConstrained="localTrackCpuConstrained",uo.LocalSenderCreated="localSenderCreated",uo.ParticipantMetadataChanged="participantMetadataChanged",uo.ParticipantNameChanged="participantNameChanged",uo.DataReceived="dataReceived",uo.SipDTMFReceived="sipDTMFReceived",uo.TranscriptionReceived="transcriptionReceived",uo.IsSpeakingChanged="isSpeakingChanged",uo.ConnectionQualityChanged="connectionQualityChanged",uo.TrackStreamStateChanged="trackStreamStateChanged",uo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",uo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",uo.TrackCpuConstrained="trackCpuConstrained",uo.MediaDevicesError="mediaDevicesError",uo.AudioStreamAcquired="audioStreamAcquired",uo.ParticipantPermissionsChanged="participantPermissionsChanged",uo.PCTrackAdded="pcTrackAdded",uo.AttributesChanged="attributesChanged",uo.LocalTrackSubscribed="localTrackSubscribed",uo.ChatMessage="chatMessage",uo.Active="active",e.EngineEvent=void 0,(ho=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",ho.Connected="connected",ho.Disconnected="disconnected",ho.Resuming="resuming",ho.Resumed="resumed",ho.Restarting="restarting",ho.Restarted="restarted",ho.SignalResumed="signalResumed",ho.SignalRestarted="signalRestarted",ho.Closing="closing",ho.MediaTrackAdded="mediaTrackAdded",ho.ActiveSpeakersUpdate="activeSpeakersUpdate",ho.DataPacketReceived="dataPacketReceived",ho.RTPVideoMapUpdate="rtpVideoMapUpdate",ho.DCBufferStatusChanged="dcBufferStatusChanged",ho.ParticipantUpdate="participantUpdate",ho.RoomUpdate="roomUpdate",ho.SpeakersChanged="speakersChanged",ho.StreamStateChanged="streamStateChanged",ho.ConnectionQualityUpdate="connectionQualityUpdate",ho.SubscriptionError="subscriptionError",ho.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",ho.RemoteMute="remoteMute",ho.SubscribedQualityUpdate="subscribedQualityUpdate",ho.LocalTrackUnpublished="localTrackUnpublished",ho.LocalTrackSubscribed="localTrackSubscribed",ho.Offline="offline",ho.SignalRequestResponse="signalRequestResponse",ho.SignalConnected="signalConnected",ho.RoomMoved="roomMoved",e.TrackEvent=void 0,(po=e.TrackEvent||(e.TrackEvent={})).Message="message",po.Muted="muted",po.Unmuted="unmuted",po.Restarted="restarted",po.Ended="ended",po.Subscribed="subscribed",po.Unsubscribed="unsubscribed",po.CpuConstrained="cpuConstrained",po.UpdateSettings="updateSettings",po.UpdateSubscription="updateSubscription",po.AudioPlaybackStarted="audioPlaybackStarted",po.AudioPlaybackFailed="audioPlaybackFailed",po.AudioSilenceDetected="audioSilenceDetected",po.VisibilityChanged="visibilityChanged",po.VideoDimensionsChanged="videoDimensionsChanged",po.VideoPlaybackStarted="videoPlaybackStarted",po.VideoPlaybackFailed="videoPlaybackFailed",po.ElementAttached="elementAttached",po.ElementDetached="elementDetached",po.UpstreamPaused="upstreamPaused",po.UpstreamResumed="upstreamResumed",po.SubscriptionPermissionChanged="subscriptionPermissionChanged",po.SubscriptionStatusChanged="subscriptionStatusChanged",po.SubscriptionFailed="subscriptionFailed",po.TrackProcessorUpdate="trackProcessorUpdate",po.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",po.TranscriptionReceived="transcriptionReceived",po.TimeSyncUpdate="timeSyncUpdate",po.PreConnectBufferFlushed="preConnectBufferFlushed";const So=/version\/(\d+(\.?_?\d+)+)/i;let Eo;function wo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===Eo||t){const e=Po.find((e=>{let{test:t}=e;return t.test(n)}));Eo=null==e?void 0:e.describe(n)}return Eo}const Po=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ro(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Io(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ro(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Io(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ro(So,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Io(e)})}];function Ro(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function Io(e){return e.includes("mac os")?Ro(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const Oo="2.15.8";class _o{}_o.setTimeout=function(){return setTimeout(...arguments)},_o.setInterval=function(){return setInterval(...arguments)},_o.clearTimeout=function(){return clearTimeout(...arguments)},_o.clearInterval=function(){return clearInterval(...arguments)};const Do=[];e.VideoQuality=void 0,function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(e.VideoQuality||(e.VideoQuality={}));class Mo extends Fi.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Mo.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Pi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=Ii(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=Mo.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),zr(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===Mo.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===Mo.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Do.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Do.splice(Do.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),xo(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),s=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(s?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(s?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?Pi.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Pi.warn("could not playback ".concat(s?"audio":"video"),n),s&&t&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===n.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Ao(this.mediaStreamTrack,t);const n=this.attachedElements.indexOf(t);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach((t=>{Ao(this.mediaStreamTrack,t),n.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],n}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ii(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Do.forEach((e=>{e.parentElement||(t=!1)})),t&&Do.push(e)}}handleAppVisibilityChanged(){return Ai(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Mo.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){or()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){or()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function xo(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks(),i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e)),tr()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(tr()||er())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Ao(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}!function(e){let t,n,i;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Xe.AUDIO;case t.Video:return Xe.VIDEO;default:return Xe.DATA}},e.kindFromProto=function(e){switch(e){case Xe.AUDIO:return t.Audio;case Xe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return Ze.CAMERA;case n.Microphone:return Ze.MICROPHONE;case n.ScreenShare:return Ze.SCREEN_SHARE;case n.ScreenShareAudio:return Ze.SCREEN_SHARE_AUDIO;default:return Ze.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Ze.CAMERA:return n.Camera;case Ze.MICROPHONE:return n.Microphone;case Ze.SCREEN_SHARE:return n.ScreenShare;case Ze.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Tn.ACTIVE:return i.Active;case Tn.PAUSED:return i.Paused;default:return i.Unknown}}}(Mo||(Mo={}));class No{constructor(e,t,n,i,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Lo=["opus","red"],Uo=["vp8","h264"],jo=["vp8","h264","vp9","av1","h265"];function Fo(e){return!!Uo.find((t=>t===e))}const Bo=Fo;var Vo;e.BackupCodecPolicy=void 0,function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(e.BackupCodecPolicy||(e.BackupCodecPolicy={})),e.AudioPresets=void 0,(Vo=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},Vo.speech={maxBitrate:24e3},Vo.music={maxBitrate:48e3},Vo.musicStereo={maxBitrate:64e3},Vo.musicHighQuality={maxBitrate:96e3},Vo.musicHighQualityStereo={maxBitrate:128e3};const qo={h90:new No(160,90,9e4,20),h180:new No(320,180,16e4,20),h216:new No(384,216,18e4,20),h360:new No(640,360,45e4,20),h540:new No(960,540,8e5,25),h720:new No(1280,720,17e5,30),h1080:new No(1920,1080,3e6,30),h1440:new No(2560,1440,5e6,30),h2160:new No(3840,2160,8e6,30)},Ko={h120:new No(160,120,7e4,20),h180:new No(240,180,125e3,20),h240:new No(320,240,14e4,20),h360:new No(480,360,33e4,20),h480:new No(640,480,5e5,20),h540:new No(720,540,6e5,25),h720:new No(960,720,13e5,30),h1080:new No(1440,1080,23e5,30),h1440:new No(1920,1440,38e5,30)},Wo={h360fps3:new No(640,360,2e5,3,"medium"),h360fps15:new No(640,360,4e5,15,"medium"),h720fps5:new No(1280,720,8e5,5,"medium"),h720fps15:new No(1280,720,15e5,15,"medium"),h720fps30:new No(1280,720,2e6,30,"medium"),h1080fps15:new No(1920,1080,25e5,15,"medium"),h1080fps30:new No(1920,1080,5e6,30,"medium"),original:new No(0,0,7e6,30,"medium")},Ho="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Go(e){return Ai(this,void 0,void 0,(function*(){return new Promise((t=>_o.setTimeout(t,e)))}))}function Jo(){return"addTransceiver"in RTCPeerConnection.prototype}function zo(){return"addTrack"in RTCPeerConnection.prototype}function Qo(){if(!("getCapabilities"in RTCRtpSender))return!1;if(tr()||er())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/av1"===n.mimeType.toLowerCase()){t=!0;break}return t}function Yo(){if(!("getCapabilities"in RTCRtpSender))return!1;if(er())return!1;if(tr()){const e=wo();if((null==e?void 0:e.version)&&ur(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&ur(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/vp9"===n.mimeType.toLowerCase()){t=!0;break}return t}function Xo(e){return"av1"===e||"vp9"===e}function Zo(e){return!(!document||nr())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function $o(){return"undefined"!=typeof RTCPeerConnection&&(Jo()||zo())}function er(){var e;return"Firefox"===(null===(e=wo())||void 0===e?void 0:e.name)}function tr(){var e;return"Safari"===(null===(e=wo())||void 0===e?void 0:e.name)}function nr(){const e=wo();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function ir(){const e=wo();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&ur(e.osVersion,"17")>=0}function sr(){var e,t;return!!or()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function or(){return"undefined"!=typeof document}function rr(){return"ReactNative"==navigator.product}function ar(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function cr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function dr(){if(!rr())return;let e=cr();return e?e.platform:void 0}function lr(){if(or())return window.devicePixelRatio;if(rr()){let e=cr();if(e)return e.devicePixelRatio}return 1}function ur(e,t){const n=e.split("."),i=t.split("."),s=Math.min(n.length,i.length);for(let e=0;e<s;++e){const t=parseInt(n[e],10),o=parseInt(i[e],10);if(t>o)return 1;if(t<o)return-1;if(e===s-1&&t===o)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function hr(e){for(const t of e)t.target.handleResize(t)}function pr(e){for(const t of e)t.target.handleVisibilityChanged(t)}let mr=null;const gr=()=>(mr||(mr=new ResizeObserver(hr)),mr);let vr=null;const fr=()=>(vr||(vr=new IntersectionObserver(pr,{root:null,rootMargin:"0px"})),vr);let kr,yr;function br(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const o=s.getContext("2d");null==o||o.fillRect(0,0,s.width,s.height),i&&o&&(o.beginPath(),o.arc(e/2,t/2,50,0,2*Math.PI,!0),o.closePath(),o.fillStyle="grey",o.fill());const r=s.captureStream(),[a]=r.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}function Tr(){if(!yr){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[yr]=i.stream.getAudioTracks(),!yr)throw Error("Could not get empty media stream audio track");yr.enabled=!1}return yr.clone()}class Cr{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>Ai(this,void 0,void 0,(function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function Sr(e){return jo.includes(e)}function Er(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function wr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Pr(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return nt.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return nt.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return nt.JOIN_FAILURE;default:return nt.UNKNOWN_REASON}}function Rr(e){return void 0!==e?Number(e):void 0}function Ir(e){return void 0!==e?BigInt(e):void 0}function Or(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function _r(e){return!!e&&e.kind==Mo.Kind.Audio}function Dr(e){return!!e&&e.kind==Mo.Kind.Video}function Mr(e){return Or(e)&&Dr(e)}function xr(e){return Or(e)&&_r(e)}function Ar(e){return!!e&&!e.isLocal}function Nr(e){return!!e&&!e.isLocal}function Lr(e){return Ar(e)&&Dr(e)}function Ur(e){return e.isLocal}function jr(e,t,n){var i,s,o,r;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=Qr(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==n?void 0:n.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(Fr(h.audio,t),null!==(i=(o=h.audio).deviceId)&&void 0!==i||(o.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(Fr(h.video,n),null!==(s=(r=h.video).deviceId)&&void 0!==s||(r.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function Fr(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Br(e){var t,n,i,s;const o={};if(e.video)if("object"==typeof e.video){const n={},s=n,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)Fr(s,r.resolution);else s[e]=r[e]})),o.video=n,null!==(t=(i=o.video).deviceId)&&void 0!==t||(i.deviceId={ideal:"default"})}else o.video=!!e.video&&{deviceId:{ideal:"default"}};else o.video=!1;return e.audio?"object"==typeof e.audio?(o.audio=e.audio,null!==(n=(s=o.audio).deviceId)&&void 0!==n||(s.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function Vr(e){return Ai(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=qr();if(n){const i=n.createAnalyser();i.fftSize=2048;const s=i.frequencyBinCount,o=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Go(t),i.getByteTimeDomainData(o);const r=o.some((e=>128!==e&&0!==e));return n.close(),!r}return!1}()}))}function qr(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const n=new t({latencyHint:"interactive"});if("suspended"===n.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Ai(this,void 0,void 0,(function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}}));n.addEventListener("statechange",(()=>{var t;"closed"===n.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))})),window.document.body.addEventListener("click",e)}return n}}function Kr(e){return"audioinput"===e?Mo.Source.Microphone:"videoinput"===e?Mo.Source.Camera:Mo.Source.Unknown}function Wr(e){return e===Mo.Source.Microphone?"audioinput":e===Mo.Source.Camera?"videoinput":void 0}function Hr(e){var t,n;let i=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i="boolean"==typeof i?{}:i,i=tr()?Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(n=e.audio)&&void 0!==n&&n,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function Gr(e){return e.split("/")[1].toLowerCase()}function Jr(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Dn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function zr(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?zr(e.track):{})}}function Qr(e){const t=Object.assign({},e);let n,i;return"object"==typeof t.audio&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(i=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?"object"==typeof s&&null!==s?structuredClone(Object.assign({},s)):structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}function Yr(e,t){return e.width*e.height<t.width*t.height}class Xr extends Fi.EventEmitter{constructor(t,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=t=>{var n,i;const{kind:s,data:o}=t.data;switch(s){case"error":Pi.error(o.error.message),this.emit(e.EncryptionEvent.EncryptionError,o.error);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==o.enabled&&o.participantIdentity===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(o.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":const t=this.decryptDataRequests.get(o.uuid);(null==t?void 0:t.resolve)&&t.resolve(o);break;case"encryptDataResponse":const s=this.encryptDataRequests.get(o.uuid);(null==s?void 0:s.resolve)&&s.resolve(o)}},this.onWorkerError=t=>{Pi.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=n}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Ys())throw new go("tried to setup end-to-end encryption on an unsupported browser");if(Pi.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:Oi.getLevel()}};this.worker&&(Pi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Pi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Pi.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==pt.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==pt.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const s={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(s)})).on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>Ai(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!Dr(e.track)||!nr())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:Gr(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)})),n.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return Ai(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}},i=new Cr;return i.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,i),this.worker.postMessage(n),i.promise}))}handleEncryptedData(e,t,n,i){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const s=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:n,keyIndex:i}},r=new Cr;return r.onFinally=()=>{this.decryptDataRequests.delete(s)},this.decryptDataRequests.set(s,r),this.worker.postMessage(o),r.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){let{key:t,participantIdentity:n,keyIndex:i}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(o)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const 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){if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Gr(n.mimeType):void 0)}}setupE2EESender(e,t){Or(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Pi.warn("early return because sender is not ready")}handleReceiver(e,t,n,i){return Ai(this,void 0,void 0,(function*(){if(this.worker){if(Xs()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Gs in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}};return void this.worker.postMessage(e)}let s=e.writableStream,o=e.readableStream;if(!s||!o){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,o=t.readable}const r={kind:"decode",data:{readableStream:o,writableStream:s,trackId:t,codec:i,participantIdentity:n,isReuse:Gs in e}};this.worker.postMessage(r,[o,s])}e[Gs]=!0}}))}handleSender(e,t,n){var i;if(!(Gs in e)&&this.worker){if(!(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Xs()){Pi.info("initialize script transform");const i={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{Pi.info("initialize encoded streams");const i=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(s,[i.readable,i.writable])}e[Gs]=!0}}}const Zr="default";class $r{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new $r),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Ai(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var i;if((null===(i=$r.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){Pi.debug("awaiting getUserMedia promise");try{e?yield $r.userMediaPromiseMap.get(e):yield Promise.all($r.userMediaPromiseMap.values())}catch(e){Pi.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(n&&(!tr()||!t.hasDeviceInUse(e))){if(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const n=""===t.label,i=!e||t.kind===e;return n&&i}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},n=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,n){return Ai(this,void 0,void 0,(function*(){if(t!==Zr)return t;const i=yield this.getDevices(e),s=i.find((e=>e.deviceId===Zr));if(!s)return void Pi.warn("could not reliably determine default device");const o=i.find((e=>e.deviceId!==Zr&&e.groupId===(null!=n?n:s.groupId)));if(o)return null==o?void 0:o.deviceId;Pi.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?$r.userMediaPromiseMap.has(e):$r.userMediaPromiseMap.size>0}}var ea;$r.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],$r.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(ea||(ea={}));class ta{constructor(){this.pendingTasks=new Map,this.taskMutex=new s,this.nextTaskIndex=0}run(e){return Ai(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ea.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ea.RUNNING,yield e()}finally{t.status=ea.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return Ai(this,void 0,void 0,(function*(){return this.run((()=>Ai(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function na(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const ia=["syncState","trickle","offer","answer","simulate","leave"];var sa;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(sa||(sa={}));class oa{get currentState(){return this.state}get isDisconnected(){return this.state===sa.DISCONNECTING||this.state===sa.DISCONNECTED}get isEstablishingConnection(){return this.state===sa.CONNECTING||this.state===sa.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=sa.DISCONNECTED,this.log=Pi,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Ii(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=t,this.requestQueue=new ta,this.queuedRequests=[],this.closingLock=new s,this.connectionLock=new s,this.state=sa.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return Ai(this,void 0,void 0,(function*(){this.state=sa.CONNECTING,this.options=n;return yield this.connect(e,t,n,i)}))}reconnect(e,t,n,i){return Ai(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=sa.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))}))}connect(t,n,i,s){this.connectOptions=i;const o=function(e,t,n){var i;const s=new URLSearchParams;s.set("access_token",e),n.reconnect&&(s.set("reconnect","1"),n.sid&&s.set("sid",n.sid));s.set("auto_subscribe",n.autoSubscribe?"1":"0"),s.set("sdk",rr()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel);t.os&&s.set("os",t.os);t.osVersion&&s.set("os_version",t.osVersion);t.browser&&s.set("browser",t.browser);t.browserVersion&&s.set("browser_version",t.browserVersion);n.adaptiveStream&&s.set("adaptive_stream","1");n.reconnectReason&&s.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&s.set("network",navigator.connection.type);return s}(n,function(){var e;const t=new Lt({sdk:Ut.JS,protocol:16,version:Oo});return rr()&&(t.os=null!==(e=dr())&&void 0!==e?e:""),t}(),i),r=function(e,t){const n=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{n.searchParams.set(t,e)})),na(n,"rtc")}(t,o),a=na(new URL(wr(r)),"validate");return new Promise(((t,n)=>Ai(this,void 0,void 0,(function*(){const o=yield this.connectionLock.lock();try{const o=()=>Ai(this,void 0,void 0,(function*(){this.close(),clearTimeout(c),n(new mo("room connection has been cancelled (signal)",e.ConnectionErrorReason.Cancelled))})),c=setTimeout((()=>{this.close(),n(new mo("room connection has timed out (signal)",e.ConnectionErrorReason.ServerUnreachable))}),i.websocketTimeout);(null==s?void 0:s.aborted)&&o(),null==s||s.addEventListener("abort",o);const d=new URL(r);d.searchParams.has("access_token")&&d.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(d),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(c)},this.ws.onerror=t=>Ai(this,void 0,void 0,(function*(){if(this.state===sa.CONNECTED)this.handleWSError(t);else{this.state=sa.DISCONNECTED,clearTimeout(c);try{const i=yield fetch(a);if(i.status.toFixed(0).startsWith("4")){const t=yield i.text();n(new mo(t,e.ConnectionErrorReason.NotAllowed,i.status))}else n(new mo("Encountered unknown websocket error during connection: ".concat(t.toString()),e.ConnectionErrorReason.InternalError,i.status))}catch(t){n(new mo(t instanceof Error?t.message:"server was not reachable",e.ConnectionErrorReason.ServerUnreachable))}}})),this.ws.onmessage=r=>Ai(this,void 0,void 0,(function*(){var a,c,d;let l;if("string"==typeof r.data){const e=JSON.parse(r.data);l=En.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);l=En.fromBinary(new Uint8Array(r.data))}if(this.state!==sa.CONNECTED){let r=!1;if("join"===(null===(a=l.message)||void 0===a?void 0:a.case)?(this.state=sa.CONNECTED,null==s||s.removeEventListener("abort",o),this.pingTimeoutDuration=l.message.value.pingTimeout,this.pingIntervalDuration=l.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),t(l.message.value)):this.state===sa.RECONNECTING&&"leave"!==l.message.case?(this.state=sa.CONNECTED,null==s||s.removeEventListener("abort",o),this.startPingInterval(),"reconnect"===(null===(c=l.message)||void 0===c?void 0:c.case)?t(l.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),t(void 0),r=!0)):this.isEstablishingConnection&&"leave"===l.message.case?n(new mo("Received leave request while trying to (re)connect",e.ConnectionErrorReason.LeaveRequest,void 0,l.message.value.reason)):i.reconnect||n(new mo("did not receive join response, got ".concat(null===(d=l.message)||void 0===d?void 0:d.case," instead"),e.ConnectionErrorReason.InternalError)),!r)return}this.signalLatency&&(yield Go(this.signalLatency)),this.handleSignalResponse(l)})),this.ws.onclose=t=>{this.isEstablishingConnection&&n(new mo("Websocket got closed during a (re)connection attempt",e.ConnectionErrorReason.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:t.reason,code:t.code,wasClean:t.wasClean,state:this.state})),this.handleOnClose(t.reason)}}finally{o()}}))))}close(){return Ai(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=sa.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,Go(250)])),e.ws=void 0}}finally{t&&(e.state=sa.DISCONNECTED),n()}}()}))}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:aa(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:aa(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Rn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new In({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Ai(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=n.getNextRequestId();return yield n.sendRequest({case:"updateMetadata",value:new qn({requestId:s,metadata:e,name:t,attributes:i})}),s}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Vn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ti({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:D.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new ci({timestamp:D.parse(Date.now()),rtt:D.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Un({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Fn({reason:nt.CLIENT_INITIATED,action:Bn.DISCONNECT})})}sendRequest(e){return Ai(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const i=!n&&!function(e){const t=ia.indexOf(e.case)>=0;return Pi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&t.state===sa.RECONNECTING)return void t.queuedRequests.push((()=>Ai(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Go(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new Sn({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===i.case){const e=ra(i.value);this.onAnswer&&this.onAnswer(e,i.value.id)}else if("offer"===i.case){const e=ra(i.value);this.onOffer&&this.onOffer(e,i.value.id)}else if("trickle"===i.case){const e=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(e,i.value.target)}else"update"===i.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=i.value.participants)&&void 0!==t?t:[]):"trackPublished"===i.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):"speakersChanged"===i.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(n=i.value.speakers)&&void 0!==n?n:[]):"leave"===i.case?this.onLeave&&this.onLeave(i.value):"mute"===i.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):"roomUpdate"===i.case?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):"connectionQuality"===i.case?this.onConnectionQuality&&this.onConnectionQuality(i.value):"streamStateUpdate"===i.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):"subscribedQualityUpdate"===i.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):"subscriptionPermissionUpdate"===i.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):"refreshToken"===i.case?this.onTokenRefresh&&this.onTokenRefresh(i.value):"trackUnpublished"===i.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):"subscriptionResponse"===i.case?this.onSubscriptionError&&this.onSubscriptionError(i.value):"pong"===i.case||("pongResp"===i.case?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===i.case?this.onRequestResponse&&this.onRequestResponse(i.value):"trackSubscribed"===i.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):"roomMoved"===i.case?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Ai(this,void 0,void 0,(function*(){if(this.state===sa.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=_o.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&_o.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=_o.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&_o.clearInterval(this.pingInterval)}}function ra(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function aa(e,t){return new xn({sdp:e.sdp,type:e.type,id:t})}class ca{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class da{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 i=n+this.ttl;return this._map.set(e,{value:t,expiresAt:i}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[i,s]of n.entries())t.push(e(s,i,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var la,ua,ha,pa,ma,ga={},va={},fa={exports:{}};function ka(){if(la)return fa.exports;la=1;var e=fa.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),fa.exports}function ya(){return ua||(ua=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var s=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:s&&!n[e.name]&&(n[e.name]={});var o=e.push?{}:s?n[e.name]:n;!function(e,n,i,s){if(s&&!i)n[s]=t(e[1]);else for(var o=0;o<i.length;o+=1)null!=e[o+1]&&(n[i[o]]=t(e[o+1]))}(i.match(e.reg),o,e.names,e.name),e.push&&n[e.push].push(o)},i=ka(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],r=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),r=o[o.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(s))return n(c,r,s)}})),t.media=o,t};var o=function(e,n){var i=n.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&n.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],i=e.split(" ").map(t),s=0;s<i.length;s+=3)n.push({component:i[s],ip:i[s+1],port:i[s+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,i=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),i=!0),{scid:n,paused:i}}))}))}}(va)),va}function ba(){if(pa)return ha;pa=1;var e=ka(),t=/%[sdv%]/g,n=function(e){var n=1,i=arguments,s=i.length;return e.replace(t,(function(e){if(n>=s)return e;var t=i[n];switch(n+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},i=function(e,t,i){var s=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var r=t.names[o];t.name?s.push(i[t.name][r]):s.push(i[t.names[o]])}else s.push(i[t.name]);return n.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return ha=function(t,n){n=n||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=n.outerOrder||s,a=n.innerOrder||o,c=[];return r.forEach((function(n){e[n].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(i(n,e,t))}))}))})),t.media.forEach((function(t){c.push(i("m",e.m[0],t)),a.forEach((function(n){e[n].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(i(n,e,t))}))}))}))})),c.join("\r\n")+"\r\n"},ha}var Ta=function(){if(ma)return ga;ma=1;var e=ya(),t=ba(),n=ka();return ga.grammar=n,ga.write=t,ga.parse=e.parse,ga.parseParams=e.parseParams,ga.parseFmtpConfig=e.parseFmtpConfig,ga.parsePayloads=e.parsePayloads,ga.parseRemoteCandidates=e.parseRemoteCandidates,ga.parseImageAttributes=e.parseImageAttributes,ga.parseSimulcastStreamList=e.parseSimulcastStreamList,ga}();function Ca(e,t,n){var i,s,o;void 0===t&&(t=50),void 0===n&&(n={});var r=null!=(i=n.isImmediate)&&i,a=null!=(s=n.callback)&&s,c=n.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),n=this;return new Promise((function(i,s){var c=r&&void 0===o;if(void 0!==o&&clearTimeout(o),o=setTimeout((function(){if(o=void 0,d=Date.now(),!r){var i=e.apply(n,t);a&&a(i),l.forEach((function(e){return(0,e.resolve)(i)})),l=[]}}),u()),c){var h=e.apply(n,t);return a&&a(h),i(h)}l.push({resolve:i,reject:s})}))};return h.cancel=function(e){void 0!==o&&clearTimeout(o),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}const Sa="negotiationStarted",Ea="negotiationComplete",wa="rtpVideoPayloadTypes";class Pa extends Fi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Pi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ca((e=>Ai(this,void 0,void 0,(function*(){this.emit(Sa);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Ii(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport),this.loggerOptions=n,this.config=t,this._pc=this.createPC(),this.offerLock=new s}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Ai(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return Ai(this,void 0,void 0,(function*(){var n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let i;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],s=Ta.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return s.media.forEach((e=>{var t;const s=Oa(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(o=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===o&&"nack"===e.type)))&&i.push(s),e.fmtp.some((e=>e.payload===o&&(e.config.includes("sprop-stereo=1")&&n.push(s),!0))))})),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){const t=Ta.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{const t=Oa(e.mid);"audio"===e.type&&this.trackBitrates.some((n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let s=!1;for(const t of e.fmtp)if(t.payload===i){t.config=t.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),n.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*n.maxbr)),s=!0;break}return s||n.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*n.maxbr)}),!0}))})),i=Ta.write(t)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(Ea),e.sdp)){Ta.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(wa,e.rtp)}))}return!0}))}createAndSendOffer(e){return Ai(this,void 0,void 0,(function*(){var t;const n=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const s=Ta.parse(null!==(t=i.sdp)&&void 0!==t?t:"");if(s.media.forEach((e=>{Ia(e),"audio"===e.type?Ra(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;if(Xo(t.codec)&&!tr()&&this.ensureVideoDDExtensionForSVC(e,s),"av1"!==t.codec)return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0}))})),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));yield this.setMungedSDP(i,Ta.write(s)),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return Ai(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=Ta.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Ia(e),"audio"===e.type&&Ra(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Ta.write(n)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ko("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 ko("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Ai(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),n.set(e.id,e);break;case"remote-candidate":i.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?i.get(s):void 0}))}setMungedSDP(e,t,n){return Ai(this,void 0,void 0,(function*(){if(t){const i=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let i="unknown error";t instanceof Error?i=t.message:"string"==typeof t&&(i=t);const s={error:i,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new yo(i)}}))}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!(null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===Ho)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var n;"video"===t.type&&(null===(n=t.ext)||void 0===n||n.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(i=e.ext)||void 0===i||i.push({value:this.ddExtID,uri:Ho})}}}function Ra(e,t,n){const i=Oa(e.mid);let s=0;e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),s>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(i)&&!e.rtcpFb.some((e=>e.payload===s&&"nack"===e.type))&&e.rtcpFb.push({payload:s,type:"nack"}),t.includes(i)&&e.fmtp.some((e=>e.payload===s&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ia(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Oa(e){return"number"==typeof e?e.toFixed(0):e}const _a="vp8",Da={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Wo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:_a,backupCodec:!0,preConnectBuffer:!1},Ma={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},xa={deviceId:{ideal:"default"},resolution:qo.h720.resolution},Aa={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Mi,disconnectOnPageLeave:!0,webAudioMix:!1},Na={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var La;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(La||(La={}));class Ua{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,n,i){var o;this.peerConnectionTimeout=Na.peerConnectionTimeout,this.log=Pi,this.updateState=()=>{var e;const t=this.state,n=this.requiredTransports.map((e=>e.getConnectionState()));n.every((e=>"connected"===e))?this.state=La.CONNECTED:n.some((e=>"failed"===e))?this.state=La.FAILED:n.some((e=>"connecting"===e))?this.state=La.CONNECTING:n.every((e=>"closed"===e))?this.state=La.CLOSED:n.some((e=>"closed"===e))?this.state=La.CLOSING:n.every((e=>"new"===e))&&(this.state=La.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(La[t]," to ").concat(La[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Ii(null!==(o=i.loggerName)&&void 0!==o?o:e.LoggerNames.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!n,this.isSubscriberConnectionRequired=n,this.publisher=new Pa(t,i),this.subscriber=new Pa(t,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,bn.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,bn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;null===(n=this.onPublisherOffer)||void 0===n||n.call(this,e,t)},this.state=La.NEW,this.connectionLock=new s,this.remoteOfferLock=new s}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return Ai(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return Ai(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Ai(this,void 0,void 0,(function*(){t===bn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Ai(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const n=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{n()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Ai(this,void 0,void 0,(function*(){var n;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map((n=>this.ensureTransportConnected(n,e,t))))}finally{i()}}))}negotiate(e){return Ai(this,void 0,void 0,(function*(){return new Promise(((t,n)=>Ai(this,void 0,void 0,(function*(){const i=setTimeout((()=>{n("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(i),n("negotiation aborted")})),this.publisher.once(Sa,(()=>{e.signal.aborted||this.publisher.once(Ea,(()=>{clearTimeout(i),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(i),n(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===bn.PUBLISHER||e===bn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(t,n){return Ai(this,arguments,void 0,(function(t,n){var i=this;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==t.getConnectionState())return new Promise(((t,o)=>Ai(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),_o.clearTimeout(r),o(new mo("room connection has been cancelled",e.ConnectionErrorReason.Cancelled))};(null==n?void 0:n.signal.aborted)&&i(),null==n||n.signal.addEventListener("abort",i);const r=_o.setTimeout((()=>{null==n||n.signal.removeEventListener("abort",i),o(new mo("could not establish pc connection",e.ConnectionErrorReason.InternalError))}),s);for(;this.state!==La.CONNECTED;)if(yield Go(50),null==n?void 0:n.signal.aborted)return void o(new mo("room connection has been cancelled",e.ConnectionErrorReason.Cancelled));_o.clearTimeout(r),null==n||n.signal.removeEventListener("abort",i),t()}))))}()}))}}class ja extends Error{constructor(e,t,n){super(t),this.code=e,this.message=Ba(t,ja.MAX_MESSAGE_BYTES),this.data=n?Ba(n,ja.MAX_DATA_BYTES):void 0}static fromProto(e){return new ja(e.code,e.message,e.data)}toProto(){return new Mt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ja(ja.ErrorCode[e],ja.ErrorMessage[e],t)}}ja.MAX_MESSAGE_BYTES=256,ja.MAX_DATA_BYTES=15360,ja.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},ja.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"};function Fa(e){return(new TextEncoder).encode(e).length}function Ba(e,t){if(Fa(e)<=t)return e;let n=0,i=e.length;const s=new TextEncoder;for(;n<i;){const o=Math.floor((n+i+1)/2);s.encode(e.slice(0,o)).length<=t?n=o:i=o-1}return e.slice(0,n)}const Va=2e3;function qa(e,t){if(!t)return 0;let n,i;return"bytesReceived"in e?(n=e.bytesReceived,i=t.bytesReceived):"bytesSent"in e&&(n=e.bytesSent,i=t.bytesSent),void 0===n||void 0===i||void 0===e.timestamp||void 0===t.timestamp?0:8*(n-i)*1e3/(e.timestamp-t.timestamp)}const Ka="undefined"!=typeof MediaRecorder;const Wa=Ka?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Ha extends Wa{constructor(e,t){if(!Ka)throw new Error("MediaRecorder is not available in this environment");let n,i;super(new MediaStream([e.mediaStreamTrack]),t);const s=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==i||i.close(),i=void 0},o=e=>{null==i||i.error(e),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",s),this.removeEventListener("error",o),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>Ai(this,void 0,void 0,(function*(){let n;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");n=t.data.byteArray}void 0!==i&&e.enqueue(n)})),this.addEventListener("dataavailable",n)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class Ga extends Mo{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,n,i){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Ca((()=>Ai(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Ai(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(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=o,this.muteLock=new s,this.pauseUpstreamLock=new s,this.trackChangeLock=new s,this.trackChangeLock.lock().then((e=>Ai(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Mo.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Ai(this,void 0,void 0,(function*(){var n;if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Ao(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(xo(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&"closed"!==(null===(n=this.sender.transport)||void 0===n?void 0:n.state)&&(yield this.sender.replaceTrack(null!=i?i:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{xo(null!=i?i:e,t)})))}))}waitForDimensions(){return Ai(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var n;if(e.kind===Mo.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=wo())||void 0===n?void 0:n.os)&&(yield Go(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield Go(50)}throw new vo("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Ai(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Er(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),Er(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Ai(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Mo.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),s=e.kind===Mo.Kind.Audio?"audioinput":"videoinput";return t?$r.getInstance().normalizeDeviceId(s,n,i):n}()}))}mute(){return Ai(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Ai(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Ai(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new vo("unable to replace an unpublished track");let n,i;return"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}}))}restart(t){return Ai(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const{deviceId:n,facingMode:i}=t,s=xi(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const o={audio:!1,video:!1};this.kind===Mo.Kind.Video?o.video=!n&&!i||{deviceId:n,facingMode:i}:o.audio=!n||Object.assign({deviceId:n},s),this.attachedElements.forEach((e=>{Ao(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===Mo.Kind.Video&&(yield r.applyConstraints(s)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ai(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),sr()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Ai(this,void 0,void 0,(function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const n=wo();if("Safari"===(null==n?void 0:n.name)&&ur(n.version,"12.0")<0)throw new go("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{n()}}))}resumeUpstream(){return Ai(this,void 0,void 0,(function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}}))}getRTCStatsReport(){return Ai(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){return Ai(this,arguments,void 0,(function(t){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),r={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(r),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),"unknown"===n.kind)throw TypeError("cannot set processor on track of unknown kind");if(xo(n._mediaStreamTrack,o),o.muted=!0,o.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:e})),setTimeout((()=>{o.play().catch((e=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:e}))}))}),100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:e}))})),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const e of n.attachedElements)e!==n.processorElement&&i&&(Ao(n._mediaStreamTrack,e),xo(n.processor.processedTrack,e));yield null===(s=n.sender)||void 0===s?void 0:s.replaceTrack(n.processor.processedTrack)}n.emit(e.TrackEvent.TrackProcessorUpdate,n.processor)}finally{o()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Ai(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()}))}internalStopProcessor(){return Ai(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,s;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(i=t.processor.processedTrack)||void 0===i||i.stop(),yield t.processor.destroy(),t.processor=void 0,n||(null===(s=t.processorElement)||void 0===s||s.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(Ka)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new Ha(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout((()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()}),1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class Ja extends Ga{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;super(t,Mo.Kind.Audio,n,i,o),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Ai(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=qa(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,ot.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,ot.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ai(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===Mo.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 Ai(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Er(this._constraints.deviceId);return this.source!==Mo.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Ai(this,void 0,void 0,(function*(){let t;if(e){const n=Br({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Ai(this,void 0,void 0,(function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n}))}startMonitor(){or()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Va)))}setProcessor(t){return Ai(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!rr()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Ai(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Ai(this,void 0,void 0,(function*(){const t=yield Vr(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const za=Object.values(qo),Qa=Object.values(Ko),Ya=Object.values(Wo),Xa=[qo.h180,qo.h360],Za=[Ko.h180,Ko.h360],$a=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var n,i;return new No(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(n=e.encoding.maxFramerate)&&void 0!==n?n:30)/(null!==(i=t.fps)&&void 0!==i?i:30))))),t.fps,e.encoding.priority)})),ec=["q","h","f"];function tc(e,t,n,i){var s,o;let r=null==i?void 0:i.videoEncoding;e&&(r=null==i?void 0:i.screenShareEncoding);const a=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!r&&!a&&!c||!t||!n)return[{}];r||(r=function(e,t,n,i){const s=function(e,t,n){if(e)return Ya;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return za;return Qa}(e,t,n);let{encoding:o}=s[0];const r=Math.max(t,n);for(let e=0;e<s.length;e+=1){const t=s[e];if(o=t.encoding,t.width>=r)break}if(i)switch(i){case"av1":case"h265":o=Object.assign({},o),o.maxBitrate=.7*o.maxBitrate;break;case"vp9":o=Object.assign({},o),o.maxBitrate=.85*o.maxBitrate}return o}(e,t,n,d),Pi.debug("using video encoding",r));const l=r.maxFramerate,u=new No(t,n,r.maxBitrate,r.maxFramerate,r.priority);if(c&&Xo(d)){const e=new oc(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=wo();if(nr()||rr()||"Chrome"===(null==n?void 0:n.name)&&ur(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,s=function(e){return e||(e=wo()),"Safari"===(null==e?void 0:e.name)&&ur(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&ur(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:ec[2-n],maxBitrate:r.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:s?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:r.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),Pi.debug("using svc encoding",{encodings:t}),t}if(!a)return[r];let h,p=[];if(p=e?null!==(s=sc(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==s?s:nc(e,u):null!==(o=sc(null==i?void 0:i.videoSimulcastLayers))&&void 0!==o?o:nc(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const i=Math.max(t,n);if(i>=960&&h)return ic(t,n,[e,h,u],l);if(i>=480)return ic(t,n,[e,u],l)}return ic(t,n,[u])}function nc(e,t){if(e)return $a(t);const{width:n,height:i}=t,s=n>i?n/i:i/n;return Math.abs(s-16/9)<Math.abs(s-4/3)?Xa:Za}function ic(e,t,n,i){const s=[];if(n.forEach(((n,o)=>{if(o>=ec.length)return;const r=Math.min(e,t),a={rid:ec[o],scaleResolutionDownBy:Math.max(1,r/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=i&&n.encoding.maxFramerate?Math.min(i,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=er()||0===o;n.encoding.priority&&d&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),s.push(a)})),rr()&&"ios"===dr()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,Pi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Pi.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return s}function sc(e){if(e)return e.sort(((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0}))}class oc{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class rc extends Ga{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=arguments.length>3?arguments[3]:void 0;super(t,Mo.Kind.Video,n,i,o),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Ai(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const n=new Map(t.map((e=>[e.rid,e]))),i=t.some((e=>"cpu"===e.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;n.forEach(((t,n)=>{var i;const s=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=qa(t,s)})),this._currentBitrate=e}this.prevStats=n})),this.senderLock=new s}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!or())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),Va))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Ai(this,void 0,void 0,(function*(){var t,n,i,s,o;yield e.pauseUpstream.call(this);try{for(var r,a=!0,c=Li(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(e){n={error:e}}finally{try{a||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Ai(this,void 0,void 0,(function*(){var t,n,i,s,o;yield e.resumeUpstream.call(this);try{for(var r,a=!0,c=Li(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){s=r.value,a=!1;const e=s;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{a||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ai(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!==Mo.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 Ai(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Mo.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Ai(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach((e=>{var i;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(i=e.rid)&&void 0!==i?i:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},o=n.get(e.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var n,i;return(null!==(n=t.frameWidth)&&void 0!==n?n:0)-(null!==(i=e.frameWidth)&&void 0!==i?i:0)})),t}))}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new Yn({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(Xo(this.codec),n)}restartTrack(e){return Ai(this,void 0,void 0,(function*(){var t,n,i,s,o;let r;if(e){const t=Br({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Li(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(o=e.sender.transport)||void 0===o?void 0:o.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Ai(this,arguments,void 0,(function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,o,r,a,c,d;if(yield t.setProcessor.call(n,e,i),null===(c=n.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Li(n.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(n.processor.processedTrack)}}catch(e){o={error:e}}finally{try{u||s||!(r=h.return)||(yield r.call(h))}finally{if(o)throw o.error}}}()}))}setDegradationPreference(e){return Ai(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Ai(this,void 0,void 0,(function*(){var t,n,i,s,o,r,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Xo(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=Li(e);!(s=(i=yield n.next()).done);t=!0){a=i.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield ac(t.sender,t.encodings,e.qualities,this.senderLock,Xo(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(Xo(e.codec),e.qualities)}}catch(e){o={error:e}}finally{try{t||s||!(r=n.return)||(yield r.call(n))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e,t){return Ai(this,void 0,void 0,(function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield ac(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Ai(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 e=this.sender.getParameters();e.encodings=e.encodings.map(((e,t)=>{var n;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(n=this.mediaStreamTrack.getSettings().height)&&void 0!==n?n:360)/360)),scalabilityMode:0===t&&Xo(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ai(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),sr()&&this.isInBackground&&this.source===Mo.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function ac(e,t,n,i,s,o,r){return Ai(this,void 0,void 0,(function*(){const a=yield i.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),{encodings:a}=i;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(s){n.some((e=>e.enabled))&&n.forEach((e=>e.enabled=!0))}a.forEach(((e,i)=>{var s;let a=null!==(s=e.rid)&&void 0!==s?s:"";""===a&&(a="q");const d=cc(a),l=n.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,o.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),er()&&(l.enabled?(e.scaleResolutionDownBy=t[i].scaleResolutionDownBy,e.maxBitrate=t[i].maxBitrate,e.maxFrameRate=t[i].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(i.encodings=a,o.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}}))}function cc(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function dc(t,n,i,s){if(!i)return[new vt({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(s){const s=i[0].scalabilityMode,o=new oc(s),r=[],a="h"==o.suffix?1.5:2,c="h"==o.suffix?2:3;for(let s=0;s<o.spatial;s+=1)r.push(new vt({quality:Math.min(e.VideoQuality.HIGH,o.spatial-1)-s,width:Math.ceil(t/Math.pow(a,s)),height:Math.ceil(n/Math.pow(a,s)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,s)):0,ssrc:0}));return r}return i.map((e=>{var i,s,o;const r=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let a=cc(null!==(s=e.rid)&&void 0!==s?s:"");return new vt({quality:a,width:Math.ceil(t/r),height:Math.ceil(n/r),bitrate:null!==(o=e.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}const lc="_lossy",uc="_reliable",hc="leave-reconnect";var pc;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(pc||(pc={}));class mc extends Fi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Na.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=pc.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Pi,this.reliableDataSequence=1,this.reliableMessageBuffer=new ca,this.reliableReceivedState=new da(3e4),this.handleDataChannel=e=>Ai(this,[e],void 0,(function(e){var t=this;let{channel:n}=e;return function*(){if(n){if(n.label===uc)t.reliableDCSub=n;else{if(n.label!==lc)return;t.lossyDCSub=n}t.log.debug("on data channel ".concat(n.id,", ").concat(n.label),t.logContext),n.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=t=>Ai(this,void 0,void 0,(function*(){var n,i,s,o,r;const a=yield this.dataProcessLock.lock();try{let a;if(t.data instanceof ArrayBuffer)a=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));a=yield t.data.arrayBuffer()}const c=kt.fromBinary(new Uint8Array(a));if(c.sequence>0&&""!==c.participantSid){const e=this.reliableReceivedState.get(c.participantSid);if(e&&c.sequence<=e)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}if("speaker"===(null===(n=c.value)||void 0===n?void 0:n.case))this.emit(e.EngineEvent.ActiveSpeakersUpdate,c.value.value.speakers);else if("encryptedPacket"===(null===(i=c.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const t=yield null===(s=this.e2eeManager)||void 0===s?void 0:s.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex),n=Tt.fromBinary(t.payload),i=new kt({value:n.value});"user"===(null===(o=i.value)||void 0===o?void 0:o.case)&&vc(i,i.value.value),this.emit(e.EngineEvent.DataPacketReceived,i,c.value.value.encryptionType)}else"user"===(null===(r=c.value)||void 0===r?void 0:r.case)&&vc(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,pt.NONE)}finally{a()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?yt.LOSSY:yt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});null!==o?(t===hc&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=_o.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),o)):i(s)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===pc.Connected&&t();const i=()=>{this.off(e.EngineEvent.Disconnected,s),t()},s=()=>{this.off(e.EngineEvent.Restarted,i),n()};this.once(e.EngineEvent.Restarted,i),this.once(e.EngineEvent.Disconnected,s)})),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);void 0!==n&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(e.EngineEvent.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return e===yt.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===sa.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(it.RR_SIGNAL_DISCONNECTED))},this.log=Ii(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new oa(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new s,this.dataProcessLock=new s,this.dcBufferStatus=new Map([[yt.LOSSY,!0],[yt.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t)}get logContext(){var e,t,n,i,s,o;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(i=null===(n=this.latestJoinResponse)||void 0===n?void 0:n.room)||void 0===i?void 0:i.sid,participant:null===(o=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===o?void 0:o.identity,pID:this.participantSid}}join(t,n,i,s){return Ai(this,void 0,void 0,(function*(){this.url=t,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const o=yield this.client.join(t,n,i,s);return this._isClosed=!1,this.latestJoinResponse=o,this.subscriberPrimary=o.subscriberPrimary,this.pcManager||(yield this.configure(o)),this.subscriberPrimary&&!o.fastPublish||this.negotiate().catch((e=>{Pi.error(e,this.logContext)})),this.registerOnLineListener(),this.clientConfiguration=o.clientConfiguration,this.emit(e.EngineEvent.SignalConnected,o),o}catch(o){if(o instanceof mo&&o.reason===e.ConnectionErrorReason.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(t,n,i,s);throw o}}))}close(){return Ai(this,void 0,void 0,(function*(){const t=yield this.closingLock.lock();if(this.isClosed)t();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{t()}}))}cleanupPeerConnections(){return Ai(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ca,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupClient(){return Ai(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new vo("a track with the same ID has already been published");return new Promise(((n,i)=>{const s=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],i(new mo("publication of local track timed out, no response from server",e.ConnectionErrorReason.Timeout))}),1e4);this.pendingTrackResolvers[t.cid]={resolve:e=>{clearTimeout(s),n(e)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Ai(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){return Ai(this,void 0,void 0,(function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==La.NEW)return;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid;const s=this.makeRTCConfiguration(t);var o;this.pcManager=new Ua(s,t.subscriberPrimary,this.loggerOptions),this.emit(e.EngineEvent.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(n,i,s)=>Ai(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(n),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),n===La.CONNECTED){const n=this.pcState===pc.New;this.pcState=pc.Connected,n&&this.emit(e.EngineEvent.Connected,t)}else n===La.FAILED&&(this.pcState!==pc.Connected&&this.pcState!==pc.Reconnecting||(this.pcState=pc.Disconnected,this.handleDisconnect("peerconnection failed","failed"===s?it.RR_SUBSCRIBER_FAILED:it.RR_PUBLISHER_FAILED)));const o=this.client.isDisconnected||this.client.currentState===sa.RECONNECTING,r=[La.FAILED,La.CLOSING,La.CLOSED].includes(n);o&&r&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(o=null===(i=t.serverInfo)||void 0===i?void 0:i.protocol)&&o>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>Ai(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>Ai(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(e.EngineEvent.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var n;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(e.EngineEvent.RoomMoved,t)},this.client.onClose=()=>{this.handleDisconnect("signal",it.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(t.regions)),t.action){case Bn.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case Bn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(hc);break;case Bn.RESUME:this.handleDisconnect(hc)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach((e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)})),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===tt.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(lc,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(uc,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return Ai(this,void 0,void 0,(function*(){if(Jo()){return yield this.createTransceiverRTCRtpSender(e,t,n)}if(zo()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new ko("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,n,i){return Ai(this,void 0,void 0,(function*(){if(Jo())return this.createSimulcastTransceiverSender(e,t,n,i);if(zo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ko("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,n){return Ai(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ko("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Dr(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:i};n&&(s.sendEncodings=n);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,n,i){return Ai(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ko("publisher is closed");const s={direction:"sendonly"};i&&(s.sendEncodings=i);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return Ai(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ko("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return Ai(this,void 0,void 0,(function*(){var n,i,s;if(!this._isClosed)if(this.attemptingReconnect)Pi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==tt.DISABLED&&(null!==(s=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==s?s:La.NEW)!==La.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let n=!0;t instanceof ko?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),n=!1):t instanceof gc||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",it.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(t){return Ai(this,void 0,void 0,(function*(){var n,i,s;try{if(!this.url||!this.token)throw new ko("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new gc;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(t){if(t instanceof mo&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new ko("could not reconnect, token might be expired");throw new gc}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==sa.CONNECTED)throw new gc("Signal connection got severed during reconnect");null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(s=this.regionUrlProvider)||void 0===s||s.resetAttempts(),e}}))}resumeConnection(t){return Ai(this,void 0,void 0,(function*(){var n;if(!this.url||!this.token)throw new ko("could not reconnect, url or token not saved");if(!this.pcManager)throw new ko("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let n="";if(t instanceof Error&&(n=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof mo&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new ko("could not reconnect, token might be expired");if(t instanceof mo&&t.reason===e.ConnectionErrorReason.LeaveRequest)throw t;throw new gc(n)}if(this.emit(e.EngineEvent.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==sa.CONNECTED)throw new gc("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(n=this.reliableDC)||void 0===n?void 0:n.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return Ai(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ko("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Ai(this,void 0,void 0,(function*(){this.pcState=pc.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Go(2e3),!this.pcManager)throw new ko("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=pc.Connected}catch(t){throw this.pcState=pc.Disconnected,new mo("could not establish PC connection, ".concat(t.message),e.ConnectionErrorReason.InternalError)}}))}publishRpcResponse(e,t,n,i){return Ai(this,void 0,void 0,(function*(){const s=new kt({destinationIdentities:[e],kind:yt.RELIABLE,value:{case:"rpcResponse",value:new Dt({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}});yield this.sendDataPacket(s,yt.RELIABLE)}))}publishRpcAck(e,t){return Ai(this,void 0,void 0,(function*(){const n=new kt({destinationIdentities:[e],kind:yt.RELIABLE,value:{case:"rpcAck",value:new _t({requestId:t})}});yield this.sendDataPacket(n,yt.RELIABLE)}))}sendDataPacket(e,t){return Ai(this,void 0,void 0,(function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=no(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new bt({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===yt.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),i=this.dataChannelForKind(t);if(i){if(t===yt.RELIABLE&&this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;i.send(n)}this.updateAndEmitDCBufferStatus(t)}))}resendReliableMessagesForResume(e){return Ai(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(yt.RELIABLE);const t=this.dataChannelForKind(yt.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(yt.RELIABLE)}))}waitForBufferStatusLow(t){return new Promise(((n,i)=>Ai(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))n();else{const s=()=>i("Engine closed");for(this.once(e.EngineEvent.Closing,s);!this.dcBufferStatus.get(t);)yield Go(10);this.off(e.EngineEvent.Closing,s),n()}}))))}ensureDataTransportConnected(t){return Ai(this,arguments,void 0,(function(t){var n=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!n.pcManager)throw new ko("PC manager is closed");const o=i?n.pcManager.subscriber:n.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!o)throw new mo("".concat(r," connection not set"),e.ConnectionErrorReason.InternalError);let a=!1;i||n.dataChannelForKind(t,i)||(n.createDataChannels(),a=!0),a||i||n.pcManager.publisher.isICEConnected||"checking"===n.pcManager.publisher.getICEConnectionState()||(a=!0),a&&n.negotiate().catch((e=>{Pi.error(e,n.logContext)}));const c=n.dataChannelForKind(t,i);if("open"===(null==c?void 0:c.readyState))return;const d=(new Date).getTime()+n.peerConnectionTimeout;for(;(new Date).getTime()<d;){if(o.isICEConnected&&"open"===(null===(s=n.dataChannelForKind(t,i))||void 0===s?void 0:s.readyState))return;yield Go(50)}throw new mo("could not establish ".concat(r," connection, state: ").concat(o.getICEConnectionState()),e.ConnectionErrorReason.InternalError)}()}))}ensurePublisherConnected(e){return Ai(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&(this.pcManager.currentState===La.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED))}negotiate(){return Ai(this,void 0,void 0,(function*(){return new Promise(((t,n)=>Ai(this,void 0,void 0,(function*(){if(!this.pcManager)return void n(new yo("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,s),this.pcManager.publisher.once(wa,(t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();Sr(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)}));try{yield this.pcManager.negotiate(i),t()}catch(e){e instanceof yo&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",it.RR_UNKNOWN),n(e)}finally{this.off(e.EngineEvent.Closing,s)}}))))}))}dataChannelForKind(e,t){if(t){if(e===yt.LOSSY)return this.lossyDCSub;if(e===yt.RELIABLE)return this.reliableDCSub}else{if(e===yt.LOSSY)return this.lossyDC;if(e===yt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),o=this.pcManager.subscriber.getRemoteDescription(),r=null===(i=null===(n=this.signalOpts)||void 0===n?void 0:n.autoSubscribe)||void 0===i||i,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==r&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new si({answer:s?aa({sdp:s.sdp,type:s.type}):void 0,offer:o?aa({sdp:o.sdp,type:o.type}):void 0,subscription:new Nn({trackSids:a,subscribe:!r,participantTracks:[]}),publishTracks:Jr(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new oi({publisherSid:t,lastSeq:e})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new ri({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(yt.LOSSY),bn.PUBLISHER),t(this.dataChannelForKind(yt.RELIABLE),bn.PUBLISHER),t(this.dataChannelForKind(yt.LOSSY,!0),bn.SUBSCRIBER),t(this.dataChannelForKind(yt.RELIABLE,!0),bn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&_o.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){or()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){or()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class gc extends Error{}function vc(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}class fc{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return ar(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Ai(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),Pi.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(t){return Ai(this,void 0,void 0,(function*(){const n=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:t});var i;if(n.ok){const e=yield n.json();return this.lastUpdateAt=Date.now(),e}throw new mo("Could not fetch region settings: ".concat(n.statusText),401===n.status?e.ConnectionErrorReason.NotAllowed:e.ConnectionErrorReason.InternalError,n.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class kc{get info(){return this._info}validateBytesReceived(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(t&&this.bytesReceived<this.totalByteSize)throw new Co("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Co("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,n,i){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=i}}class yc extends kc{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Cr,n=null,i=null;if(this.signal){const e=this.signal;i=()=>{var n;null===(n=t.reject)||void 0===n||n.call(t,e.reason)},e.addEventListener("abort",i),n=e}const s=()=>{e.releaseLock(),n&&i&&n.removeEventListener("abort",i),this.signal=void 0};return{next:()=>Ai(this,void 0,void 0,(function*(){var n,i;try{const{done:s,value:o}=yield Promise.race([e.read(),t.promise,null!==(i=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==i?i:new Promise((()=>{}))]);return s?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(o),{done:!1,value:o.content})}catch(e){throw s(),e}})),return(){return Ai(this,void 0,void 0,(function*(){return s(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ai(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,s,o;let r=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Li(a);!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const e=o;r.add(e)}}catch(e){i={error:e}}finally{try{d||n||!(s=l.return)||(yield s.call(l))}finally{if(i)throw i.error}}return Array.from(r)}()}))}}class bc extends kc{constructor(e,t,n,i){super(e,t,n,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Rr(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.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;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const t=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new Cr,s=null,o=null;if(this.signal){const e=this.signal;o=()=>{var t;null===(t=i.reject)||void 0===t||t.call(i,e.reason)},e.addEventListener("abort",o),s=e}const r=()=>{t.releaseLock(),s&&o&&s.removeEventListener("abort",o),this.signal=void 0};return{next:()=>Ai(this,void 0,void 0,(function*(){var s,o;try{const{done:r,value:a}=yield Promise.race([t.read(),i.promise,null!==(o=null===(s=this.outOfBandFailureRejectingFuture)||void 0===s?void 0:s.promise)&&void 0!==o?o:new Promise((()=>{}))]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let t;this.handleChunkReceived(a);try{t=n.decode(a.content)}catch(t){throw new Co("Cannot decode datastream chunk ".concat(a.chunkIndex," as text: ").concat(t),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(e){throw r(),e}})),return(){return Ai(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ai(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,s,o;let r="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Li(a);!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;r+=o}}catch(e){i={error:e}}finally{try{d||n||!(s=l.return)||(yield s.call(l))}finally{if(i)throw i.error}}return r}()}))}}class Tc{constructor(){this.log=Pi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new Co('A text stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(t,n){if(this.byteStreamHandlers.has(t))throw new Co('A byte stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(t){var n,i,s,o;const r=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),a=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(r.length>0||a.length>0){const c=new Co("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const[e,t]of a)null===(i=(n=t.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(n,c),this.byteStreamControllers.delete(e);for(const[e,t]of r)null===(o=(s=t.outOfBandFailureRejectingFuture).reject)||void 0===o||o.call(s,c),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return Ai(this,void 0,void 0,(function*(){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(t,n,i){return Ai(this,void 0,void 0,(function*(){var s;if("byteHeader"===t.contentHeader.case){const o=this.byteStreamHandlers.get(t.topic);if(!o)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let r;const a=new Cr;a.promise.catch((e=>{this.log.error(e)}));const c={id:t.streamId,name:null!==(s=t.contentHeader.value.name)&&void 0!==s?s:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Rr(t.timestamp),attributes:t.attributes,encryptionType:i},d=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(t.streamId))throw new Co("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:c,controller:r,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:a})}});o(new yc(c,d,Rr(t.totalLength),a),{identity:n})}else if("textHeader"===t.contentHeader.case){const s=this.textStreamHandlers.get(t.topic);if(!s)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let o;const r=new Cr;r.promise.catch((e=>{this.log.error(e)}));const a={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(o=i,this.textStreamControllers.has(t.streamId))throw new Co("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:a,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:r})}});s(new bc(a,c,Rr(t.totalLength),r),{identity:n})}}))}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new Co("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):t.content.length>0&&i.controller.enqueue(t));const s=this.textStreamControllers.get(t.streamId);s&&(s.info.encryptionType!==n?(s.controller.error(new Co("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(s.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):t.content.length>0&&s.controller.enqueue(t))}handleStreamTrailer(t,n){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new Co("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),i.controller.close(),this.textStreamControllers.delete(t.streamId)));const s=this.byteStreamControllers.get(t.streamId);s&&(s.info.encryptionType!==n?s.controller.error(new Co("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(s.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),t.attributes),s.controller.close()),this.byteStreamControllers.delete(t.streamId))}}class Cc{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 Ai(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class Sc extends Cc{}class Ec extends Cc{}class wc{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Ai(this,void 0,void 0,(function*(){var n;const i=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,o=null===(n=null==t?void 0:t.attachments)||void 0===n?void 0:n.map((()=>crypto.randomUUID())),r=new Array(o?o.length+1:1).fill(0),a=(e,n)=>{var i;r[n]=e;const s=r.reduce(((e,t)=>e+t),0);null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,s)},c=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:o,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&o&&(yield Promise.all(t.attachments.map(((e,n)=>Ai(this,void 0,void 0,(function*(){return this._sendFile(o[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,n+1)}})})))))),c.info}))}streamText(t){return Ai(this,void 0,void 0,(function*(){var n,i,s;const o=null!==(n=null==t?void 0:t.streamId)&&void 0!==n?n:crypto.randomUUID(),r={id:o,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?pt.GCM:pt.NONE},a=new Ht({streamId:o,mimeType:r.mimeType,topic:r.topic,timestamp:Ir(r.timestamp),totalLength:Ir(null==t?void 0:t.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Kt({version:null==t?void 0:t.version,attachedStreamIds:null==t?void 0:t.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?qt.UPDATE:qt.CREATE})}}),c=null==t?void 0:t.destinationIdentities,d=new kt({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(d,yt.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(e){return Ai(this,void 0,void 0,(function*(){for(const t of function(e,t){const n=[];let i=(new TextEncoder).encode(e);for(;i.length>t;){let e=t;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}n.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&n.push(i),n}(e,15e3)){yield u.waitForBufferStatusLow(yt.RELIABLE);const e=new Gt({content:t,streamId:o,chunkIndex:Ir(l)}),n=new kt({destinationIdentities:c,value:{case:"streamChunk",value:e}});yield u.sendDataPacket(n,yt.RELIABLE),l+=1}}))},close(){return Ai(this,void 0,void 0,(function*(){const e=new Jt({streamId:o}),t=new kt({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield u.sendDataPacket(t,yt.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let p=()=>Ai(this,void 0,void 0,(function*(){yield m.close()}));u.once(e.EngineEvent.Closing,p);const m=new Sc(h,r,(()=>this.engine.off(e.EngineEvent.Closing,p)));return m}))}sendFile(e,t){return Ai(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return Ai(this,void 0,void 0,(function*(){var i;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(i=null==n?void 0:n.mimeType)&&void 0!==i?i:t.type,topic:null==n?void 0:n.topic,destinationIdentities:null==n?void 0:n.destinationIdentities}),o=t.stream().getReader();for(;;){const{done:e,value:t}=yield o.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return Ai(this,void 0,void 0,(function*(){var t,n,i,o,r,a;const c=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),d=null==e?void 0:e.destinationIdentities,l={id:c,mimeType:null!==(n=null==e?void 0:e.mimeType)&&void 0!==n?n:"application/octet-stream",topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?pt.GCM:pt.NONE},u=new Ht({totalLength:Ir(null!==(a=l.size)&&void 0!==a?a:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:Ir(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Wt({name:l.name})}}),h=new kt({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,yt.RELIABLE);let p=0;const m=new s,g=this.engine,v=this.log,f=new WritableStream({write(e){return Ai(this,void 0,void 0,(function*(){const t=yield m.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+15e3);yield g.waitForBufferStatusLow(yt.RELIABLE);const i=new kt({destinationIdentities:d,value:{case:"streamChunk",value:new Gt({content:t,streamId:c,chunkIndex:Ir(p)})}});yield g.sendDataPacket(i,yt.RELIABLE),p+=1,n+=t.byteLength}}finally{t()}}))},close(){return Ai(this,void 0,void 0,(function*(){const e=new Jt({streamId:c}),t=new kt({destinationIdentities:d,value:{case:"streamTrailer",value:e}});yield g.sendDataPacket(t,yt.RELIABLE)}))},abort(e){v.error("Sink error:",e)}});return new Ec(f,l)}))}}class Pc extends Mo{constructor(e,t,n,i,s){super(e,n,s),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}setMediaStream(t){this.mediaStream=t;const n=i=>{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Ai(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),Va)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var n;this.timeSyncHandle=requestAnimationFrame((()=>t()));const i=null===(n=this.receiver)||void 0===n?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:t,rtpTimestamp:n}=i;n&&this.rtpTimestamp!==n&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}};t()}}class Rc extends Pc{constructor(e,t,n,i,s,o){super(e,t,Mo.Kind.Audio,n,o),this.monitorReceiver=()=>Ai(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=qa(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;rr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(rr())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Ai(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Zo(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Zo(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,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(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Ai(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Ic extends Pc{constructor(e,t,n,i,s){super(e,t,Mo.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>Ai(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=qa(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Ca((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===Mo.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Ao(this._mediaStreamTrack,t):xo(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new Oc(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Ai(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)})),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ai(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var n,i;const s=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),o=!(null!==(i=null===(n=this.adaptiveStreamSettings)||void 0===n?void 0:n.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!o||r;(this.lastVisible!==a||t)&&(!a&&Date.now()-s<100?_o.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,n;let i=0,s=0;const o=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*o,n=e.height()*o;t+n>i+s&&(i=t,s=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===s||(this.lastDimensions={width:i,height:s},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return lr();if(!t){return lr()>2?2:1}return t}}class Oc{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,this.isPiP=_c(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,n;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=_c(this.element),null===(n=this.handleVisibilityChanged)||void 0===n||n.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=_c(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Dc(e),this.isPiP=or()&&_c(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Dc(this.element),this.isPiP=_c(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,fr().observe(this.element),gr().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(n=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===n||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,s;null===(e=fr())||void 0===e||e.unobserve(this.element),null===(t=gr())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(n=window.documentPictureInPicture)||void 0===n||n.removeEventListener("enter",this.onEnterPiP),null===(s=null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function _c(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Dc(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function Dc(e,t){const n=t||window;let i=e.offsetTop,s=e.offsetLeft;const o=e.offsetWidth,r=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&s<n.pageXOffset+n.innerWidth&&i+r>n.pageYOffset&&s+o>n.pageXOffset&&!a&&"none"!==c}class Mc extends Fi.EventEmitter{constructor(t,n,i,s){var o;super(),this.metadataMuted=!1,this.encryption=pt.NONE,this.log=Pi,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Ii(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=Mo.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),zr(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==pt.NONE}get audioTrack(){if(_r(this.track))return this.track}get videoTrack(){if(Dr(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Mo.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Mo.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(e){var t,n;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(n=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",n.NotAllowed="not_allowed"}(Mc||(Mc={}));class xc extends Mc{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,s){super(t,n.sid,n.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&Dr(this.track)&&this.emit(e.TrackEvent.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),this.track.off(e.TrackEvent.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.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 Ai(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Ai(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Ai(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Ai(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(_r(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(ot.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(ot.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(ot.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(ot.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(ot.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(ot.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function Ac(e,t){return Ai(this,void 0,void 0,(function*(){null!=e||(e={});let n=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:o}=Qr(e);let r=o.audio,a=o.video;if(i&&"object"==typeof o.audio&&(o.audio.processor=i),s&&"object"==typeof o.video&&(o.video.processor=s),e.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){const e=o.audio.deviceId;o.audio.deviceId={exact:e},n=!0,r=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){const e=o.video.deviceId;o.video.deviceId={exact:e},n=!0,a=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}(!0===o.audio||"object"==typeof o.audio&&!o.audio.deviceId)&&(o.audio={deviceId:"default"}),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");const c=jr(o,Ma,xa),d=Br(c),l=navigator.mediaDevices.getUserMedia(d);o.audio&&($r.userMediaPromiseMap.set("audioinput",l),l.catch((()=>$r.userMediaPromiseMap.delete("audioinput")))),o.video&&($r.userMediaPromiseMap.set("videoinput",l),l.catch((()=>$r.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((n=>Ai(this,void 0,void 0,(function*(){const o="audio"===n.kind;let r,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=o?d.audio:d.video;"boolean"!=typeof l&&(r=l);const u=n.getSettings().deviceId;(null==r?void 0:r.deviceId)&&Er(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});const h=function(e,t,n){switch(e.kind){case"audio":return new Ja(e,t,!1,void 0,n);case"video":return new rc(e,t,!1,n);default:throw new vo("unsupported track type: ".concat(e.kind))}}(n,r,t);return h.kind===Mo.Kind.Video?h.source=Mo.Source.Camera:h.kind===Mo.Kind.Audio&&(h.source=Mo.Source.Microphone),h.mediaStream=e,_r(h)&&i?yield h.setProcessor(i):Dr(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(i){if(!n)throw i;return Ac(Object.assign(Object.assign({},e),{audio:r,video:a}),t)}}))}function Nc(e){return Ai(this,void 0,void 0,(function*(){return(yield Ac({audio:!1,video:null==e||e}))[0]}))}function Lc(e){return Ai(this,void 0,void 0,(function*(){return(yield Ac({audio:null==e||e,video:!1}))[0]}))}e.ConnectionQuality=void 0,function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(e.ConnectionQuality||(e.ConnectionQuality={}));class Uc extends Fi.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===ut.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===lt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,s,o,r){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ut.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=Pi,this.log=Ii(null!==(c=null==r?void 0:r.loggerName)&&void 0!==c?c:e.LoggerNames.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=o?o:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Cr,this.once(e.ParticipantEvent.Active,(()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(Mo.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Mo.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Mo.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(t){var n;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version)&&(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===lt.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==lt.ACTIVE&&this.emit(e.ParticipantEvent.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const n=function(e,t){var n;void 0===e&&(e={}),void 0===t&&(t={});const i=[...Object.keys(t),...Object.keys(e)],s={};for(const o of i)e[o]!==t[o]&&(s[o]=null!==(n=t[o])&&void 0!==n?n:"");return s}(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,n)}setPermissions(t){var n,i,s,o,r,a;const c=this.permissions,d=t.canPublish!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(s=this.permissions)||void 0===s?void 0:s.canPublishData)||t.hidden!==(null===(o=this.permissions)||void 0===o?void 0:o.hidden)||t.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])}))||t.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=t,d&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,c),d}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=function(t){switch(t){case et.EXCELLENT:return e.ConnectionQuality.Excellent;case et.GOOD:return e.ConnectionQuality.Good;case et.POOR:return e.ConnectionQuality.Poor;case et.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),n!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>_r(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case Mo.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case Mo.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class jc extends Uc{constructor(t,n,i,s,o,r){super(t,n,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=pt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Cr)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,i,s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(i=(n=this.signalConnectedFuture).reject)||void 0===i||i.call(n,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(o=null===(s=this.activeAgentFuture)||void 0===s?void 0:s.reject)||void 0===o||o.call(s,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Cr),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:n,message:i}=e,s=this.pendingSignalRequests.get(t);s&&(n!==mi.OK&&s.reject(new To(i,n)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,n=null,i=null;"payload"===t.value.case?n=t.value.value:"error"===t.value.case&&(i=ja.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,i);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new ei({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),zr(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),zr(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),zr(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(t,n)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),zr(n))),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleSubscribedQualityUpdate=e=>Ai(this,void 0,void 0,(function*(){var t,n,i,s,o;if(!(null===(o=this.roomOptions)||void 0===o?void 0:o.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!r.videoTrack)return;const a=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Li(a);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;Bo(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),zr(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){n={error:e}}finally{try{d||t||!(i=l.return)||(yield i.call(l))}finally{if(n)throw n.error}}})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Ai(this,void 0,void 0,(function*(){if(e.source===Mo.Source.ScreenShare||e.source===Mo.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),zr(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(xr(e)||Mr(e))try{if(or())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Mo.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),zr(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),zr(e))),xr(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),zr(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=o,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==pt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){var n;this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())})),(null===(n=this.signalConnectedFuture)||void 0===n?void 0:n.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalConnected,this.handleSignalConnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Ai(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Ai(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Ai(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Ai(this,arguments,void 0,(function(e){var t=this;let{metadata:n,name:i,attributes:s}=e;return function*(){return new Promise(((e,o)=>Ai(t,void 0,void 0,(function*(){var t,r;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(r=null!=i?i:this.name)&&void 0!==r?r:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:i,metadata:n,attributes:s}});performance.now()-d<5e3&&!a;){if((!i||this.name===i)&&(!n||this.metadata===n)&&(!s||Object.entries(s).every((e=>{let[t,n]=e;return this.attributes[t]===n||""===n&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield Go(50)}o(new To("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&o(e)}}))))}()}))}setCameraEnabled(e,t,n){return this.setTrackEnabled(Mo.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Mo.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Mo.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return Ai(this,void 0,void 0,(function*(){this.encryptionType=e?pt.GCM:pt.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,n,i,s){return Ai(this,void 0,void 0,(function*(){var o,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(t);if(n)if(a)yield a.unmute();else{let n;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case Mo.Source.Camera:n=yield this.createTracks({video:null===(o=i)||void 0===o||o});break;case Mo.Source.Microphone:n=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case Mo.Source.ScreenShare:n=yield this.createScreenTracks(Object.assign({},i));break;default:throw new vo(t)}}catch(i){throw null==n||n.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,i,Wr(t)),this.pendingPublishing.delete(t),i}for(const e of n){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===Mo.Source.Microphone&&_r(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),e.startPreConnectBuffer())}try{const e=[];for(const t of n)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),zr(t))),e.push(this.publishTrack(t,s));const t=yield Promise.all(e);[a]=t}catch(e){throw null==n||n.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(t)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(t)&&(a=yield this.waitForPendingPublicationOfSource(t),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),a&&a.track)if(t===Mo.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(Mo.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Ai(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(Mo.Source.Camera)&&!this.pendingPublishing.has(Mo.Source.Microphone)){this.pendingPublishing.add(Mo.Source.Camera),this.pendingPublishing.add(Mo.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(Mo.Source.Camera),this.pendingPublishing.delete(Mo.Source.Microphone)}}}))}createTracks(t){return Ai(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const s=jr(t,null===(n=this.roomOptions)||void 0===n?void 0:n.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const t=yield Ac(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(_r(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=Mo.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),Dr(t)&&(this.cameraError=void 0,t.source=Mo.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return Ai(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new go("getDisplayMedia not supported");void 0!==t.resolution||ir()||(t.resolution=Wo.h1080fps30.resolution);const n=Hr(t),i=yield navigator.mediaDevices.getDisplayMedia(n),s=i.getVideoTracks();if(0===s.length)throw new vo("no video track found");const o=new rc(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=Mo.Source.ScreenShare,t.contentHint&&(o.mediaStreamTrack.contentHint=t.contentHint);const r=[o];if(i.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new Ja(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=Mo.Source.ScreenShareAudio,r.push(t)}return r}))}publishTrack(e,t){return Ai(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return Ai(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,o,r,a;let c,d;if(xr(e)&&e.setAudioContext(n.audioContext),yield null===(s=n.reconnectFuture)||void 0===s?void 0:s.promise,n.republishPromise&&!i&&(yield n.republishPromise),Or(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case Mo.Source.Microphone:t="audioinput";break;case Mo.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Ja(e,c,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=new rc(e,c,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new vo("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});if(n.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return n.log.warn("track has already been published, skipping",Object.assign(Object.assign({},n.logContext),zr(d))),d;const l=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(o=l.forceStereo)&&void 0!==o?o:u;h&&(void 0===l.dtx&&n.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},n.logContext),zr(e))),void 0===l.red&&n.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=l.dtx)&&void 0!==r||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=wo(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&ur(e.osVersion,t)>=0)||"Safari"===e.name&&ur(e.version,t)>=0}()&&n.roomOptions.e2ee&&(n.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},n.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise(((t,i)=>Ai(n,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==sa.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:zr(e)}));const n=setTimeout((()=>{i(new bo("publishing rejected as engine not connected within timeout",408))}),15e3);yield this.waitUntilEngineConnected(),clearTimeout(n);const s=yield this.publish(e,l,h);t(s)}else try{const n=yield this.publish(e,l,h);t(n)}catch(e){i(e)}}catch(e){i(e)}}))));n.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Cr),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),zr(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return!(!t||0!==n.length&&!n.map((e=>function(e){switch(e){case Ze.CAMERA:return Mo.Source.Camera;case Ze.MICROPHONE:return Mo.Source.Microphone;case Ze.SCREEN_SHARE:return Mo.Source.ScreenShare;case Ze.SCREEN_SHARE_AUDIO:return Mo.Source.ScreenShareAudio;default:return Mo.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),zr(e))),!1)}publish(t,n,i){return Ai(this,void 0,void 0,(function*(){var s,o,r,a,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(t))throw new bo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>Or(t)&&e.source===t.source))&&t.source!==Mo.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),zr(t))),n.stopMicTrackOnMute&&_r(t)&&(t.stopOnMute=!0),t.source===Mo.Source.ScreenShare&&er()&&(n.simulcast=!1),"av1"!==n.videoCodec||Qo()||(n.videoCodec=void 0),"vp9"!==n.videoCodec||Yo()||(n.videoCodec=void 0),void 0===n.videoCodec&&(n.videoCodec=_a),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>n.videoCodec===Gr(e.mime)))||(n.videoCodec=Gr(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=[],v=!(null===(s=n.dtx)||void 0===s||s),f=t.getSourceTrackSettings();f.autoGainControl&&g.push(ot.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&g.push(ot.TF_ECHO_CANCELLATION),f.noiseSuppression&&g.push(ot.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&g.push(ot.TF_STEREO),v&&g.push(ot.TF_NO_DTX),xr(t)&&t.hasPreConnectBuffer&&g.push(ot.TF_PRECONNECT_BUFFER);const k=new Pn({cid:t.mediaStreamTrack.id,name:n.name,type:Mo.kindToProto(t.kind),muted:t.isMuted,source:Mo.sourceToProto(t.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(o=n.red)||void 0===o||o),stream:null==n?void 0:n.stream,backupCodecPolicy:null==n?void 0:n.backupCodecPolicy,audioFeatures:g});let y;if(t.kind===Mo.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(n){const i=null!==(a=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==a?a:qo.h720.resolution;e={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),zr(t)),{dims:e}))}k.width=e.width,k.height=e.height,Mr(t)&&(Xo(m)&&(t.source===Mo.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),zr(t))))),n.scalabilityMode=null!==(c=n.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),k.simulcastCodecs=[new wn({codec:m,cid:t.mediaStreamTrack.id})],!0===n.backupCodec&&(n.backupCodec={codec:_a}),n.backupCodec&&m!==n.backupCodec.codec&&k.encryption===pt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new wn({codec:n.backupCodec.codec,cid:""})))),y=tc(t.source===Mo.Source.ScreenShare,k.width,k.height,n),k.layers=dc(k.width,k.height,y,Xo(n.videoCodec))}else t.kind===Mo.Kind.Audio&&(y=[{maxBitrate:null===(d=n.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=n.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=n.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new ko("cannot publish track when not connected");const b=()=>Ai(this,void 0,void 0,(function*(){var i,s,o;if(!this.engine.pcManager)throw new ko("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,y),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Mr(t)&&(null!==(i=n.degradationPreference)&&void 0!==i||(n.degradationPreference=function(e){return e.source===Mo.Source.ScreenShare||e.constraints.height&&Er(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(n.degradationPreference)),y)if(er()&&t.kind===Mo.Kind.Audio){let e;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===t.sender){e=n;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(s=y[0])||void 0===s?void 0:s.maxBitrate)?y[0].maxBitrate/1e3:0})}else t.codec&&Xo(t.codec)&&(null===(o=y[0])||void 0===o?void 0:o.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:t.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()}));let T;const C=new Promise(((e,n)=>Ai(this,void 0,void 0,(function*(){var i;try{T=yield this.engine.addTrack(k),e(T)}catch(e){t.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),zr(t)),{error:e}))}))),n(e)}}))));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([C,b()]);T=e[0]}else{let e;if(T=yield C,T.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===Mo.Kind.Video){const i=Gr(e);i!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),zr(t)),{codec:i})),n.videoCodec=i,y=tc(t.source===Mo.Source.ScreenShare,k.width,k.height,n))}yield b()}const S=new xc(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,S))),S.options=n,t.sid=T.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:T})),Mr(t)?t.startMonitor(this.engine.client):xr(t)&&t.startMonitor(),this.addTrackPublication(S),this.emit(e.ParticipantEvent.LocalTrackPublished,S),xr(t)&&T.audioFeatures.includes(ot.TF_PRECONNECT_BUFFER)){const n=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===T.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),zr(t))),t.stopPreConnectBuffer()}})),n){const e=new Promise(((e,s)=>Ai(this,void 0,void 0,(function*(){var o,r,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),zr(t)));const m=setTimeout((()=>{s(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),zr(t)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Li(n);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){r={error:e}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(r)throw r.error}}yield v.close(),e()}catch(e){s(e)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),zr(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),zr(t)),{error:e}))}))}}return S}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return Ai(this,void 0,void 0,(function*(){var i;if(this.encryptionType!==pt.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new vo("track is not published");if(!Mr(e))throw new vo("track is not a video track");const o=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),r=function(e,t,n){var i,s,o,r;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&Pi.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(i=a.width)&&void 0!==i?i:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(o=a.height)&&void 0!==o?o:null===(r=e.dimensions)||void 0===r?void 0:r.height;return e.source===Mo.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),tc(e.source===Mo.Source.ScreenShare,c,d,n)}(e,t,o);if(!r)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),zr(e)));const a=e.addSimulcastTrack(t,r);if(!a)return;const c=new Pn({cid:a.mediaStreamTrack.id,type:Mo.kindToProto(e.kind),muted:e.isMuted,source:Mo.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=dc(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new ko("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Ai(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,o,r),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:r,trackInfo:d}))}))}unpublishTrack(t,n){return Ai(this,void 0,void 0,(function*(){var i,s;if(Or(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),zr(t))),yield e)}const o=this.getPublicationForTrack(t),r=o?zr(o):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!o||!o.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(t=o.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===n&&(n=null===(s=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===s||s),n?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<La.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",a=!0);if(this.engine.removeTrack(c)&&(a=!0),Mr(t)){for(const[,e]of t.simulcastCodecs)e.sender&&(this.engine.removeTrack(e.sender)&&(a=!0),e.sender=void 0);t.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(o.trackSid),o.kind){case Mo.Kind.Audio:this.audioTrackPublications.delete(o.trackSid);break;case Mo.Kind.Video:this.videoTrackPublications.delete(o.trackSid)}return this.emit(e.ParticipantEvent.LocalTrackUnpublished,o),o.setTrack(void 0),a&&(yield this.engine.negotiate()),o}))}unpublishTracks(e){return Ai(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Ai(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((i,s)=>Ai(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))})),yield Promise.all(t.map((e=>Ai(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===Mo.Source.ScreenShare||t.source===Mo.Source.ScreenShareAudio||!xr(t)&&!Mr(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(e){s(e)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Ai(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const i=n.reliable?yt.RELIABLE:yt.LOSSY,s=n.destinationIdentities,o=n.topic;let r=new Et({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:o});const a=new kt({kind:i,value:{case:"user",value:r}});yield t.engine.sendDataPacket(a,i)}()}))}publishDtmf(e,t){return Ai(this,void 0,void 0,(function*(){const n=new kt({kind:yt.RELIABLE,value:{case:"sipDtmf",value:new wt({code:e,digit:t})}});yield this.engine.sendDataPacket(n,yt.RELIABLE)}))}sendChatMessage(t,n){return Ai(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==n?void 0:n.attachments},s=new kt({value:{case:"chatMessage",value:new It(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,yt.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}editChatMessage(t,n){return Ai(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),s=new kt({value:{case:"chatMessage",value:new It(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp),editTimestamp:D.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,yt.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}sendText(e,t){return Ai(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return Ai(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return Ai(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return Ai(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return Ai(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:n,method:i,payload:s,responseTimeout:o=1e4}=e;return function*(){return new Promise(((e,r)=>Ai(t,void 0,void 0,(function*(){var t,a,c,d;if(Fa(s)>15360)return void r(ja.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&ur(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void r(ja.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(n,l,i,s,o-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),r(ja.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:n});const h=setTimeout((()=>{this.pendingResponses.delete(l),r(ja.builtIn("RESPONSE_TIMEOUT"))}),o);this.pendingResponses.set(l,{resolve:(t,n)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),n?r(n):e(null!=t?t:"")},participantIdentity:n})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,s){return Ai(this,void 0,void 0,(function*(){const o=new kt({destinationIdentities:[e],kind:yt.RELIABLE,value:{case:"rpcRequest",value:new Ot({id:t,method:n,payload:i,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(o,yt.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,ja.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,n;const i=this.trackPublications.get(e.sid);if(i){const s=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),zr(i)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}setActiveAgent(e){var t,n,i,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(n=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===n||n.call(t,e):null===(s=null===(i=this.activeAgentFuture)||void 0===i?void 0:i.reject)||void 0===s||s.call(i,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Cr),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(xr(i)||Mr(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return Ai(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[n]=t;return n.source===e}));if(t)return t[1];yield Go(20)}}))}}class Fc extends Mc{constructor(t,n,i,s){super(t,n.sid,n.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const s=new Nn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new xt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Mc.SubscriptionStatus.Unsubscribed:super.isSubscribed?Mc.SubscriptionStatus.Subscribed:Mc.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Mc.PermissionStatus.Allowed:Mc.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}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()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(n=this.requestedVideoDimensions)||void 0===n?void 0:n.height)===e.height||(Lr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Lr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:e.VideoQuality.HIGH}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==t&&(s&&(s.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),s.off(e.TrackEvent.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,s)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(e.TrackEvent.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Lr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Ln({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Mo.Kind.Video){let o=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(o){Yr(this.videoDimensionsAdaptiveStream,o)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),o=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(n=this.trackInfo,i=this.requestedMaxQuality,null===(s=n.layers)||void 0===s?void 0:s.find((e=>e.quality===i)));e&&Yr(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),o=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),o=this.videoDimensionsAdaptiveStream;o?(t.width=Math.ceil(o.width),t.height=Math.ceil(o.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:e.VideoQuality.HIGH})),t.quality=e.VideoQuality.HIGH)}var n,i,s;this.emit(e.TrackEvent.UpdateSettings,t)}}class Bc extends Uc{static fromParticipantInfo(e,t,n){return new Bc(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,s,o,r){super(t,n||"",i,s,o,r,arguments.length>7&&void 0!==arguments[7]?arguments[7]:ut.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),zr(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,n)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,n)})),t.on(e.TrackEvent.Subscribed,(n=>{this.emit(e.ParticipantEvent.TrackSubscribed,n,t)})),t.on(e.TrackEvent.Unsubscribed,(n=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,n,t)})),t.on(e.TrackEvent.SubscriptionFailed,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,n)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Mo.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&&void 0!==arguments[0]?arguments[0]:Mo.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,s,o,r){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,s,o,r-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),zr(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Ic(t,n,s,o):new Rc(t,n,s,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(i),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&Ar(c)&&_r(c)&&c.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach((e=>{var t,s;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const n=Mo.kindFromProto(e.type);if(!n)return;o=new Fc(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),o.updateInfo(e),i.set(e.sid,o);const r=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));r&&o.source!==Mo.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:zr(r),newTrack:zr(o)})),this.addTrackPublication(o)}n.set(e.sid,o)})),this.trackPublications.forEach((e=>{n.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),zr(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case Mo.Kind.Audio:this.audioTrackPublications.delete(t);break;case Mo.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return Ai(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;_r(n.track)&&Ar(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var Vc;e.ConnectionState=void 0,(Vc=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Vc.Connecting="connecting",Vc.Connected="connected",Vc.Reconnecting="reconnecting",Vc.SignalReconnecting="signalReconnecting";class qc extends Fi.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(t){var n,i,o,r;if(super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Pi,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(t,n,i)=>Ai(this,void 0,void 0,(function*(){var s;if(!$o())throw rr()?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 o=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),o(),Promise.resolve();if(this.connectFuture)return o(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ar(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new fc(t,n):this.regionUrlProvider.updateToken(n),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(s,a,c)=>Ai(this,void 0,void 0,(function*(){var d,l;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==o||o();try{yield this.attemptConnection(null!=c?c:t,n,i,u),this.abortController=void 0,s()}catch(t){if(this.regionUrlProvider&&t instanceof mo&&t.reason!==e.ConnectionErrorReason.Cancelled&&t.reason!==e.ConnectionErrorReason.NotAllowed){let n=null;try{n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(t){if(t instanceof mo&&(401===t.status||t.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(t)}n&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(n),this.logContext),this.recreateEngine(),yield r(s,a,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Pr(t)),a(t))}else{let e=nt.UNKNOWN_REASON;t instanceof mo&&(e=Pr(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(t)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Cr(((e,t)=>{r(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,s,o)=>Ai(this,void 0,void 0,(function*(){var r,a,c;const d=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout},o.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,n]=e;return"".concat(t,": ").concat(n)})).join(", ")),{room:null===(r=d.room)||void 0===r?void 0:r.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new fo("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,s)=>Ai(this,void 0,void 0,(function*(){var o,r;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(o=this.engine)||void 0===o?void 0:o.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Na),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,this.engine,this.connOptions,this.options,s);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const n=new mo("could not establish signal connection",e.ConnectionErrorReason.ServerUnreachable);throw t instanceof Error&&(n.message="".concat(n.message,": ").concat(t.message)),t instanceof mo&&(n.reason=t.reason,n.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),n}if(s.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new mo("Connection attempt aborted",e.ConnectionErrorReason.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,s)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}or()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),or()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),s=0;s<t;s++)i[s]=arguments[s];return Ai(n,[...i],void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,s,o,r;const a=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected",t.logContext);t.log.info("disconnect from room",Object.assign({},t.logContext)),(t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming)&&(t.log.warn("abort connection attempt",t.logContext),null===(i=t.abortController)||void 0===i||i.abort(),null===(o=null===(s=t.connectFuture)||void 0===s?void 0:s.reject)||void 0===o||o.call(s,new mo("Client initiated disconnect",e.ConnectionErrorReason.Cancelled)),t.connectFuture=void 0),(null===(r=t.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield t.engine.client.sendLeave()),t.engine&&(yield t.engine.close()),t.handleDisconnect(n,nt.CLIENT_INITIATED),t.engine=void 0}finally{a()}}()}))},this.onPageLeave=()=>Ai(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Ai(this,void 0,void 0,(function*(){const t=[],n=wo();if(n&&"iOS"===n.os){const n="livekit-dummy-audio-el";let i=document.getElementById(n);if(!i){i=document.createElement("audio"),i.id=n,i.autoplay=!0,i.hidden=!0;const t=Tr();t.enabled=!0;const s=new MediaStream([t]);i.srcObject=s,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:s,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(e.RoomEvent.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>Ai(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var n;null===(n=t.track)||void 0===n||n.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>Ai(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let n=this.remoteParticipants.get(e.identity);e.state===lt.DISCONNECTED?this.handleParticipantDisconnected(e.identity,n):n=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const n=[],i={};t.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),n.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),n.push(t))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleSpeakersChanged=t=>{const n=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||n.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?n.set(e.sid,t):n.delete(e.sid))}));const i=Array.from(n.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const n=this.getRemoteParticipantBySid(t.participantSid);if(!n)return;const i=n.getTrackPublicationBySid(t.trackSid);if(!i||!i.track)return;const s=Mo.streamStateFromProto(t.state);i.track.setStreamState(s),s!==i.track.streamState&&(n.emit(e.ParticipantEvent.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,i,i.track.streamState,n))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const n=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(n,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(n,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(n,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(n,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,n);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(t,n,i,s)=>{this.emit(e.RoomEvent.DataReceived,n.payload,t,i,n.topic,s),null==t||t.emit(e.ParticipantEvent.DataReceived,n.payload,i,s)},this.handleSipDtmf=(t,n)=>{this.emit(e.RoomEvent.SipDTMFReceived,n,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,n)},this.handleTranscription=(t,n)=>{const i=n.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(n.transcribedParticipantIdentity),s=null==i?void 0:i.trackPublications.get(n.trackId),o=function(e,t){return e.segments.map((e=>{let{id:n,text:i,language:s,startTime:o,endTime:r,final:a}=e;var c;const d=null!==(c=t.get(n))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(n):t.set(n,d),{id:n,text:i,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(r.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(n,this.transcriptionReceivedTimes);null==s||s.emit(e.TrackEvent.TranscriptionReceived,o),null==i||i.emit(e.ParticipantEvent.TranscriptionReceived,o,s),this.emit(e.RoomEvent.TranscriptionReceived,o,i,s)},this.handleChatMessage=(t,n)=>{const i=function(e){const{id:t,timestamp:n,message:i,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}(n);this.emit(e.RoomEvent.ChatMessage,i,t)},this.handleMetrics=(t,n)=>{this.emit(e.RoomEvent.MetricsReceived,t,n)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Ai(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=wo())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const n=this.roomInfo;this.roomInfo=t,n&&n.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==n?void 0:n.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>Ai(this,void 0,void 0,(function*(){var n,i,s,o,r,a;if(null===(n=t.track)||void 0===n||n.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(e.TrackEvent.Restarted,this.onLocalTrackRestarted),null===(r=null===(o=null===(s=t.track)||void 0===s?void 0:s.getProcessor())||void 0===o?void 0:o.onPublish)||void 0===r||r.call(o,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),xr(t.track)){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const c=yield null===(a=t.track)||void 0===a?void 0:a.getDeviceId(!1),d=Wr(t.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,c),this.emit(e.RoomEvent.ActiveDeviceChanged,d,c))})),this.onLocalTrackUnpublished=t=>{var n,i;null===(n=t.track)||void 0===n||n.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(e.TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>Ai(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=Wr(t.source);i&&n&&n!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(n," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,n),this.emit(e.RoomEvent.ActiveDeviceChanged,i,n))})),this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,n)=>{this.emit(e.RoomEvent.MediaDevicesError,t,n)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(e.RoomEvent.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Aa),t),this.log=Ii(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ma),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},xa),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Da),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Tc,this.outgoingDataStreamManager=new wc(this.engine,this.log),this.disconnectLock=new s,this.localParticipant=new jc("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Er(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Er(this.options.audioCaptureDefaults.deviceId)),(null===(o=this.options.audioOutput)||void 0===o?void 0:o.deviceId)&&this.switchActiveDevice("audiooutput",Er(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),or()){const e=new AbortController;null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),qc.cleanupRegistry&&qc.cleanupRegistry.register(this,(()=>{e.abort()}))}}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){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)}setE2EEEnabled(e){return Ai(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var t;const n=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&(this.e2eeManager="e2eeManager"in i?i.e2eeManager:new Xr(i,n),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{Ur(n)&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,n)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,(t=>this.emit(e.RoomEvent.EncryptionError,t))),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Ai(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,n)=>{const i=n=>{""!==n.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,i),t(n.sid))};this.engine.on(e.EngineEvent.RoomUpdate,i),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,i),n("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new mc(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,n)=>{this.onTrackAdded(e,t,n)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,n)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,n)})).on(e.EngineEvent.LocalTrackSubscribed,(t=>{const n=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:n}=e;return n===t}));n?(this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,n),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,n,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(e.EngineEvent.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(e.RoomEvent.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return $r.getInstance().getDevices(e,t)}prepareConnection(t,n){return Ai(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(ar(new URL(t))&&n){this.regionUrlProvider=new fc(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(wr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(wr(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Ai(this,void 0,void 0,(function*(){let n,i=()=>Ai(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new ai({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new ai({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new ai({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new ai({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>Ai(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new ai({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Ai(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new ai({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":n=new ai({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Ai(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Fn({reason:nt.CLIENT_INITIATED,action:Bn.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new ai({scenario:{case:"subscriberBandwidth",value:Ir(t)}});break;case"leave-full-reconnect":n=new ai({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,n){return Ai(this,arguments,void 0,(function(t,n){var i=this;let s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var o,r,a,c,d,l,u;let h=!0,p=!1;const m=s?{exact:n}:n;if("audioinput"===t){p=0===i.localParticipant.audioTrackPublications.size;const e=null!==(o=i.getActiveDevice(t))&&void 0!==o?o:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===Mo.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.audioCaptureDefaults.deviceId=e,t}const s=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&s&&(p=!0)}else if("videoinput"===t){p=0===i.localParticipant.videoTrackPublications.size;const e=null!==(r=i.getActiveDevice(t))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Mo.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.videoCaptureDefaults.deviceId=e,t}const s=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&s&&(p=!0)}else if("audiooutput"===t){if(p=!0,!Zo()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(n=null!==(a=yield $r.getInstance().normalizeDeviceId("audiooutput",n))&&void 0!==a?a:""),null!==(c=(u=i.options).audioOutput)&&void 0!==c||(u.audioOutput={});const e=null!==(d=i.getActiveDevice(t))&&void 0!==d?d:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=n;try{i.options.webAudioMix&&(null===(l=i.audioContext)||void 0===l||l.setSinkId(n)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:n}))))}catch(t){throw i.options.audioOutput.deviceId=e,t}}return p&&(i.localParticipant.activeDeviceMap.set(t,n),i.emit(e.RoomEvent.ActiveDeviceChanged,t,n)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const s=()=>{this.onTrackAdded(t,n,i),o()},o=()=>{this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,o)};return this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),void this.once(e.RoomEvent.Disconnected,o)}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===t.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const s=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(n.id),o=s[0];let r=s[1],a=t.id;if(r&&r.startsWith("TR")&&(a=r),o===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===o));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(o),this.logContext);let d;this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const l=c.addSubscribedMediaTrack(t,a,n,i,d);(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var n,i,s;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(n=e.track)||void 0===n||n.detach(),null===(i=e.track)||void 0===i||i.stop()):null===(s=e.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),or()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n){var i;this.remoteParticipants.delete(t),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n),n.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,t,n,i,s,o){return Ai(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==o)return void(yield this.engine.publishRpcResponse(e,t,null,ja.builtIn("UNSUPPORTED_VERSION")));const r=this.rpcHandlers.get(n);if(!r)return void(yield this.engine.publishRpcResponse(e,t,null,ja.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const o=yield r({requestId:t,callerIdentity:e,payload:i,responseTimeout:s});Fa(o)>15360?(a=ja.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=o}catch(e){e instanceof ja?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),e),a=ja.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}selectDefaultDevices(){return Ai(this,void 0,void 0,(function*(){var t,n,i;const s=$r.getInstance().previousDevices,o=yield $r.getInstance().getDevices(void 0,!1),r=wo();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let t of o){const n=s.find((e=>e.deviceId===t.deviceId));n&&""!==n.label&&n.kind===t.kind&&n.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,t.kind,t.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let e of a){const r=Kr(e),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(t=a.track)||void 0===t?void 0:t.isUserProvided))continue;const c=o.filter((t=>t.kind===e)),d=this.getActiveDevice(e);d===(null===(n=s.filter((t=>t.kind===e))[0])||void 0===n?void 0:n.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(e,c[0].deviceId):"audioinput"===e&&!nr()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&nr()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return Ai(this,void 0,void 0,(function*(){var t,n;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=qr())&&void 0!==t?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Go(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const i="running"===(null===(n=this.audioContext)||void 0===n?void 0:n.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var n;let i;return i=t?Bc.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new Bc(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),i}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(n){e.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity)}return e}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,i),i.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,i)})).on(e.ParticipantEvent.TrackSubscribed,((t,n)=>{t.kind===Mo.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===Mo.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,i)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,n)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,n,i)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,i)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,i)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,i)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,i)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,i)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,i)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,i)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,n)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,n,i)})).on(e.ParticipantEvent.Active,(()=>{this.emitWhenConnected(e.RoomEvent.ParticipantActive,i),i.kind===ut.AGENT&&this.localParticipant.setActiveAgent(i)})),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Nr(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=_o.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,nt.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&_o.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,n]=e;this.emit(t,...n)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];if(this.state===e.ConnectionState.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([t,i]);else if(this.state===e.ConnectionState.Connected)return this.emit(t,...i);return!1}simulateParticipants(t){return Ai(this,void 0,void 0,(function*(){var n,i;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},t.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},t.participants);if(this.handleDisconnect(),this.roomInfo=new rt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:D.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new dt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected),s.video){const t=new xc(Mo.Kind.Video,new gt({source:Ze.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO,name:"video-dummy"}),new rc(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:br(160*(null!==(n=o.aspectRatios[0])&&void 0!==n?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(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(s.audio){const t=new xc(Mo.Kind.Audio,new gt({source:Ze.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO}),new Ja(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Tr(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<o.count-1;e+=1){let t=new dt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:lt.ACTIVE,tracks:[],joinedAt:D.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(o.video){const s=br(160*(null!==(i=o.aspectRatios[e%o.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),r=new gt({source:Ze.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO});n.addSubscribedMediaTrack(s,r.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(o.audio){const e=Tr(),i=new gt({source:Ze.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];if(t!==e.RoomEvent.ActiveSpeakersChanged&&t!==e.RoomEvent.TranscriptionReceived){const e=Kc(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:e}))}return super.emit(t,...i)}}function Kc(e){return e.map((e=>{if(e)return Array.isArray(e)?Kc(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}qc.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()}));var Wc,Hc=Object.freeze({__proto__:null,Convert:class{static toAgentAttributes(e){return JSON.parse(e)}static agentAttributesToJson(e){return JSON.stringify(e)}static toTranscriptionAttributes(e){return JSON.parse(e)}static transcriptionAttributesToJson(e){return JSON.stringify(e)}}});e.CheckStatus=void 0,(Wc=e.CheckStatus||(e.CheckStatus={}))[Wc.IDLE=0]="IDLE",Wc[Wc.RUNNING=1]="RUNNING",Wc[Wc.SKIPPED=2]="SKIPPED",Wc[Wc.SUCCESS=3]="SUCCESS",Wc[Wc.FAILED=4]="FAILED";class Gc extends Fi.EventEmitter{constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.options={},this.url=t,this.token=n,this.name=this.constructor.name,this.room=new qc(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return Ai(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(t){return Ai(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions)),this.room}))}disconnect(){return Ai(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(e.CheckStatus.SKIPPED)}switchProtocol(t){return Ai(this,void 0,void 0,(function*(){let n=!1,i=!1;if(this.room.on(e.RoomEvent.Reconnecting,(()=>{n=!0})),this.room.once(e.RoomEvent.Reconnected,(()=>{i=!0})),this.room.simulateScenario("force-".concat(t)),yield new Promise((e=>setTimeout(e,1e3))),!n)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield Go(100)}throw new Error("Could not reconnect using ".concat(t," 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 null===(e=this.room)||void 0===e?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Jc extends Gc{get description(){return"Cloud regions"}perform(){return Ai(this,void 0,void 0,(function*(){const e=new fc(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let i=0;i<3;i++){const i=yield e.getNextBestRegionUrl();if(!i)break;if(n.has(i))continue;n.add(i);const s=yield this.checkCloudRegion(i);this.appendMessage("".concat(s.region," RTT: ").concat(s.rtt,"ms, duration: ").concat(s.duration,"ms")),t.push(s)}t.sort(((e,t)=>.5*(e.duration-t.duration)+.5*(e.rtt-t.rtt)));const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return Ai(this,void 0,void 0,(function*(){var t,n;yield this.connect(e),"tcp"===this.options.protocol&&(yield this.switchProtocol("tcp"));const i=null===(t=this.room.serverInfo)||void 0===t?void 0:t.region;if(!i)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),o="A".repeat(1e3),r=Date.now();for(let e=0;e<1e3;e++)yield s.write(o);yield s.close();const a=Date.now(),c=yield null===(n=this.room.engine.pcManager)||void 0===n?void 0:n.publisher.getStats(),d={region:i,rtt:1e4,duration:a-r};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const zc=1e4;class Qc extends Gc{get description(){return"Connection via UDP vs TCP"}perform(){return Ai(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/10*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/10*100).toFixed(2),"%"))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return Ai(this,void 0,void 0,(function*(){yield this.connect(),"tcp"===e?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 i=0;const s=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],r=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,a={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},c=setInterval((()=>Ai(this,void 0,void 0,(function*(){const e=yield r.getRTCStatsReport();null==e||e.forEach((e=>{"outbound-rtp"===e.type?(a.packetsSent=e.packetsSent,a.qualityLimitationDurations=e.qualityLimitationDurations,a.bitrateTotal+=e.targetBitrate,a.count++):"remote-inbound-rtp"===e.type&&(a.packetsLost=e.packetsLost,a.rttTotal+=e.roundTripTime,a.jitterTotal+=e.jitter)}))}))),1e3);return yield new Promise((e=>setTimeout(e,zc))),clearInterval(c),o.stop(),t.remove(),yield this.disconnect(),a}))}}class Yc extends Gc{get description(){return"Can publish audio"}perform(){return Ai(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Lc();if(yield Vr(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let s=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(s=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))}))}}class Xc extends Gc{get description(){return"Can publish video"}perform(){return Ai(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Nc();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,5e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let s=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(s+=e.packetsSent)})),0===s)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))}))}checkForVideo(e){return Ai(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((t=>{n.onplay=()=>{setTimeout((()=>{var i,s,o,r;const a=document.createElement("canvas"),c=e.getSettings(),d=null!==(s=null!==(i=c.width)&&void 0!==i?i:n.videoWidth)&&void 0!==s?s:1280,l=null!==(r=null!==(o=c.height)&&void 0!==o?o:n.videoHeight)&&void 0!==r?r:720;a.width=d,a.height=l;const u=a.getContext("2d");u.drawImage(n,0,0);const h=u.getImageData(0,0,a.width,a.height).data;let p=!0;for(let e=0;e<h.length;e+=4)if(0!==h[e]||0!==h[e+1]||0!==h[e+2]){p=!1;break}p?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),t()}),1e3)},n.play()})),t.getTracks().forEach((e=>e.stop())),n.remove()}))}}class Zc extends Gc{get description(){return"Resuming connection after interruption"}perform(){return Ai(this,void 0,void 0,(function*(){var t;const n=yield this.connect();let i,s=!1,o=!1;const r=new Promise((e=>{setTimeout(e,5e3),i=e})),a=()=>{s=!0};n.on(e.RoomEvent.SignalReconnecting,a).on(e.RoomEvent.Reconnecting,a).on(e.RoomEvent.Reconnected,(()=>{o=!0,i(!0)})),null===(t=n.engine.client.ws)||void 0===t||t.close();const c=n.engine.client.onClose;if(c&&c(""),yield r,!s)throw new Error("Did not attempt to reconnect");if(!o||n.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class $c extends Gc{get description(){return"Can connect via TURN"}perform(){return Ai(this,void 0,void 0,(function*(){var e,t;const n=new oa,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,o=!1,r=!1;for(let e of i.iceServers)for(let t of e.urls)t.startsWith("turn:")?(o=!0,r=!0):t.startsWith("turns:")&&(o=!0,r=!0,s=!0),t.startsWith("stun:")&&(r=!0);r?o&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class ed extends Gc{get description(){return"Establishing WebRTC connection"}perform(){return Ai(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{const e=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,s)=>{if(i.candidate){const e=new RTCIceCandidate(i);let s="".concat(e.protocol," ").concat(e.address,":").concat(e.port," ").concat(e.type);e.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(e.address)?"tcp"===e.protocol&&"passive"===e.tcpType?(t=!0,s+=" (passive)"):"udp"===e.protocol&&(n=!0):s+=" (private)"),this.appendMessage(s)}e&&e(i,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),Pi.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class td extends Gc{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Ai(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 i=new oa;const s=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),(null===(e=s.serverInfo)||void 0===e?void 0:e.edition)===Nt.Cloud&&(null===(t=s.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=s.serverInfo)||void 0===n?void 0:n.region)),yield i.close()}))}}class nd extends Fi.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Ai(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=e=>{this.updateCheck(t,e)};n.on("update",i);const s=yield n.run();return n.off("update",i),s}))}checkWebsocket(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck(td)}))}checkWebRTC(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck(ed)}))}checkTURN(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck($c)}))}checkReconnect(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck(Zc)}))}checkPublishAudio(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck(Yc)}))}checkPublishVideo(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck(Xc)}))}checkConnectionProtocol(){return Ai(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(Qc);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return Ai(this,void 0,void 0,(function*(){return this.createAndRunCheck(Jc)}))}}class id{}class sd{}function od(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}new TextEncoder;const rd=new TextDecoder;function ad(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:rd.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=rd.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return function(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t)}catch(e){throw new TypeError("The input to be decoded is not correctly encoded.")}}class cd extends Error{constructor(e,t){var n;super(e,t),od(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}od(cd,"code","ERR_JOSE_GENERIC");od(class extends cd{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),od(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),od(this,"claim",void 0),od(this,"reason",void 0),od(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");od(class extends cd{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),od(this,"code","ERR_JWT_EXPIRED"),od(this,"claim",void 0),od(this,"reason",void 0),od(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");od(class extends cd{constructor(){super(...arguments),od(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");od(class extends cd{constructor(){super(...arguments),od(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");od(class extends cd{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),od(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");od(class extends cd{constructor(){super(...arguments),od(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");od(class extends cd{constructor(){super(...arguments),od(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class dd extends cd{constructor(){super(...arguments),od(this,"code","ERR_JWT_INVALID")}}od(dd,"code","ERR_JWT_INVALID");od(class extends cd{constructor(){super(...arguments),od(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");od(class extends cd{constructor(){super(...arguments),od(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");od(class extends cd{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),od(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");od(class extends cd{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),od(this,Symbol.asyncIterator,void 0),od(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");od(class extends cd{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),od(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");od(class extends cd{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),od(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var ld=e=>{if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n};function ud(e){const t=function(e){if("string"!=typeof e)throw new dd("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:n}=e.split(".");if(5===n)throw new dd("Only JWTs using Compact JWS serialization can be decoded");if(3!==n)throw new dd("Invalid JWT");if(!t)throw new dd("JWTs must contain a payload");let i,s;try{i=ad(t)}catch(e){throw new dd("Failed to base64url decode the payload")}try{s=JSON.parse(rd.decode(i))}catch(e){throw new dd("Failed to parse the decoded payload as JSON")}if(!ld(s))throw new dd("Invalid JWT Claims Set");return s}(e),{roomConfig:n}=t,i=xi(t,["roomConfig"]);return Object.assign(Object.assign({},i),{roomConfig:t.roomConfig?yn.fromJson(t.roomConfig):void 0})}class hd extends sd{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new s}isSameAsCachedFetchOptions(e){if(!this.cachedFetchOptions)return!1;for(const t of Object.keys(this.cachedFetchOptions))switch(t){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":if(this.cachedFetchOptions[t]!==e[t])return!1;break;default:throw new Error("Options key ".concat(t," not being checked for equality!"))}return!0}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!function(e){const t=ud(e.participantToken);if(!(null==t?void 0:t.exp))return!0;const n=1e3*t.exp;return new Date(n-6e4)>=new Date}(this.cachedResponse)&&!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?ud(this.cachedResponse.participantToken):null}fetch(e){return Ai(this,void 0,void 0,(function*(){const t=yield this.fetchMutex.lock();try{if(this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();this.cachedFetchOptions=e;const t=yield this.update(e);return this.cachedResponse=t,t.toJson()}finally{t()}}))}}class pd extends id{constructor(e){super(),this.literalOrFn=e}fetch(){return Ai(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class md extends hd{constructor(e){super(),this.customFn=e}update(e){return Ai(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,ki.fromJson(n,{ignoreUnknownFields:!0})}))}}class gd extends hd{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.url=e,this.endpointOptions=t}createRequestFromOptions(e){var t,n,i;const s=new fi;for(const o of Object.keys(e))switch(o){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":s[o]=e[o];break;case"participantAttributes":s.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":s.roomConfig=null!==(n=s.roomConfig)&&void 0!==n?n:new yn,0===s.roomConfig.agents.length&&s.roomConfig.agents.push(new Yt),s.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":s.roomConfig=null!==(i=s.roomConfig)&&void 0!==i?i:new yn,0===s.roomConfig.agents.length&&s.roomConfig.agents.push(new Yt),s.roomConfig.agents[0].metadata=e.agentMetadata;break;default:throw new Error("Options key ".concat(o," not being included in forming request!"))}return s}update(e){return Ai(this,void 0,void 0,(function*(){var t;const n=this.createRequestFromOptions(e),i=yield fetch(this.url,Object.assign(Object.assign({},this.endpointOptions),{method:null!==(t=this.endpointOptions.method)&&void 0!==t?t:"POST",headers:Object.assign({"Content-Type":"application/json"},this.endpointOptions.headers),body:n.toJsonString({useProtoFieldName:!0})}));if(!i.ok)throw new Error("Error generating token from endpoint ".concat(this.url,": received ").concat(i.status," / ").concat(yield i.text()));const s=yield i.json();return ki.fromJson(s,{ignoreUnknownFields:!0})}))}}class vd extends gd{constructor(e,t){const{baseUrl:n="https://cloud-api.livekit.io"}=t,i=xi(t,["baseUrl"]);super("".concat(n,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},i),{headers:{"X-Sandbox-ID":e}}))}}const fd={literal:e=>new pd(e),custom:e=>new md(e),endpoint(e){return new gd(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new vd(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const kd=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),yd=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function bd(e){var t;const n=e.trim().toLowerCase();if(""!==n)return kd.has(n)?kd.get(n):null===(t=Array.from(yd.entries()).find((e=>{let[t]=e;return n.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=io,e.Checker=Gc,e.ConnectionCheck=nd,e.ConnectionError=mo,e.CriticalTimers=_o,e.CryptorError=class extends so{constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=n,this.participantIdentity=i}},e.DataPacket_Kind=yt,e.DataStreamError=Co,e.DefaultReconnectPolicy=Mi,e.DeviceUnsupportedError=go,e.DisconnectReason=nt,e.Encryption_Type=pt,e.ExternalE2EEKeyProvider=class extends io{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return Ai(this,void 0,void 0,(function*(){const t="string"==typeof e?yield $s(e):yield eo(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=so,e.LocalAudioTrack=Ja,e.LocalParticipant=jc,e.LocalTrack=Ga,e.LocalTrackPublication=xc,e.LocalTrackRecorder=Ha,e.LocalVideoTrack=rc,e.Mutex=s,e.NegotiationError=yo,e.Participant=Uc,e.ParticipantKind=ut,e.PublishDataError=class extends so{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}},e.PublishTrackError=bo,e.RemoteAudioTrack=Rc,e.RemoteParticipant=Bc,e.RemoteTrack=Pc,e.RemoteTrackPublication=Fc,e.RemoteVideoTrack=Ic,e.Room=qc,e.RpcError=ja,e.ScreenSharePresets=Wo,e.SignalRequestError=To,e.SubscriptionError=st,e.TokenSource=fd,e.TokenSourceConfigurable=sd,e.TokenSourceCustom=md,e.TokenSourceEndpoint=gd,e.TokenSourceFixed=id,e.TokenSourceLiteral=pd,e.TokenSourceSandboxTokenServer=vd,e.Track=Mo,e.TrackInvalidError=vo,e.TrackPublication=Mc,e.TrackType=Xe,e.UnexpectedConnectionState=ko,e.UnsupportedServer=fo,e.VideoPreset=No,e.VideoPresets=qo,e.VideoPresets43=Ko,e.asEncryptablePacket=no,e.attachToElement=xo,e.attributes=Hc,e.audioCodecs=Lo,e.compareVersions=ur,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=qr();if(!i)throw new Error("Audio Context not supported on this browser");const s=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,o=i.createMediaStreamSource(new MediaStream([s])),r=i.createAnalyser();r.minDecibels=n.minDecibels,r.maxDecibels=n.maxDecibels,r.fftSize=n.fftSize,r.smoothingTimeConstant=n.smoothingTimeConstant,o.connect(r);const a=new Uint8Array(r.frequencyBinCount);return{calculateVolume:()=>{r.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:r,cleanup:()=>Ai(this,void 0,void 0,(function*(){yield i.close(),n.cloneTrack&&s.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=eo,e.createKeyMaterialFromString=$s,e.createLocalAudioTrack=Lc,e.createLocalScreenTracks=function(e){return Ai(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||ir()||(e.resolution=Wo.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new go("getDisplayMedia not supported");const t=Hr(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new vo("no video track found");const s=new rc(i[0],void 0,!1);s.source=Mo.Source.ScreenShare;const o=[s];if(n.getAudioTracks().length>0){const e=new Ja(n.getAudioTracks()[0],void 0,!1);e.source=Mo.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=Ac,e.createLocalVideoTrack=Nc,e.deriveKeys=function(e,t){return Ai(this,void 0,void 0,(function*(){const n=to(e.algorithm.name,t),i=yield crypto.subtle.deriveKey(n,e,{name:Hs,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Ao,e.facingModeFromDeviceLabel=bd,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=Or(e)?e.mediaStreamTrack:e,s=i.getSettings();let o={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in s){const e=s.facingMode;Pi.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(o={facingMode:e,confidence:"high"})}if(["low","medium"].includes(o.confidence)){Pi.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=bd(i.label);void 0!==e&&(o=e)}return o},e.getBrowser=wo,e.getEmptyAudioStreamTrack=Tr,e.getEmptyVideoStreamTrack=function(){return kr||(kr=br()),kr.clone()},e.getLogger=Ii,e.importKey=function(e){return Ai(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:Hs},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isAudioCodec=function(e){return Lo.includes(e)},e.isAudioTrack=_r,e.isBackupCodec=Bo,e.isBackupVideoCodec=Fo,e.isBrowserSupported=$o,e.isE2EESupported=Ys,e.isInsertableStreamSupported=Zs,e.isLocalParticipant=Ur,e.isLocalTrack=Or,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=Ar,e.isScriptTransformSupported=Xs,e.isVideoCodec=Sr,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=Dr,e.needsRbspUnescaping=function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1},e.parseRbsp=function(e){const t=[];for(var n=e.length,i=0;i<e.length;)n-i>=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)},e.protocolVersion=16,e.ratchet=function(e,t){return Ai(this,void 0,void 0,(function*(){const n=to(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.setLogExtension=function(t,n){(n?[n]:Ri).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,s,o)=>{const r=i(n,s,o),a=e.LogLevel[n],c=a>=s&&a<e.LogLevel.silent;return(e,n)=>{n?r(e,n):r(e),c&&t(a,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){if(t)wi.getLogger(t).setLevel(e);else for(const t of Ri)t.setLevel(e)},e.supportsAV1=Qo,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsDynacast=function(){return Jo()},e.supportsVP9=Yo,e.version=Oo,e.videoCodecs=jo,e.writeRbsp=function(e){const t=[];for(var n=0,i=0;i<e.length;++i){var s=e[i];s<=3&&n>=2&&(t.push(3),n=0),t.push(s),0==s?++n:n=0}return new Uint8Array(t)}}));
2
2
  //# sourceMappingURL=livekit-client.umd.js.map