livekit-client 2.24.0 → 2.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -4
- package/dist/core/api/SignalClient.mjs +3 -1
- package/dist/core/api/SignalClient.mjs.map +1 -1
- package/dist/core/e2ee/E2eeManager.mjs +7 -10
- package/dist/core/e2ee/E2eeManager.mjs.map +1 -1
- package/dist/core/package.json.mjs +1 -1
- package/dist/core/room/rpc/client/RpcClientManager.mjs +18 -0
- package/dist/core/room/rpc/client/RpcClientManager.mjs.map +1 -1
- package/dist/core/room/rpc/extension.mjs +1 -0
- package/dist/core/room/rpc/extension.mjs.map +1 -1
- package/dist/core/room/rpc/utils.mjs +2 -0
- package/dist/core/room/rpc/utils.mjs.map +1 -1
- package/dist/core/room/utils.mjs +4 -1
- package/dist/core/room/utils.mjs.map +1 -1
- package/dist/core/ts4.2/e2ee/E2eeManager.d.ts +1 -0
- package/dist/core/ts4.2/room/rpc/extension.d.ts +3 -3
- package/dist/core/ts4.2/room/rpc/utils.d.ts +1 -0
- package/dist/core/types/src/e2ee/E2eeManager.d.ts +1 -0
- package/dist/core/types/src/room/rpc/extension.d.ts +3 -3
- package/dist/core/types/src/room/rpc/utils.d.ts +1 -0
- package/dist/livekit-client.e2ee.worker.js +1 -1
- package/dist/livekit-client.e2ee.worker.js.map +1 -1
- package/dist/livekit-client.e2ee.worker.mjs +6 -3
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
- package/dist/livekit-client.esm.mjs +48 -21
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.fm.worker.js.map +1 -1
- package/dist/livekit-client.fm.worker.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/api/SignalClient.d.ts.map +1 -1
- package/dist/src/e2ee/E2eeManager.d.ts +1 -0
- package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
- package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
- package/dist/src/room/rpc/client/RpcClientManager.d.ts +5 -0
- package/dist/src/room/rpc/client/RpcClientManager.d.ts.map +1 -1
- package/dist/src/room/rpc/extension.d.ts +3 -3
- package/dist/src/room/rpc/extension.d.ts.map +1 -1
- package/dist/src/room/rpc/legacyExtension.d.ts +1 -1
- package/dist/src/room/rpc/utils.d.ts +1 -0
- package/dist/src/room/rpc/utils.d.ts.map +1 -1
- package/dist/src/room/utils.d.ts.map +1 -1
- package/dist/ts4.2/e2ee/E2eeManager.d.ts +1 -0
- package/dist/ts4.2/room/rpc/client/RpcClientManager.d.ts +5 -0
- package/dist/ts4.2/room/rpc/extension.d.ts +3 -3
- package/dist/ts4.2/room/rpc/legacyExtension.d.ts +1 -1
- package/dist/ts4.2/room/rpc/utils.d.ts +1 -0
- package/package.json +1 -1
- package/src/api/SignalClient.test.ts +43 -0
- package/src/api/SignalClient.ts +6 -1
- package/src/e2ee/E2eeManager.test.ts +86 -2
- package/src/e2ee/E2eeManager.ts +11 -9
- package/src/e2ee/worker/FrameCryptor.test.ts +26 -0
- package/src/e2ee/worker/FrameCryptor.ts +7 -4
- package/src/room/Room.test.ts +24 -0
- package/src/room/rpc/client/RpcClientManager.test.ts +29 -0
- package/src/room/rpc/client/RpcClientManager.ts +17 -0
- package/src/room/rpc/extension.ts +4 -1
- package/src/room/rpc/utils.ts +2 -0
- package/src/room/utils.test.ts +36 -1
- package/src/room/utils.ts +11 -1
|
@@ -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(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)}let n=!0,i=!0;function r(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function o(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void c("Unable to polyfill events");const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.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),r.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 s(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(n=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function a(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(i=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function c(){if("object"==typeof window){if(n)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function d(e,t){i&&console.warn(e+" is deprecated, please use "+t+" instead.")}function l(e){return"[object Object]"===Object.prototype.toString.call(e)}function u(e){return l(e)?Object.keys(e).reduce((function(t,n){const i=l(e[n]),r=i?u(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})}),{}):e}function h(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?h(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{h(e,e.get(t),n)}))})))}function p(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;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&&h(e,n,r)}))})),r}const m=c;function g(e,t){if(t.version>=64)return;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 r=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[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(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 s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){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 s=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&n.length&&t.includes("back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),m("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return m("chrome: "+JSON.stringify(e)),r(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){r(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 r(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 f(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function v(e,t){if(!(t.version>102))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 r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),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 r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else o(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function k(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 r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};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 y(e,t){if(t.version>=67)return;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=>p(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}),o(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>p(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const n=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 n.apply(this,arguments)}}function b(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 r=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]})),r.apply(this,arguments)}}function T(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return b(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 r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.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||{},r.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 r=this._streams[n.id];if(r)r.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 s=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],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.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 S(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 E(e,t){t.version>102||o(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var C=Object.freeze({__proto__:null,fixNegotiationNeeded:E,shimAddTrackRemoveTrack:T,shimAddTrackRemoveTrackWithNative:b,shimGetSendersWithDtmf:k,shimGetUserMedia:g,shimMediaStream:f,shimOnTrack:v,shimPeerConnection:S,shimSenderReceiverGetStats:y});function w(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){d("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 R(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 P(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!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]})))}function I(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;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=Array.prototype.slice.call(arguments),r=e[0],o=e[1],s=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):i.apply(this,[r||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(ke){if("TypeError"!==ke.name)throw ke;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(o,s)}}function _(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 O(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}),o(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function D(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){d("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function M(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function A(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const t=e.length>0;t&&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=n.apply(this,arguments);if(t){const t=i.sender,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 L(e,t){if("object"!=typeof e||!e.RTCRtpSender)return;if(t.version>=110)return;const n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){const e=n.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function N(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}function x(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}var U=Object.freeze({__proto__:null,shimAddTransceiver:A,shimCreateAnswer:x,shimCreateOffer:N,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in 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:L,shimGetStats:I,shimGetUserMedia:w,shimOnTrack:R,shimPeerConnection:P,shimRTCDataChannel:M,shimReceiverGetStats:O,shimRemoveStream:D,shimSenderGetStats:_});function F(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),r=1;r<n;r++)i[r-1]=arguments[r];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 j(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 B(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,n){const i=r.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=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function q(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(V(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function V(e){return e&&void 0!==e.video?Object.assign({},e,{video:u(e.video)}):e}function W(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?(d("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 H(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 K(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 z(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var G=Object.freeze({__proto__:null,shimAudioContext:z,shimCallbacksAPI:B,shimConstraints:V,shimCreateOfferLegacy:K,shimGetUserMedia:q,shimLocalStreamsAPI:F,shimRTCIceServerUrls:W,shimRemoteStreamsAPI:j,shimTrackEventTransceiver:H});function J(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Q,Y={exports:{}};var X=(Q||(Q=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 i=8;i<t.length;i+=2)switch(t[i]){case"raddr":n.relatedAddress=t[i+1];break;case"rport":n.relatedPort=parseInt(t[i+1],10);break;case"tcptype":n.tcpType=t[i+1];break;case"ufrag":n.ufrag=t[i+1],n.usernameFragment=t[i+1];break;default:void 0===n[t[i]]&&(n[t[i]]=t[i+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&&void 0!==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 r=0;r<i.length;r++)n=i[r].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],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.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 o=3;o<i.length;o++){const r=i[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const i=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(i.parameters=o.length?t.parseFmtp(o[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").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 r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.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 r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[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),r&&(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 r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.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 r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[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 r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=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:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},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 r;const o=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+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 t=0;t<i.length;t++)switch(i[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[t].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 t=0;t<n.length;t++)if(n[t].length<2||"="!==n[t].charAt(1))return!1;return!0},e.exports=t}(Y)),Y.exports),Z=J(X),$=t({__proto__:null,default:Z},[X]);function ee(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=Z.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,o(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function te(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||o(e,"icecandidate",(e=>{if(e.candidate){const t=Z.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ne(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>102)return;if("firefox"===t.browser&&t.version>=113)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){"plan-b"===this.getConfiguration().sdpSemantics&&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=Z.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Z.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 r=Z.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let r;r=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:()=>r}),this._sctp=o}return n.apply(this,arguments)}}function ie(e,t){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;if("chrome"===t.browser&&t.version>=149)return;if("firefox"===t.browser&&t.version>60)return;function n(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return n(e,this),e},o(e,"datachannel",(e=>(n(e.channel,e.target),e)))}function re(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 oe(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 se(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 ae(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 ce=Object.freeze({__proto__:null,removeExtmapAllowMixed:oe,shimAddIceCandidateNullOrEmpty:se,shimConnectionState:re,shimMaxMessageSize:ne,shimParameterlessSetLocalDescription:ae,shimRTCIceCandidate:ee,shimRTCIceCandidateRelayProtocol:te,shimSendThrowTypeError:ie});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=c,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 n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e){const t=parseInt(e.version,10);if(t>=90)return{browser:"chrome",version:t}}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(r(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(r(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(r(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=r(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),o={browserDetails:i,commonShim:ce,extractVersion:r,disableLog:s,disableWarnings:a,sdp:$};switch(i.browser){case"chrome":if(!C||!S||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),o;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),o;n("adapter.js shimming chrome."),o.browserShim=C,se(e,i),ae(e),g(e,i),f(e),S(e,i),v(e,i),T(e,i),k(e),y(e,i),E(e,i),ee(e),te(e),re(e),ne(e,i),ie(e,i),oe(e,i);break;case"firefox":if(!U||!P||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),o;n("adapter.js shimming firefox."),o.browserShim=U,se(e,i),ae(e),w(e,i),P(e,i),I(e,i),R(e),D(e),_(e),O(e),M(e),A(e,i),L(e,i),N(e,i),x(e,i),ee(e),re(e),ne(e,i),ie(e,i);break;case"safari":if(!G||!t.shimSafari)return n("Safari shim is not included in this adapter release."),o;n("adapter.js shimming safari."),o.browserShim=G,se(e,i),ae(e),W(e),K(e),B(e),F(e),j(e),H(e),q(e),z(e),ee(e),te(e),ne(e,i),ie(e,i),oe(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class de{constructor(e,t,n,i,r){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:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const le=["opus","red"],ue=["vp8","h264"],he=["vp8","h264","vp9","av1","h265"];function pe(e){return!!ue.find((t=>t===e))}var me;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,(me=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},me.speech={maxBitrate:24e3},me.music={maxBitrate:48e3},me.musicStereo={maxBitrate:64e3},me.musicHighQuality={maxBitrate:96e3},me.musicHighQualityStereo={maxBitrate:128e3};const ge={h90:new de(160,90,9e4,20),h180:new de(320,180,16e4,20),h216:new de(384,216,18e4,20),h360:new de(640,360,45e4,20),h540:new de(960,540,8e5,25),h720:new de(1280,720,17e5,30),h1080:new de(1920,1080,3e6,30),h1440:new de(2560,1440,5e6,30),h2160:new de(3840,2160,8e6,30)},fe={h120:new de(160,120,7e4,20),h180:new de(240,180,125e3,20),h240:new de(320,240,14e4,20),h360:new de(480,360,33e4,20),h480:new de(640,480,5e5,20),h540:new de(720,540,6e5,25),h720:new de(960,720,13e5,30),h1080:new de(1440,1080,23e5,30),h1440:new de(1920,1440,38e5,30)},ve={h360fps3:new de(640,360,2e5,3,"medium"),h360fps15:new de(640,360,4e5,15,"medium"),h720fps5:new de(1280,720,8e5,5,"medium"),h720fps15:new de(1280,720,15e5,15,"medium"),h720fps30:new de(1280,720,2e6,30,"medium"),h1080fps15:new de(1920,1080,25e5,15,"medium"),h1080fps30:new de(1920,1080,5e6,30,"medium"),original:new de(0,0,7e6,30,"medium")};var ke=Object.defineProperty,ye=(e,t,n)=>((e,t,n)=>t in e?ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class be{constructor(){ye(this,"_locking"),ye(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 Te(e,t){if(!e)throw new Error(t)}function Se(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ee(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Ce(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const we=Symbol("@bufbuild/protobuf/enum-type");function Re(e){const t=e[we];return Te(t,"missing enum type on enum object"),t}function Pe(e,t,n,i){e[we]=Ie(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function Ie(e,t,n){const i=Object.create(null),r=Object.create(null),o=[];for(const s of t){const e=Oe(s);o.push(e),i[s.name]=e,r[s.no]=e}return{typeName:e,values:o,findName:e=>i[e],findNumber:e=>r[e]}}function _e(e,t,n){const i={};for(const r of t){const e=Oe(r);i[e.localName]=e.no,i[e.no]=e.localName}return Pe(i,e,t),i}function Oe(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class De{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,r=i.makeReadOptions(t);return i.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(ke){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(ke instanceof Error?ke.message:String(ke)))}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 Me(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Ae(e,t,n){for(let o=0;o<28;o+=7){const i=e>>>o,r=!(i>>>7==0&&0==t),s=255&(r?128|i:i);if(n.push(s),!r)return}const i=e>>>28&15|(7&t)<<4,r=!!(t>>3);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),o=255&(r?128|i:i);if(n.push(o),!r)return}n.push(t>>>31&1)}}const Le=4294967296;function Ne(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function o(t,o){const s=Number(e.slice(t,o));r*=n,i=i*n+s,i>=Le&&(r+=i/Le|0,i%=Le)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?Fe(i,r):Ue(i,r)}function xe(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(Le*t+e);const i=16777215&(e>>>24|t<<8),r=t>>16&65535;let o=(16777215&e)+6777216*i+6710656*r,s=i+8147497*r,a=2*r;const c=1e7;return o>=c&&(s+=Math.floor(o/c),o%=c),s>=c&&(a+=Math.floor(s/c),s%=c),a.toString()+je(s)+je(o)}function Ue(e,t){return{lo:0|e,hi:0|t}}function Fe(e,t){return t=~t,e?e=1+~e:t+=1,Ue(e,t)}const je=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Be(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 qe(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let n=5;128&e&&n<10;n++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Ve=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"),r=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>r||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=>Te(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>Te(/^[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),Ne(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),Ne(e)),dec:(e,t)=>function(e,t){let n=Ue(e,t);const i=2147483648&n.hi;i&&(n=Fe(n.lo,n.hi));const r=xe(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>xe(e,t)}}();var We,He,Ke;function ze(e,t,n){if(t===n)return!0;if(e==We.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 We.UINT64:case We.FIXED64:case We.INT64:case We.SFIXED64:case We.SINT64:return t==n}return!1}function Ge(e,t){switch(e){case We.BOOL:return!1;case We.UINT64:case We.FIXED64:case We.INT64:case We.SFIXED64:case We.SINT64:return 0==t?Ve.zero:"0";case We.DOUBLE:case We.FLOAT:return 0;case We.BYTES:return new Uint8Array(0);case We.STRING:return"";default:return 0}}function Je(e,t){switch(e){case We.BOOL:return!1===t;case We.STRING:return""===t;case We.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function Qe(e,t){this.v=e,this.k=t}function Ye(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Xe(e){if(Array.isArray(e))return e}function Ze(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}function $e(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function et(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function tt(e,t){return Xe(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||it(e,t)||$e()}function nt(e){return Xe(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||it(e)||$e()}function it(e,t){if(e){if("string"==typeof e)return Ye(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ye(e,t):void 0}}function rt(e){var t,n;function i(t,n){try{var o=e[t](n),s=o.value,a=s instanceof Qe;Promise.resolve(a?s.v:s).then((function(n){if(a){var c="return"===t&&s.k?t:"next";if(!s.k||n.done)return i(c,n);n=e[c](n).value}r(!!o.done,n)}),(function(e){i("throw",e)}))}catch(e){r(2,e)}}function r(e,r){2===e?t.reject(r):t.resolve({value:r,done:e}),(t=t.next)?i(t.key,t.arg):n=null}this._invoke=function(e,r){return new Promise((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};n?n=n.next=a:(t=n=a,i(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}!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"}(We||(We={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(He||(He={})),rt.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},rt.prototype.next=function(e){return this._invoke("next",e)},rt.prototype.throw=function(e){return this._invoke("throw",e)},rt.prototype.return=function(e){return this._invoke("return",e)},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"}(Ke||(Ke={}));class ot{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],n),n+=this.chunks[i].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(Ee(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Se(e),Be(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){Ce(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){Ee(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Se(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Se(e),Be(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=Ve.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=Ve.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=Ve.enc(e);return Ae(t.lo,t.hi,this.buf),this}sint64(e){let t=Ve.enc(e),n=t.hi>>31;return Ae(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Ve.uEnc(e);return Ae(t.lo,t.hi,this.buf),this}}class st{constructor(e,t){this.varint64=Me,this.uint32=qe,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 Ke.Varint:for(;128&this.buf[this.pos++];);break;case Ke.Bit64:this.pos+=4;case Ke.Bit32:this.pos+=4;break;case Ke.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Ke.StartGroup:for(;;){const e=tt(this.tag(),2),n=e[0],i=e[1];if(i===Ke.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(i,n)}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 Ve.dec(...this.varint64())}uint64(){return Ve.uDec(...this.varint64())}sint64(){let e=tt(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,Ve.dec(t,n)}bool(){let e=tt(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Ve.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ve.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 at(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 Ge(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 ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),dt=[];for(let Hp=0;Hp<ct.length;Hp++)dt[ct[Hp].charCodeAt(0)]=Hp;dt["-".charCodeAt(0)]=ct.indexOf("+"),dt["_".charCodeAt(0)]=ct.indexOf("/");const lt={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),r=0,o=0,s=0;for(let a=0;a<e.length;a++){if(n=dt[e.charCodeAt(a)],void 0===n)switch(e[a]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:s=n,o=1;break;case 1:i[r++]=s<<2|(48&n)>>4,s=n,o=2;break;case 2:i[r++]=(15&s)<<4|(60&n)>>2,s=n,o=3;break;case 3:i[r++]=(3&s)<<6|n,o=0}}if(1==o)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let o=0;o<e.length;o++)switch(t=e[o],i){case 0:n+=ct[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=ct[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=ct[r|t>>6],n+=ct[63&t],i=0}return i&&(n+=ct[r],n+="=",1==i&&(n+="=")),n}};function ut(e,t,n){mt(t,e);const i=t.runtime.bin.makeReadOptions(n),r=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=tt(at(t),2),s=o[0],a=o[1];for(const c of r)t.runtime.bin.readField(s,i.readerFactory(c.data),t.field,c.wireType,i);return a()}function ht(e,t,n,i){mt(t,e);const r=t.runtime.bin.makeReadOptions(i),o=t.runtime.bin.makeWriteOptions(i);if(pt(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 s=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,s,o);const c=r.readerFactory(s.finish());for(;c.pos<c.len;){const t=tt(c.tag(),2),n=t[0],i=t[1],r=c.skip(i,n);e.getType().runtime.bin.onUnknownField(e,n,i,r)}}function pt(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 mt(e,t){Te(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function gt(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:!Je(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ft(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?Ge(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function vt(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(De.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 kt(e,t){return vt(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}We.DOUBLE,We.FLOAT,We.INT64,We.UINT64,We.INT32,We.UINT32,We.BOOL,We.STRING,We.BYTES;const yt={ignoreUnknownFields:!1},bt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Tt(e){return e?Object.assign(Object.assign({},yt),e):yt}function St(e){return e?Object.assign(Object.assign({},bt),e):bt}const Et=Symbol(),Ct=Symbol();function wt(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 Rt(e,t,n,i,r){let o=n.localName;if(n.repeated){if(Te("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t)));const s=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e)));switch(n.kind){case"message":s.push(n.T.fromJson(e,i));break;case"enum":const t=_t(n.T,e,i.ignoreUnknownFields,!0);t!==Ct&&s.push(t);break;case"scalar":try{s.push(It(n.T,e,n.L,!0))}catch(ke){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.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(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t)));const a=e[o];for(const e of Object.entries(t)){var s=tt(e,2);const o=s[0],c=s[1];if(null===c)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=Pt(n.K,o)}catch(ke){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.message)),new Error(i)}switch(n.V.kind){case"message":a[d]=n.V.T.fromJson(c,i);break;case"enum":const e=_t(n.V.T,c,i.ignoreUnknownFields,!0);e!==Ct&&(a[d]=e);break;case"scalar":try{a[d]=It(n.V.T,c,He.BIGINT,!0)}catch(ke){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:o},o="value"),n.kind){case"message":const s=n.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let a=e[o];vt(a)?a.fromJson(t,i):(e[o]=a=s.fromJson(t,i),s.fieldWrapper&&!n.oneof&&(e[o]=s.fieldWrapper.unwrapField(a)));break;case"enum":const c=_t(n.T,t,i.ignoreUnknownFields,!1);switch(c){case Et:ft(n,e);break;case Ct:break;default:e[o]=c}break;case"scalar":try{const i=It(n.T,t,n.L,!1);if(i===Et)ft(n,e);else e[o]=i}catch(ke){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.message)),new Error(i)}}}function Pt(e,t){if(e===We.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return It(e,t,He.BIGINT,!0).toString()}function It(e,t,n,i){if(null===t)return i?Ge(e,n):Et;switch(e){case We.DOUBLE:case We.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==We.FLOAT&&Ce(i),i;case We.INT32:case We.FIXED32:case We.SFIXED32:case We.SINT32:case We.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==We.UINT32||e==We.FIXED32?Ee(r):Se(r),r;case We.INT64:case We.SFIXED64:case We.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=Ve.parse(t);return n?o.toString():o;case We.FIXED64:case We.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=Ve.uParse(t);return n?s.toString():s;case We.BOOL:if("boolean"!=typeof t)break;return t;case We.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(ke){throw new Error("invalid UTF8")}return t;case We.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return lt.dec(t)}throw new Error}function _t(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:Et;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 Ct}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(wt(t)))}function Ot(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Dt(e,t,n){if("map"==e.kind){Te("object"==typeof t&&null!=t);const s={},a=Object.entries(t);switch(e.V.kind){case"scalar":for(const n of a){var i=tt(n,2);const t=i[0],r=i[1];s[t.toString()]=At(e.V.T,r)}break;case"message":for(const e of a){var r=tt(e,2);const t=r[0],i=r[1];s[t.toString()]=i.toJson(n)}break;case"enum":const t=e.V.T;for(const e of a){var o=tt(e,2);const i=o[0],r=o[1];s[i.toString()]=Mt(t,r,n.enumAsInteger)}}return n.emitDefaultValues||a.length>0?s:void 0}if(e.repeated){Te(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(At(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(Mt(e.T,t[r],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 At(e.T,t);case"enum":return Mt(e.T,t,n.enumAsInteger);case"message":return kt(e.T,t).toJson(n)}}function Mt(e,t,n){var i;if(Te("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function At(e,t){switch(e){case We.INT32:case We.SFIXED32:case We.SINT32:case We.FIXED32:case We.UINT32:return Te("number"==typeof t),t;case We.FLOAT:case We.DOUBLE:return Te("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case We.STRING:return Te("string"==typeof t),t;case We.BOOL:return Te("boolean"==typeof t),t;case We.UINT64:case We.FIXED64:case We.INT64:case We.SFIXED64:case We.SINT64:return Te("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case We.BYTES:return Te(t instanceof Uint8Array),lt.enc(t)}}const Lt=Symbol("@bufbuild/protobuf/unknown-fields"),Nt={readUnknownFields:!0,readerFactory:e=>new st(e)},xt={writeUnknownFields:!0,writerFactory:()=>new ot};function Ut(e){return e?Object.assign(Object.assign({},Nt),e):Nt}function Ft(e){return e?Object.assign(Object.assign({},xt),e):xt}function jt(e,t,n,i,r){let o=n.repeated,s=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),n.kind){case"scalar":case"enum":const a="enum"==n.kind?We.INT32:n.T;let c=Vt;if("scalar"==n.kind&&n.L>0&&(c=qt),o){let n=e[s];if(i==Ke.LengthDelimited&&a!=We.STRING&&a!=We.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,a))}else n.push(c(t,a))}else e[s]=c(t,a);break;case"message":const d=n.T;o?e[s].push(Bt(t,new d,r,n)):vt(e[s])?Bt(t,e[s],r,n):(e[s]=Bt(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[s]=d.fieldWrapper.unwrapField(e[s])));break;case"map":let l=function(e,t,n){const i=t.uint32(),r=t.pos+i;let o,s;for(;t.pos<r;){switch(tt(t.tag(),1)[0]){case 1:o=Vt(t,e.K);break;case 2:switch(e.V.kind){case"scalar":s=Vt(t,e.V.T);break;case"enum":s=t.int32();break;case"message":s=Bt(t,new e.V.T,n,void 0)}}}void 0===o&&(o=Ge(e.K,He.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===s)switch(e.V.kind){case"scalar":s=Ge(e.V.T,He.BIGINT);break;case"enum":s=e.V.T.values[0].no;break;case"message":s=new e.V.T}return[o,s]}(n,t,r),u=tt(l,2),h=u[0],p=u[1];e[s][h]=p}}function Bt(e,t,n,i){const r=t.getType().runtime.bin,o=null==i?void 0:i.delimited;return r.readMessage(t,e,o?i.no:e.uint32(),n,o),t}function qt(e,t){const n=Vt(e,t);return"bigint"==typeof n?n.toString():n}function Vt(e,t){switch(t){case We.STRING:return e.string();case We.BOOL:return e.bool();case We.DOUBLE:return e.double();case We.FLOAT:return e.float();case We.INT32:return e.int32();case We.INT64:return e.int64();case We.UINT64:return e.uint64();case We.FIXED64:return e.fixed64();case We.BYTES:return e.bytes();case We.FIXED32:return e.fixed32();case We.SFIXED32:return e.sfixed32();case We.SFIXED64:return e.sfixed64();case We.SINT64:return e.sint64();case We.UINT32:return e.uint32();case We.SINT32:return e.sint32()}}function Wt(e,t,n,i){Te(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?We.INT32:e.T;if(r)if(Te(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,Ke.LengthDelimited).fork();let r=tt(Gt(t),2)[1];for(let o=0;o<i.length;o++)e[r](i[o]);e.join()}(n,s,e.no,t);else for(const i of t)zt(n,s,e.no,i);else zt(n,s,e.no,t);break;case"message":if(r){Te(Array.isArray(t));for(const r of t)Kt(n,i,e,r)}else Kt(n,i,e,t);break;case"map":Te("object"==typeof t&&null!=t);for(const r of Object.entries(t)){var o=tt(r,2);Ht(n,i,e,o[0],o[1])}}}function Ht(e,t,n,i,r){e.tag(n.no,Ke.LengthDelimited),e.fork();let o=i;switch(n.K){case We.INT32:case We.FIXED32:case We.UINT32:case We.SFIXED32:case We.SINT32:o=Number.parseInt(i);break;case We.BOOL:Te("true"==i||"false"==i),o="true"==i}switch(zt(e,n.K,1,o),n.V.kind){case"scalar":zt(e,n.V.T,2,r);break;case"enum":zt(e,We.INT32,2,r);break;case"message":Te(void 0!==r),e.tag(2,Ke.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Kt(e,t,n,i){const r=kt(n.T,i);n.delimited?e.tag(n.no,Ke.StartGroup).raw(r.toBinary(t)).tag(n.no,Ke.EndGroup):e.tag(n.no,Ke.LengthDelimited).bytes(r.toBinary(t))}function zt(e,t,n,i){Te(void 0!==i);let r=tt(Gt(t),2),o=r[0],s=r[1];e.tag(n,o)[s](i)}function Gt(e){let t=Ke.Varint;switch(e){case We.BYTES:case We.STRING:t=Ke.LengthDelimited;break;case We.DOUBLE:case We.FIXED64:case We.SFIXED64:t=Ke.Bit64;break;case We.FIXED32:case We.SFIXED32:case We.FLOAT:t=Ke.Bit32}return[t,We[e].toLowerCase()]}function Jt(e){if(void 0===e)return e;if(vt(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Qt(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Yt{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 Xt(e,t){const n=$t(e);return t?n:on(rn(n))}const Zt=$t;function $t(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}const en=new Set(["constructor","toString","toJSON","valueOf"]),tn=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),nn=e=>"".concat(e,"$"),rn=e=>tn.has(e)?nn(e):e,on=e=>en.has(e)?nn(e):e;class sn{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=Xt(e,!1)}addField(e){Te(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 an=(cn=e=>new Yt(e,(e=>function(e){var t,n,i,r,o,s;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Xt(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Zt(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(i=d.L)&&void 0!==i?i:He.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(o=d.req)&&void 0!==o&&o,e.opt=null!==(s=d.opt)&&void 0!==s&&s,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=We.BYTES&&d.T!=We.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new sn(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),dn=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]=Ge(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:Tt,makeWriteOptions:St,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(wt(t)));i=null!=i?i:new e;const r=new Map,o=n.typeRegistry;for(const a of Object.entries(t)){var s=tt(a,2);const t=s[0],c=s[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=r.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));r.set(d.oneof,t)}Rt(i,c,d,n,e)}else{let r=!1;if((null==o?void 0:o.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const s=o.findExtension(t.substring(1,t.length-1));if(s&&s.extendee.typeName==e.typeName){r=!0;const e=tt(at(s),2),t=e[0],o=e[1];Rt(t,c,s.field,n,s),ht(i,s,o(),n)}}if(!r&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!gt(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Ot(r))continue}const n=Dt(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const s=o.findExtensionFor(n.typeName,r.no);if(s&&pt(e,s)){const n=ut(e,s,t),r=Dt(s.field,n,t);void 0!==r&&(i[s.field.jsonName]=r)}}}catch(ke){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=ke instanceof Error?ke.message:String(ke);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>It(e,t,null!=n?n:He.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||Je(e,t)?At(e,t):void 0},debug:wt},bin:{makeReadOptions:Ut,makeWriteOptions:Ft,listUnknownFields(e){var t;return null!==(t=e[Lt])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Lt]},writeUnknownFields(e,t){const n=e[Lt];if(n)for(const i of n)t.tag(i.no,i.wireType).raw(i.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[Lt])||(r[Lt]=[]),r[Lt].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const o=e.getType(),s=r?t.len:t.pos+n;let a,c;for(;t.pos<s;){var d=tt(t.tag(),2);if(a=d[0],c=d[1],!0===r&&c==Ke.EndGroup)break;const n=o.fields.find(a);if(n)jt(e,t,n,c,i);else{const n=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,n)}}if(r&&(c!=Ke.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:jt,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(gt(r,e))Wt(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,n);else if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){void 0!==t&&Wt(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:Pe,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const r of n.fields.byMember()){const n=r.localName,o=t,s=e;if(null!=s[n])switch(r.kind){case"oneof":const e=s[n].case;if(void 0===e)continue;const t=r.findField(e);let a=s[n].value;t&&"message"==t.kind&&!vt(a,t.T)?a=new t.T(a):t&&"scalar"===t.kind&&t.T===We.BYTES&&(a=Qt(a)),o[n]={case:e,value:a};break;case"scalar":case"enum":let c=s[n];r.T===We.BYTES&&(c=r.repeated?c.map(Qt):Qt(c)),o[n]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===We.BYTES)for(const t of Object.entries(s[n])){var i=tt(t,2);const e=i[0],r=i[1];o[n][e]=Qt(r)}else Object.assign(o[n],s[n]);break;case"message":const e=r.V.T;for(const t of Object.keys(s[n])){let i=s[n][t];e.fieldWrapper||(i=new e(i)),o[n][t]=i}}break;case"message":const d=r.T;if(r.repeated)o[n]=s[n].map((e=>vt(e,d)?e:new d(e)));else{const e=s[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?o[n]=Qt(e):o[n]=e:o[n]=vt(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],r=n[e.localName];if(e.repeated){if(i.length!==r.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,r[n])));case"scalar":return i.every(((t,n)=>ze(e.T,t,r[n])));case"enum":return i.every(((e,t)=>ze(We.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=i,n=r;return e.T.fieldWrapper&&(void 0===t||vt(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||vt(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return ze(We.INT32,i,r);case"scalar":return ze(e.T,i,r);case"oneof":if(i.case!==r.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,r.value);case"enum":return ze(We.INT32,i.value,r.value);case"scalar":return ze(o.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const s=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return s.every((e=>t.equals(i[e],r[e])));case"enum":return s.every((e=>ze(We.INT32,i[e],r[e])));case"scalar":const n=e.V.T;return s.every((e=>ze(n,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const o of t.fields.byMember()){const t=e[o.localName];let n;if(o.repeated)n=t.map(Jt);else if("map"==o.kind){n=i[o.localName];for(const e of Object.entries(t)){var r=tt(e,2);const t=r[0],i=r[1];n[t]=Jt(i)}}else n="oneof"==o.kind?o.findField(t.case)?{case:t.case,value:Jt(t.value)}:{case:void 0}:Jt(t);i[o.localName]=n}for(const o of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,o.no,o.wireType,o.data);return n}}),{newFieldList:cn,initFields:dn}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const o=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),s={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(s.prototype,new De),Object.assign(s,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new s).fromBinary(e,t),fromJson:(e,t)=>(new s).fromJson(e,t),fromJsonString:(e,t)=>(new s).fromJsonString(e,t),equals:(t,n)=>e.util.equals(s,t,n)}),s}(this,e,t,n)},makeEnum:_e,makeEnumType:Ie,getEnumType:Re,makeExtension(e,t,n){return function(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),r=e.util.newFieldList([n]).list()[0]}return r},runtime:e}}(this,e,t,n)}});var cn,dn;class ln extends De{constructor(e){super(),this.seconds=Ve.zero,this.nanos=0,an.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(an.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=Ve.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 ln.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ln({seconds:Ve.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new ln).fromBinary(e,t)}static fromJson(e,t){return(new ln).fromJson(e,t)}static fromJsonString(e,t){return(new ln).fromJsonString(e,t)}static equals(e,t){return an.util.equals(ln,e,t)}}ln.runtime=an,ln.typeName="google.protobuf.Timestamp",ln.fields=an.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const un=an.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ln},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:hn,repeated:!0},{no:5,name:"events",kind:"message",T:mn,repeated:!0}])),hn=an.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:pn,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),pn=an.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ln},{no:3,name:"value",kind:"scalar",T:2}])),mn=an.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:ln},{no:7,name:"normalized_end_timestamp",kind:"message",T:ln,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),gn=an.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),fn=an.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"}]),vn=an.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),kn=an.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),yn=an.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),bn=an.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Tn=an.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Sn=an.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),En=an.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Cn=an.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"},{no:16,name:"AGENT_ERROR"}]),wn=an.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"}]),Rn=an.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Pn=an.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"}]),In=an.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),_n=an.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:On,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:bi}])),On=an.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),Dn=an.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:an.getEnumType(bn),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}])),Mn=an.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:an.getEnumType(An)},{no:4,name:"tracks",kind:"message",T:Fn,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:Dn},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:an.getEnumType(Ln)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:an.getEnumType(Cn)},{no:18,name:"kind_details",kind:"enum",T:an.getEnumType(Nn),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:jn,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:an.getEnumType(fi),repeated:!0}])),An=an.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ln=an.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),Nn=an.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),xn=an.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Un=an.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Jn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:an.getEnumType(Qn)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),Fn=an.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:an.getEnumType(yn)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:an.getEnumType(bn)},{no:10,name:"layers",kind:"message",T:Jn,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Un,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:an.getEnumType(xn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:bi},{no:19,name:"audio_features",kind:"enum",T:an.getEnumType(Pn),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:an.getEnumType(kn)},{no:21,name:"packet_trailer_features",kind:"enum",T:an.getEnumType(In),repeated:!0}])),jn=an.makeMessageType("livekit.DataTrackInfo",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:an.getEnumType(xn)},{no:5,name:"frame_encoding",kind:"message",T:Bn,opt:!0},{no:6,name:"schema",kind:"message",T:Hn,opt:!0}])),Bn=an.makeMessageType("livekit.DataTrackFrameEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:an.getEnumType(qn),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),qn=an.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),Vn=an.makeMessageType("livekit.DataTrackSchemaEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:an.getEnumType(Wn),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),Wn=an.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),Hn=an.makeMessageType("livekit.DataTrackSchemaId",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:Vn}])),Kn=an.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),zn=an.makeMessageType("livekit.DataBlobKey",(()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:Hn,oneof:"key"}])),Gn=an.makeMessageType("livekit.DataBlob",(()=>[{no:1,name:"key",kind:"message",T:zn},{no:2,name:"contents",kind:"scalar",T:12}])),Jn=an.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:an.getEnumType(Tn)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}])),Qn=an.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"}]),Yn=an.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:an.getEnumType(Xn)},{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:ni,oneof:"value"},{no:3,name:"speaker",kind:"message",T:ei,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ii,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ri,oneof:"value"},{no:8,name:"metrics",kind:"message",T:un,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:si,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:ai,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:ci,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:di,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:wi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ri,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Pi,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Zn,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),Xn=an.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Zn=an.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:an.getEnumType(xn)},{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}])),$n=an.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:ni,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:si,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:ai,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:ci,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:di,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:wi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ri,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Pi,oneof:"value"}])),ei=an.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ti,repeated:!0}])),ti=an.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}])),ni=an.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}])),ii=an.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),ri=an.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:oi,repeated:!0}])),oi=an.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),si=an.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}])),ai=an.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13},{no:6,name:"compressed_payload",kind:"scalar",T:12}])),ci=an.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),di=an.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:li,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),li=an.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}])),ui=an.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),hi=an.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:an.getEnumType(pi)},{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}])),pi=an.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),mi=an.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:an.getEnumType(gi)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:an.getEnumType(fi),repeated:!0}])),gi=an.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"},{no:15,name:"DOTNET"}]),fi=an.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),vi=an.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:ki},{no:2,name:"screen",kind:"message",T:ki},{no:3,name:"resume_connection",kind:"enum",T:an.getEnumType(En)},{no:4,name:"disabled_codecs",kind:"message",T:yi},{no:5,name:"force_relay",kind:"enum",T:an.getEnumType(En)}])),ki=an.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:an.getEnumType(En)}])),yi=an.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:On,repeated:!0},{no:2,name:"publish",kind:"message",T:On,repeated:!0}])),bi=an.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ti=an.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Si=an.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Ei=an.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:an.getEnumType(Ti)},{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"}),Ci=an.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),wi=an.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:an.getEnumType(xn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ei,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ci,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:an.getEnumType(Si)}]),{localName:"DataStream_Header"}),Ri=an.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"}),Pi=an.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"}),Ii=an.makeMessageType("livekit.FilterParams",(()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}])),_i=an.makeMessageType("livekit.WebhookConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:Ii}])),Oi=an.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Di=an.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),Mi=an.makeMessageType("livekit.RoomAgentDispatch",(()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9},{no:3,name:"restart_policy",kind:"enum",T:an.getEnumType(Di)},{no:4,name:"deployment",kind:"scalar",T:9},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Ai=an.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"},{no:8,name:"PASSTHROUGH"}]),Li=an.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),Ni=an.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),xi=an.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),Ui=an.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),Fi=an.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),ji=an.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),Bi=an.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:an.getEnumType(gn)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:an.getEnumType(fn)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5}])),qi=an.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:an.getEnumType(Ni)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),Vi=an.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:an.getEnumType(xi)},{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:an.getEnumType(Ui)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Hi,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:7,name:"azure",kind:"message",T:zi,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),Wi=an.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:an.getEnumType(Fi)},{no:6,name:"image_codec",kind:"enum",T:an.getEnumType(vn)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Hi,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:10,name:"azure",kind:"message",T:zi,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),Hi=an.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:Ji}])),Ki=an.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:Ji}])),zi=an.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}])),Gi=an.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}])),Ji=an.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}])),Qi=an.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:an.getEnumType(Ai),oneof:"options"},{no:2,name:"advanced",kind:"message",T:Bi,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Zi,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Vi,repeated:!0}])),Yi=an.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:Hi,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:4,name:"azure",kind:"message",T:zi,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),Xi=an.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:an.getEnumType(ji)},{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:Zi,oneof:"output"},{no:7,name:"stream",kind:"message",T:qi,oneof:"output"},{no:10,name:"segments",kind:"message",T:Vi,oneof:"output"},{no:8,name:"preset",kind:"enum",T:an.getEnumType(Ai),oneof:"options"},{no:9,name:"advanced",kind:"message",T:Bi,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Zi,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:qi,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Vi,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:Wi,repeated:!0},{no:16,name:"webhooks",kind:"message",T:_i,repeated:!0}])),Zi=an.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:an.getEnumType(Li)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Hi,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:5,name:"azure",kind:"message",T:zi,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),$i=an.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:Xi},{no:3,name:"participant",kind:"message",T:Qi},{no:2,name:"tracks",kind:"message",T:Yi}])),er=an.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:$i},{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:Mi,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}])),tr=an.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),nr=an.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ir=an.makeEnum("livekit.NegotiatedDataChannelID",[{no:0,name:"NDCI_INVALID"},{no:100,name:"NDCI_RELIABLE"},{no:101,name:"NDCI_LOSSY"},{no:102,name:"NDCI_DATA_TRACK"}]),rr=an.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),or=an.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:Tr,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tr,oneof:"message"},{no:3,name:"trickle",kind:"message",T:gr,oneof:"message"},{no:4,name:"add_track",kind:"message",T:cr,oneof:"message"},{no:5,name:"mute",kind:"message",T:fr,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Er,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Or,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ar,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Nr,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Qr,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Zr,oneof:"message"},{no:13,name:"simulate",kind:"message",T:to,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:xr,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:no,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Dr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Mr,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:dr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:ur,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Cr,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:Rr,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:Ir,oneof:"message"}])),sr=an.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:vr,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tr,oneof:"message"},{no:3,name:"offer",kind:"message",T:Tr,oneof:"message"},{no:4,name:"trickle",kind:"message",T:gr,oneof:"message"},{no:5,name:"update",kind:"message",T:Sr,oneof:"message"},{no:6,name:"track_published",kind:"message",T:yr,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ar,oneof:"message"},{no:9,name:"mute",kind:"message",T:fr,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Fr,oneof:"message"},{no:11,name:"room_update",kind:"message",T:jr,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:qr,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Wr,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:zr,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Yr,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:br,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:kr,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:io,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:so,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ao,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:lo,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Xr,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:go,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Gr,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:lr,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:hr,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:pr,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:Pr,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:_r,oneof:"message"}])),ar=an.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:Jn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:an.getEnumType(Qn)}])),cr=an.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:an.getEnumType(yn)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:an.getEnumType(bn)},{no:9,name:"layers",kind:"message",T:Jn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ar,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:an.getEnumType(xn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:an.getEnumType(kn)},{no:17,name:"audio_features",kind:"enum",T:an.getEnumType(Pn),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:an.getEnumType(In),repeated:!0}])),dr=an.makeMessageType("livekit.PublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:an.getEnumType(xn)},{no:4,name:"frame_encoding",kind:"message",T:Bn,opt:!0},{no:5,name:"schema",kind:"message",T:Hn,opt:!0}])),lr=an.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:jn}])),ur=an.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),hr=an.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:jn}])),pr=an.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:mr}}])),mr=an.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",(()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}]),{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),gr=an.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:an.getEnumType(tr)},{no:3,name:"final",kind:"scalar",T:8}])),fr=an.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),vr=an.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:_n},{no:2,name:"participant",kind:"message",T:Mn},{no:3,name:"other_participants",kind:"message",T:Mn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ur,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:vi},{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:hi},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:On,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),kr=an.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Ur,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:vi},{no:3,name:"server_info",kind:"message",T:hi},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),yr=an.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Fn}])),br=an.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Tr=an.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Sr=an.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:Mn,repeated:!0}])),Er=an.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:ui,repeated:!0}])),Cr=an.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:wr,repeated:!0}])),wr=an.makeMessageType("livekit.UpdateDataSubscription.Update",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Kn}]),{localName:"UpdateDataSubscription_Update"}),Rr=an.makeMessageType("livekit.StoreDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Gn}])),Pr=an.makeMessageType("livekit.StoreDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:zn}])),Ir=an.makeMessageType("livekit.GetDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:zn}])),_r=an.makeMessageType("livekit.GetDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Gn}])),Or=an.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:an.getEnumType(Tn)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}])),Dr=an.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:an.getEnumType(Pn),repeated:!0}])),Mr=an.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}])),Ar=an.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:an.getEnumType(Cn)},{no:3,name:"action",kind:"enum",T:an.getEnumType(Lr)},{no:4,name:"regions",kind:"message",T:ro}])),Lr=an.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Nr=an.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Jn,repeated:!0}])),xr=an.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}])),Ur=an.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}])),Fr=an.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ti,repeated:!0}])),jr=an.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:_n}])),Br=an.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:an.getEnumType(Sn)},{no:3,name:"score",kind:"scalar",T:2}])),qr=an.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Br,repeated:!0}])),Vr=an.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:an.getEnumType(nr)}])),Wr=an.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Vr,repeated:!0}])),Hr=an.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:an.getEnumType(Tn)},{no:2,name:"enabled",kind:"scalar",T:8}])),Kr=an.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Hr,repeated:!0}])),zr=an.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Hr,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Kr,repeated:!0}])),Gr=an.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Oi,repeated:!0}])),Jr=an.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}])),Qr=an.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Jr,repeated:!0}])),Yr=an.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}])),Xr=an.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:_n},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Mn},{no:4,name:"other_participants",kind:"message",T:Mn,repeated:!0}])),Zr=an.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:Tr},{no:2,name:"subscription",kind:"message",T:Er},{no:3,name:"publish_tracks",kind:"message",T:yr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:eo,repeated:!0},{no:5,name:"offer",kind:"message",T:Tr},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:$r,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:lr,repeated:!0},{no:9,name:"data_subscription",kind:"message",T:Cr}])),$r=an.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),eo=an.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:an.getEnumType(tr)}])),to=an.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:an.getEnumType(rr),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"}])),no=an.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),io=an.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),ro=an.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:oo,repeated:!0}])),oo=an.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}])),so=an.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:an.getEnumType(Rn)}])),ao=an.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:an.getEnumType(co)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:gr,oneof:"request"},{no:5,name:"add_track",kind:"message",T:cr,oneof:"request"},{no:6,name:"mute",kind:"message",T:fr,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:xr,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Dr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Mr,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:dr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:ur,oneof:"request"}])),co=an.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),lo=an.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),uo=an.makeMessageType("livekit.ConnectionSettings",(()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}])),ho=an.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:mi},{no:2,name:"connection_settings",kind:"message",T:uo},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:cr,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Tr},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:an.getEnumType(wn)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Zr}])),po=an.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:an.getEnumType(mo)},{no:2,name:"join_request",kind:"scalar",T:12}])),mo=an.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),go=an.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),fo=an.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:er,opt:!0}])),vo=an.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));var ko,yo={exports:{}},bo=yo.exports;var To,So,Eo=(ko||(ko=1,function(e){var t,n;t=bo,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"],r={},o=null;function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(ke){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(),r=0;r<i.length;r++){var o=i[r];this[o]=r<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,r,o){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?a:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var s,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(o){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.length+1))[1])}catch(o){}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:s},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(r){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(r){}}}(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&&(s=m(o.getLevel())),c.call(u),o===u)for(var e in r)r[e].rebuild()},s=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=r[e];return t||(t=r[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 r},o.default=o,o},e.exports?e.exports=n():t.log=n()}(yo)),yo.exports),Co=J(Eo);e.LogLevel=void 0,(To=e.LogLevel||(e.LogLevel={}))[To.trace=0]="trace",To[To.debug=1]="debug",To[To.info=2]="info",To[To.warn=3]="warn",To[To.error=4]="error",To[To.silent=5]="silent",e.LoggerNames=void 0,(So=e.LoggerNames||(e.LoggerNames={})).Default="livekit",So.Room="livekit-room",So.TokenSource="livekit-token-source",So.Participant="livekit-participant",So.Track="livekit-track",So.Publication="livekit-track-publication",So.Engine="livekit-engine",So.Signal="livekit-signal",So.PCManager="livekit-pc-manager",So.PCTransport="livekit-pc-transport",So.E2EE="lk-e2ee",So.DataTracks="livekit-data-tracks",So.Region="livekit-region",So.ICE="livekit-ice",So.Stats="livekit-stats";let wo=Co.getLogger(e.LoggerNames.Default);const Ro=Object.values(e.LoggerNames).map((e=>Co.getLogger(e)));function Po(e,t){const n=Co.getLogger(e);return n.setDefaultLevel(wo.getLevel()),t?function(e,t){const n=n=>(i,r)=>{const o=t(),s=o||r?Object.assign(Object.assign({},o),r):void 0;e[n](i,s)},i=Object.create(e);return i.trace=n("trace"),i.debug=n("debug"),i.info=n("info"),i.warn=n("warn"),i.error=n("error"),i}(n,t):n}wo.setDefaultLevel(e.LogLevel.info);const Io=Co.getLogger(e.LoggerNames.E2EE),_o=new Set,Oo=Io.setLevel.bind(Io);function Do(e){return _o.add(e),()=>{_o.delete(e)}}function Mo(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 r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}function Ao(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(ke){o(ke)}}function a(e){try{c(i.throw(e))}catch(ke){o(ke)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function Lo(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 No(e){return this instanceof No?(this.v=e,this):new No(e)}function xo(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(e,t||[]),o=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,d)}})),i[Symbol.asyncIterator]=function(){return this},i;function s(e,t){r[e]&&(i[e]=function(t){return new Promise((function(n,i){o.push([e,t,n,i])>1||a(e,t)}))},t&&(i[e]=t(i[e])))}function a(e,t){try{(n=r[e](t)).value instanceof No?Promise.resolve(n.value.v).then(c,d):l(o[0][2],n)}catch(ke){l(o[0][3],ke)}var n}function c(e){a("next",e)}function d(e){a("throw",e)}function l(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function Uo(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Lo(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,r){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,r,(t=e[n](t)).done,t.value)}))}}}Io.setLevel=(e,t)=>{Oo(e,t);const n=Io.getLevel();_o.forEach((e=>e(n)))},"function"==typeof SuppressedError&&SuppressedError;var Fo,jo={exports:{}};var Bo,qo,Vo=function(){if(Fo)return jo.exports;Fo=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 r(){r.init.call(this)}jo.exports=r,jo.exports.once=function(e,t){return new Promise((function(n,i){function r(n){e.removeListener(t,o),i(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",r),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,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function s(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?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,o,c,d;if(s(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),(r=a(e))>0&&c.length>r&&!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},r=d.bind(i);return r.listener=n,i.wrapFn=r,r}function u(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]: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}(r):p(r,r.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 r(o){i.once&&e.removeEventListener(t,r),n(o)}))}}return Object.defineProperty(r,"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}}),r.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},r.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},r.prototype.getMaxListeners=function(){return a(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,o=this._events;if(void 0!==o)r=r&&void 0===o.error;else if(!r)return!1;if(r){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,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},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return s(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,o,a;if(s(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(r=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,r=o;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},r.prototype.off=r.prototype.removeListener,r.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 r,o=Object.keys(n);for(i=0;i<o.length;++i)"removeListener"!==(r=o[i])&&this.removeAllListeners(r);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},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},jo.exports}();class Wo extends(qo=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Bo=Wo,Wo.resolve=e=>Reflect.get(qo,"resolve",Bo).call(Bo,e);const Ho=/version\/(\d+(\.?_?\d+)+)/i;let Ko;function zo(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===Ko||t){const e=Go.find((e=>e.test.test(n)));Ko=null==e?void 0:e.describe(n)}return Ko}const Go=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Jo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Qo(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Jo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Qo(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Jo(Ho,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Qo(e)})}];function Jo(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 Qo(e){return e.includes("mac os")?Jo(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const Yo="2.24.0";class Xo extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}class Zo extends Xo{}var $o,es,ts,ns,is,rs,os;e.ConnectionErrorReason=void 0,($o=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[$o.NotAllowed=0]="NotAllowed",$o[$o.ServerUnreachable=1]="ServerUnreachable",$o[$o.InternalError=2]="InternalError",$o[$o.Cancelled=3]="Cancelled",$o[$o.LeaveRequest=4]="LeaveRequest",$o[$o.Timeout=5]="Timeout",$o[$o.WebSocket=6]="WebSocket",$o[$o.ServiceNotFound=7]="ServiceNotFound";class ss extends Zo{constructor(t,n,i,r){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=e.ConnectionErrorReason[n]}static notAllowed(t,n,i){return new ss(t,e.ConnectionErrorReason.NotAllowed,n,i)}static timeout(t){return new ss(t,e.ConnectionErrorReason.Timeout)}static leaveRequest(t,n){return new ss(t,e.ConnectionErrorReason.LeaveRequest,void 0,n)}static internal(t,n){return new ss(t,e.ConnectionErrorReason.InternalError,void 0,n)}static cancelled(t){return new ss(t,e.ConnectionErrorReason.Cancelled)}static serverUnreachable(t,n){return new ss(t,e.ConnectionErrorReason.ServerUnreachable,n)}static websocket(t,n,i){return new ss(t,e.ConnectionErrorReason.WebSocket,n,i)}static serviceNotFound(t,n){return new ss(t,e.ConnectionErrorReason.ServiceNotFound,void 0,n)}}function as(t){return t.reason!==e.ConnectionErrorReason.Cancelled&&(t.reason!==e.ConnectionErrorReason.NotAllowed||403===t.status)}class cs extends Xo{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class ds extends Xo{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class ls extends Xo{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class us extends Xo{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class hs extends Xo{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class ps extends Xo{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class ms extends Xo{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class gs extends Zo{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:co[t]}}e.DataStreamErrorReason=void 0,(es=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[es.AlreadyOpened=0]="AlreadyOpened",es[es.AbnormalEnd=1]="AbnormalEnd",es[es.DecodeFailed=2]="DecodeFailed",es[es.LengthExceeded=3]="LengthExceeded",es[es.Incomplete=4]="Incomplete",es[es.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",es[es.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",es[es.HeaderTooLarge=9]="HeaderTooLarge",es[es.PayloadTooLarge=10]="PayloadTooLarge";class fs extends Zo{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}class vs extends Xo{constructor(e){super(18,e),this.name="SignalReconnectError"}}e.MediaDeviceFailure=void 0,(ts=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",ts.NotFound="NotFound",ts.DeviceInUse="DeviceInUse",ts.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={}));class ks{}function ys(e){const t={};for(const i of Object.entries(e)){var n=tt(i,2);const e=n[0],r=n[1];void 0!==r&&(t[e]=r)}return t}function bs(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function Ts(e){return Math.round(1e4*e)/1e4}function Ss(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?Ts(t/n):void 0}function Es(e,t){if(void 0!==e.playoutDelay)return Ts(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,i=null==t?void 0:t.totalSamplesCount;return void 0!==n&&i?Ts(n/i):void 0}function Cs(e){var t,n;const i=new Map,r=[],o=[],s=[];let a;e.forEach((e=>i.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=i.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?i.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");o.push(ys({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:bs(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:Ss(e),playoutDelay:Es(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");s.push(ys({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:bs(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:bs(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":a=e;break;case"candidate-pair":r.push(e)}}));const l=null==a?void 0:a.selectedCandidatePairId,u=null!==(n=null!==(t=l?i.get(l):void 0)&&void 0!==t?t:r.find((e=>e.selected)))&&void 0!==n?n:r.find((e=>e.nominated)),h=(null==u?void 0:u.localCandidateId)?i.get(u.localCandidateId):void 0,p=(null==u?void 0:u.remoteCandidateId)?i.get(u.remoteCandidateId):void 0,m=ys({ice:null==a?void 0:a.iceState,dtls:null==a?void 0:a.dtlsState,route:h&&p?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(p.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==u?void 0:u.currentRoundTripTime,availableOutgoingBitrate:null==u?void 0:u.availableOutgoingBitrate,availableIncomingBitrate:null==u?void 0:u.availableIncomingBitrate,bytesSent:null==u?void 0:u.bytesSent,bytesReceived:null==u?void 0:u.bytesReceived,candidatePairChanges:null==a?void 0:a.selectedCandidatePairChanges});return{connection:Object.keys(m).length>0?m:void 0,outbound:s.length>0?s:void 0,inbound:o.length>0?o:void 0}}function ws(e,t,n){var i,r,o,s;const a=xs(null!=e?e:{}),c=a.optionsWithoutProcessor,d=a.audioProcessor,l=a.videoProcessor,u=null==t?void 0:t.processor,h=null==n?void 0:n.processor,p=null!=c?c:{};return!0===p.audio&&(p.audio={}),!0===p.video&&(p.video={}),p.audio&&(Rs(p.audio,t),null!==(i=(o=p.audio).deviceId)&&void 0!==i||(o.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=null!=d?d:u)),p.video&&(Rs(p.video,n),null!==(r=(s=p.video).deviceId)&&void 0!==r||(s.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=null!=l?l:h)),p}function Rs(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Ps(e){var t,n,i,r;const o={};if(e.video)if("object"==typeof e.video){const n={},r=n,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)Rs(r,s.resolution);else r[e]=s[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=(r=o.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function Is(e){return Ao(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=_s();if(!n)return!1;let i,r;try{r=n.createAnalyser(),r.fftSize=2048;const o=r.frequencyBinCount,s=new Uint8Array(o);i=n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])),i.connect(r);const a=()=>"running"===n.state;if(!a()){try{yield Promise.race([n.resume(),Ks(200)])}catch(Bo){}if(!a())return!1}yield Ks(t),r.getByteTimeDomainData(s);return!s.some((e=>128!==e&&0!==e))}finally{null==i||i.disconnect(),null==r||r.disconnect(),yield n.close().catch((()=>{}))}}()}))}function _s(){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=()=>Ao(this,void 0,void 0,(function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(ke){console.warn("Error trying to auto-resume audio context",ke)}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 Os(e){return"audioinput"===e?Bs.Source.Microphone:"videoinput"===e?Bs.Source.Camera:Bs.Source.Unknown}function Ds(e){return e===Bs.Source.Microphone?"audioinput":e===Bs.Source.Camera?"videoinput":void 0}function Ms(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=oa()?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 As(e){return e.split("/")[1].toLowerCase()}function Ls(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new yr({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Ns(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?Ns(e.track):{})}}function xs(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:(r=t,void 0===r?r:"function"==typeof structuredClone?"object"==typeof r&&null!==r?structuredClone(Object.assign({},r)):structuredClone(r):JSON.parse(JSON.stringify(r)))};var r}function Us(e,t){return e.width*e.height<t.width*t.height}ks.setTimeout=function(){return setTimeout(...arguments)},ks.setInterval=function(){return setInterval(...arguments)},ks.clearTimeout=function(){return clearTimeout(...arguments)},ks.clearInterval=function(){return clearInterval(...arguments)},e.RoomEvent=void 0,(ns=e.RoomEvent||(e.RoomEvent={})).Connected="connected",ns.Reconnecting="reconnecting",ns.SignalReconnecting="signalReconnecting",ns.Reconnected="reconnected",ns.Disconnected="disconnected",ns.ConnectionStateChanged="connectionStateChanged",ns.Moved="moved",ns.MediaDevicesChanged="mediaDevicesChanged",ns.ParticipantConnected="participantConnected",ns.ParticipantDisconnected="participantDisconnected",ns.TrackPublished="trackPublished",ns.TrackSubscribed="trackSubscribed",ns.TrackSubscriptionFailed="trackSubscriptionFailed",ns.TrackUnpublished="trackUnpublished",ns.TrackUnsubscribed="trackUnsubscribed",ns.TrackMuted="trackMuted",ns.TrackUnmuted="trackUnmuted",ns.LocalTrackPublished="localTrackPublished",ns.LocalTrackUnpublished="localTrackUnpublished",ns.LocalAudioSilenceDetected="localAudioSilenceDetected",ns.ActiveSpeakersChanged="activeSpeakersChanged",ns.ParticipantMetadataChanged="participantMetadataChanged",ns.ParticipantNameChanged="participantNameChanged",ns.ParticipantAttributesChanged="participantAttributesChanged",ns.ParticipantActive="participantActive",ns.RoomMetadataChanged="roomMetadataChanged",ns.DataReceived="dataReceived",ns.SipDTMFReceived="sipDTMFReceived",ns.TranscriptionReceived="transcriptionReceived",ns.ConnectionQualityChanged="connectionQualityChanged",ns.TrackStreamStateChanged="trackStreamStateChanged",ns.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ns.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ns.AudioPlaybackStatusChanged="audioPlaybackChanged",ns.VideoPlaybackStatusChanged="videoPlaybackChanged",ns.MediaDevicesError="mediaDevicesError",ns.ParticipantPermissionsChanged="participantPermissionsChanged",ns.SignalConnected="signalConnected",ns.RecordingStatusChanged="recordingStatusChanged",ns.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",ns.EncryptionError="encryptionError",ns.DCBufferStatusChanged="dcBufferStatusChanged",ns.ActiveDeviceChanged="activeDeviceChanged",ns.ChatMessage="chatMessage",ns.LocalTrackSubscribed="localTrackSubscribed",ns.MetricsReceived="metricsReceived",ns.DataTrackPublished="dataTrackPublished",ns.DataTrackUnpublished="dataTrackUnpublished",ns.LocalDataTrackPublished="localDataTrackPublished",ns.LocalDataTrackUnpublished="localDataTrackUnpublished",e.ParticipantEvent=void 0,(is=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",is.TrackSubscribed="trackSubscribed",is.TrackSubscriptionFailed="trackSubscriptionFailed",is.TrackUnpublished="trackUnpublished",is.TrackUnsubscribed="trackUnsubscribed",is.TrackMuted="trackMuted",is.TrackUnmuted="trackUnmuted",is.LocalTrackPublished="localTrackPublished",is.LocalTrackUnpublished="localTrackUnpublished",is.LocalTrackCpuConstrained="localTrackCpuConstrained",is.LocalSenderCreated="localSenderCreated",is.ParticipantMetadataChanged="participantMetadataChanged",is.ParticipantNameChanged="participantNameChanged",is.DataReceived="dataReceived",is.SipDTMFReceived="sipDTMFReceived",is.TranscriptionReceived="transcriptionReceived",is.IsSpeakingChanged="isSpeakingChanged",is.ConnectionQualityChanged="connectionQualityChanged",is.TrackStreamStateChanged="trackStreamStateChanged",is.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",is.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",is.TrackCpuConstrained="trackCpuConstrained",is.MediaDevicesError="mediaDevicesError",is.AudioStreamAcquired="audioStreamAcquired",is.ParticipantPermissionsChanged="participantPermissionsChanged",is.PCTrackAdded="pcTrackAdded",is.AttributesChanged="attributesChanged",is.LocalTrackSubscribed="localTrackSubscribed",is.ChatMessage="chatMessage",is.Active="active",e.EngineEvent=void 0,(rs=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",rs.Connected="connected",rs.Disconnected="disconnected",rs.Resuming="resuming",rs.Resumed="resumed",rs.Restarting="restarting",rs.Restarted="restarted",rs.SignalResumed="signalResumed",rs.SignalRestarted="signalRestarted",rs.Closing="closing",rs.MediaTrackAdded="mediaTrackAdded",rs.ActiveSpeakersUpdate="activeSpeakersUpdate",rs.DataPacketReceived="dataPacketReceived",rs.RTPVideoMapUpdate="rtpVideoMapUpdate",rs.DCBufferStatusChanged="dcBufferStatusChanged",rs.ParticipantUpdate="participantUpdate",rs.RoomUpdate="roomUpdate",rs.SpeakersChanged="speakersChanged",rs.StreamStateChanged="streamStateChanged",rs.ConnectionQualityUpdate="connectionQualityUpdate",rs.SubscriptionError="subscriptionError",rs.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",rs.RemoteMute="remoteMute",rs.SubscribedQualityUpdate="subscribedQualityUpdate",rs.LocalTrackUnpublished="localTrackUnpublished",rs.LocalTrackSubscribed="localTrackSubscribed",rs.Offline="offline",rs.SignalRequestResponse="signalRequestResponse",rs.SignalConnected="signalConnected",rs.RoomMoved="roomMoved",rs.PublishDataTrackResponse="publishDataTrackResponse",rs.UnPublishDataTrackResponse="unPublishDataTrackResponse",rs.DataTrackSubscriberHandles="dataTrackSubscriberHandles",rs.DataTrackPacketReceived="dataTrackPacketReceived",rs.Joined="joined",rs.TokenRefreshed="tokenRefreshed",rs.ServerRegionsReported="serverRegionsReported",rs.RequestSubscribedCodecRefresh="requestSubscribedCodecRefresh",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=[];var js;e.VideoQuality=void 0,(js=e.VideoQuality||(e.VideoQuality={}))[js.LOW=0]="LOW",js[js.MEDIUM=1]="MEDIUM",js[js.HIGH=2]="HIGH";class Bs extends Vo.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Bs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=wo,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=i.loggerContextCb,this.log=Po(null!==(r=i.loggerName)&&void 0!==r?r:e.LoggerNames.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=Bs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Ns(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===Bs.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===Bs.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Fs.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Fs.splice(Fs.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),qs(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),r=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(r?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(r?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:n}),r&&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){Vs(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=>{Vs(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.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",Cs(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=Po(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Fs.forEach((e=>{e.parentElement||(t=!1)})),t&&Fs.push(e)}}handleAppVisibilityChanged(){return Ao(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Bs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){la()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){la()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function qs(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)),oa()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(oa()||na())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Vs(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;"audio"===e.kind&&ia()&&(t.srcObject=null),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 yn.AUDIO;case t.Video:return yn.VIDEO;default:return yn.DATA}},e.kindFromProto=function(e){switch(e){case yn.AUDIO:return t.Audio;case yn.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return bn.CAMERA;case n.Microphone:return bn.MICROPHONE;case n.ScreenShare:return bn.SCREEN_SHARE;case n.ScreenShareAudio:return bn.SCREEN_SHARE_AUDIO;default:return bn.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case bn.CAMERA:return n.Camera;case bn.MICROPHONE:return n.Microphone;case bn.SCREEN_SHARE:return n.ScreenShare;case bn.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case nr.ACTIVE:return i.Active;case nr.PAUSED:return i.Paused;default:return i.Unknown}}}(Bs||(Bs={}));const Ws="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Hs(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}function Ks(e){return new Wo((t=>ks.setTimeout(t,e)))}function zs(){return"addTransceiver"in RTCPeerConnection.prototype}function Gs(){return"addTrack"in RTCPeerConnection.prototype}function Js(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oa()||na())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 Qs(){if(!("getCapabilities"in RTCRtpSender))return!1;if(na())return!1;if(oa()){const e=zo();if((null==e?void 0:e.version)&&va(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&va(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 Ys(e){return"av1"===e||"vp9"===e}function Xs(e){var t;const n=null===(t=e.getHeaderExtensionsToNegotiate)||void 0===t?void 0:t.call(e);if(!n||!e.setHeaderExtensionsToNegotiate)return!1;const i=n.find((e=>e.uri===Ws));if(!i)return!1;if("stopped"!==i.direction)return!0;i.direction="sendrecv";try{return e.setHeaderExtensionsToNegotiate(n),!0}catch(ke){return!1}}function Zs(e,t){var n;return Ys(e)&&!!(null==t?void 0:t.simulcast)&&!!(null===(n=t.scalabilityMode)||void 0===n?void 0:n.startsWith("L1T"))}function $s(){const e=zo();return sa()||ua()||"Chrome"===(null==e?void 0:e.name)&&va(e.version,"113")<0}function ea(e){return!(!document||sa())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function ta(){return"undefined"!=typeof RTCPeerConnection&&(zs()||Gs())}function na(){var e;return"Firefox"===(null===(e=zo())||void 0===e?void 0:e.name)}function ia(){const e=zo();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function ra(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!ia()}function oa(){var e;return"Safari"===(null===(e=zo())||void 0===e?void 0:e.name)}function sa(){const e=zo();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function aa(){var e;return"iOS"===(null===(e=zo())||void 0===e?void 0:e.os)||function(){if(!la())return!1;const e=zo();return"Safari"===(null==e?void 0:e.name)&&"macOS"===(null==e?void 0:e.os)&&navigator.maxTouchPoints>1}()}function ca(){const e=zo();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)&&va(e.osVersion,"17")>=0}function da(){var e,t;return!!la()&&(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 la(){return"undefined"!=typeof document}function ua(){return"ReactNative"==navigator.product}function ha(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function pa(e){return ha(e)?e.hostname.split(".")[0]:null}function ma(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ga(){if(!ua())return;let e=ma();return e?e.platform:void 0}function fa(){if(la())return window.devicePixelRatio;if(ua()){let e=ma();if(e)return e.devicePixelRatio}return 1}function va(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let o=0;o<r;++o){const e=parseInt(n[o],10),t=parseInt(i[o],10);if(e>t)return 1;if(e<t)return-1;if(o===r-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function ka(e){for(const t of e)t.target.handleResize(t)}function ya(e){for(const t of e)t.target.handleVisibilityChanged(t)}let ba=null;const Ta=()=>(ba||(ba=new ResizeObserver(ka)),ba);let Sa=null;const Ea=()=>(Sa||(Sa=new IntersectionObserver(ya,{root:null,rootMargin:"0px"})),Sa);let Ca,wa,Ra;function Pa(){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 r=document.createElement("canvas");r.width=e,r.height=t;const o=r.getContext("2d");null==o||o.fillRect(0,0,r.width,r.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 s=tt(r.captureStream().getTracks(),1)[0];if(!s)throw Error("Could not get empty media stream video track");return s.enabled=n,s}const Ia=new Set;function _a(){if(!wa){const t=new AudioContext,n=t.createOscillator(),i=t.createGain();i.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();n.connect(i),i.connect(r),n.start();var e=tt(r.stream.getAudioTracks(),1);if(wa=e[0],!wa)throw t.close().catch((()=>{})),Error("Could not get empty media stream audio track");wa.enabled=!1,Ra=t}const t=wa.clone();return Ia.add(t),t}function Oa(e){return Ao(this,void 0,void 0,(function*(){if(!Ia.delete(e))return;if(e.stop(),Ia.size>0)return;const t=Ra;null==wa||wa.stop(),wa=void 0,Ra=void 0,yield null==t?void 0:t.close()}))}class Da{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>Ao(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 Ma(e){return he.includes(e)}function Aa(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")}const La=new WeakSet;function Na(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function xa(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return Cn.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return Cn.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return Cn.JOIN_FAILURE;default:return Cn.UNKNOWN_REASON}}function Ua(e){return void 0!==e?Number(e):void 0}function Fa(e){return void 0!==e?BigInt(e):void 0}function ja(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Ba(e){return!!e&&e.kind==Bs.Kind.Audio}function qa(e){return!!e&&e.kind==Bs.Kind.Video}function Va(e){return ja(e)&&qa(e)}function Wa(e){return ja(e)&&Ba(e)}function Ha(e){return!!e&&!e.isLocal}function Ka(e){return!!e&&!e.isLocal}function za(e){return Ha(e)&&qa(e)}function Ga(e){return e.isLocal}function Ja(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Qa(){return"undefined"!=typeof CompressionStream}let Ya=null;function Xa(){return"boolean"!=typeof Ya&&(Ya=function(){if("undefined"==typeof CompressionStream||"undefined"==typeof DecompressionStream)return!1;try{return new CompressionStream("deflate-raw"),new DecompressionStream("deflate-raw"),!0}catch(Bo){return!1}}()),Ya}function Za(e,t){const n=tt(Hs(t.id),2)[1];return(null==n?void 0:n.startsWith("TR"))?n:e.id.startsWith("TR")?e.id:void 0}function $a(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=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)})),tc(n,"rtc")}(e,t);return n?i:tc(i,"v1")}function ec(e){return e.endsWith("/")?e:"".concat(e,"/")}function tc(e,t){return e.pathname="".concat(ec(e.pathname)).concat(t),e}function nc(e){if("string"==typeof e)return sr.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return sr.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const ic="AES-GCM",rc="lk_e2ee",oc="lk_e2ee_track_id",sc={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function ac(){return dc()||cc()}function cc(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function dc(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function lc(e){return Ao(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 uc(e){return Ao(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function hc(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"))}}function pc(e){var t,n,i,r,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===(r=e.value)||void 0===r?void 0:r.case)&&"encryptedPacket"!==(null===(o=e.value)||void 0===o?void 0:o.case))return new $n({value:e.value})}function mc(){return ra()}function gc(e){return!!(null==e?void 0:e.worker)&&(dc()||mc())}function fc(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function vc(e){var t;return null!==(t=null==e?void 0:e.frameMetadata)&&void 0!==t?t:null==e?void 0:e.packetTrailer}function kc(e,t){e.frameMetadata=t,e.packetTrailer=t}class yc{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new yc),this._instance}addFailedConnectionAttempt(e){var t;const n=pa(new URL(e));if(!n)return;let i=null!==(t=this.failedConnectionAttempts.get(n))&&void 0!==t?t:0;this.failedConnectionAttempts.set(n,i+1),this.backOffPromises.set(n,Ks(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&pa(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&pa(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}yc._instance=null;const bc="default";class Tc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Tc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Ao(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=Tc.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){wo.debug("awaiting getUserMedia promise");try{e?yield Tc.userMediaPromiseMap.get(e):yield Promise.all(Tc.userMediaPromiseMap.values())}catch(ke){wo.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(n&&(!oa()||!t.hasDeviceInUse(e))){if(0===r.filter((t=>!e||t.kind===e)).length||r.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);r=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=r,e&&(r=r.filter((t=>t.kind===e))),r}()}))}normalizeDeviceId(e,t,n){return Ao(this,void 0,void 0,(function*(){if(t!==bc)return t;const i=yield this.getDevices(e),r=i.find((e=>e.deviceId===bc));if(!r)return void wo.warn("could not reliably determine default device");const o=i.find((e=>e.deviceId!==bc&&e.groupId===(null!=n?n:r.groupId)));if(o)return null==o?void 0:o.deviceId;wo.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Tc.userMediaPromiseMap.has(e):Tc.userMediaPromiseMap.size>0}}var Sc;Tc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Tc.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Sc||(Sc={}));class Ec{constructor(){this.pendingTasks=new Map,this.taskMutex=new be,this.nextTaskIndex=0}run(e){return Ao(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Sc.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Sc.RUNNING,yield e()}finally{t.status=Sc.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return Ao(this,void 0,void 0,(function*(){return this.run((()=>Ao(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function Cc(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const i of e)if(i.aborted)return i;const t=new AbortController,n=Array(e.length);return e.forEach(((e,i)=>{const r=()=>{t.abort(e.reason),(()=>{for(const e of n)e()})()};e.addEventListener("abort",r),n[i]=()=>e.removeEventListener("abort",r)})),t.signal}function wc(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}const Rc=["client"];var Pc=class{constructor(){Ze(this,"listeners",new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){const n=this.listeners.get("*");if(n)for(const r of n)r(e,t);const i=this.listeners.get(e);if(i)for(const r of i)r(t)}clear(){this.listeners.clear()}},Ic=class extends Error{constructor(e,t){super("non-serializable value at ".concat(e," (").concat(t,")")),this.path=e,this.label=t}};const _c=(e,t,n)=>{if(null===e)return null;switch(typeof e){case"string":case"boolean":return e;case"number":if(!Number.isFinite(e))throw new Ic(t,Dc(e));return e;case"object":return Oc(e,t,n);default:throw new Ic(t,typeof e)}},Oc=(e,t,n)=>{var i,r;if(n.has(e))throw new Ic(t,"circular reference");if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new Ic(t,"sparse array or array with non-index properties");n.add(e);const i=e.map(((e,i)=>_c(e,"".concat(t,"[").concat(i,"]"),n)));return n.delete(e),i}const o=Object.getPrototypeOf(e);if(o!==Object.prototype&&null!==o)throw new Ic(t,null!==(i=null===(r=e.constructor)||void 0===r?void 0:r.name)&&void 0!==i?i:"object");n.add(e);const s={};for(const a of Object.keys(e)){const i=_c(e[a],"".concat(t,".").concat(a),n);Object.defineProperty(s,a,{value:i,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),s},Dc=e=>Number.isNaN(e)?"NaN":e>0?"Infinity":"-Infinity",Mc=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Set;if(null===e||"object"!=typeof e)return e;if(t.has(e))return e;if(Array.isArray(e)){t.add(e);const n=e.map((e=>Mc(e,t)));return t.delete(e),n}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&null!==n)return e;t.add(e);const i={};for(const r of Object.keys(e)){const n=Mc(e[r],t);Object.defineProperty(i,r,{value:n,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),i},Ac=Symbol("machina.type");var Lc=class{constructor(e){Ze(this,"id",void 0),Ze(this,"initialState",void 0),Ze(this,Ac,"BehavioralFsm"),Ze(this,"states",void 0),Ze(this,"emitter",new Pc),Ze(this,"clients",new WeakMap),Ze(this,"knownClients",new Set),Ze(this,"childSubscriptions",[]),Ze(this,"disposed",!1),Ze(this,"transitionDepth",0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){var n;if(this.disposed)return;const i=this.getOrCreateClientMeta(e);for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];i.currentActionArgs=o;const a=null===(n=this.states[i.state])||void 0===n?void 0:n._child;if(a&&a.canHandle(e,t))try{a.handle(e,t,...o)}finally{i.currentActionArgs=void 0}else this.handleLocally(e,t,o,i)}canHandle(e,t){var n,i,r;if(this.disposed)return!1;const o=null!==(n=null===(i=this.clients.get(e))||void 0===i?void 0:i.state)&&void 0!==n?n:this.initialState,s=this.states[o];if(null!==(r=null==s?void 0:s[t])&&void 0!==r?r:null==s?void 0:s["*"])return!0;const a=null==s?void 0:s._child;return!!a&&a.canHandle(e,t)}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){var t;return null===(t=this.clients.get(e))||void 0===t?void 0:t.state}transition(e,t){if(this.disposed)return;const n=this.getOrCreateClientMeta(e),i=n.state;if(t!==i)if(Object.hasOwn(this.states,t)){if(this.transitionDepth++,this.transitionDepth>20)throw this.transitionDepth=0,new Error("Max transition depth (".concat(20,') exceeded in FSM "').concat(this.id,'". Likely an infinite _onEnter → transition loop.'));try{const r=this.states[i],o=this.states[t];if(null!=r&&r._onExit&&"function"==typeof r._onExit){const t=this.buildHandlerArgs(e,"",n);r._onExit(t)}n.state=t;const s={fromState:i,toState:t,client:e};let a;if(this.emitter.emit("transitioning",s),null!=o&&o._onEnter&&"function"==typeof o._onEnter){const t=this.buildHandlerArgs(e,"",n);a=o._onEnter(t)}this.emitter.emit("transitioned",s);const c=null==o?void 0:o._child;c&&c.reset(e),this.processQueue(e,n),"string"==typeof a&&n.state===t&&this.transition(e,a)}finally{this.transitionDepth--}}else this.emitter.emit("invalidstate",{stateName:t,client:e})}compositeState(e){var t;const n=this.clients.get(e);if(!n)return"";const i=null===(t=this.states[n.state])||void 0===t?void 0:t._child;if(i){const t=i.compositeState(e);if(t)return"".concat(n.state,".").concat(t)}return n.state}rehydrate(e,t){if(this.disposed)return;if("string"==typeof t)return void this.rehydrateCompositePath(e,t);const n=this.planSnapshotWrites(e,t);for(const i of n)i()}dehydrate(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.clients.get(e);if(!n)return;const i={state:n.state,deferred:n.deferredQueue.map((e=>this.snapshotDeferredInput(e)))},r=this.collectChildSnapshots(e,n.state,t);return r&&(i.children=r),i}planSnapshotWrites(e,t){if(this.disposed)return[];const n=t.state,i=t.deferred,r=t.children;if(!Object.hasOwn(this.states,n))throw new Error('rehydrate: unknown state "'.concat(n,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));const o=[];if(r)for(const c of Object.keys(r)){var s;if(!Object.hasOwn(this.states,c))throw new Error('rehydrate: unknown state "'.concat(c,'" in FSM "').concat(this.id,'" referenced by snapshot.children.'));const t=null===(s=this.states[c])||void 0===s?void 0:s._child;if(!t)throw new Error('rehydrate: state "'.concat(c,'" in FSM "').concat(this.id,'" has no _child, but the snapshot has a children["').concat(c,'"] entry.'));o.push(...t.planRehydrate(e,r[c]))}const a=i.map((e=>function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?et(Object(n),!0).forEach((function(t){Ze(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):et(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({inputName:e.inputName,args:Mc(e.args)},void 0!==e.untilState?{untilState:e.untilState}:{})));return o.push((()=>{this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:n,deferredQueue:a})})),o}rehydrateCompositePath(e,t){const n=nt(t.split(".")),i=n[0],r=Ye(n).slice(1);if(!Object.hasOwn(this.states,i))throw new Error('rehydrate: unknown state "'.concat(i,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));if(r.length>0){var o;const n=r.join("."),s=null===(o=this.states[i])||void 0===o?void 0:o._child;if(!s)throw new Error('rehydrate: state "'.concat(i,'" in FSM "').concat(this.id,'" has no _child, but composite path "').concat(t,'" requires one.'));s.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:i,deferredQueue:[]})}collectChildSnapshots(e,t,n){const i=new Map;for(const s of Object.keys(this.states)){var r;const e=null===(r=this.states[s])||void 0===r?void 0:r._child;if(!e)continue;const t=i.get(e.instance);t?t.stateNames.push(s):i.set(e.instance,{childLink:e,stateNames:[s]})}let o;for(const s of i.values()){const i=s.childLink,r=s.stateNames,a=n&&r.includes(t);if("Fsm"===i.instance[Ac]&&!a)continue;const c=i.dehydrate(e,a);if(c){null!=o||(o={});for(const e of r)o[e]=c}}return o}snapshotDeferredInput(e){let t;try{n=e.args,t=_c(n,"args",new Set)}catch(r){if(!(r instanceof Ic))throw r;const t=e.untilState?' (until "'.concat(e.untilState,'")'):"";throw new Error('dehydrate: deferred input "'.concat(e.inputName,'"').concat(t,' in FSM "').concat(this.id,'" has a non-serializable value at ').concat(r.path," (").concat(r.label,")"))}var n;const i={inputName:e.inputName,args:t};return void 0!==e.untilState&&(i.untilState=e.untilState),i}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(const n of this.childSubscriptions)n.off();if(null==e||!e.preserveChildren){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;i&&!e.has(i.instance)&&(e.add(i.instance),i.dispose())}}this.emitter.clear()}wrapChildLinks(){for(const e of Object.keys(this.states)){const t=this.states[e],n=null==t?void 0:t._child;if(n){if("object"!=typeof n)throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got ').concat(String(n)));if(!(Ac in n))throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got a plain object'));t._child=Nc(n)}}}setupChildSubscriptions(){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;if(!i||e.has(i.instance))continue;e.add(i.instance);const r=i.onAny(((e,t)=>{if("nohandler"===e){var n;const e=t;if(void 0!==e.client)this.bubbleNohandler(e.client,i,e.inputName,null!==(n=e.args)&&void 0!==n?n:[]);else for(const t of this.knownClients){var r;const n=t.deref();void 0!==n?this.bubbleNohandler(n,i,e.inputName,null!==(r=e.args)&&void 0!==r?r:[]):this.knownClients.delete(t)}return}const o=t;if(o&&"object"==typeof o&&"client"in o)this.isChildActiveForClient(o.client,i)&&this.emitter.emit(e,t);else for(const s of this.knownClients){const n=s.deref();if(n){if(this.isChildActiveForClient(n,i)){this.emitter.emit(e,t);break}}else this.knownClients.delete(s)}}));this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,i){if(!this.isChildActiveForClient(e,t))return;const r=this.clients.get(e);r.currentActionArgs=i,this.handleLocally(e,n,i,r)}isChildActiveForClient(e,t){var n;const i=this.clients.get(e);return!!i&&(null===(n=this.states[i.state])||void 0===n||null===(n=n._child)||void 0===n?void 0:n.instance)===t.instance}handleLocally(e,t,n,i){var r;const o=this.states[i.state],s=null!==(r=null==o?void 0:o[t])&&void 0!==r?r:null==o?void 0:o["*"];if(!s)return this.emitter.emit("nohandler",{inputName:t,args:n,client:e}),void(i.currentActionArgs=void 0);try{this.emitter.emit("handling",{inputName:t,client:e});const r=this.buildHandlerArgs(e,t,i);let o;"string"==typeof s?o=s:"function"==typeof s&&(o=s(r,...n)),this.emitter.emit("handled",{inputName:t,client:e}),"string"==typeof o&&this.transition(e,o)}finally{i.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new WeakRef(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:i=>{if(!n.currentActionArgs)return;const r={inputName:t,args:[...n.currentActionArgs],untilState:null==i?void 0:i.until};n.deferredQueue.push(r),this.emitter.emit("deferred",{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){const n=[],i=[];for(const r of t.deferredQueue)void 0===r.untilState||r.untilState===t.state?n.push(r):i.push(r);t.deferredQueue=i;for(const r of n)this.handle(e,r.inputName,...r.args)}};function Nc(e){if(!e||"object"!=typeof e)throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got ".concat(String(e)));const t=e[Ac];if("BehavioralFsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(t,n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(t),rehydrate(t,n){e.rehydrate(t,n)},dehydrate:(t,n)=>e.dehydrate(t,n),planRehydrate:(t,n)=>e.planSnapshotWrites(t,n),dispose(){e.dispose()}};if("Fsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];e.handle(n,...r)},reset(t){e.reset()},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(),rehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dehydrate(e,t){throw new Error("dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.")},planRehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dispose(){e.dispose()}};throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ".concat(String(null!=t?t:"undefined")))}var xc=class{constructor(e){var t;Ze(this,"id",void 0),Ze(this,"initialState",void 0),Ze(this,Ac,"Fsm"),Ze(this,"states",void 0),Ze(this,"bfsm",void 0),Ze(this,"context",void 0),Ze(this,"emitter",new Pc),Ze(this,"disposed",!1),this.id=e.id,this.initialState=e.initialState,this.context=null!==(t=e.context)&&void 0!==t?t:{},this.bfsm=new Lc(e),this.states=e.states,this.bfsm.on("*",((e,t)=>{if(t&&"object"==typeof t&&"client"in t){t.client;const n=function(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)n=o[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}(t,Rc);this.emitter.emit(e,n)}else this.emitter.emit(e,t)})),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.bfsm.handle(this.context,e,...n)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function Uc(e,t){return t.attemptId===e.attemptId}const Fc=(e,t)=>{if(Uc(e.ctx,t))return"connected"},jc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"connecting"},Bc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"reconnecting"},qc=(e,t)=>(e.ctx.closeReason=t.reason,"disconnecting"),Vc={new:{connect:jc,close:qc},connecting:{connectComplete:Fc,connectFailed:(e,t)=>(e.ctx.lastError=t.error,"closed"),close:qc},connected:{reconnect:Bc,transportFailed:(e,t)=>{let n=e.ctx;if(Uc(n,t))return n.lastError=t.reason,"offline"},close:qc},offline:{connect:jc,reconnect:Bc,close:qc},reconnecting:{reconnectComplete:Fc,reconnectFailed:(e,t)=>(e.ctx.lastError=t.error,t.recoverable?"offline":"closed"),close:qc},disconnecting:{closeComplete:"closed"},closed:{connect:jc,reconnect:Bc}};function Wc(){return new xc({id:"signal",initialState:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"new",context:{attemptId:0},states:Vc})}class Hc{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(null===(n=t.signal)||void 0===n?void 0:n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!==(i=t.protocols)&&void 0!==i?i:[]);let o,s;r.binaryType="arraybuffer",this.ws=r;const a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};r.readyState===WebSocket.CONNECTING&&(o=e,s(ss.websocket("Websocket closed before the connection opened")));const t=e.closeCode,n=e.reason;r.close(t,void 0===n?void 0:function(e){const t=new TextEncoder;if(t.encode(e).length<=Kc)return e;let n="",i=0;for(const r of e){if(i+=t.encode(r).length,i>Kc)break;n+=r}return n}(n))};this.opened=new Wo(((e,t)=>{s=t;const n=()=>{t(ss.websocket("Encountered websocket error during connection establishment"))},i=e=>{t(ss.websocket("Websocket closed during connection establishment with code ".concat(e.code).concat(e.reason?": ".concat(e.reason):"")))};r.onopen=()=>{o?a(o):(e({readable:new ReadableStream({start(e){r.onmessage=t=>{let n=t.data;r.readyState===WebSocket.OPEN&&e.enqueue(n)},r.onerror=t=>{return e.error(ss.websocket((i="websocket",(n=t)instanceof Error?n.name&&n.message?"".concat(n.name,": ").concat(n.message):n.name:"Encountered unknown ".concat(i," error: ").concat(String(n)))));var n,i},r.onclose=t=>{t.wasClean||1e3===t.code?e.close():e.error(ss.websocket("WS closed unexpectedly with code ".concat(t.code)))}},cancel:a}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",n),r.removeEventListener("close",i))},r.addEventListener("error",n),r.addEventListener("close",i)})),this.closed=new Wo(((e,t)=>{const n=()=>Ao(this,void 0,void 0,(function*(){const n=new Wo((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield Wo.race([Ks(250),n]);i?e(i):t(ss.websocket("Encountered unspecified websocket error without a timely close event"))}));r.addEventListener("close",(t=>{let i=t.code,o=t.reason;e({closeCode:i,reason:o}),r.removeEventListener("error",n)})),r.addEventListener("error",n)})),t.signal&&(t.signal.onabort=()=>a()),this.close=a}}const Kc=123;const zc=["syncState","trickle","offer","answer","simulate","leave"];var Gc;!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"}(Gc||(Gc={}));class Jc{get currentState(){return function(e){switch(e){case"connected":return Gc.CONNECTED;case"connecting":return Gc.CONNECTING;case"reconnecting":return Gc.RECONNECTING;case"disconnecting":return Gc.DISCONNECTING;default:return Gc.DISCONNECTED}}(this.lifecycleState)}get isDisconnected(){const e=this.currentState;return e===Gc.DISCONNECTING||e===Gc.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){const t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return Ao(this,void 0,void 0,(function*(){this.log.debug("waiting for an in-flight close to settle before establishing a session"),(yield this.closingLock.lock())()}))}get isEstablishingConnection(){return"connecting"===this.lifecycleState||"reconnecting"===this.lifecycleState}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.log=wo,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=n.loggerContextCb,this.log=Po(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal,(()=>this.logContext)),this.useJSON=t,this.requestQueue=new Ec,this.queuedRequests=[],this.closingLock=new be,this.connectionLock=new be,this.machine=Wc(),this.machine.on("transitioned",(e=>{let t=e.fromState,n=e.toState;this.log.debug("signal lifecycle: ".concat(t," -> ").concat(n))})),this.machine.on("nohandler",(e=>{let t=e.inputName;this.log.debug("ignoring signal lifecycle input ".concat(t," in state ").concat(this.lifecycleState))})),this.machine}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 Ao(this,arguments,void 0,(function(e,t,n,i){var r=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){if("disconnecting"===r.lifecycleState&&(yield r.settleInFlightClose()),!r.sendLifecycleInput({type:"connect"}))throw ss.internal("cannot establish a signal session from '".concat(r.lifecycleState,"', close the current one first"));r.options=n;try{return yield r.connect(e,t,n,i,o,s)}catch(ke){throw r.sendLifecycleInput({type:"connectFailed",error:ke}),ke}}()}))}reconnect(t,n,i,r){return Ao(this,void 0,void 0,(function*(){if(this.options){if("disconnecting"===this.lifecycleState&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:"reconnect"}))throw ss.internal("cannot resume the signal session from '".concat(this.lifecycleState,"'"));this.clearPingInterval();try{return yield this.connect(t,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(ke){throw this.sendLifecycleInput({type:"reconnectFailed",error:ke,recoverable:(o=ke,!(o instanceof ss)||o.reason!==e.ConnectionErrorReason.LeaveRequest&&o.reason!==e.ConnectionErrorReason.NotAllowed)}),ke}var o}else this.log.warn("attempted to reconnect without signal options being set, ignoring")}))}connect(e,t,n,i){return Ao(this,arguments,void 0,(function(e,t,n,i){var r=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){const a=yield r.connectionLock.lock();let c,d;try{r.connectOptions=n,r.useV0SignalPath=o;const i=function(e){var t;const n=new mi({capabilities:e,sdk:gi.JS,protocol:18,clientProtocol:2,version:Yo});return ua()&&(n.os=null!==(t=ga())&&void 0!==t?t:""),n}(n.clientInfoCapabilities),a=o?function(e,t,n){var i;const r=new URLSearchParams;r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid));r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",ua()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),r.set("client_protocol",t.clientProtocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);n.adaptiveStream&&r.set("adaptive_stream","1");n.disableIceLite&&r.set("disable_ice_lite","1");void 0!==n.subscriberAllowPause&&r.set("subscriber_allow_pause",n.subscriberAllowPause?"1":"0");n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type);return r}(t,i,n):yield function(e,t,n,i){return Ao(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const o=new ho({clientInfo:t,connectionSettings:new uo({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream,disableIceLite:!!n.disableIceLite,subscriberAllowPause:n.subscriberAllowPause}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:i});n.reconnectReason&&(o.reconnectReason=n.reconnectReason);const s=o.toBinary();let a,c;if(Qa()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(s)),t.close();const n=[],i=e.readable.getReader();for(;;){const e=yield i.read(),t=e.done,r=e.value;if(t)break;n.push(r)}const r=n.reduce(((e,t)=>e+t.length),0),o=new Uint8Array(r);let d=0;for(const s of n)o.set(s,d),d+=s.length;a=o,c=mo.GZIP}else a=s,c=mo.NONE;const d=new po({joinRequest:a,compression:c}).toBinary(),l=e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r}))}(t,i,n,s);c=$a(e,a,o).toString(),d=(l=c,tc(new URL(Na(l)),"validate")).toString()}catch(ke){throw a(),ke}var l;if(null==i?void 0:i.aborted)throw a(),r.log.debug("signal connect abandoned before opening a transport"),ss.cancelled("Connection aborted");return new Promise(((e,t)=>Ao(r,void 0,void 0,(function*(){var r,o,s,l,u;try{let a=!1;const h=e=>Ao(this,void 0,void 0,(function*(){if(a)return;a=!0;const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;const n=e.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:t;default:return"toString"in n?n.toString():t}}(e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(!0,n))).catch((e=>{this.log.error(e),this.close(!0,n)})):this.close(!0,n),p(),t(e instanceof ss?e:ss.cancelled(n))}));null==i||i.addEventListener("abort",h);const p=()=>{clearTimeout(m),null==i||i.removeEventListener("abort",h)},m=setTimeout((()=>{h(ss.timeout("room connection has timed out (signal)"))}),n.websocketTimeout),g=new URL(c);if(g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.ws){const e=performance.now();yield this.teardownTransport("replaced by a new connection attempt"),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}if(a)return void this.log.debug("signal connect abandoned after tearing down the previous transport");const f=this.attemptId;this.log.info("signal connecting to ".concat(g),{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws=new Hc(c);let v=!1;this.ws.opened.catch((()=>{v=!0}));try{this.ws.closed.then((e=>{this.isEstablishingConnection&&!v&&t(ss.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),this.log.debug("websocket closed",{reason:e.reason,code:e.closeCode,attemptId:f,state:this.lifecycleState}),this.handleOnClose(e.reason||(1e3===e.closeCode?"server closed the signal connection":"Unexpected WS error"),f)})).catch((e=>{this.isEstablishingConnection&&!v&&t(ss.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const i=yield this.ws.opened.catch((e=>Ao(this,void 0,void 0,(function*(){if(a)this.log.debug("signal connect abandoned while the websocket was opening");else if("connected"===this.lifecycleState)this.handleWSError(e),t(e);else{clearTimeout(m);const n=yield this.handleConnectionError(e,d);t(n)}}))));if(clearTimeout(m),!i)return;const c=i.readable.getReader();let h;this.streamWriter=i.writable.getWriter();try{const e=Date.now()+5e3;for(;;){const t=e-Date.now();if(t<=0)throw ss.timeout("signal connection timed out while waiting for the first message");let n;const i=yield Promise.race([c.read(),new Promise(((e,i)=>{n=setTimeout((()=>{i(ss.timeout("signal connection timed out while waiting for the first message"))}),t)}))]);if(clearTimeout(n),!i.value)throw ss.internal("no message received as first message");const a=nc(i.value);if("reconnecting"!==this.lifecycleState||"reconnect"===(null===(r=a.message)||void 0===r?void 0:r.case)||"leave"===(null===(o=a.message)||void 0===o?void 0:o.case)){h=a;break}this.log.warn("dropping signal message while awaiting reconnect response",{messageCase:null===(s=a.message)||void 0===s?void 0:s.case})}}catch(ke){return c.releaseLock(),t(ke),void this.close()}if(c.releaseLock(),a)return void this.log.debug("signal connect abandoned while waiting for the first message");const p=this.validateFirstMessage(h,null!==(l=n.reconnect)&&void 0!==l&&l);if(!p.isValid)return void t(p.error);"join"===(null===(u=h.message)||void 0===u?void 0:u.case)&&(this.pingTimeoutDuration=h.message.value.pingTimeout,this.pingIntervalDuration=h.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(h.message.value)),this.handleSignalConnected(i,m,f),e(p.response)}catch(ke){t(ke)}finally{p()}}finally{a()}}))))}()}))}startReadingLoop(e){return Ao(this,void 0,void 0,(function*(){const t=this.attemptId;for(;;){this.signalLatency&&(yield Ks(this.signalLatency));try{const t=yield e.read(),n=t.done,i=t.value;if(n)break;const r=nc(i);this.handleSignalResponse(r)}catch(ke){yield this.handleOnClose("error in reading loop",t,void 0,ke);break}}}))}close(){return Ao(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){const i=t&&e.sendLifecycleInput({type:"close",reason:n}),r=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{i&&e.sendLifecycleInput({type:"closeComplete"}),r()}}()}))}teardownTransport(e){return Ao(this,void 0,void 0,(function*(){try{this.clearPingInterval();const t=this.ws;t&&(this.ws=void 0,this.streamWriter=void 0,t.close({closeCode:1e3,reason:e}),yield Promise.race([t.closed,Ks(250)]))}catch(ke){this.log.debug("websocket error while closing",{error:ke})}}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Yc(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Yc(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new gr({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new fr({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Ao(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const r=n.getNextRequestId();return yield n.sendRequest({case:"updateMetadata",value:new xr({requestId:r,metadata:e,name:t,attributes:i})}),r}()}))}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 Nr({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Qr({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ve.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new no({timestamp:Ve.parse(Date.now()),rtt:Ve.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Dr({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ar({reason:Cn.CLIENT_INITIATED,action:Lr.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new dr({pubHandle:e,name:t,encryption:n?xn.GCM:xn.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new ur({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Cr({updates:[new wr({trackSid:e,subscribe:t})]})})}sendRequest(e){return Ao(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=zc.indexOf(e.case)>=0;return wo.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e),r="reconnecting"===t.lifecycleState||t.queuedRequests.length>0;if(i&&r)return void t.queuedRequests.push((()=>Ao(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Ks(t.signalLatency));const o="leave"===e.case&&!!t.streamWriter;if(t.isDisconnected&&!o)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const s=new or({message:e});try{t.useJSON?yield t.streamWriter.write(s.toJsonString()):yield t.streamWriter.write(s.toBinary().buffer)}catch(ke){t.log.error("error sending signal message",{error:ke})}}()}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message");let r=!1;if("answer"===i.case){const e=Qc(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=Qc(i.value);this.onOffer&&this.onOffer(e,i.value.id,i.value.midToTrackId)}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(),r=!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)):"mediaSectionsRequirement"===i.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(i.value):"publishDataTrackResponse"===i.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(i.value):"unpublishDataTrackResponse"===i.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(i.value):"dataTrackSubscriberHandles"===i.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(i.value):this.log.debug("unsupported message",{msgCase:i.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.attemptId,i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0;return function*(){const o=t.onClose;t.sendLifecycleInput({type:"transportFailed",attemptId:n,reason:e})?(void 0!==r&&t.log.error("error reading from signal stream",{error:r}),yield t.teardownTransport(e),t.log.info("websocket connection closed: ".concat(e),{reason:e}),i&&(t.log.info("waiting for ".concat(i,"ms until reconnecting signal")),yield Ks(i)),o&&o(e)):t.log.debug("ignoring transport close in state ".concat(t.lifecycleState),Object.assign({reason:e,attemptId:n,currentAttemptId:t.attemptId},void 0!==r?{error:r}:{}))}()}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.isDisconnected||(this.pingTimeoutDuration?this.pingTimeout=ks.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set"))}clearPingTimeout(){this.pingTimeout&&ks.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=ks.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ks.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){clearTimeout(t);this.sendLifecycleInput("reconnecting"===this.lifecycleState?{type:"reconnectComplete",attemptId:n}:{type:"connectComplete",attemptId:n})?(this.log.info("signal connected"),this.startPingInterval(),this.startReadingLoop(e.readable.getReader())):this.log.debug("discarding a connection whose attempt no longer owns the session",{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState})}validateFirstMessage(e,t){var n,i,r,o;return"join"===(null===(n=e.message)||void 0===n?void 0:n.case)||"reconnecting"===this.lifecycleState&&"reconnect"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.isEstablishingConnection&&"leave"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!1,error:ss.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:ss.internal("Unexpected first message")}:{isValid:!1,error:ss.internal("did not receive join response, got ".concat(null===(o=e.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(e,t){return Ao(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{signal:wc(3e3)});switch(n.status){case 404:const e=yield n.text();return e.includes("requested room does not exist")?ss.notAllowed(e,n.status):ss.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield n.text();return ss.notAllowed(t,n.status)}return e instanceof ss?e:ss.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(ke){return ke instanceof ss?ke:ss.serverUnreachable(ke instanceof Error?ke.message:"server was not reachable")}}))}}function Qc(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 Yc(e,t){return new Tr({sdp:e.sdp,type:e.type,id:t})}class Xc{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 n of this._map.entries()){var t=tt(n,2);const i=t[0];t[1].expiresAt<e&&this._map.delete(i)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const n of this._map.entries()){var t=tt(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,i,this.asValueMap())}}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const r of n.entries()){var i=tt(r,2);const o=i[0],s=i[1];t.push(e(s,o,n))}return t}asValueMap(){const e=new Map;for(const n of this._map.entries()){var t=tt(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(i,r.value)}return e}}var Zc,$c,ed,td,nd,id={},rd={},od={exports:{}};function sd(){if(Zc)return od.exports;Zc=1;var e=od.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")}))})),od.exports}function ad(){return $c||($c=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var r=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:r&&!n[e.name]&&(n[e.name]={});var o=e.push?{}:r?n[e.name]:n;!function(e,n,i,r){if(r&&!i)n[r]=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=sd(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(r))return n(c,s,r)}})),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),r=0;r<i.length;r+=3)n.push({component:i[r],ip:i[r+1],port:i[r+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}}))}))}}(rd)),rd}function cd(){if(td)return ed;td=1;var e=sd(),t=/%[sdv%]/g,n=function(e){var n=1,i=arguments,r=i.length;return e.replace(t,(function(e){if(n>=r)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 r=[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 s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return ed=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 s=n.outerOrder||r,a=n.innerOrder||o,c=[];return s.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"},ed}var dd=function(){if(nd)return id;nd=1;var e=ad(),t=cd(),n=sd();return id.grammar=n,id.write=t,id.parse=e.parse,id.parseParams=e.parseParams,id.parseFmtpConfig=e.parseFmtpConfig,id.parsePayloads=e.parsePayloads,id.parseRemoteCandidates=e.parseRemoteCandidates,id.parseImageAttributes=e.parseImageAttributes,id.parseSimulcastStreamList=e.parseSimulcastStreamList,id}();function ld(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i,r;let o;const s=null!==(i=n.isImmediate)&&void 0!==i&&i,a=null!==(r=n.callback)&&void 0!==r&&r,c=n.maxWait;let d=Date.now(),l=[];const u=function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];const u=this;return new Promise(((n,r)=>{const h=s&&void 0===o;if(void 0!==o&&ks.clearTimeout(o),o=ks.setTimeout((function(){if(o=void 0,d=Date.now(),!s){const t=e.apply(u,i);a&&a(t),l.forEach((e=>(0,e.resolve)(t))),l=[]}}),function(){if(void 0!==c){const e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){const t=e.apply(u,i);return a&&a(t),n(t)}l.push({resolve:n,reject:r})}))};return u.cancel=function(e){void 0!==o&&ks.clearTimeout(o),l.forEach((t=>(0,t.reject)(e))),l=[]},u}const ud=1e3,hd=300,pd=1500;function md(e,t,n){var i,r,o;if(null===(i=e.msid)||void 0===i?void 0:i.includes(t))return null!==(o=null===(r=e.rtp.find((e=>e.codec.toUpperCase()===n.toUpperCase())))||void 0===r?void 0:r.payload)&&void 0!==o?o:0}function gd(e,t){if(e.maxbr<300)return;const n=Math.min(Math.round(.9*e.maxbr),e.maxbr);if(e.isScreenShare)return n;const i=Math.min(function(e){if(void 0===e)return ud;const t=Math.min(Math.max((e-pd)/2e3,0),1);return Math.round(ud-700*t)}(t),function(){const e="undefined"!=typeof navigator?navigator.connection:void 0;switch(null==e?void 0:e.effectiveType){case"slow-2g":case"2g":return hd;case"3g":return 500;default:return ud}}());return Math.min(n,i)}const fd="negotiationStarted",vd="negotiationComplete",kd="offerAnswered",yd="rtpVideoPayloadTypes";class bd extends Vo.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=wo,this.iceLog=wo,this.ddExtID=0,this.latestOfferId=0,this.answeredOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.hasAppliedVideoStartBitrate=!1,this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ld((e=>Ao(this,void 0,void 0,(function*(){this.emit(fd);try{yield this.createAndSendOffer()}catch(ke){if(!e)throw ke;e(ke)}}))),20),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.loggerOptions=n,this.log=Po(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport,(()=>this.logContext)),this.iceLog=Po(e.LoggerNames.ICE,(()=>this.logContext)),this.config=t,this._pc=this.createPC(),this.offerLock=new be}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:e.candidate.candidate}),null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug("ICE candidate error",{event:e}),null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug("data channel opened by peer",{label:e.channel.label,id:e.channel.id}),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 Ao(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)}))}isStaleAnswer(e){return this.latestOfferId>0&&e>0&&e!==this.latestOfferId}setRemoteDescription(e,t){return Ao(this,void 0,void 0,(function*(){var n;if("answer"===e.type&&this.isStaleAnswer(t))return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;if("answer"===e.type){if(function(e,t,n,i,r){return t===e||(e>0?e===n:"stable"===i&&!r)}(t,this.answerInFlight,this.answeredOfferId,null===(n=this._pc)||void 0===n?void 0:n.signalingState,void 0!==this.pendingInitialOffer))return this.log.warn("ignoring duplicate answer",{offerId:t}),!1;this.answerInFlight=t}try{return yield this.applyRemoteDescription(e,t)}finally{"answer"===e.type&&(this.answerInFlight=void 0)}}))}applyRemoteDescription(e,t){return Ao(this,void 0,void 0,(function*(){var n,i;let r;if("offer"===e.type){let t=function(e){var t;const n=[],i=[],r=dd.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return r.media.forEach((e=>{var t;const r=Rd(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(o=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===o&&"nack"===e.type)))&&i.push(r),e.fmtp.some((e=>e.payload===o&&(Sd(e.config,"sprop-stereo=1")&&n.push(r),!0))))})),{stereoMids:n,nackMids:i}}(e),n=t.stereoMids,i=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=i}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=dd.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{wd(e)})),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(e,dd.write(t))}const t=dd.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{const t=Rd(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 r=!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)),r=!0;break}return r||n.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*n.maxbr)}),!0}))}));const o=this.getPlaceholderMids();o.size>0&&Cd(t.media,(e=>o.has(Rd(e.mid)))),r=dd.write(t)}if(yield this.setMungedSDP(e,r,!0),"answer"===e.type&&t>0&&(this.answeredOfferId=t),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(kd,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(vd),e.sdp)){dd.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(yd,e.rtp)}))}return!0}))}createInitialOffer(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer");const t=this.latestOfferId+1;this.latestOfferId=t;const n=yield this.pc.createOffer();this.pendingInitialOffer={sdp:n.sdp,type:n.type};const i=dd.parse(null!==(e=n.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{wd(e)})),n.sdp=dd.write(i),{offer:n,offerId:t}}finally{t()}}))}createAndSendOffer(e){return Ao(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.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&("have-local-offer"===this._pc.signalingState||this.pendingInitialOffer)){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t){if(null==e?void 0:e.iceRestart)throw new hs("ICE restart requested without a remote description, peer connection must be recreated");return this.renegotiate=!0,void this.log.debug("requesting renegotiation")}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.log.debug("starting to negotiate");const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:i.sdp});const r=dd.parse(null!==(t=i.sdp)&&void 0!==t?t:""),o=this.hasAppliedVideoStartBitrate?void 0:function(e,t,n){let i;for(const r of e)if("video"===r.type&&"recvonly"!==r.direction&&"inactive"!==r.direction)for(const e of t){if(!e.cid)continue;const t=md(r,e.cid,e.codec);if(void 0===t)continue;const o=t>0?gd(e,n):void 0;void 0!==o&&(void 0===i||o>i)&&(i=o);break}return i}(r.media,this.trackBitrates,this.connectionSetupTimeEstimateMs());let s=!1;r.media.forEach((e=>{wd(e),"audio"===e.type?Ed(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!t.cid)return!1;const n=md(e,t.cid,t.codec);return void 0!==n&&(n>0&&(void 0!==o&&(s=function(e,t,n){const i=e.fmtp.find((e=>e.payload===t));return i?i.config.includes("x-google-start-bitrate")||(i.config+=";x-google-start-bitrate=".concat(n)):e.fmtp.push({payload:t,config:"x-google-start-bitrate=".concat(n)}),!0}(e,n,o)||s),Ys(t.codec)&&!oa()&&(this.ddExtID=function(e,t,n){var i,r;const o=function(e,t){const n=function(e,t){var n;for(const i of e.media){const e=null===(n=i.ext)||void 0===n?void 0:n.find((e=>e.uri===t));if(e)return e.value}return}(e,Ws);if(void 0!==n)return Td(e,n,Ws)?void 0:n;if(0!==t&&!Td(e,t,Ws))return t;return function(e){let t=0;return e.media.forEach((e=>{var n;null===(n=e.ext)||void 0===n||n.forEach((e=>{e.value>t&&(t=e.value)}))})),t+1===15?16:t+1}(e)}(t,n);if(void 0===o)return n;(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Ws)))||(null!==(r=e.ext)&&void 0!==r||(e.ext=[]),e.ext.push({value:o,uri:Ws}));return o}(e,r,this.ddExtID))),!0)}))}));const a=this.getPlaceholderMids();if(a.size>0&&Cd(r.media,(e=>a.has(Rd(e.mid)))),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:n});const c=dd.write(r);yield this.setMungedSDP(i,c),s&&i.sdp===c&&(this.hasAppliedVideoStartBitrate=!0,this.log.info("applied x-google-start-bitrate",{startBitrateKbps:o,connectionSetupTimeMs:this.connectionSetupTimeEstimateMs()})),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=dd.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{wd(e),"audio"===e.type&&Ed(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,dd.write(n)),t}))}getPlaceholderMids(){var e,t;return function(e){const t=new Set;for(const n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}(null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new us("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConnectionSetupTime(e){this.connectionSetupTimeMs=e}setConnectionStartedAt(e){this.connectionStartedAt=e}connectionSetupTimeEstimateMs(){return void 0!==this.connectionSetupTimeMs?this.connectionSetupTimeMs:void 0!==this.connectionStartedAt?Math.round(performance.now()-this.connectionStartedAt):void 0}setConfiguration(e){var t;if(!this._pc)throw new us("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(){var e;return null===(e=this._pc)||void 0===e?void 0:e.getStats()}getMaxMessageSize(){var e,t;return null===(t=null===(e=this._pc)||void 0===e?void 0:e.sctp)||void 0===t?void 0:t.maxMessageSize}getConnectedAddress(){return Ao(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 r=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?i.get(r):void 0}))}setMungedSDP(e,t,n){return Ao(this,void 0,void 0,(function*(){var i,r;const o=e.sdp;if(t){e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description")),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(ke){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:ke,mungedSdp:t,originalSdp:o}),e.sdp=o}}try{n?yield null===(i=this._pc)||void 0===i?void 0:i.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(ke){let r="unknown error";ke instanceof Error?r=ke.message:"string"==typeof ke&&(r=ke);const s={error:r,sdp:e.sdp};throw t&&t!==o&&(s.mungedSdp=t),!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:s}),new hs(r)}}))}}function Td(e,t,n){return e.media.some((e=>{var i;return null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.value===t&&e.uri!==n))}))}function Sd(e,t){return e.split(";").some((e=>e.trim()===t))}function Ed(e,t,n){const i=Rd(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(r=e.payload,!0))),r>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(i)&&!e.rtcpFb.some((e=>e.payload===r&&"nack"===e.type))&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(i)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===r&&(Sd(e.config,"stereo=1")||(e.config+=";stereo=1"),!0))))}function Cd(e,t){var n,i,r,o,s,a,c,d;const l=new Map;for(const u of e){const e=t(u);for(const t of null!==(n=u.rtp)&&void 0!==n?n:[]){const n=t.payload,s=null!==(o=null===(r=null===(i=u.fmtp)||void 0===i?void 0:i.find((e=>e.payload===n)))||void 0===r?void 0:r.config)&&void 0!==o?o:"";e&&l.has(n)||l.set(n,s)}}for(const u of e)if(t(u))for(const e of null!==(s=u.rtp)&&void 0!==s?s:[]){const t=e.payload,n=l.get(t),i=null===(a=u.fmtp)||void 0===a?void 0:a.find((e=>e.payload===t));""===n?u.fmtp=(null!==(c=u.fmtp)&&void 0!==c?c:[]).filter((e=>e.payload!==t)):i?i.config=n:u.fmtp=[...null!==(d=u.fmtp)&&void 0!==d?d:[],{payload:t,config:n}]}}function wd(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 Rd(e){return"number"==typeof e?e.toFixed(0):e}const Pd=7e3,Id=[0,300,1200,2700,4800,Pd,Pd,Pd,Pd,Pd];class _d{constructor(e){this._retryDelays=void 0!==e?[...e]:Id}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return 0===e.retryCount&&0===t?500*Math.random():Math.round(t*(.5+Math.random()))}}const Od="vp8",Dd={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,stopMicTrackOnMute:!1,preConnectBuffer:!1},Md={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Ad={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new _d,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Ld={autoSubscribe:!0,disableIceLite:!1,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Nd,xd;!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"}(Nd||(Nd={}));class Ud{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=i.rtcConfig,o=i.peerConnectionTimeout,s=void 0===o?Ld.peerConnectionTimeout:o;var a;this.log=wo,this.iceLog=wo,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=Nd.CONNECTED:i.some((e=>"failed"===e))?this.state=Nd.FAILED:i.some((e=>"connecting"===e))?this.state=Nd.CONNECTING:i.every((e=>"closed"===e))?this.state=Nd.CLOSED:i.some((e=>"closed"===e))?this.state=Nd.CLOSING:i.every((e=>"new"===e))&&(this.state=Nd.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(Nd[n]," to ").concat(Nd[this.state])),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.loggerOptions=n,this.peerConnectionTimeout=s,this.log=Po(null!==(a=n.loggerName)&&void 0!==a?a:e.LoggerNames.PCManager,(()=>this.logContext)),this.iceLog=Po(e.LoggerNames.ICE,(()=>this.logContext)),this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new bd(r,n),this._mode=t,"publisher-only"!==t&&(this.subscriber=new bd(r,n),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tr.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.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tr.PUBLISHER)},this.publisher.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=Nd.NEW,this.connectionLock=new be,this.remoteOfferLock=new be}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()}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 Ao(this,void 0,void 0,(function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(ke){this.log.warn("could not removeTrack",{error:ke})}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return Ao(this,void 0,void 0,(function*(){this.iceLog.warn("triggering ICE restart"),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Ao(this,void 0,void 0,(function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===tr.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()});const o=yield this.remoteOfferLock.lock();try{if(!(yield null===(i=this.subscriber)||void 0===i?void 0:i.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{o()}}))}updateConfiguration(e,t){var n;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Ao(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.publisher.negotiate().catch((e=>{this.log.error(e)}))),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 Ao(this,void 0,void 0,(function*(){return new Wo(((t,n)=>{const i=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>i)return this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),void t();let r=!1;const o=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(kd,s),e.signal.removeEventListener("abort",a))},s=e=>{e>i&&(o(),t())},a=()=>{o(),n(new hs("negotiation aborted"))},c=setTimeout((()=>{o(),n(new hs("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",a),this.publisher.on(kd,s),this.publisher.negotiate((e=>{o(),e instanceof Error?n(e):n(new Error(String(e)))}))}))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getTransceiverForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((t=>t.receiver===e))}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===tr.PUBLISHER||e===tr.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Ao(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,r)=>Ao(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection"),ks.clearTimeout(s),r(ss.cancelled("room connection has been cancelled"))};let o=!1;const s=ks.setTimeout((()=>{o=!0,null==t||t.signal.removeEventListener("abort",n),r(ss.internal("could not establish pc connection"))}),i);for((null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);this.state!==Nd.CONNECTED;){if(yield Ks(50),o)return;if(null==t?void 0:t.signal.aborted)return void r(ss.cancelled("room connection has been cancelled"))}ks.clearTimeout(s),null==t||t.signal.removeEventListener("abort",n),e()}))))}()}))}}class Fd{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new be,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){const t=this.handle;this.handle=e,t&&t!==e&&this.release(t,"data channel replaced")}detach(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"data channel torn down";const t=this.handle;this.handle=void 0,t&&this.release(t,e)}release(e,t){this.invalidateWaiters(t),e.close()}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(e){return Ao(this,void 0,void 0,(function*(){const t=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock(e)}finally{t()}}))}waitForHeadroomWithoutLock(e){return Ao(this,void 0,void 0,(function*(){if(this.isEngineClosed())throw new us("engine closed");if("open"!==e.readyState)throw new us("DataChannel ".concat(this.kind," is ").concat(e.readyState));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new Wo(((n,i)=>{const r=()=>{a(),n()},o=()=>{a(),i(new us("DataChannel ".concat(this.kind," closed while draining the buffer")))},s=()=>{a(),i(new us("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},a=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",o),t.removeEventListener("abort",s)};t.aborted?s():(e.addEventListener("bufferedamountlow",r),e.addEventListener("close",o),t.addEventListener("abort",s))}))}))}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,null===(e=this.onBufferStatusChanged)||void 0===e||e.call(this,n))}}class jd extends Fd{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return Ao(this,void 0,void 0,(function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":if(!this.isBelowHighWaterMark(t))try{yield this.waitForHeadroomWithLock(t)}catch(n){if(this.isEngineClosed())throw n;return}break;case"drop":if(!this.isBelowLowWaterMark(t))return this.dropCount+=1,void(this.dropCount%100==0&&wo.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount)))}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(!(n instanceof TypeError))throw n;wo.error(n)}}}))}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=ks.setInterval((()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}}),1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(ks.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class Bd{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter((e=>!e.sent))}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(!t.sent)break;if(this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class qd extends Fd{constructor(e){super(e),this.messageBuffer=new Bd,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return Ao(this,void 0,void 0,(function*(){if(this.isDeferringSends())return void this.messageBuffer.push({data:e,sequence:t,sent:!1});const n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock(n)}catch(i){if(this.isEngineClosed())throw i;return void this.messageBuffer.push({data:e,sequence:t,sent:!1})}this.isDeferringSends()?this.messageBuffer.push({data:e,sequence:t,sent:!1}):(this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus())}}))}replay(e){return Ao(this,void 0,void 0,(function*(){if(!this.getChannel())return;this.messageBuffer.popToSequence(e);const t=yield this.lockHeadroom();try{const e=this.getChannel();if(!e)throw new us("DataChannel not found, kind: ".concat(this.kind));this.messageBuffer.markAllUnsent();for(let t=this.messageBuffer.getUnsent();t.length>0;t=this.messageBuffer.getUnsent())for(const n of t)yield this.waitForHeadroomWithoutLock(e),e.send(n.data),this.messageBuffer.markSent(n)}finally{t()}this.refreshBufferStatus()}))}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new Bd,this.sequence=1}}!function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(xd||(xd={}));function Vd(e){return e===xd.RELIABLE?65536:8192}function Wd(e){return e===xd.RELIABLE?1048576:262144}const Hd="_lossy",Kd="_reliable",zd="_data_track";function Gd(e){e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null}class Jd{constructor(e){this.negotiated=!1,this.opts=e;const t=t=>({kind:t,lowWaterMark:Vd(t),highWaterMark:Wd(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new qd(Object.assign(Object.assign({},t(xd.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new jd(Object.assign(Object.assign({},t(xd.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new jd(Object.assign(Object.assign({},t(xd.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case xd.RELIABLE:return this.reliable;case xd.LOSSY:return this.lossy;case xd.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&void 0!==arguments[1]&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case xd.RELIABLE:return this.reliableSub;case xd.LOSSY:return this.lossySub;case xd.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return Boolean(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}get publisherChannelsNegotiated(){return this.hasPublisherChannels&&this.negotiated}createPublisherChannels(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];for(const r of[this.lossy,this.reliable,this.dataTrack]){const e=r.channelHandle;e&&Gd(e)}const n=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)},i=e=>t?{negotiated:t,id:e}:{};n(this.lossy,e.createPublisherDataChannel(Hd,Object.assign({ordered:!1,maxRetransmits:0},i(ir.NDCI_LOSSY))),this.opts.onDataMessage),n(this.reliable,e.createPublisherDataChannel(Kd,Object.assign({ordered:!0},i(ir.NDCI_RELIABLE))),this.opts.onDataMessage),n(this.dataTrack,e.createPublisherDataChannel(zd,Object.assign({ordered:!1,maxRetransmits:0},i(ir.NDCI_DATA_TRACK))),this.opts.onDataTrackMessage),this.negotiated=t,this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===Kd)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Hd)this.lossySub=e,t=this.opts.onDataMessage;else{if(e.label!==zd)return!1;this.dataTrackSub=e,t=this.opts.onDataTrackMessage}return e.onmessage=t,!0}teardown(){const e=[this.lossy,this.reliable,this.dataTrack],t=[this.lossySub,this.reliableSub,this.dataTrackSub];for(const n of e){const e=n.channelHandle;e&&Gd(e),n.detach("peer connections cleaned up")}for(const n of t)n&&(Gd(n),n.close());this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const Qd="leave-reconnect";var Yd;!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"}(Yd||(Yd={}));class Xd extends Vo.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get serverVersion(){var e,t,n;return(null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.serverInfo)||void 0===t?void 0:t.version)||(null===(n=this.latestJoinResponse)||void 0===n?void 0:n.serverVersion)||void 0}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Ld.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Yd.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=wo,this.reliableReceivedState=new Xc(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.pendingNegotiationAborts=new Set,this.handleDataChannel=e=>Ao(this,[e],void 0,(function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug("on data channel ".concat(n.id,", ").concat(n.label))}()})),this.handleDataMessage=t=>Ao(this,void 0,void 0,(function*(){var n,i,r,o;const s=yield this.dataProcessLock.lock();try{const s=yield this.decodeDataMessage(t);if(!s)return;const c=Yn.fromBinary(s);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");let t;try{t=yield this.e2eeManager.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex)}catch(a){return void this.log.debug("failed to decrypt data packet",{error:a,participantIdentity:c.participantIdentity})}const n=$n.fromBinary(t.payload),i=new Yn({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(r=i.value)||void 0===r?void 0:r.case)&&Zd(i,i.value.value),this.emit(e.EngineEvent.DataPacketReceived,i,c.value.value.encryptionType)}else"user"===(null===(o=c.value)||void 0===o?void 0:o.case)&&Zd(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,xn.NONE)}finally{s()}})),this.handleDataTrackMessage=e=>Ao(this,void 0,void 0,(function*(){const t=yield this.decodeDataMessage(e);t&&this.emit("dataTrackPacketReceived",t)})),this.handleDataError=e=>{if(this._isClosed)return;const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("undefined"!=typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){const n=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(n.message),{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||"connected"!==(null===(t=this.pcManager)||void 0===t?void 0:t.publisher.getConnectionState())||this.log.error("publisher data channel '".concat(xd[e],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected")),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.emit(e.EngineEvent.Disconnected),this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms"))},r=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(null===o)return void i(r);if(t===Qd&&(o=this.getNextRetryDelay({elapsedMs:r,retryCount:0}),null===o))return void i(r);this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(e.EngineEvent.TokenRefreshed,this.token);const s=ks.setTimeout((()=>this.attemptReconnect(n).finally((()=>{this.reconnectTimeout===s&&(this.reconnectTimeout=void 0)}))),o);this.reconnectTimeout=s},this.waitForRestarted=t=>new Promise((n=>{if(t.aborted)return void n(!1);const i=()=>{t.removeEventListener("abort",r),n(!0)},r=()=>{t.removeEventListener("abort",r),this.off(e.EngineEvent.Restarted,i),n(!1)};this.once(e.EngineEvent.Restarted,i),t.addEventListener("abort",r)})),this.onRtpMapAvailable=t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();Ma(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)},this.handleBrowserOnLine=()=>Ao(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(Na(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===Gc.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Gc.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(wn.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Ao(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Na(this.url),{method:"HEAD"}),Ks(4e3).then((()=>Promise.reject()))])}catch(ke){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=Po(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new Jc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new be,this.dataProcessLock=new be,this.dataChannels=new Jd({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(t,n)=>this.emit(e.EngineEvent.DCBufferStatusChanged,n,t)}),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>{this.handleLocalConnectionQuality(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),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onJoined=t=>this.emit(e.EngineEvent.Joined,t);const i=()=>{for(const e of Array.from(this.pendingNegotiationAborts))e()};this.on(e.EngineEvent.Closing,i),this.on(e.EngineEvent.Restarting,i)}get logContext(){var e,t,n,i,r,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===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===o?void 0:o.identity,participantID:this.participantSid}}join(t,n,i,r){return Ao(this,arguments,void 0,(function(t,n,i,r){var o=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var a,c,d,l;o._isNewlyCreated=!1,o.url=t,o.token=n,o.signalOpts=i,o.maxJoinAttempts=i.maxRetries;try{o.joinAttempts+=1,o.joinStartedAt=performance.now(),o.setupSignalClientCallbacks();const u=!s&&Qa()&&!na();let h;if(u){o.pcManager||(yield o.configure(),o.applyInitialPublisherLayout(!0));const e=yield null===(a=o.pcManager)||void 0===a?void 0:a.publisher.createInitialOffer();e&&(h=Yc(e.offer,e.offerId))}if(null==r?void 0:r.aborted)throw ss.cancelled("Connection aborted");if(!s&&o.shouldFailOnV1Path)throw o.shouldFailOnV1Path=!1,ss.serviceNotFound("Simulated v1 path failure","v0-rtc");const p=yield o.client.join(t,n,i,r,s,h);if(null==r?void 0:r.aborted)throw o.log.info("join cancelled after the signal join response"),ss.cancelled("Connection aborted");if(o._isClosed=!1,o.latestJoinResponse=p,o.participantSid=null===(c=p.participant)||void 0===c?void 0:c.sid,o.subscriberPrimary=p.subscriberPrimary,u)null===(d=o.pcManager)||void 0===d||d.updateConfiguration(o.makeRTCConfiguration(p)),o.dataChannels.publisherChannelsNegotiated&&!o.useNegotiatedDataChannels()&&(o.log.debug("server does not support negotiated data channels, using in-band ones"),o.createDataChannels(!1));else{if(!o.pcManager){if(yield o.configure(p,!s),null==r?void 0:r.aborted)throw o.log.info("join cancelled after configuring peer connections"),ss.cancelled("Connection aborted");s||o.applyInitialPublisherLayout()}o.subscriberPrimary&&!p.fastPublish||o.negotiate().catch((e=>{o.log.error(e)}))}void 0!==o.joinStartedAt&&(null===(l=o.pcManager)||void 0===l||l.publisher.setConnectionStartedAt(o.joinStartedAt)),o.registerOnLineListener(),o.clientConfiguration=p.clientConfiguration,o.emit(e.EngineEvent.SignalConnected,p);let m=p.serverInfo;return m||(m={version:p.serverVersion,region:p.serverRegion}),o.log.info("connected to Livekit Server ".concat(Object.entries(m).map((e=>{let t=tt(e,2),n=t[0],i=t[1];return"".concat(n,": ").concat(i)})).join(", "))),{joinResponse:p,serverInfo:m}}catch(ke){if(ke instanceof ss)if(ke.reason===e.ConnectionErrorReason.ServerUnreachable){if(o.log.warn("Couldn't connect to server, attempt ".concat(o.joinAttempts," of ").concat(o.maxJoinAttempts)),o.joinAttempts<o.maxJoinAttempts)return o.join(t,n,i,r,s)}else if(ke.reason===e.ConnectionErrorReason.ServiceNotFound)return o.log.warn("Initial connection failed: ".concat(ke.message," – Retrying")),o.pcManager&&(o.pcManager.onStateChange=void 0,yield o.cleanupPeerConnections()),o.join(t,n,i,r,!0);throw ke}}()}))}close(t){return Ao(this,void 0,void 0,(function*(){var n,i;null===(n=this.reconnectAbortController)||void 0===n||n.abort(),this.reconnectAbortController=void 0,null===(i=this.restartAttemptController)||void 0===i||i.abort(),this.restartAttemptController=void 0;const r=yield this.closingLock.lock();if(this.isClosed)r();else try{this._isClosed=!0,this.joinAttempts=0,this.joinStartedAt=void 0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(t)}finally{r()}}))}cleanupPeerConnections(){return Ao(this,void 0,void 0,(function*(){var e;this.dataChannels.teardown(),yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return Ao(this,void 0,void 0,(function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ds("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=ks.setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(ss.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{ks.clearTimeout(i),t(e)},reject:()=>{ks.clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(ke){this.log.warn("failed to remove track",{error:ke})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.dataChannelForKind(xd.RELIABLE,!0))||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Ao(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionStrategy(e){this.regionStrategy=e}configure(t,n){return Ao(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===Nd.NEW){if(t){this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const e=this.makeRTCConfiguration(t);this.pcManager=new Ud(n?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,{rtcConfig:e,peerConnectionTimeout:this.peerConnectionTimeout})}else{const e=this.makeRTCConfiguration();this.pcManager=new Ud("publisher-only",this.loggerOptions,{rtcConfig:e,peerConnectionTimeout:this.peerConnectionTimeout})}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=(t,n,i)=>Ao(this,void 0,void 0,(function*(){var r;if(this.log.debug("primary PC state changed ".concat(t)),t===Nd.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===Nd.CONNECTED){if(void 0!==this.joinStartedAt){const e=Math.round(performance.now()-this.joinStartedAt);this.joinStartedAt=void 0,this.log.info("connection setup took ".concat(e," ms")),null===(r=this.pcManager)||void 0===r||r.publisher.setConnectionSetupTime(e)}const t=this.pcState===Yd.New;this.pcState=Yd.Connected,t&&this.emit(e.EngineEvent.Connected,this.latestJoinResponse)}else t===Nd.FAILED&&(this.pcState!==Yd.Connected&&this.pcState!==Yd.Reconnecting||(this.pcState=Yd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?wn.RR_SUBSCRIBER_FAILED:wn.RR_PUBLISHER_FAILED)));const o=this.client.isDisconnected||this.client.currentState===Gc.RECONNECTING,s=[Nd.FAILED,Nd.CLOSING,Nd.CLOSED].includes(t);o&&s&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)}}}))}setupSignalClientCallbacks(){this.client.onAnswer=(t,n,i)=>Ao(this,void 0,void 0,(function*(){this.pcManager&&(this.pcManager.publisher.isStaleAnswer(n)?this.log.warn("ignoring answer for old offer",{offerId:n,latestOfferId:this.pcManager.publisher.latestOfferId}):(this.log.debug("received server answer",{RTCSdpType:t.type,sdp:t.sdp,midToTrackId:i}),"publisher-only"===this.pcManager.mode&&Object.keys(i).length>0&&(this.midToTrackId=i),yield this.pcManager.setPublisherAnswer(t,n),this.emit(e.EngineEvent.RequestSubscribedCodecRefresh)))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>Ao(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;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",{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),{cid:e.cid});const n=this.pendingTrackResolvers[e.cid].resolve;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=t=>{this.token=t,this.emit(e.EngineEvent.TokenRefreshed,t)},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.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate().catch((e=>{this.log.error(e)}))},this.client.onPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.PublishDataTrackResponse,t)},this.client.onUnPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.UnPublishDataTrackResponse,t)},this.client.onDataTrackSubscriberHandles=t=>{this.emit(e.EngineEvent.DataTrackSubscriberHandles,t)},this.client.onClose=()=>{this.handleDisconnect("signal",wn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{var n;switch(this.log.info("client leave request received (action=".concat(null==t?void 0:t.action,")"),{reason:null==t?void 0:t.reason}),t.regions&&(this.log.debug("updating regions"),this.emit(e.EngineEvent.ServerRegionsReported,t.regions)),t.action){case Lr.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close("server leave: ".concat(null!==(n=Cn[t.reason])&&void 0!==n?n:t.reason));break;case Lr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Qd);break;case Lr.RESUME:this.handleDisconnect(Qd)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!mc())&&dc()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){const 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===En.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(e){this.createDataChannels(e),ua()||this.addMediaSections(3,3)}addMediaSections(e,t){var n,i,r;const o={direction:"recvonly"};for(let a=0;a<e;a++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("audio",o);const s="publisher-only"===(null===(i=this.pcManager)||void 0===i?void 0:i.mode);for(let a=0;a<t;a++){const e=null===(r=this.pcManager)||void 0===r?void 0:r.addPublisherTransceiverOfKind("video",o);if(s&&e){const t=Xs(e);this.log.debug("dependency descriptor negotiated for received video",{negotiated:t})}}}useNegotiatedDataChannels(){var e,t,n,i;return"publisher-only"===(null===(e=this.pcManager)||void 0===e?void 0:e.mode)&&(null!==(i=null===(n=null===(t=this.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===n?void 0:n.protocol)&&void 0!==i?i:0)>=18}createDataChannels(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.useNegotiatedDataChannels();this.pcManager&&(this.dataChannels.hasPublisherChannels&&(this.publisherConnectionPromise=void 0),this.dataChannels.createPublisherChannels(this.pcManager,e))}decodeDataMessage(e){return Ao(this,void 0,void 0,(function*(){return e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data instanceof Blob?new Uint8Array(yield e.data.arrayBuffer()):void this.log.error("unsupported data type",{data:e.data})}))}createSender(e,t,n){return Ao(this,void 0,void 0,(function*(){let i;if(zs())i=yield this.createTransceiverRTCRtpSender(e,t,n);else{if(!Gs())throw new us("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),i=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupFrameMetadataSender(i,t),i}))}createSimulcastSender(e,t,n,i){return Ao(this,void 0,void 0,(function*(){let r;if(zs())r=yield this.createSimulcastTransceiverSender(e,t,n,i);else{if(!Gs())throw new us("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupFrameMetadataSender(r,n),r}))}get frameMetadataWorker(){var e;return null===(e=this.frameMetadataOptions)||void 0===e?void 0:e.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=this.frameMetadataWorker;if(!i||(null===(n=this.signalOpts)||void 0===n?void 0:n.e2eeEnabled))return;const r=vc(t),o=fc(r);if(mc())return void(o&&(e.transform=new RTCRtpScriptTransform(i,{kind:"encode",packetTrailer:r})));if(!gc(this.frameMetadataOptions)||!("createEncodedStreams"in e))return void(o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext));const s=e.createEncodedStreams(),a=s.readable,c=s.writable;o?i.postMessage({kind:"encode",data:{readableStream:a,writableStream:c,packetTrailer:r}},[a,c]):a.pipeTo(c)}createTransceiverRTCRtpSender(e,t,n){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),qa(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};n&&(r.sendEncodings=n);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender}))}createSimulcastTransceiverSender(e,t,n,i){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}handleLocalConnectionQuality(e){if(!this.participantSid)return;const t=e.updates.find((e=>e.participantSid===this.participantSid));t&&(t.quality===Sn.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=ks.setTimeout((()=>{this.lostQualityTimeout=void 0,this._isClosed||this.pcState!==Yd.Connected||this.attemptingReconnect||this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",wn.RR_PUBLISHER_FAILED))}),1e4))}clearLostQualityTimeout(){this.lostQualityTimeout&&(ks.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return null!==(t=null===(e=this.pcManager)||void 0===e?void 0:e.publisher.getSenders().some((e=>!!e.track&&"live"===e.track.readyState)))&&void 0!==t&&t}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:wn.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(t){return Ao(this,void 0,void 0,(function*(){var n,i,r;if(this._isClosed)return;if(this.attemptingReconnect)return void this.log.warn("already attempting reconnect, returning early");this.clearLostQualityTimeout(),(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==En.DISABLED&&(null!==(r=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==r?r:Nd.NEW)!==Nd.NEW||(this.fullReconnectOnNext=!0);const o=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let s=!1;const a=new AbortController;this.reconnectAbortController=a;try{if(this.attemptingReconnect=!0,o?yield this.restartConnection(a.signal):yield this.resumeConnection(t),a.signal.aborted)return void this.log.info("reconnect attempt cancelled, not marking it as succeeded");this.clearPendingReconnect(),s=!0}catch(ke){if(a.signal.aborted)return void this.log.info("reconnect attempt cancelled, not retrying",{error:ke});this.reconnectAttempts+=1;let n=!0;ke instanceof us?(this.log.debug("received unrecoverable error",{error:ke}),n=!1):!o&&ke instanceof vs||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",wn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms")))}finally{this.reconnectAbortController===a&&(this.reconnectAbortController=void 0),this.attemptingReconnect=!1,s&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(ke){this.log.warn("encountered error in reconnect policy",{error:ke})}return null}restartConnection(t,n){return Ao(this,void 0,void 0,(function*(){var i,r,o,s;try{if(t.aborted)return void this.log.info("full reconnect cancelled before starting",{regionUrl:n});if(!this.url||!this.token)throw new us("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),null===(i=this.restartAttemptController)||void 0===i||i.abort();const o=new AbortController;if(this.restartAttemptController=o,this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient(),t.aborted)return void this.log.info("full reconnect cancelled after cleaning up the previous session",{regionUrl:n});let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new vs;s=(yield this.join(null!=n?n:this.url,this.token,this.signalOpts,t,!this.options.singlePeerConnection)).joinResponse}catch(ke){if(ke instanceof ss&&ke.reason===e.ConnectionErrorReason.NotAllowed)throw new us("could not reconnect, token might be expired");throw new vs}if(t.aborted)return void this.log.info("full reconnect cancelled after the signal join response",{regionUrl:n});if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,s,o.signal),yield this.waitForPCReconnected(),t.aborted)return void this.log.info("full reconnect cancelled after peer connections reconnected",{regionUrl:n});if(this.client.currentState!==Gc.CONNECTED)throw new vs("Signal connection got severed during reconnect");null===(r=this.regionStrategy)||void 0===r||r.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(a){if(t.aborted)return void this.log.info("full reconnect cancelled after a failed attempt",{regionUrl:n});const e=yield null===(o=this.regionStrategy)||void 0===o?void 0:o.getNextUrl(t);if(t.aborted)return void this.log.info("full reconnect cancelled during region selection",{regionUrl:n});if(e)return void(yield this.restartConnection(t,e));throw null===(s=this.regionStrategy)||void 0===s||s.resetAttempts(),a}}))}resumeConnection(t){return Ao(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new us("could not reconnect, url or token not saved");if(!this.pcManager)throw new us("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(r){let t="";if(r instanceof Error&&(t=r.message,this.log.error(r.message,{error:r})),r instanceof ss&&r.reason===e.ConnectionErrorReason.NotAllowed)throw new us("could not reconnect, token might be expired");if(r instanceof ss&&r.reason===e.ConnectionErrorReason.LeaveRequest)throw r;throw new vs(t)}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");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Gc.CONNECTED)throw new vs("Signal connection got severed during reconnect");this.client.setReconnected();const i=this.dataChannelForKind(xd.RELIABLE);"open"===(null==i?void 0:i.readyState)&&null===i.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq).catch((e=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:e}))})),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(t,n){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("PC manager is closed");let i=!1;const r=()=>{i=!0};let o,s,a,c;const d=new Promise(((i,r)=>{o=i,s=()=>r(ss.internal("could not establish pc connection")),a=()=>r(ss.cancelled("room connection has been cancelled")),this.once(e.EngineEvent.Restarted,o),this.once(e.EngineEvent.Closing,s),null==n||n.signal.addEventListener("abort",a),c=ks.setTimeout(s,null!=t?t:this.peerConnectionTimeout)}));this.once(e.EngineEvent.Restarting,r);try{yield Promise.race([this.pcManager.ensurePCTransportConnection(n,t),d]),i&&(yield d)}finally{ks.clearTimeout(c),null==n||n.signal.removeEventListener("abort",a),this.off(e.EngineEvent.Restarting,r),this.off(e.EngineEvent.Restarted,o),this.off(e.EngineEvent.Closing,s)}}))}waitForPCReconnected(){return Ao(this,void 0,void 0,(function*(){this.pcState=Yd.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Ks(2e3),!this.pcManager)throw new us("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Yd.Connected}catch(ke){throw this.pcState=Yd.Disconnected,ss.internal("could not establish PC connection, ".concat(ke.message))}}))}publishRpcAck(e,t){return Ao(this,void 0,void 0,(function*(){const n=new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcAck",value:new ci({requestId:t})}});yield this.sendDataPacket(n,xd.RELIABLE)}))}sendDataPacket(e,t){return Ao(this,void 0,void 0,(function*(){var n,i;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=pc(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Zn({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===xd.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const r=e.toBinary(),o=Math.min(null!==(i=null===(n=this.pcManager)||void 0===n?void 0:n.getMaxPublisherMessageSize())&&void 0!==i?i:64e3,64e3);if(void 0!==o&&0!==o&&r.byteLength>o)throw new ps("cannot publish data packet larger than ".concat(o," bytes (got ").concat(r.byteLength,")"));t===xd.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)}))}sendDataTrackFrame(e){return Ao(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(xd.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)}))}resendReliableMessagesForResume(e){return Ao(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(xd.RELIABLE),yield this.reliableChannel.replay(e)}))}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return Ao(this,void 0,void 0,(function*(){const t=this.dataChannelForKind(e);if(!t)throw new us("DataChannel not found, kind: ".concat(e));return this.flowControlFor(e).waitForHeadroomWithLock(t)}))}ensureDataTransportConnected(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var i;if(!t.pcManager)throw new us("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,o=n?"Subscriber":"Publisher";if(!r)throw ss.internal("".concat(o," connection not set"));let s=!1;n||t.dataChannelForKind(e,n)||(t.createDataChannels(),s=!0),s||n||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch((e=>{t.log.error(e)}));const a=t.dataChannelForKind(e,n);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(r.isICEConnected&&"open"===(null===(i=t.dataChannelForKind(e,n))||void 0===i?void 0:i.readyState))return;yield Ks(50)}throw ss.internal("could not establish ".concat(o," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Ao(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;const e=this.pcManager.currentState;return!![Nd.CONNECTING,Nd.CONNECTED].includes(e)&&(!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)&&(!(e===Nd.CONNECTING&&void 0!==this.transportConnectingSince&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout)||(this.log.warn("transport stuck in connecting state",this.logContext),!1)))}negotiate(){return Ao(this,void 0,void 0,(function*(){return new Wo(((e,t)=>Ao(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new hs("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.dataChannels.hasPublisherChannels||this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new hs("cannot negotiate on closed engine")),this.pendingNegotiationAborts.add(i),this.pcManager.publisher.off(yd,this.onRtpMapAvailable),this.pcManager.publisher.once(yd,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(ke){if(n.signal.aborted)return void e();ke instanceof hs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",wn.RR_UNKNOWN),ke instanceof Error?t(ke):t(new Error(String(ke)))}finally{this.pendingNegotiationAborts.delete(i)}}))))}))}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var i,r,o,s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup");const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),l=null===(r=this.pcManager.subscriber)||void 0===r?void 0:r.getLocalDescription(),u=null===(s=null===(o=this.signalOpts)||void 0===o?void 0:o.autoSubscribe)||void 0===s||s,h=new Array,p=new Array;e.forEach((e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)})),this.client.sendSyncState(new Zr({answer:"publisher-only"===this.pcManager.mode?c?Yc({sdp:c.sdp,type:c.type}):void 0:l?Yc({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?a?Yc({sdp:a.sdp,type:a.type}):void 0:d?Yc({sdp:d.sdp,type:d.type}):void 0,subscription:new Er({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ls(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new $r({publisherSid:t,lastSeq:e}))),publishDataTracks:n}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new eo({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(xd.LOSSY),tr.PUBLISHER),t(this.dataChannelForKind(xd.RELIABLE),tr.PUBLISHER),t(this.dataChannelForKind(xd.LOSSY,!0),tr.SUBSCRIBER),t(this.dataChannelForKind(xd.RELIABLE,!0),tr.SUBSCRIBER),t(this.dataChannelForKind(xd.DATA_TRACK_LOSSY),tr.PUBLISHER),t(this.dataChannelForKind(xd.DATA_TRACK_LOSSY,!0),tr.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&(ks.clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){la()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){la()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t,n;const i=null===(n=null===(t=this.pcManager)||void 0===t?void 0:t.getTransceiverForReceiver(e))||void 0===n?void 0:n.mid;if(i){const e=Object.entries(this.midToTrackId).find((e=>tt(e,1)[0]===i));if(e)return e[1]}}}function Zd(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}const $d=Po(e.LoggerNames.Region),el=5e3;class tl{static fetchRegionSettings(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=yield tl.fetchLock.lock();try{const i=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(i.ok){const e=function(e){var t;const n=e.get("Cache-Control");if(n){const e=null===(t=n.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(i.headers),t=e?1e3*e:el;return{regionSettings:yield i.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===i.status?ss.notAllowed("Could not fetch region settings: ".concat(i.statusText),i.status):ss.internal("Could not fetch region settings: ".concat(i.statusText))}catch(ke){throw ke instanceof ss?ke:(null==n?void 0:n.aborted)?ss.cancelled("Region fetching was aborted"):ss.serverUnreachable("Could not fetch region settings, ".concat(ke instanceof Error?"".concat(ke.name,": ").concat(ke.message):ke))}finally{i()}}))}static scheduleRefetch(t,n,i){return Ao(this,void 0,void 0,(function*(){const r=tl.settingsTimeouts.get(t.hostname);clearTimeout(r),tl.settingsTimeouts.set(t.hostname,setTimeout((()=>Ao(this,void 0,void 0,(function*(){try{const e=yield tl.fetchRegionSettings(t,n);tl.updateCachedRegionSettings(t,n,e)}catch(r){if(r instanceof ss&&r.reason===e.ConnectionErrorReason.NotAllowed)return void $d.debug("token is not valid, cancelling auto region refresh");$d.debug("auto refetching of region settings failed",{error:r}),tl.scheduleRefetch(t,n,i)}}))),i))}))}static updateCachedRegionSettings(e,t,n){tl.cache.set(e.hostname,n),tl.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=tl.settingsTimeouts.get(e);t&&(clearTimeout(t),tl.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=tl.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=tl.connectionTrackers.get(e);t&&0===t.connectionCount&&($d.debug("stopping region refetch after disconnect delay",{hostname:e}),tl.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=tl.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=tl.connectionTrackers.get(e);t||(t={connectionCount:0},tl.connectionTrackers.set(e,t)),t.connectionCount++,tl.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=tl.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&tl.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const n=this.getServerUrl(),i=tl.cache.get(n.hostname);tl.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==i?void 0:i.maxAgeInMs)&&void 0!==t?t:el)}isCloud(){return ha(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Ao(this,void 0,void 0,(function*(){return tl.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return Ao(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=tl.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),tl.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(n.length>0){const e=n[0];return this.attemptedRegions.push(e),$d.info("switching to region: ".concat(e.region),{region:e.region}),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){tl.updateCachedRegionSettings(this.serverUrl,this.token,e)}}tl.cache=new Map,tl.settingsTimeouts=new Map,tl.connectionTrackers=new Map,tl.fetchLock=new be;const nl=["e2eeManager","frameMetadataOptions","byteStreamOpener","videoPublisher"];function il(e,t,n){const i=Symbol("lk.extension.".concat(e)),r=e=>({key:i,requires:t,install:(t,i)=>n(t,i,"function"==typeof e?e():e)});return Object.assign((e=>r(e)),r())}function rl(e,t){const n=new Map;for(const s of t){if(n.has(s.key))throw new Error("extension '".concat(String(s.key),"' is listed twice"));n.set(s.key,s)}const i=[],r=new Set,o=(e,t)=>{var s,a;const c=null!==(s=n.get(e.key))&&void 0!==s?s:e;if(t.includes(c.key))throw new Error("extension '".concat(String(c.key),"' depends on itself"));r.has(c.key)||(r.add(c.key),null===(a=c.requires)||void 0===a||a.forEach((e=>o(e,[...t,c.key]))),i.push(c))};t.forEach((e=>o(e,[]))),e.installExtensions(i)}const ol=2e3;function sl(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 al="undefined"!=typeof MediaRecorder;const cl=al?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class dl extends cl{constructor(e,t){if(!al)throw new Error("MediaRecorder is not available in this environment");let n,i;super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),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",r),this.removeEventListener("error",o),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>Ao(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:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",o)}}class ll extends Bs{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 r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=ld((()=>Ao(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Ao(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 be,this.pauseUpstreamLock=new be,this.trackChangeLock=new be,this.trackChangeLock.lock().then((e=>Ao(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!==Bs.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;return t&&n?{width:t,height:n}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get isStopped(){return this.manuallyStopped}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,n){return Ao(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Vs(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,audioContext:this.audioContext,localTrack:this}),r=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!n||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{qs(null!=r?r:e,t)}))),yield this.onMediaStreamTrackChanged()}))}onMediaStreamTrackChanged(){return Ao(this,void 0,void 0,(function*(){}))}waitForDimensions(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){if(e.kind===Bs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const n=Date.now();for((aa()||ia()&&e.source===Bs.Source.ScreenShare)&&(yield function(e,t){return Ao(this,arguments,void 0,(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return function*(){var i;if("undefined"==typeof document)return!1;if("ended"===e.readyState||e.muted||!e.enabled)return!1;const r="function"==typeof HTMLVideoElement.prototype.requestVideoFrameCallback,o=n.find((t=>t instanceof HTMLVideoElement&&t.srcObject instanceof MediaStream&&t.srcObject.getVideoTracks().includes(e)&&(r||t.readyState<2))),s=null!=o?o:document.createElement("video");let a,c,d;o||(s.playsInline=!0,s.muted=!0,s.srcObject=new MediaStream([e]),s.play().catch((e=>{wo.debug("could not play element while waiting for the first video frame",{error:e})})));try{return yield new Promise((e=>{a=setTimeout((()=>e(!1)),t),r?c=s.requestVideoFrameCallback((()=>e(!0))):(d=()=>e(!0),s.addEventListener("loadeddata",d))}))}finally{clearTimeout(a),void 0!==c&&(null===(i=s.cancelVideoFrameCallback)||void 0===i||i.call(s,c)),d&&s.removeEventListener("loadeddata",d),o||(s.pause(),s.srcObject=null)}}()}))}(e._mediaStreamTrack,t,e.attachedElements));;){const i=e.dimensions;if(i)return i;if(Date.now()-n>=t)break;yield Ks(50)}throw new ds("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Ao(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Aa(e)&&"live"===this._mediaStreamTrack.readyState||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Aa(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Ao(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Bs.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),i=n.deviceId,r=n.groupId,o=e.kind===Bs.Kind.Audio?"audioinput":"videoinput";return t?Tc.getInstance().normalizeDeviceId(o,i,r):i}()}))}mute(){return Ao(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Ao(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Ao(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new ds("unable to replace an unpublished track");let n,i;"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())}finally{n()}return yield this.onSenderTrackSwapped(),this}))}onSenderTrackSwapped(){return Ao(this,void 0,void 0,(function*(){}))}restart(t,n){return Ao(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const i=t,r=i.deviceId,o=i.facingMode,s=Mo(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const a={audio:!1,video:!1};let c;this.kind===Bs.Kind.Video?a.video=!r&&!o||{deviceId:r,facingMode:o}:a.audio=!r||Object.assign({deviceId:r},s),this.attachedElements.forEach((e=>{Vs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();try{c=yield navigator.mediaDevices.getUserMedia(a)}catch(ke){throw function(e){"object"==typeof e&&null!==e&&La.add(e)}(ke),ke}const d=c.getTracks()[0];try{this.kind===Bs.Kind.Video&&(yield d.applyConstraints(s)),d.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(d,!1,n)}catch(ke){throw this._mediaStreamTrack!==d&&d.stop(),ke}return this._constraints=t,this.pendingDeviceChange=!1,this.emit(e.TrackEvent.Restarted,this),this}finally{this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),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 Ao(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),da()&&(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().catch((e=>{this.log.error("failed to destroy processor",Object.assign(Object.assign({},this.logContext),{error:e}))})),this.processor=void 0}pauseUpstream(){return Ao(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=zo();if("Safari"===(null==n?void 0:n.name)&&va(n.version,"12.0")<0)throw new cs("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 Ao(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 Ao(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 Ao(this,arguments,void 0,(function(t){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),s={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext,localTrack:n};if(yield t.init(s),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(qs(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&&(Vs(n._mediaStreamTrack,e),qs(n.processor.processedTrack,e));yield null===(r=n.sender)||void 0===r?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(e.TrackEvent.TrackProcessorUpdate,n.processor)}finally{o()}yield n.onSenderTrackSwapped()}()}))}getProcessor(){return this.processor}stopProcessor(){return Ao(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()}yield e.onSenderTrackSwapped()}()}))}internalStopProcessor(){return Ao(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r;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===(r=t.processorElement)||void 0===r||r.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(al)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 dl(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 ul extends ll{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;super(t,Bs.Kind.Audio,n,i,o),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Ao(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(ke){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:ke}))}e&&this.prevStats&&(this._currentBitrate=sl(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,Pn.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,Pn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ao(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===Bs.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 Ao(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Bs.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!this.pendingDeviceChange||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}restartTrack(e){return Ao(this,void 0,void 0,(function*(){let t;if(e){const n=Ps({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}applyConstraints(e){return Ao(this,void 0,void 0,(function*(){const t=yield this.trackChangeLock.lock();try{const t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}}))}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return Ao(this,void 0,void 0,(function*(){const i=yield n.restart.call(this,e,t);return this.checkForSilence(),i}))}startMonitor(){la()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ol)))}observeProcessedTrack(e){this.observedProcessedTrack!==e&&(this.observedProcessedTrack&&(this.observedProcessedTrack.removeEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.observedProcessedTrack.removeEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable),this.observedProcessedTrack=void 0,this.isKrispNoiseFilterEnabled&&this.handleKrispNoiseFilterDisable()),e&&(e.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),e.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable),this.observedProcessedTrack=e))}setProcessor(t){return Ao(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!ua()&&!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,localTrack:this};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.observeProcessedTrack(this.processor.processedTrack)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}onMediaStreamTrackChanged(){return Ao(this,void 0,void 0,(function*(){var e;this.observeProcessedTrack(null===(e=this.processor)||void 0===e?void 0:e.processedTrack)}))}internalStopProcessor(){const e=Object.create(null,{internalStopProcessor:{get:()=>super.internalStopProcessor}});return Ao(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){t.observeProcessedTrack(void 0),yield e.internalStopProcessor.call(t,n)}()}))}stop(){this.observeProcessedTrack(void 0),super.stop()}setAudioContext(t){return Ao(this,void 0,void 0,(function*(){var n;if(this.audioContext===t)return;const i=yield this.trackChangeLock.lock();try{if(this.audioContext=t,!this.processor||ua())return;if(!t)return this.log.debug("stopping audio processor, audio context has been removed",this.logContext),void(yield this.internalStopProcessor());this.log.debug("restarting audio processor on new audio context",this.logContext),yield this.processor.restart({kind:this.kind,track:this._mediaStreamTrack,audioContext:t,localTrack:this}),this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack),this.observeProcessedTrack(this.processor.processedTrack)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}getSenderStats(){return Ao(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach((e=>{if("outbound-rtp"===e.type){n={type:"audio",streamId:e.id,packetsSent:e.packetsSent,bytesSent:e.bytesSent,timestamp:e.timestamp};const i=t.get(e.remoteId);i&&(n.packetsLost=i.packetsLost,n.jitter=i.jitter,n.roundTripTime=i.roundTripTime)}})),n}))}checkForSilence(){return Ao(this,void 0,void 0,(function*(){const t=yield Is(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}class hl extends Bs{constructor(t,n,i,r,o){super(t,i,o),this.timeSyncLoop=()=>{var t;if(0===this.listenerCount(e.TrackEvent.TimeSyncUpdate))return void(this.timeSyncHandle=void 0);this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);const n=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(n){const t=n.timestamp,i=n.rtpTimestamp;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}},this.onTimeSyncListenerAdded=t=>{t===e.TrackEvent.TimeSyncUpdate&&void 0===this.timeSyncHandle&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?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 Ao(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()),ol)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){this.off("newListener",this.onTimeSyncListenerAdded),this.on("newListener",this.onTimeSyncListenerAdded),void 0===this.timeSyncHandle&&this.timeSyncLoop()}}class pl extends hl{constructor(e,t,n,i,r,o){super(e,t,Bs.Kind.Audio,n,o),this.connectedNodes=[],this.monitorReceiver=()=>Ao(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=sl(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;if(this.audioContext)null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1);else for(const n of this.attachedElements)n.volume=e;ua()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(void 0!==this.elementVolume)return this.elementVolume;if(ua())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Ao(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(ea(t))return t.setSinkId(e)})))}))}attach(e){const t=!this.sourceNode;return e?super.attach(e):e=super.attach(),this.sinkId&&ea(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)})),this.audioContext&&(e.volume=0,e.muted=!0,t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e))),void 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){var t;if(this.audioContext!==e)if(this.audioContext=e,e){for(const e of this.attachedElements)e.volume=0,e.muted=!0;this.attachedElements.length>0&&this.connectWebAudio(e,this.attachedElements[0])}else{this.disconnectWebAudio();for(const e of this.attachedElements)e.muted=!1,e.volume=null!==(t=this.elementVolume)&&void 0!==t?t:1}}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.connectedNodes=[this.sourceNode],this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e,this.connectedNodes.push(e)})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.connectedNodes.push(this.gainNode),this.gainNode.connect(t.destination),void 0!==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;for(let i=0;i<this.connectedNodes.length-1;i+=1)try{this.connectedNodes[i].disconnect(this.connectedNodes[i+1])}catch(n){}this.connectedNodes=[],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 Ao(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 ml extends Vo.EventEmitter{constructor(t,n,i,r){var o;super(),this.metadataMuted=!1,this.encryption=xn.NONE,this.log=wo,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Po(null!==(o=null==r?void 0:r.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=Bs.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)),Ns(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==xn.NONE}get audioTrack(){if(Ba(this.track))return this.track}get videoTrack(){if(qa(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Bs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Bs.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"}(ml||(ml={}));class gl extends ml{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&qa(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 Ao(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Ao(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Ao(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Ao(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Ba(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Pn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Pn.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Pn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Pn.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(Pn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Pn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}let fl;function vl(e){fl=e}function kl(){if(!fl)throw new ds("video capture is not available in this build, add the video extension");return fl}function yl(e,t){return Ao(this,void 0,void 0,(function*(){null!=e||(e={});let n=!1;const i=xs(e),r=i.audioProcessor,o=i.videoProcessor,s=i.optionsWithoutProcessor;let a=s.audio,c=s.video;if(r&&"object"==typeof s.audio&&(s.audio.processor=r),o&&"object"==typeof s.video&&(s.video.processor=o),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){const e=s.audio.deviceId;s.audio.deviceId={exact:e},n=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:e}})}if(s.video&&"object"==typeof s.video&&"string"==typeof s.video.deviceId){const e=s.video.deviceId;s.video.deviceId={exact:e},n=!0,c=Object.assign(Object.assign({},s.video),{deviceId:{ideal:e}})}!0===s.audio?s.audio={deviceId:"default"}:"object"==typeof s.audio&&null!==s.audio&&(s.audio=Object.assign(Object.assign({},s.audio),{deviceId:s.audio.deviceId||"default"})),!0===s.video?s.video={deviceId:"default"}:"object"!=typeof s.video||s.video.deviceId||(s.video.deviceId="default");const d=Ps(ws(s,Md,s.video?kl().defaults:void 0)),l=navigator.mediaDevices.getUserMedia(d);s.audio&&(Tc.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Tc.userMediaPromiseMap.delete("audioinput")))),s.video&&(Tc.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Tc.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((n=>Ao(this,void 0,void 0,(function*(){let i;const s="audio"===n.kind?d.audio:d.video;"boolean"!=typeof s&&(i=s);const a=n.getSettings().deviceId;(null==i?void 0:i.deviceId)&&Aa(i.deviceId)!==a?i.deviceId=a:i||(i={deviceId:a});const c="audio"===n.kind?new ul(n,i,!1,void 0,t):kl().createTrack(n,i,!1,t);return c.kind===Bs.Kind.Video?c.source=Bs.Source.Camera:c.kind===Bs.Kind.Audio&&(c.source=Bs.Source.Microphone),c.mediaStream=e,Ba(c)&&r?yield c.setProcessor(r):qa(c)&&o&&(yield c.setProcessor(o)),c})))))}catch(ke){if(!n)throw ke;return yl(Object.assign(Object.assign({},e),{audio:a,video:c}),t)}}))}function bl(e){return Ao(this,void 0,void 0,(function*(){return(yield yl({audio:null==e||e,video:!1}))[0]}))}var Tl;e.ConnectionQuality=void 0,(Tl=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Tl.Good="good",Tl.Poor="poor",Tl.Lost="lost",Tl.Unknown="unknown";class Sl extends Vo.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===Ln.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===An.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,r,o,s){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Ln.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=wo,this.loggerOptions=s,this.log=Po(null!==(c=null==s?void 0:s.loggerName)&&void 0!==c?c:e.LoggerNames.Participant,(()=>this.logContext)),this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=o?o:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const t of this.trackPublications){const n=tt(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(const t of this.trackPublications){const n=tt(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Da,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(Bs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Bs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Bs.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}isOlderSession(e){const t=this.participantInfo;return!(!t||t.sid===e.sid)&&(e.joinedAt!==t.joinedAt?e.joinedAt<t.joinedAt:e.joinedAtMs&&t.joinedAtMs&&e.joinedAtMs!==t.joinedAtMs?e.joinedAtMs<t.joinedAtMs:e.sid<t.sid)}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===An.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==An.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)],r={};for(const o of i)e[o]!==t[o]&&(r[o]=null!==(n=t[o])&&void 0!==n?n:"");return r}(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,n)}setPermissions(t){var n,i,r,o,s,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===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(o=this.permissions)||void 0===o?void 0:o.hidden)||t.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.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 Sn.EXCELLENT:return e.ConnectionQuality.Excellent;case Sn.GOOD:return e.ConnectionQuality.Good;case Sn.POOR:return e.ConnectionQuality.Poor;case Sn.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){return Ao(this,void 0,void 0,(function*(){this.audioContext=e,yield Promise.all(Array.from(this.audioTrackPublications.values()).map((e=>e.track)).filter(Ba).map((t=>t.setAudioContext(e))))}))}addTrackPublication(t){this.log.debug("adding track publication",{trackSid:t.trackSid,source:t.source,kind:t.kind}),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 Bs.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case Bs.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class El extends Sl{constructor(t,n,i,r){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};super(t,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=xn.NONE,this.e2eeStateMutex=new be,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Da)},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,r,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(i=(n=this.signalConnectedFuture).reject)||void 0===i||i.call(n,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(o=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===o||o.call(r,new Error("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 Da),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const t=e.requestId,n=e.reason,i=e.message,r=this.pendingSignalRequests.get(t);r&&(n!==co.OK&&r.reject(new gs(i,n)),this.pendingSignalRequests.delete(t))},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{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 Jr({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",Ns(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Ns(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Ns(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.onTrackCpuConstrained=(t,n)=>{this.log.debug("track cpu constrained",Ns(n)),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",{trackSid:e.trackSid})},this.handleTrackEnded=e=>Ao(this,void 0,void 0,(function*(){if(e.source===Bs.Source.ScreenShare||e.source===Bs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Ns(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Wa(e)||Va(e))try{if(la())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Bs.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Ns(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(ke){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Ns(e)),Wa(e)?yield this.restartOnDefaultAudioDevice(e):yield e.restartTrack())}catch(ke){this.log.warn("could not restart track, muting instead",Ns(e)),yield e.mute()}})),this.slots=o,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==xn.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.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return Ao(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Ao(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Ao(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=e.metadata,i=e.name,r=e.attributes;return function*(){return new Wo(((e,o)=>Ao(t,void 0,void 0,(function*(){var t,s;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(s=null!=i?i:this.name)&&void 0!==s?s:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:i,metadata:n,attributes:r}});performance.now()-d<5e3&&!a;){if((!i||this.name===i)&&(!n||this.metadata===n)&&(!r||Object.entries(r).every((e=>{let t=tt(e,2),n=t[0],i=t[1];return this.attributes[n]===i||""===i&&!this.attributes[n]}))))return this.pendingSignalRequests.delete(c),void e();yield Ks(50)}o(new gs("Request to update local metadata timed out","TimeoutError"))}catch(ke){ke instanceof Error?o(ke):o(new Error(String(ke)))}}))))}()}))}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Bs.Source.Microphone,e,t,n)}setE2EEEnabled(e){return Ao(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?xn.GCM:xn.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every((t=>t.isEncrypted===e)))return;yield this.republishAllTracks(void 0,!1)}finally{t()}}))}setTrackEnabled(t,n,i,r){return Ao(this,void 0,void 0,(function*(){var o,s;this.log.debug("setTrackEnabled",{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",{source:t}),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case Bs.Source.Camera:n=yield this.createTracks({video:null===(o=i)||void 0===o||o});break;case Bs.Source.Microphone:n=yield this.createTracks({audio:null===(s=i)||void 0===s||s});break;case Bs.Source.ScreenShare:n=yield this.requireVideoPublisher().createScreenTracks(Object.assign({},i));break;default:throw new ds(t)}}catch(ke){throw null==n||n.forEach((e=>{e.stop()})),ke instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,ke,Ds(t)),this.pendingPublishing.delete(t),ke}for(const e of n){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),r);t===Bs.Source.Microphone&&Ba(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),e.startPreConnectBuffer())}try{const e=[];for(const t of n)this.log.info("publishing track",Ns(t)),e.push(this.publishTrack(t,r));a=tt(yield Promise.all(e),1)[0]}catch(ke){throw null==n||n.forEach((e=>{e.stop()})),ke}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",{source:t})),a&&a.track)if(t===Bs.Source.ScreenShare){const e=[this.unpublishTrack(a.track)],t=this.getTrackPublication(Bs.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),a=tt(yield Promise.all(e),1)[0]}else yield a.mute();return a}))}createTracks(t){return Ao(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const r=ws(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 yl(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return yield Promise.all(t.map((t=>Ao(this,void 0,void 0,(function*(){return Ba(t)&&(this.microphoneError=void 0,yield t.setAudioContext(this.audioContext),t.source=Bs.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),qa(t)&&(this.cameraError=void 0,t.source=Bs.Source.Camera),t})))))}catch(o){throw o instanceof Error&&(t.audio&&(this.microphoneError=o),t.video&&(this.cameraError=o)),o}}))}get trackLoggerOptions(){return{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext}}requireVideoPublisher(){if(!this.slots.videoPublisher)throw new ds("video publishing is not available in this build, add the video extension");return this.slots.videoPublisher}publishTrack(e,t){return Ao(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}waitForNextEngineRestart(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise(((n,i)=>{const r=()=>{clearTimeout(a),this.engine.off(e.EngineEvent.Restarted,o),this.engine.off(e.EngineEvent.Closing,s)},o=()=>{r(),n()},s=()=>{r(),i(new Error("engine closed before restart completed"))},a=setTimeout((()=>{r(),i(new Error("timed out waiting for engine restart"))}),t);this.engine.once(e.EngineEvent.Restarted,o),this.engine.once(e.EngineEvent.Closing,s)}))}publishOrRepublishTrack(e,t){return Ao(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var o,s,a,c;let d,l;if(Wa(e)&&(yield e.setAudioContext(n.audioContext)),yield null===(o=n.reconnectFuture)||void 0===o?void 0:o.promise,n.republishPromise&&!i&&(yield n.republishPromise),ja(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)d=e.getConstraints();else{let t;switch(d=e.constraints,e.source){case Bs.Source.Microphone:t="audioinput";break;case Bs.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(d=Object.assign(Object.assign({},d),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new ul(e,d,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=kl().createTrack(e,d,!0,n.trackLoggerOptions);break;default:throw new ds("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&&(l=t)})),l)return n.log.warn("track has already been published, skipping",Ns(l)),l;const u=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),h="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,p=null!==(s=u.forceStereo)&&void 0!==s?s:h;p&&(void 0===u.dtx&&n.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Ns(e)),void 0===u.red&&n.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(a=u.dtx)&&void 0!==a||(u.dtx=!1),null!==(c=u.red)&&void 0!==c||(u.red=!1)),u.source&&(e.source=u.source);const m=new Promise(((t,i)=>Ao(n,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Gc.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:Ns(e)});let n=!1;const r=setTimeout((()=>{n=!0,e.stop(),i(new ms("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),n)return;const o=yield this.publish(e,u,p);t(o)}else try{const n=yield this.publish(e,u,p);t(n)}catch(ke){i(ke)}}catch(ke){i(ke)}}))));n.pendingPublishPromises.set(e,m);try{return yield m}catch(ke){if(!r&&ke instanceof hs)return n.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:ke}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,i,!0);throw ke}finally{n.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Da),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Ns(e)),!1;const t=this.permissions,n=t.canPublish,i=t.canPublishSources;return!(!n||0!==i.length&&!i.map((e=>function(e){switch(e){case bn.CAMERA:return Bs.Source.Camera;case bn.MICROPHONE:return Bs.Source.Microphone;case bn.SCREEN_SHARE:return Bs.Source.ScreenShare;case bn.SCREEN_SHARE_AUDIO:return Bs.Source.ScreenShareAudio;default:return Bs.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Ns(e)),!1)}publish(t,n,i){return Ao(this,void 0,void 0,(function*(){var r,o,s,a,c,d,l,u;if(!this.hasPermissionsToPublish(t))throw new ms("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>ja(t)&&e.source===t.source))&&t.source!==Bs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Ns(t)),n.stopMicTrackOnMute&&Ba(t)&&(t.stopOnMute=!0),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 h=[],p=!(null===(r=n.dtx)||void 0===r||r),m=t.getSourceTrackSettings();m.autoGainControl&&h.push(Pn.TF_AUTO_GAIN_CONTROL),m.echoCancellation&&h.push(Pn.TF_ECHO_CANCELLATION),m.noiseSuppression&&h.push(Pn.TF_NOISE_SUPPRESSION),m.channelCount&&m.channelCount>1&&h.push(Pn.TF_STEREO),p&&h.push(Pn.TF_NO_DTX),Wa(t)&&t.hasPreConnectBuffer&&h.push(Pn.TF_PRECONNECT_BUFFER);const g=this.normalizeRequestedFrameMetadataOptions(t,n),f=new cr({cid:t.mediaStreamTrack.id,name:n.name,type:Bs.kindToProto(t.kind),muted:t.isMuted,source:Bs.sourceToProto(t.source),disableDtx:p,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:h,packetTrailerFeatures:g});let v;if(Va(t)?v=yield this.requireVideoPublisher().prepare(t,n,f):t.kind===Bs.Kind.Audio&&(v=[{maxBitrate:null===(s=n.audioPreset)||void 0===s?void 0:s.maxBitrate,priority:null!==(c=null===(a=n.audioPreset)||void 0===a?void 0:a.priority)&&void 0!==c?c:"high",networkPriority:null!==(l=null===(d=n.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high"}]),!this.engine||this.engine.isClosed)throw new us("cannot publish track when not connected");const k=()=>Ao(this,void 0,void 0,(function*(){var i;if(!this.engine.pcManager)throw new us("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,v),Va(t)&&(t.publishOptions=n),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Va(t)&&this.requireVideoPublisher().senderCreated(t,n,v,f),v&&na()&&t.kind===Bs.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===(i=v[0])||void 0===i?void 0:i.maxBitrate)?v[0].maxBitrate/1e3:0})}yield this.engine.negotiate()}));let y;const b=new Promise(((e,n)=>Ao(this,void 0,void 0,(function*(){var i;try{y=yield this.engine.addTrack(f),e(y)}catch(r){if(t.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)){try{this.engine.pcManager.publisher.removeTrack(t.sender)}catch(ke){this.log.error(ke)}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({},Ns(t)),{error:e}))}))}n(r)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===g.length){const e=yield Promise.all([b,k()]);y=e[0]}else y=yield b,Va(t)&&(v=null!==(u=this.requireVideoPublisher().serverCodecChanged(t,n,y,f))&&void 0!==u?u:v),yield k();const T=new gl(t.kind,y,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,T))),T.options=n,t.sid=y.sid,Va(t)&&(t.publishOptions=n,f.width&&f.height&&(t.lastEncodedDimensions={width:f.width,height:f.height})),this.log.debug("publishing ".concat(t.kind," with encodings"),{encodings:v,trackInfo:y}),Va(t)?t.startMonitor(this.engine.client):Wa(t)&&t.startMonitor(),this.addTrackPublication(T),this.emit(e.ParticipantEvent.LocalTrackPublished,T),Wa(t)&&y.audioFeatures.includes(Pn.TF_PRECONNECT_BUFFER)){const n=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===y.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",Ns(t)),t.stopPreConnectBuffer()}})),n){const e=new Promise(((e,r)=>Ao(this,void 0,void 0,(function*(){var o,s,a,c,d,l;try{this.log.debug("waiting for agent",Ns(t));const f=setTimeout((()=>{r(new Error("agent not active within 10 seconds"))}),1e4),v=yield this.waitUntilActiveAgentPresent();if(clearTimeout(f),this.log.debug("sending preconnect buffer",Ns(t)),!this.slots.byteStreamOpener)throw new Error("the dataStreams extension is required to send the preconnect buffer");const k=yield this.slots.byteStreamOpener({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:T.trackSid,sampleRate:String(null!==(d=m.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=m.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Uo(n);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield k.write(e)}}catch(g){s={error:g}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(s)throw s.error}}yield k.close(),e()}catch(ke){r(ke)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Ns(t))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},Ns(t)),{error:e}))}))}}return T}))}canPublishFrameMetadata(){return!!this.engine.e2eeManager||gc(this.engine.frameMetadataOptions)}normalizeRequestedFrameMetadataOptions(e,t){const n=vc(t);if(e.kind!==Bs.Kind.Video||!fc(n))return kc(t,void 0),[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),Ns(e))),kc(t,void 0),[];const i=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(In.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(In.PTF_FRAME_ID),t}(n),r=function(e){if(!e||0===e.length)return;const t={};return e.includes(In.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(In.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(i);return kc(t,r),i}get isLocal(){return!0}unpublishTrack(t,n){return Ao(this,void 0,void 0,(function*(){var i,r;if(ja(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.debug("awaiting publish promise before attempting to unpublish",Ns(t)),yield e)}const o=this.getPublicationForTrack(t),s=o?Ns(o):void 0;if(this.log.info("unpublishing track",s),!o||!o.track)return void this.log.warn("track was not unpublished because no publication was found",s);(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===(r=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===r||r),n?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Nd.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",a=!0);try{a=this.engine.removeTrack(c)}catch(ke){this.log.warn(ke),a=!0}if(Va(t)){for(const e of t.simulcastCodecs){const t=tt(e,2)[1];if(t.sender){try{a=this.engine.removeTrack(t.sender)}catch(ke){this.log.warn(ke),a=!0}t.sender=void 0}}t.simulcastCodecs.clear()}}catch(ke){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},s),{error:ke}))}switch(this.trackPublications.delete(o.trackSid),o.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(o.trackSid);break;case Bs.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 Ao(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Ao(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 Wo(((i,r)=>Ao(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=>Ao(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===Bs.Source.ScreenShare||t.source===Bs.Source.ScreenShareAudio||!Wa(t)&&!Va(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(t){t instanceof Error?r(t):r(new Error(String(t)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Ao(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?xd.RELIABLE:xd.LOSSY,r=n.reliable?Xn.RELIABLE:Xn.LOSSY,o=n.destinationIdentities,s=n.topic;let a=new ni({participantIdentity:t.identity,payload:e,destinationIdentities:o,topic:s});const c=new Yn({kind:r,value:{case:"user",value:a}});yield t.engine.sendDataPacket(c,i)}()}))}publishDtmf(e,t){return Ao(this,void 0,void 0,(function*(){const n=new Yn({kind:Xn.RELIABLE,value:{case:"sipDtmf",value:new ii({code:e,digit:t})}});yield this.engine.sendDataPacket(n,xd.RELIABLE)}))}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()}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 r=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},Ns(i)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}})),!0)}setActiveAgent(e){var t,n,i,r;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===(r=null===(i=this.activeAgentFuture)||void 0===i?void 0:i.reject)||void 0===r||r.call(i,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Da),this.activeAgentFuture.promise)}restartOnDefaultAudioDevice(e){return Ao(this,void 0,void 0,(function*(){var t,n;try{ia()?yield e.setDeviceId({exact:"default"}):yield e.restartTrack()}catch(ke){if(!function(e){return"object"==typeof e&&null!==e&&La.has(e)}(ke)||function(e){return"object"==typeof e&&null!==e&&"name"in e&&("NotAllowedError"===e.name||"SecurityError"===e.name||"PermissionDeniedError"===e.name||"PermissionDismissedError"===e.name)}(ke)||e.isStopped)throw ke;this.log.debug("could not reacquire the audio device, retrying with an enumerated device",Ns(e));const r=yield Tc.getInstance().getDevices("audioinput",!1);yield e.setDeviceId(null!==(n=null===(t=null==r?void 0:r[0])||void 0===t?void 0:t.deviceId)&&void 0!==n?n:"default")}}))}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(Wa(i)||Va(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return Ao(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>tt(t,1)[0].source===e));if(t)return t[1];yield Ks(20)}}))}}class Cl extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class wl extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,i;super.set(e,t);const r=null===(n=this.pending)||void 0===n?void 0:n.get(e);if(r){for(const e of r)e.isResolved||null===(i=e.resolve)||void 0===i||i.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return Ao(this,void 0,void 0,(function*(){const n=this.get(e);if(void 0!==n)return n;if(null==t?void 0:t.aborted)throw new Cl("The operation was aborted.",t.reason);const i=new Da(void 0,(()=>{const t=this.pending.get(e);if(!t)return;const n=t.indexOf(i);-1!==n&&t.splice(n,1),0===t.length&&this.pending.delete(e)})),r=this.pending.get(e);if(r?r.push(i):this.pending.set(e,[i]),t){const e=()=>{var e;i.isResolved||null===(e=i.reject)||void 0===e||e.call(i,new Cl("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0});const n=()=>{t.removeEventListener("abort",e)};i.promise.then(n,n)}return i.promise}))}}class Rl extends ml{constructor(t,n,i,r){super(t,n.sid,n.name,r),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 r=new Er({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ui({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?ml.SubscriptionStatus.Unsubscribed:super.isSubscribed?ml.SubscriptionStatus.Subscribed:ml.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ml.PermissionStatus.Allowed:ml.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||(za(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&za(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,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),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 za(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Or({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Bs.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n){Us(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=function(e,t){var n;return null===(n=e.layers)||void 0===n?void 0:n.find((e=>e.quality===t))}(this.trackInfo,this.requestedMaxQuality);e&&Us(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(t.width=Math.ceil(n.width),t.height=Math.ceil(n.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)}this.emit(e.TrackEvent.UpdateSettings,t)}}class Pl extends hl{constructor(e,t,n,i,r){super(e,t,Bs.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>Ao(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=sl(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=ld((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return null===(n=this.frameMetadataExtractor)||void 0===n?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===Bs.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Vs(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 Il(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 n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Ao(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 n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ao(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var n,i;const r=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,s=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!o||s;(this.lastVisible!==a||t)&&(!a&&Date.now()-r<100?ks.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,n;let i=0,r=0;const o=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*o,n=e.height()*o;t+n>i+r&&(i=t,r=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},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 fa();if(!t){return fa()>2?2:1}return t}}class Il{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const n=e.target,i=e.isIntersecting;n===this.element&&(this.isIntersecting=i,this.isPiP=_l(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask((()=>{requestAnimationFrame((()=>{var e;this.isPiP=_l(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=_l(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Ol(e),this.isPiP=la()&&_l(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Ol(this.element),this.isPiP=_l(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ea().observe(this.element),Ta().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,r;null===(e=Ea())||void 0===e||e.unobserve(this.element),null===(t=Ta())||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===(r=null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function _l(e){var t;if(document.pictureInPictureElement===e)return!0;const n=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window;return!!n&&(function(e,t){var n,i,r;if((null===(n=e.defaultView)||void 0===n?void 0:n.top)===t)return!0;let o=e;for(;o;){if(o===t.document)return!0;try{o=null===(r=null===(i=o.defaultView)||void 0===i?void 0:i.frameElement)||void 0===r?void 0:r.ownerDocument}catch(s){return!1}}return!1}(e.ownerDocument,n)&&Ol(e,n))}function Ol(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const o=e.offsetWidth,s=e.offsetHeight,a=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+s>n.pageYOffset&&r+o>n.pageXOffset&&!a&&"none"!==c}class Dl extends Sl{static fromParticipantInfo(e,t,n){return new Dl(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,[],t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,o,s){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:Ln.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,l=arguments.length>10&&void 0!==arguments[10]?arguments[10]:[];super(t,n||"",i,r,o,s,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new wl(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d,this.capabilities=l}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),Ns(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]:Bs.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]:Bs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,r,o,s){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===s?(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===s&&(s=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,r,o,s-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),Ns(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Pl(t,n,r,o):new pl(t,n,r,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)&&Ha(c)&&Ba(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,r;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const n=Bs.kindFromProto(e.type);if(!n)return;o=new Rl(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),o.updateInfo(e),i.set(e.sid,o);const s=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));s&&o.source!==Bs.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:Ns(s),newTrack:Ns(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),Ns(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 r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(t);break;case Bs.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return Ao(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;Ba(n.track)&&Ha(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const n of this.dataTracks.entries()){var t=tt(n,2);const i=t[0];e===t[1].info.sid&&this.dataTracks.delete(i)}}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 Ml;e.ConnectionState=void 0,(Ml=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Ml.Connecting="connecting",Ml.Connected="connected",Ml.Reconnecting="reconnecting",Ml.SignalReconnecting="signalReconnecting";let Al;class Ll extends Vo.EventEmitter{get hasE2EESetup(){return void 0!==this.slots.e2eeManager}constructor(t){var n,i,r,o,s;if(super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.ownsAudioContext=!1,this.audioContextReleased=!1,this.audioContextMutex=new be,this.acquiredEmptyAudioTracks=new Set,this.isVideoPlaybackBlocked=!1,this.log=wo,this.statsLog=wo,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.installedExtensions=new Map,this.slots={},this.extensionDisposers=[],this.dataPacketHandlers=new Map,this.disposed=!1,this.connect=(t,n,i)=>Ao(this,void 0,void 0,(function*(){var r;if(this.disposed)throw new us("room has been disposed");if(!ta())throw ua()?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.disposed)throw o(),new us("room has been disposed");if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name)),o(),Promise.resolve();if(this.connectFuture)return o(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.getServerUrl().toString())!==ec(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ha(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new tl(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",{error:e})})));const s=(r,a,c)=>Ao(this,void 0,void 0,(function*(){this.abortController&&this.abortController.abort();const d=new AbortController;this.abortController=d,null==o||o();const l=(e,t)=>{this.abortController===d&&this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),a(e)};try{if(yield yc.getInstance().getBackOffPromise(t),d.signal.aborted)throw ss.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=c?c:t,n,i,d),this.abortController=void 0,r()}catch(u){if(this.regionUrlProvider&&u instanceof ss&&as(u)){let n=null;try{this.log.debug("Fetching next region"),n=yield this.regionUrlProvider.getNextBestRegionUrl(d.signal)}catch(h){if(h instanceof ss&&(401===h.status||h.reason===e.ConnectionErrorReason.Cancelled))return void l(h)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(u.reason)&&(this.log.debug("Adding failed connection attempt to back off"),yc.getInstance().addFailedConnectionAttempt(t)),n&&!d.signal.aborted?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(n)),this.recreateEngine(!0),yield s(r,a,n)):l(u,xa(u))}else{let e=Cn.UNKNOWN_REASON;u instanceof ss&&(e=xa(u)),l(u,e)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Da(((e,t)=>{s(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,r,o)=>Ao(this,void 0,void 0,(function*(){const s=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,disableIceLite:i.disableIceLite,subscriberAllowPause:i.subscriberAllowPause,clientInfoCapabilities:this.getClientInfoCapabilities(),maxRetries:i.maxRetries,e2eeEnabled:!!this.slots.e2eeManager,websocketTimeout:i.websocketTimeout},o.signal,!r.singlePeerConnection),a=s.joinResponse,c=s.serverInfo;if(this.serverInfo=c,!c.version)throw new ls("unknown server version");return"0.15.1"===c.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),a})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.slots.e2eeManager)try{this.slots.e2eeManager.setSifTrailer(e.sifTrailer)}catch(ke){this.log.error(ke instanceof Error?ke.message:"Could not set SifTrailer",{error:ke})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,r)=>Ao(this,void 0,void 0,(function*(){var o,s;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.recreateEngine(!0)):this.maybeCreateEngine();const a=this.engine;(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&a.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(!0).catch((e=>this.log.warn("Could not acquire audio context",Object.assign(Object.assign({},this.logContext),{error:e})))),this.connOptions=Object.assign(Object.assign({},Ld),i),this.connOptions.rtcConfig&&(a.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(a.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,a,this.connOptions,this.options,r);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(c){yield a.close(),this.recreateEngine(!1,a);const e=r.signal.aborted?ss.cancelled("Signal connection aborted"):ss.serverUnreachable("could not establish signal connection");throw c instanceof Error&&(e.message="".concat(e.message,": ").concat(c.message)),c instanceof ss&&(e.reason=c.reason,e.status=c.status),this.log.debug("error trying to establish signal connection",{error:c}),e}if(r.signal.aborted)throw yield a.close(),this.recreateEngine(!1,a),ss.cancelled("Connection attempt aborted");try{yield a.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(ke){throw yield a.close(),this.recreateEngine(!1,a),ke}la()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),la()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),yc.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ao(n,[...i],void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r,o;const s=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected");if(t.log.info("disconnect from room"),t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming){const e="Abort connection attempt due to user initiated disconnect";t.log.warn(e),null===(i=t.abortController)||void 0===i||i.abort(e),null===(o=null===(r=t.connectFuture)||void 0===r?void 0:r.reject)||void 0===o||o.call(r,ss.cancelled("Client initiated disconnect")),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(n,Cn.CLIENT_INITIATED),t.engine=void 0}finally{s()}}()}))},this.onPageLeave=()=>Ao(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>Ao(this,void 0,void 0,(function*(){const e=[],t=zo();t&&"iOS"===t.os&&!this.audioContextReleased&&e.push(this.acquireDummyAudioElement()),this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([...this.audioContextReleased?[]:[this.acquireAudioContext()],...e.map((e=>(this.options.webAudioMix||(e.muted=!1),e.play())))]),this.handleAudioPlaybackStarted()}catch(n){throw this.handleAudioPlaybackFailed(n),n}})),this.startVideo=()=>Ao(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.handleRestarting=()=>{var t;this.clearConnectionReconcile(),this.isResuming=!1,null!==(t=this.roomInfoBeforeRestart)&&void 0!==t||(this.roomInfoBeforeRestart=this.roomInfo),this.roomInfo=this.roomInfoBeforeRestart,this.bufferedEvents=[];for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);!this.connectFuture&&this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=(t,n)=>Ao(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),{region:t.serverRegion}),this.bufferedEvents=[];const i=void 0!==this.connectFuture,r=this.engine.waitForRestarted(n);this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",{error:o})}(yield r)&&!n.aborted&&(this.log.debug("fully reconnected to server",{region:t.serverRegion}),this.roomInfoBeforeRestart=void 0,i?this.bufferedEvents=[]:(this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()))})),this.handleParticipantUpdates=e=>{var t;const n=[];for(const i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i),n.push(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);(null==e?void 0:e.isOlderSession(i))?this.log.debug("ignoring update from an older participant session",{remoteIdentity:i.identity,staleSid:i.sid,currentSid:e.sid}):(i.state===An.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e,i.disconnectReason===Cn.UNKNOWN_REASON?void 0:i.disconnectReason):this.getOrCreateParticipant(i.identity,i),n.push(i))}this.extensionResults.forEach((e=>{var t;return null===(t=e.onParticipantUpdates)||void 0===t?void 0:t.call(e,n)}))},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 r=Bs.streamStateFromProto(t.state),o=i.track.streamState;i.track.setStreamState(r),r!==o&&(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=>{this.cancelPendingTrackAdded(e.trackSid);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)=>{var n;const i=this.remoteParticipants.get(e.participantIdentity);"user"===e.value.case?this.handleUserPacket(i,e.value.value,e.kind,t,e.participantIdentity):"transcription"===e.value.case?this.handleTranscription(i,e.value.value):"sipDtmf"===e.value.case?this.handleSipDtmf(i,e.value.value):"metrics"===e.value.case?this.handleMetrics(e.value.value,i):e.value.case&&(null===(n=this.dataPacketHandlers.get(e.value.case))||void 0===n||n(e,t,i))},this.handleUserPacket=(t,n,i,r,o)=>{this.emit(e.RoomEvent.DataReceived,n.payload,t,i,n.topic,r,o),null==t||t.emit(e.ParticipantEvent.DataReceived,n.payload,i,r)},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),r=null==i?void 0:i.trackPublications.get(n.trackId),o=function(e,t){return e.segments.map((e=>{let n=e.id,i=e.text,r=e.language,o=e.startTime,s=e.endTime,a=e.final;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(s.toString()),final:a,language:r,firstReceivedTime:d,lastReceivedTime:l}}))}(n,this.transcriptionReceivedTimes);null==r||r.emit(e.TrackEvent.TranscriptionReceived,o),null==i||i.emit(e.ParticipantEvent.TranscriptionReceived,o,r),this.emit(e.RoomEvent.TranscriptionReceived,o,i,r)},this.handleMetrics=(t,n)=>{this.emit(e.RoomEvent.MetricsReceived,t,n)},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",{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=()=>Ao(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=zo())||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.logWebRTCStats=()=>Ao(this,void 0,void 0,(function*(){var e,t,n,i;const r=null===(e=this.engine)||void 0===e?void 0:e.pcManager;if(r)try{const e=tt(yield Promise.all([r.publisher.getStats(),null===(t=r.subscriber)||void 0===t?void 0:t.getStats()]),2),o=e[0],s=e[1],a=o&&Cs(o),c=s&&Cs(s);this.statsLog.info("webrtc stats",{publisher:null==a?void 0:a.connection,subscriber:null==c?void 0:c.connection,inbound:[...null!==(n=null==a?void 0:a.inbound)&&void 0!==n?n:[],...null!==(i=null==c?void 0:c.inbound)&&void 0!==i?i:[]],outbound:null==a?void 0:a.outbound})}catch(o){this.statsLog.debug("could not collect webrtc stats",{error:o})}})),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=>Ao(this,void 0,void 0,(function*(){var n,i,r,o,s,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===(s=null===(o=null===(r=t.track)||void 0===r?void 0:r.getProcessor())||void 0===o?void 0:o.onPublish)||void 0===s||s.call(o,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),Wa(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=Ds(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=>Ao(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=Ds(t.source);i&&n&&n!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(n," active")),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.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Ad),t),this.log=Po(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room,(()=>this.logContext)),this.statsLog=Po(e.LoggerNames.Stats,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Md),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign({},null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Dd),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new be,this.localParticipant=new El("","",this.engine,this.options,this.slots),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Aa(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Aa(this.options.audioCaptureDefaults.deviceId)),(null===(r=this.options.audioOutput)||void 0===r?void 0:r.deviceId)&&this.switchActiveDevice("audiooutput",Aa(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),la()){const e=new AbortController;let t;this.cleanupController=e;const n=this.constructor.cleanupRegistry;n?(t=Ll.createWeakDeviceChangeListener(new WeakRef(this)),n.register(this,e)):t=this.handleDeviceChange,null===(s=null===(o=navigator.mediaDevices)||void 0===o?void 0:o.addEventListener)||void 0===s||s.call(o,"devicechange",t,{signal:e.signal})}}installExtensions(e){var t;const n={log:this.log,get:e=>{const t=this.installedExtensions.get(e.key);if(!t)throw new Error("extension '".concat(String(e.key),"' is not installed"));return t},slot:e=>this.slots[e],getOrCreateParticipant:(e,t)=>this.getOrCreateParticipant(e,t),simulateConnected:(e,t)=>this.simulateConnected(e,t),acquireEmptyAudioStreamTrack:()=>this.acquireEmptyAudioStreamTrack()},i=[];for(const o of e){if(this.installedExtensions.has(o.key))throw new Error("extension '".concat(String(o.key),"' is already installed"));const e=o.install(this,n);this.installedExtensions.set(o.key,e),i.push(e);for(const n of Object.entries(null!==(t=e.dataPackets)&&void 0!==t?t:{})){var r=tt(n,2);const e=r[0],t=r[1];if(this.dataPacketHandlers.has(e))throw new Error("data packet case '".concat(e,"' is already handled by another extension"));this.dataPacketHandlers.set(e,((e,n,i)=>t(e.value.value,e,n,i)))}for(const t of nl)void 0!==e[t]&&(this.slots[t]=e[t]);xl(this,Ll.prototype,e.room,o),xl(this.localParticipant,El.prototype,e.localParticipant,o),e.dispose&&this.extensionDisposers.push(e.dispose)}this.applySlotsToEngine(),i.forEach((e=>{var t;return null===(t=e.onEngineCreated)||void 0===t?void 0:t.call(e,this.engine)}))}applySlotsToEngine(){this.engine.e2eeManager=this.slots.e2eeManager,this.engine.frameMetadataOptions=this.slots.frameMetadataOptions}get extensionResults(){return Array.from(this.installedExtensions.values())}dispose(){return Ao(this,void 0,void 0,(function*(){var t;if(!this.disposed){this.disposed=!0,this.state!==e.ConnectionState.Disconnected&&(yield this.disconnect());for(const e of this.extensionDisposers.reverse())e();null===(t=this.cleanupController)||void 0===t||t.abort()}}))}get logContext(){var e,t,n;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:null===(t=this.localParticipant)||void 0===t?void 0:t.identity,participantID:null===(n=this.localParticipant)||void 0===n?void 0:n.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 this.state===e.ConnectionState.Disconnected?Wo.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?Wo.resolve(this.roomInfo.sid):new Wo(((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(new us("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.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new Xd(this.options),this.applySlotsToEngine(),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=>{var t;null===(t=this.abortController)||void 0===t||t.abort("room disconnected by the server during connection attempt"),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.debug("Resuming signal connection"),!this.connectFuture&&this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.connectFuture?this.bufferedEvents=[]:(this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected),this.emitBufferedEvents())})).on(e.EngineEvent.SignalResumed,(()=>{(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Restarted,(()=>{this.state===e.ConnectionState.Connected&&this.emitBufferedEvents()})).on(e.EngineEvent.Offline,(()=>{!this.connectFuture&&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,(e=>{this.handleLocalTrackSubscribed(e)})).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)})).on(e.EngineEvent.TokenRefreshed,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)})).on(e.EngineEvent.ServerRegionsReported,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:el})})).on(e.EngineEvent.RequestSubscribedCodecRefresh,(()=>{for(const e of this.localParticipant.videoTrackPublications.values())Va(e.track)&&e.track.refreshSubscribedCodecs()})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.slots.e2eeManager&&this.slots.e2eeManager.setupEngine(this.engine),this.extensionResults.forEach((e=>{var t;return null===(t=e.onEngineCreated)||void 0===t?void 0:t.call(e,this.engine)})))}createRegionStrategy(){return{getNextUrl:e=>Ao(this,void 0,void 0,(function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null})),resetAttempts:()=>{var e;return null===(e=this.regionUrlProvider)||void 0===e?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Tc.getInstance().getDevices(e,t)}static createWeakDeviceChangeListener(e){return()=>{var t;null===(t=e.deref())||void 0===t||t.handleDeviceChange()}}prepareConnection(t,n){return Ao(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t));try{if(ha(new URL(t))&&n){this.regionUrlProvider=new tl(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(Na(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Na(t),{method:"HEAD"})}catch(ke){this.log.warn("could not prepare connection",{error:ke})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Ao(this,void 0,void 0,(function*(){let n,i=()=>Ao(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":const r="number"==typeof t?t:0;yield this.engine.client.handleOnClose("simulate disconnect",void 0,r);break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":n=new to({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new to({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new to({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new to({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=()=>Ao(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new to({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Ao(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new to({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 to({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Ao(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Ar({reason:Cn.CLIENT_INITIATED,action:Lr.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new to({scenario:{case:"subscriberBandwidth",value:Fa(t)}});break;case"leave-full-reconnect":n=new to({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}acquireDummyAudioElement(){Al||(Al=function(){const e=document.createElement("audio");e.id="livekit-dummy-audio-el",e.autoplay=!0,e.hidden=!0;const t=_a();t.enabled=!0;const n=new MediaStream([t]);return e.srcObject=n,document.body.append(e),{element:e,stream:n,track:t,refCount:0}}());const e=Al;if(this.releaseDummyAudioElement)return e.element;e.refCount+=1;const t=()=>{e.element.srcObject=document.hidden?null:e.stream,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio().catch((e=>this.log.warn("Could not restart audio on page becoming visible",Object.assign(Object.assign({},this.logContext),{error:e})))))};return document.addEventListener("visibilitychange",t),this.releaseDummyAudioElement=()=>{this.releaseDummyAudioElement=void 0,document.removeEventListener("visibilitychange",t),e.refCount-=1,e.refCount>0||(e.element.srcObject=null,e.element.remove(),Al=void 0,Oa(e.track).catch((e=>this.log.warn("Could not release the dummy audio element track",Object.assign(Object.assign({},this.logContext),{error:e})))))},e.element}acquireEmptyAudioStreamTrack(){const e=_a();return this.acquiredEmptyAudioTracks.add(e),e}releaseAcquiredEmptyAudioTrack(e){this.acquiredEmptyAudioTracks.delete(e)&&Oa(e).catch((e=>this.log.warn("Could not release empty audio stream track",Object.assign(Object.assign({},this.logContext),{error:e}))))}releaseAcquiredEmptyAudioTracks(){for(const e of this.acquiredEmptyAudioTracks)this.releaseAcquiredEmptyAudioTrack(e)}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,n){return Ao(this,arguments,void 0,(function(t,n){var i=this;let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var o,s,a,c,d,l,u;let h=!0,p=!1;const m=r?{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===Bs.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(ke){throw i.options.audioCaptureDefaults.deviceId=e,ke}const r=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&&r&&(p=!0)}else if("videoinput"===t){p=0===i.localParticipant.videoTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Bs.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(ke){throw i.options.videoCaptureDefaults.deviceId=e,ke}const r=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&&r&&(p=!0)}else if("audiooutput"===t){if(p=!0,!ea()&&!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 Tc.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(ke){throw i.options.audioOutput.deviceId=e,ke}}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.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally((()=>t.close())):null==t||t.close(),t===this.engine&&(this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine())}onTrackAdded(t,n,i){var r,o;if([e.ConnectionState.Connecting,e.ConnectionState.Reconnecting].includes(this.state)){const o=Za(t,n);this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))});const s=()=>{a(),n.getTracks().includes(t)?this.onTrackAdded(t,n,i):this.log.debug("skipping deferred track, the server no longer sends it",{mediaTrackId:t.id,mediaStreamId:n.id})},a=()=>{if(this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,a),o){const e=this.pendingTrackAddedCallbacks.get(o);null==e||e.delete(a),0===(null==e?void 0:e.size)&&this.pendingTrackAddedCallbacks.delete(o)}};if(this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),this.once(e.RoomEvent.Disconnected,a),o){const e=null!==(r=this.pendingTrackAddedCallbacks.get(o))&&void 0!==r?r:new Set;e.add(a),this.pendingTrackAddedCallbacks.set(o,e)}return}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===t.readyState)return void this.log.debug("skipping incoming track as it already ended");const s=Hs(n.id),a=s[0],c=s[1];let d=null!==(o=Za(t,n))&&void 0!==o?o:t.id;if(a===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const l=Array.from(this.remoteParticipants.values()).find((e=>e.sid===a));if(!l)return void(a.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a)));if(!d.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a));d=e}let u;d.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(c,", trackId: ").concat(d),{remoteParticipantID:a,streamId:c,trackId:d}),this.options.adaptiveStream&&(u="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const h=l.addSubscribedMediaTrack(t,d,n,i,u);(null==h?void 0:h.isEncrypted)&&!this.slots.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;null===(t=this.pendingTrackAddedCallbacks.get(e))||void 0===t||t.forEach((e=>e()))}handleLocalTrackSubscribed(t){const n=()=>this.localParticipant.getTrackPublications().find((e=>e.trackSid===t)),i=n();if(i)return void this.emitLocalTrackSubscribed(i);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:t});let r;const o=e=>{e.trackSid===t&&(s(),this.emitLocalTrackSubscribed(e))},s=()=>{clearTimeout(r),this.localParticipant.off(e.ParticipantEvent.LocalTrackPublished,o),this.off(e.RoomEvent.Disconnected,s)};this.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,o),this.once(e.RoomEvent.Disconnected,s),r=setTimeout((()=>{s();const e=n();e?this.emitLocalTrackSubscribed(e):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:t})}),1e4)}emitLocalTrackSubscribed(t){this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,t),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,t,this.localParticipant)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i,r,o;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.roomInfoBeforeRestart=void 0,this.transcriptionReceivedTimes.clear(),this.extensionResults.forEach((e=>{var t;return null===(t=e.onDisconnect)||void 0===t?void 0:t.call(e)})),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{const n=t?[]:Array.from(this.localParticipant.audioTrackPublications.values()).map((e=>e.track)).filter(Wa);this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var n,i,r;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===(r=e.track)||void 0===r||r.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.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],null===(i=this.releaseDummyAudioElement)||void 0===i||i.call(this),this.releaseAcquiredEmptyAudioTracks(),this.releaseAudioContext(n).catch((e=>this.log.warn("Could not release audio context",Object.assign(Object.assign({},this.logContext),{error:e})))),la()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(o=null===(r=navigator.mediaDevices)||void 0===r?void 0:r.removeEventListener)||void 0===o||o.call(r,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n,i){this.remoteParticipants.delete(t),n&&(n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n,i),n.setDisconnected())}selectDefaultDevices(){return Ao(this,void 0,void 0,(function*(){var t,n,i;const r=Tc.getInstance().previousDevices,o=yield Tc.getInstance().getDevices(void 0,!1),s=zo();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let c of o){const t=r.find((e=>e.deviceId===c.deviceId));t&&""!==t.label&&t.kind===c.kind&&t.label!==c.label&&"default"===this.getActiveDevice(c.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let e of a){const s=Os(e),a=this.localParticipant.getTrackPublication(s);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=r.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&&!sa()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&sa()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return Ao(this,arguments,void 0,(function(){var t=this;let n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function*(){var i,r;const o=yield t.audioContextMutex.lock();try{if(t.audioContextReleased&&!n)return;t.audioContextReleased=!1;const o="boolean"!=typeof t.options.webAudioMix?t.options.webAudioMix.audioContext:void 0;if(o?yield t.setRoomAudioContext(o,!1):t.audioContext&&"closed"!==t.audioContext.state||(yield t.setRoomAudioContext(null!==(i=_s())&&void 0!==i?i:void 0,!0)),t.audioContext&&"suspended"===t.audioContext.state)try{yield Promise.race([t.audioContext.resume(),Ks(200)])}catch(ke){t.log.warn("Could not resume audio context",{error:ke})}const s="running"===(null===(r=t.audioContext)||void 0===r?void 0:r.state);s!==t.canPlaybackAudio&&(t.audioEnabled=s,t.emit(e.RoomEvent.AudioPlaybackStatusChanged,s))}finally{o()}}()}))}setRoomAudioContext(e,t){return Ao(this,void 0,void 0,(function*(){const n=!!e&&t;if(this.audioContext===e)return void(this.ownsAudioContext=n);const i=this.ownsAudioContext?this.audioContext:void 0;this.audioContext=e,this.ownsAudioContext=n;try{this.options.webAudioMix&&(yield Promise.all(Array.from(this.remoteParticipants.values()).map((t=>t.setAudioContext(e))))),yield this.localParticipant.setAudioContext(e)}catch(r){this.log.warn("Could not move audio tracks to the new audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{if(i&&"closed"!==i.state)try{yield i.close()}catch(r){this.log.warn("Could not close audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}}}))}releaseAudioContext(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return function*(){e.audioContextReleased=!0;const n=e.audioContext,i=yield e.audioContextMutex.lock();try{if(!e.audioContextReleased||e.audioContext!==n)return;if(!e.ownsAudioContext)return;try{yield Promise.all(t.map((e=>e.setAudioContext(void 0))))}catch(r){e.log.warn("Could not detach retained audio tracks from the audio context",Object.assign(Object.assign({},e.logContext),{error:r}))}yield e.setRoomAudioContext(void 0,!1)}finally{i()}}()}))}createParticipant(e,t){var n;let i;return t?(i=Dl.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.extensionResults.forEach((e=>{var n;return null===(n=e.onParticipantCreated)||void 0===n?void 0:n.call(e,i,t)}))):i=new Dl(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext).catch((e=>this.log.warn("Could not set audio context",Object.assign(Object.assign({},this.logContext),{error:e})))),(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)))),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===Bs.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===Bs.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.cancelPendingTrackAdded(t.trackSid),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===Ln.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(),n=[].concat(...this.extensionResults.map((e=>{var t,n;return null!==(n=null===(t=e.syncState)||void 0===t?void 0:t.call(e))&&void 0!==n?n:[]})));this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ka(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t){const n=this.remoteParticipants.get(t);if((null==n?void 0:n.sid)===e)return n}}getClientInfoCapabilities(){const e=[];return(gc(this.slots.frameMetadataOptions)||this.slots.e2eeManager)&&e.push(fi.CAP_PACKET_TRAILER),Xa()&&e.push(fi.CAP_COMPRESSION_DEFLATE_RAW),e}setStatsLogging(e){e?this.statsLogInterval||(this.statsLogInterval=ks.setInterval((()=>{this.logWebRTCStats()}),3e4)):this.statsLogInterval&&(ks.clearInterval(this.statsLogInterval),this.statsLogInterval=void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ks.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Cn.STATE_MISMATCH))))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&ks.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(t)),this.state=t,this.setStatsLogging(t===e.ConnectionState.Connected),this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=tt(e,2),n=t[0],i=t[1];this.emit(n,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===e.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}simulateConnected(t,n){this.handleDisconnect(),this.roomInfo=t,this.localParticipant.updateInfo(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected)}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(t!==e.RoomEvent.ActiveSpeakersChanged&&t!==e.RoomEvent.TranscriptionReceived){const n=Nl(i).filter((e=>void 0!==e));t!==e.RoomEvent.TrackSubscribed&&t!==e.RoomEvent.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),{event:t,args:n}),this.log.debug("room event ".concat(t),{event:t,args:n})}return super.emit(t,...i)}}function Nl(e){return e.map((e=>{if(e)return Array.isArray(e)?Nl(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}function xl(e,t,n,i){if(!n)return;const r=Object.getOwnPropertyDescriptors(n);for(const o of Object.keys(r)){if(Object.getOwnPropertyDescriptor(e,o)||o in t)throw new Error("extension '".concat(String(i.key),"' redefines '").concat(o,"'"));o in e&&delete r[o]}Object.defineProperties(e,r)}Ll.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e.abort()}));var Ul=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)}}});const Fl=65535,jl=4294967295;class Bl{static u16(e){return new Bl(e,Fl)}static u32(e){return new Bl(e,jl)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new Bl(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t+e))}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t-e))}getThenIncrement(){const e=this.value;return this.increment(),new Bl(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return 0!==n&&n<this.maxSize+1}}class ql{static fromRtpTicks(e){return new ql(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*jl);return ql.fromRtpTicks(e)}constructor(e,t){this.timestamp=Bl.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new ql(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Vl{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new Vl(t,new Date,e)}static startingAtTime(e,t,n){return new Vl(n,e,t)}static rtpStartingNow(e){return Vl.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Vl.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=Vl.durationInMsToTicks(t,this.rateInHz),i=this.base.clone();return i.wrappingAdd(n),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(1e6*e*t+5e8)/1e9;return Math.round(n)}}function Wl(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw new Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Hl,Kl,zl;!function(e){e[e.TooShort=0]="TooShort",e[e.HeaderOverrun=1]="HeaderOverrun",e[e.MissingExtWords=2]="MissingExtWords",e[e.UnsupportedVersion=3]="UnsupportedVersion",e[e.InvalidHandle=4]="InvalidHandle",e[e.MalformedExt=5]="MalformedExt"}(Hl||(Hl={}));class Gl extends Zo{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Hl[t]}static tooShort(){return new Gl("Too short to contain a valid header",Hl.TooShort)}static headerOverrun(){return new Gl("Header exceeds total packet length",Hl.HeaderOverrun)}static missingExtWords(){return new Gl("Extension word indicator is missing",Hl.MissingExtWords)}static unsupportedVersion(e){return new Gl("Unsupported version ".concat(e),Hl.UnsupportedVersion)}static invalidHandle(e){return new Gl("invalid track handle: ".concat(e.message),Hl.InvalidHandle,{cause:e})}static malformedExt(e){return new Gl("Extension with tag ".concat(e," is malformed"),Hl.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(Kl||(Kl={}));class Jl extends Zo{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=Kl[t]}static tooSmallForHeader(){return new Jl("Buffer cannot fit header",Kl.TooSmallForHeader)}static tooSmallForPayload(){return new Jl("Buffer cannot fit payload",Kl.TooSmallForPayload)}}class Ql{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),i=this.toBinaryInto(n);if(e!==i)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(i," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}!function(e){e[e.UserTimestamp=2]="UserTimestamp",e[e.E2ee=1]="E2ee"}(zl||(zl={}));class Yl extends Ql{}class Xl extends Yl{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+Xl.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Xl.tag),t+=1,e.setUint8(t,Xl.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:Xl.tag,lengthBytes:Xl.lengthBytes,timestamp:this.timestamp}}}Xl.tag=zl.UserTimestamp,Xl.lengthBytes=8;class Zl extends Yl{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+Zl.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Zl.tag),t+=1,e.setUint8(t,Zl.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:Zl.tag,lengthBytes:Zl.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}Zl.tag=zl.E2ee,Zl.lengthBytes=13;class $l extends Ql{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){t+=this.e2ee.toBinaryInto(e)}if(this.userTimestamp){t+=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t))}const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){const t=Wl(e);let n,i,r=0;for(;t.byteLength-r>=2;){const e=t.getUint8(r);r+=1;const o=t.getUint8(r);if(r+=1,0!==e)switch(e){case zl.UserTimestamp:if(t.byteLength-r<Xl.lengthBytes)throw Gl.malformedExt(e);n=new Xl(t.getBigUint64(r)),r+=o;break;case zl.E2ee:if(t.byteLength-r<Zl.lengthBytes)throw Gl.malformedExt(e);const s=t.getUint8(r),a=new Uint8Array(12);for(let e=0;e<a.length;e+=1){let n=r;n+=1,n+=1*e,a[e]=t.getUint8(n)}i=new Zl(s,a),r+=o;break;default:if(t.byteLength-r<o)throw Gl.malformedExt(e);r+=o}}return[new $l({userTimestamp:n,e2ee:i}),t.byteLength]}toJSON(){var e,t,n,i;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(i=null===(n=this.e2ee)||void 0===n?void 0:n.toJSON())&&void 0!==i?i:null}}}const eu={from:e=>({payload:e.payload,extensions:new $l({userTimestamp:e.userTimestamp?new Xl(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null===(t=e.extensions.userTimestamp)||void 0===t?void 0:t.timestamp}}};var tu;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(tu||(tu={}));class nu extends Zo{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=tu[t]}isReason(e){return this.reason===e}static tooLarge(){return new nu("Value too large to be a valid track handle",tu.TooLarge)}static reserved(e){return new nu("0x".concat(e.toString(16)," is a reserved value."),tu.Reserved)}}const iu={fromNumber(e){if(0===e)throw nu.reserved(e);if(e>Fl)throw nu.tooLarge();return e}};class ru{constructor(){this.value=0}get(){return this.value+=1,this.value>Fl?null:this.value}reset(){this.value=0}}class ou extends Ql{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!==(t=e.extensions)&&void 0!==t?t:new $l}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes;let i=12;return t>0&&(i+=2+t+n),i}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Jl.tooSmallForHeader();let t,n=0;switch(this.marker){case su.Inter:t=0;break;case su.Final:t=1;break;case su.Start:t=2;break;case su.Single:t=3}n|=t<<3;const i=this.extensionsMetrics(),r=i.lengthBytes,o=i.lengthWords,s=i.paddingLengthBytes;r>0&&(n|=4);let a=0;if(e.setUint8(a,n),a+=1,e.setUint8(a,0),a+=1,e.setUint16(a,this.trackHandle),a+=2,e.setUint16(a,this.sequence.value),a+=2,e.setUint16(a,this.frameNumber.value),a+=2,e.setUint32(a,this.timestamp.asTicks()),a+=4,r>0){const t=o-1;e.setUint16(a,t),a+=2;a+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+a));for(let n=0;n<s;n+=1)e.setUint8(a,0),a+=1}const c=this.toBinaryLengthBytes();if(a!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(a," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=Wl(e);if(t.byteLength<12)throw Gl.tooShort();let n=0;const i=t.getUint8(n);n+=1;const r=i>>5&7;if(r>0)throw Gl.unsupportedVersion(r);let o;switch(i>>3&3){case 2:o=su.Start;break;case 1:o=su.Final;break;case 3:o=su.Single;break;default:o=su.Inter}const s=(i>>2&1)>0;let a;n+=1;try{a=iu.fromNumber(t.getUint16(n))}catch(ke){throw ke instanceof nu&&(ke.isReason(tu.Reserved)||ke.isReason(tu.TooLarge))?Gl.invalidHandle(ke):ke}n+=2;const c=Bl.u16(t.getUint16(n));n+=2;const d=Bl.u16(t.getUint16(n));n+=2;const l=ql.fromRtpTicks(t.getUint32(n));n+=4;let u=new $l;if(s){if(t.byteLength-n<2)throw Gl.missingExtWords();let e=t.getUint16(n);n+=2;let i=4*(e+1)-2;if(n+i>t.byteLength)throw Gl.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+n,i);const o=tt($l.fromBinary(r),2);u=o[0],n+=o[1]}return[new ou({marker:o,trackHandle:a,sequence:c,frameNumber:d,timestamp:l,extensions:u}),n]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var su,au,cu,du,lu;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(su||(su={}));class uu extends Ql{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;if(t+=this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw Jl.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return n}static fromBinary(e){const t=Wl(e),n=tt(ou.fromBinary(t),2),i=n[0],r=n[1],o=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new uu(i,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}class hu extends Zo{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=au[t]}static mtuTooShort(){return new hu("MTU is too short to send frame",au.MtuTooShort)}}!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(au||(au={}));class pu{constructor(e,t){this.sequence=Bl.u16(0),this.frameNumber=Bl.u16(0),this.clock=Vl.rtpStartingNow(ql.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?su.Single:0===e?su.Start:e===t-1?su.Final:su.Inter}*packetize(e,t){var n;const i=this.frameNumber.getThenIncrement(),r={marker:su.Inter,trackHandle:this.handle,sequence:Bl.u16(0),frameNumber:i,timestamp:null!==(n=null==t?void 0:t.now)&&void 0!==n?n:this.clock.now(),extensions:e.extensions},o=new ou(r).toBinaryLengthBytes();if(o>=this.mtuSizeBytes)throw hu.mtuTooShort();const s=this.mtuSizeBytes-o,a=Math.ceil(e.payload.byteLength/s);for(let d=0,l=0;l<e.payload.byteLength;d=(c=[d+1,l+s])[0],l=c[1],c){var c;const t=this.sequence.getThenIncrement(),n=new ou(Object.assign(Object.assign({},r),{marker:pu.computeFrameMarker(d,a),sequence:t})),i=Math.min(s,e.payload.byteLength-l),o=new Uint8Array(e.payload.buffer,e.payload.byteOffset+l,i);yield new uu(n,o)}}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.DuplicateName=1]="DuplicateName",e[e.Timeout=2]="Timeout",e[e.LimitReached=3]="LimitReached",e[e.Disconnected=4]="Disconnected",e[e.Cancelled=5]="Cancelled",e[e.InvalidName=6]="InvalidName",e[e.Unknown=7]="Unknown"}(cu||(cu={}));class mu extends Zo{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=cu[t],this.rawMessage=null==n?void 0:n.rawMessage}static notAllowed(e){return new mu("Data track publishing unauthorized",cu.NotAllowed,{rawMessage:e})}static duplicateName(e){return new mu("Track name already taken",cu.DuplicateName,{rawMessage:e})}static invalidName(e){return new mu("Track name is invalid",cu.InvalidName,{rawMessage:e})}static timeout(){return new mu("Publish data track timed-out. Does the LiveKit server support data tracks?",cu.Timeout)}static limitReached(e){return new mu("Data track publication limit reached",cu.LimitReached,{rawMessage:e})}static unknown(e,t){return new mu("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),cu.Unknown)}static disconnected(){return new mu("Room disconnected",cu.Disconnected)}static cancelled(){return new mu("Publish data track cancelled by caller",cu.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(du||(du={}));class gu extends Zo{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=du[t]}static trackUnpublished(){return new gu("Track is no longer published",du.TrackUnpublished)}static dropped(e){return new gu("Frame was dropped",du.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(lu||(lu={}));class fu extends Zo{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=lu[t]}static packetizer(e){return new fu("Error packetizing frame",lu.Packetizer,{cause:e})}static encryption(e){return new fu("Error encrypting frame",lu.Encryption,{cause:e})}}const vu=Symbol.for("lk.track"),ku=Symbol.for("lk.data-track");class yu{constructor(t,n){this.trackSymbol=vu,this.isLocal=!0,this.typeSymbol=ku,this.handle=null,this.log=wo,this.flushedFuture=new Da,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null===(t=(e=this.flushedFuture).resolve)||void 0===t||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(n=(t=this.flushedFuture).resolve)||void 0===n||n.call(t),this.flushedFuture=new Da)},this.options=t,this.manager=n,this.log=Po(e.LoggerNames.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const i=new yu(e,t);return i.handle=n,i}get info(){const e=this.descriptor;return"active"===(null==e?void 0:e.type)?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return Ao(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}}))}isPublished(){var e;return"active"===(null===(e=this.descriptor)||void 0===e?void 0:e.type)&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw gu.trackUnpublished();const t=eu.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return Ao(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return Ao(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else wo.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}const bu={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==xn.NONE}),toProtobuf:e=>new jn({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?xn.GCM:xn.NONE})};class Tu{constructor(e,t,n){this.trackSymbol=vu,this.isLocal=!1,this.typeSymbol=ku,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=tt(this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize),2),n=t[0];return t[1].catch((()=>{})),n}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}const Su=Object.values(ge),Eu=Object.values(fe),Cu=Object.values(ve),wu=[ge.h180,ge.h360],Ru=[fe.h180,fe.h360],Pu=["q","h","f"];function Iu(e,t,n,i){var r,o;let s=null==i?void 0:i.videoEncoding;e&&(s=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,l=Zs(d,i);if(!s&&!a&&!c||!t||!n)return[{}];s||(s=function(e,t,n,i){const r=function(e,t,n){if(e)return Cu;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return Su;return Eu}(e,t,n);let o=r[0].encoding;const s=Math.max(t,n);for(let a=0;a<r.length;a+=1){const e=r[a];if(o=e.encoding,e.width>=s)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),wo.debug("using video encoding",s));const u=s.maxFramerate,h=new de(t,n,s.maxBitrate,s.maxFramerate,s.priority);if(c&&Ys(d)&&!l){const e=new Au(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=zo();if($s()){const i="h"==e.suffix?2:3,r=function(e){return e||(e=zo()),"Safari"===(null==e?void 0:e.name)&&va(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&va(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:Pu[2-n],maxBitrate:s.maxBitrate/Math.pow(i,n),maxFramerate:h.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:s.maxBitrate,maxFramerate:h.encoding.maxFramerate,scalabilityMode:c});return h.encoding.priority&&(t[0].priority=h.encoding.priority,t[0].networkPriority=h.encoding.priority),wo.debug("using svc encoding",{encodings:t}),t}if(!a)return[s];const p=e=>(l&&e.forEach((e=>{e.scalabilityMode=c})),e);let m,g;if(m=e?null!==(r=Mu(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:Ou(e,h):null!==(o=Mu(null==i?void 0:i.videoSimulcastLayers))&&void 0!==o?o:Ou(e,h),m.length>0){const e=m[0];if(m.length>1)g=tt(m,2)[1];const i=Math.max(t,n);if(i>=960&&g)return p(Du(t,n,[e,g,h],u));if(i>=480)return p(Du(t,n,[e,h],u))}return p(Du(t,n,[h]))}function _u(e,t,n){var i,r,o,s;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&wo.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===(r=e.dimensions)||void 0===r?void 0:r.width,d=null!==(o=a.height)&&void 0!==o?o:null===(s=e.dimensions)||void 0===s?void 0:s.height;e.source===Bs.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1);return Iu(e.source===Bs.Source.ScreenShare,c,d,n)}function Ou(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(n=t).encoding.maxFramerate}].map((e=>{var t,i;return new de(Math.floor(n.width/e.scaleResolutionDownBy),Math.floor(n.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=n.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(i=e.fps)&&void 0!==i?i:30))))),e.fps,n.encoding.priority)}));var n;const i=t.width,r=t.height,o=i>r?i/r:r/i;return Math.abs(o-16/9)<Math.abs(o-4/3)?wu:Ru}function Du(e,t,n,i){const r=[];if(n.forEach(((n,o)=>{if(o>=Pu.length)return;const s=Math.min(e,t),a={rid:Pu[o],scaleResolutionDownBy:Math.max(1,s/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=zo(),l="Firefox"===(null==d?void 0:d.name)&&"iOS"!==d.os||0===o;n.encoding.priority&&l&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),r.push(a)})),ua()&&"ios"===ga()){let e;r.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;r.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,wo.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),wo.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return r}function Mu(e){if(e)return e.slice().sort(((e,t)=>{const n=e.encoding,i=t.encoding;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 Au{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 Lu extends ll{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],r=arguments.length>3?arguments[3]:void 0;super(t,Bs.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Ao(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(ke){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:ke}))}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 r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=sl(t,r)})),this._currentBitrate=e}this.prevStats=n})),this.senderLock=new be}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;this.signalClient=e;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),la()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ol)))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;yield e.pauseUpstream.call(this);try{for(var s,a=!0,c=Uo(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);a=!0){r=s.value,a=!1;const e=r;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(d){n={error:d}}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 Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;yield e.resumeUpstream.call(this);try{for(var s,a=!0,c=Uo(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);a=!0){r=s.value,a=!1;const e=r;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(d){n={error:d}}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 Ao(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!==Bs.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 Ao(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Bs.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Ao(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 r={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&&(r.jitter=o.jitter,r.packetsLost=o.packetsLost,r.roundTripTime=o.roundTripTime),t.push(r)}})),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}))}isSvcPublish(e){return Ys(e)&&!Zs(e,this.publishOptions)}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new Hr({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(this.isSvcPublish(this.codec),n)}restartTrack(e){return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;let s;if(e){const t=Ps({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Uo(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){r=a.value,c=!1;const e=r;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(l){n={error:l}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return Ao(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return Ao(this,void 0,void 0,(function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(ke){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:ke}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const i=Iu(this.source===Bs.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,i),this.encodings=i,this.lastEncodedDimensions=t;for(const r of this.simulcastCodecs){var n=tt(r,2);const t=n[0],i=n[1];if(!i.sender||"closed"===(null===(e=i.sender.transport)||void 0===e?void 0:e.state))continue;if(!pe(t))continue;const o=_u(this,t,Object.assign({},this.publishOptions));o&&(yield this.applyEncodingsToSender(i.sender,o),i.encodings=o)}}catch(ke){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:ke}))}finally{t()}}))}applyEncodingsToSender(e,t){return Ao(this,void 0,void 0,(function*(){const n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach(((e,n)=>{if(!1===e.active)return;const i=t[n];void 0!==i.scaleResolutionDownBy&&(e.scaleResolutionDownBy=i.scaleResolutionDownBy),void 0!==i.maxBitrate&&(e.maxBitrate=i.maxBitrate),void 0!==i.maxFramerate&&(e.maxFramerate=i.maxFramerate),void 0!==i.priority&&(e.priority=i.priority,e.networkPriority=i.priority)})),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Ao(this,arguments,void 0,(function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,o,s,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=Uo(n.simulcastCodecs.values());!(r=(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(p){o={error:p}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(o)throw o.error}}}()}))}setDegradationPreference(e){return Ao(this,void 0,void 0,(function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(const e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)}))}applyDegradationPreference(e){return Ao(this,void 0,void 0,(function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);const t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(ke){this.log.warn("failed to set degradationPreference",Object.assign({error:ke},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){return Ao(this,void 0,void 0,(function*(){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout((()=>{this.refreshSubscribedCodecs()}),5e3))}))}refreshSubscribedCodecs(){return Ao(this,void 0,void 0,(function*(){if(this.subscribedCodecs)return this.setPublishingCodecs(this.subscribedCodecs).catch((e=>this.log.warn("failed to refresh codec for track",Object.assign(Object.assign({},this.logContext),{error:e}))))}))}setPublishingCodecs(e){return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o,s,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(this.isSvcPublish(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=Uo(e);!(r=(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 Nu(t.sender,t.encodings,e.qualities,this.senderLock,this.isSvcPublish(e.codec),this.log,this.logContext));else for(const n of e.qualities)if(n.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(this.isSvcPublish(e.codec),e.qualities)}}catch(d){o={error:d}}finally{try{t||r||!(s=n.return)||(yield s.call(n))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e,t){return Ao(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 Nu(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Ao(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&&Ys(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(ke){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:ke})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ao(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),da()&&this.isInBackground&&this.source===Bs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Nu(e,t,n,i,r,o,s){return Ao(this,void 0,void 0,(function*(){const a=yield i.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),a=i.encodings;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(r){n.some((e=>e.enabled))&&n.forEach((e=>e.enabled=!0))}a.forEach(((e,i)=>{var r;let a=null!==(r=e.rid)&&void 0!==r?r:"";""===a&&(a="q");const d=xu(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"),s),na()&&(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({},s),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}}))}function xu(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Uu(t,n,i,r){if(!i)return[new Jn({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(r){const r=i[0].scalabilityMode,o=new Au(r),s=[],a="h"==o.suffix?1.5:2,c="h"==o.suffix?2:3;for(let d=0;d<o.spatial;d+=1)s.push(new Jn({quality:Math.min(e.VideoQuality.HIGH,o.spatial-1)-d,width:Math.ceil(t/Math.pow(a,d)),height:Math.ceil(n/Math.pow(a,d)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return s}return i.map((e=>{var i,r,o;const s=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let a=xu(null!==(r=e.rid)&&void 0!==r?r:"");return new Jn({quality:a,width:Math.ceil(t/s),height:Math.ceil(n/s),bitrate:null!==(o=e.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}class Fu{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 fs("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 fs("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}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)}}class ju extends Fu{[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch((()=>{}));const t=t=>{e.cancel(t).catch((()=>{})),e.releaseLock(),this.signal=void 0};return{next:()=>Ao(this,void 0,void 0,(function*(){var n;try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const i=yield new Promise(((n,i)=>{if(t){const r=()=>i(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(n,i).finally((()=>{t.removeEventListener("abort",r)}))}else e.read().then(n,i)}));return i.done?(this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(n=this.onProgress)||void 0===n||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(i.value),{done:!1,value:i.value.content})}catch(i){throw t(i),i}})),return(){return Ao(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,o;let s=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Uo(a);!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const e=o;s.add(e)}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return Array.from(s)}()}))}}class Bu extends Fu{[Symbol.asyncIterator](){const t=this.reader.getReader();t.closed.catch((()=>{}));const n=new TextDecoder("utf-8"),i=this.signal,r=e=>{t.cancel(e).catch((()=>{})),t.releaseLock(),this.signal=void 0};return{next:()=>Ao(this,void 0,void 0,(function*(){var o;try{if(null==i?void 0:i.aborted)throw i.reason;const r=yield new Promise(((e,n)=>{if(i){const r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),t.read().then(e,n).finally((()=>{i.removeEventListener("abort",r)}))}else t.read().then(e,n)}));if(r.done)return this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(o=this.onProgress)||void 0===o||o.call(this,1)),{done:!0,value:void 0};{let t;this.handleChunkReceived(r.value);try{t=n.decode(r.value.content)}catch(s){throw new fs("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(s),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(s){throw r(s),s}})),return(){return Ao(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,o;let s="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Uo(a);!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;s+=o}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return s}()}))}}class qu extends Error{constructor(e,t,n,i){super(t),this.code=e,this.message=zu(t,qu.MAX_MESSAGE_BYTES),this.data=n?zu(n,qu.MAX_DATA_BYTES):void 0,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}static fromProto(e){return new qu(e.code,e.message,e.data)}toProto(){return new li({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new qu(qu.ErrorCode[e],qu.ErrorMessage[e],t,n)}}qu.MAX_MESSAGE_BYTES=256,qu.MAX_DATA_BYTES=15360,qu.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},qu.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Vu="lk.rpc_request",Wu="lk.rpc_response";var Hu;!function(e){e.RPC_REQUEST_ID="lk.rpc_request_id",e.RPC_REQUEST_METHOD="lk.rpc_request_method",e.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",e.RPC_REQUEST_VERSION="lk.rpc_request_version"}(Hu||(Hu={}));function Ku(e){return(new TextEncoder).encode(e).length}function zu(e,t){if(Ku(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const o=Math.floor((n+i+1)/2);r.encode(e.slice(0,o)).length<=t?n=o:i=o-1}const o=n>0?e.charCodeAt(n-1):0;return o>=55296&&o<=56319&&(n-=1),e.slice(0,n)}class Gu extends Vo.EventEmitter{constructor(e,t,n,i){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=i}performRpc(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=e.destinationIdentity,i=e.method,r=e.payload,o=e.responseTimeout,s=void 0===o?15e3:o;return function*(){const e=t.getRemoteParticipantClientProtocol(n);if(Ku(r)>15360&&e<1)throw qu.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const o=t.getServerVersion();if(o&&va(o,"1.8.0")<0)throw qu.builtIn("UNSUPPORTED_SERVER");const a=Math.max(s,8e3),c=crypto.randomUUID(),d=new Da;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,qu.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==l&&clearTimeout(l)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:n});const h=d.promise.finally((()=>{null!==l&&clearTimeout(l),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))}));h.catch((()=>{}));try{yield t.publishRpcRequest(n,c,i,r,a,e)}catch(ke){throw clearTimeout(u),t.pendingAcks.delete(c),t.pendingResponses.delete(c),ke}return t.pendingResponses.has(c)&&(l=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,qu.builtIn("RESPONSE_TIMEOUT"))}),s)),[c,h]}()}))}publishRpcRequest(e,t,n,i,r,o){return Ao(this,void 0,void 0,(function*(){o>=1?yield this.outgoingDataStreamManager.sendText(i,{topic:Vu,destinationIdentities:[e],attributes:{[Hu.RPC_REQUEST_ID]:t,[Hu.RPC_REQUEST_METHOD]:n,[Hu.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Hu.RPC_REQUEST_VERSION]:"".concat(2)}}):this.emit("sendDataPacket",{packet:new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcRequest",value:new ai({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=n[Hu.RPC_REQUEST_ID];if(!i)return void this.log.warn("RPC data stream malformed: ".concat(Hu.RPC_REQUEST_ID," not set."));const r=this.pendingResponses.get(i);if(r&&r.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(i," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));let o;try{o=yield e.readAll()}catch(ke){return this.log.warn("Error reading RPC response payload: ".concat(ke)),void this.handleIncomingRpcResponseFailure(i,qu.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:ke}))}this.handleIncomingRpcResponseSuccess(i,o)}))}handleIncomingRpcResponseSuccess(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).resolve)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).reject)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const o of this.pendingAcks){var n=tt(o,2);const t=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(t)}for(const o of this.pendingResponses){var i=tt(o,2);const n=i[0];var r=i[1];const s=r.participantIdentity,a=r.completionFuture;s===e&&(null===(t=a.reject)||void 0===t||t.call(a,qu.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}}}class Ju extends Vo.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return Ao(this,void 0,void 0,(function*(){var n;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,qu.builtIn("UNSUPPORTED_VERSION"));const i=this.rpcHandlers.get(t.method);if(!i)return void this.publishRpcResponsePacket(e,t.id,null,qu.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield i({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(o){let i;return o instanceof qu?i=o:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),o),i=qu.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(n=null==o?void 0:o.message)&&void 0!==n?n:o),{cause:o})),void this.publishRpcResponsePacket(e,t.id,null,i)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=n[Hu.RPC_REQUEST_ID],r=n[Hu.RPC_REQUEST_METHOD],o=parseInt(n[Hu.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),s=parseInt(n[Hu.RPC_REQUEST_VERSION],10);if(!i||!r||Number.isNaN(o)||Number.isNaN(s))return this.log.warn("RPC data stream malformed: ".concat(Hu.RPC_REQUEST_ID," / ").concat(Hu.RPC_REQUEST_METHOD," / ").concat(Hu.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Hu.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,i,null,qu.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,i),2!==s)return void this.publishRpcResponsePacket(t,i,null,qu.builtIn("UNSUPPORTED_VERSION"));let a;try{a=yield e.readAll()}catch(ke){return this.log.warn("Error reading RPC request payload: ".concat(ke)),void this.publishRpcResponsePacket(t,i,null,qu.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:ke}))}const c=this.rpcHandlers.get(r);if(!c)return void this.publishRpcResponsePacket(t,i,null,qu.builtIn("UNSUPPORTED_METHOD"));let d;try{d=yield c({requestId:i,callerIdentity:t,payload:a,responseTimeout:o})}catch(l){let e;return l instanceof qu?e=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),l),e=qu.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,i,null,e)}yield this.publishRpcResponse(t,i,null!=d?d:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcAck",value:new ci({requestId:t})}})})}publishRpcResponsePacket(e,t,n,i){this.emit("sendDataPacket",{packet:new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcResponse",value:new di({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}})})}publishRpcResponse(e,t,n){return Ao(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1)return void(yield this.outgoingDataStreamManager.sendText(n,{topic:Wu,destinationIdentities:[e],attributes:{[Hu.RPC_REQUEST_ID]:t}}));if(Ku(n)>15360)return this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),void this.publishRpcResponsePacket(e,t,null,qu.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,n,null)}))}}class Qu{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){const e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class Yu{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{const t=e.data;if("metadata"===t.kind){const e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{wo.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(t){t!==this.room&&(this.room=t,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),t.on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)})).on(e.RoomEvent.TrackUnsubscribed,(e=>{this.teardownTrack(e)})).on(e.RoomEvent.Disconnected,(()=>{this.cleanup()})))}setupReceiver(e,t){var n,i,r;const o=e.receiver;if(!o)return;if(!(!!(null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0))return void((null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup)||this.setupPassthroughReceiver(o,e.mediaStreamID));if(!gc(this.worker?{worker:this.worker}:void 0)&&!(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup))return void wo.warn("frame metadata transform not supported; skipping extraction");const s=new Qu,a=e.mediaStreamID;this.extractors.set(a,s),e.frameMetadataExtractor=s,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(o,a,!0)}setupPassthroughReceiver(e,t){mc()?"transform"in e&&(e.transform=null):(this.worker&&gc({worker:this.worker})&&!this.workerPipelines.has(e)||this.worker&&this.workerPipelines.has(e))&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const i=this.worker;if(!i)return;if(mc())return void(e.transform=new RTCRtpScriptTransform(i,{kind:"decode",trackId:t}));const r=this.workerPipelines.get(e);if(r){const o={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:n}};return i.postMessage(o),void this.workerPipelines.set(e,t)}if(!("createEncodedStreams"in e))return void wo.warn("createEncodedStreams not supported");let o;try{o=e.createEncodedStreams()}catch(a){return void wo.warn("failed to create encoded streams",{error:a})}const s={kind:"decode",data:{readableStream:o.readable,writableStream:o.writable,trackId:t,hasPacketTrailer:n}};i.postMessage(s,[o.readable,o.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof Pl&&(e.frameMetadataExtractor=void 0)}cleanup(){for(const e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear()}dispose(){var e;this.cleanup(),null===(e=this.worker)||void 0===e||e.terminate()}}const Xu=Yu;function Zu(){return new CompressionStream("deflate-raw")}function $u(){return new DecompressionStream("deflate-raw")}function eh(e,t){return Ao(this,void 0,void 0,(function*(){const n=new DecompressionStream("deflate-raw"),i=n.writable.getWriter();return i.write(e).catch((()=>{})),i.close().catch((()=>{})),th(n.readable,t)}))}function th(t,n){return Ao(this,void 0,void 0,(function*(){const i=t.getReader(),r=[];let o=0;for(;;){const t=yield i.read(),s=t.done,a=t.value;if(s)break;if(r.push(a),o+=a.byteLength,"number"==typeof n&&o>n)throw yield i.cancel(),new fs("Decompressed payload exceeds the maximum payload size of ".concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge)}const s=new Uint8Array(o);let a=0;for(const e of r)s.set(e,a),a+=e.byteLength;return s}))}const nh=15e3;class ih{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.maxPayloadByteLength,n=void 0===t?5e9:t,i=e.maxOpenStreamsPerParticipant,r=void 0===i?500:i;this.log=wo,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=n,this.maxOpenStreamsPerParticipant=r}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new fs('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 fs('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)}clearControllers(){const t=new fs("Room disconnected in the middle of receiving data",e.DataStreamErrorReason.AbnormalEnd);for(const e of this.byteStreamControllers.values()){e.controller.error(t)}for(const e of this.textStreamControllers.values()){e.controller.error(t)}this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(t){const n=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),i=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(n.length>0||i.length>0){const s=new fs("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const e of i){var r=tt(e,2);const t=r[0];r[1].controller.error(s),this.byteStreamControllers.delete(t)}for(const e of n){var o=tt(e,2);const t=o[0];o[1].controller.error(s),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(this.isConnected)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!'))}else this.bufferedPackets.push({packet:e,encryptionType:t})}hasTooManyOpenStreams(e){let t=0;for(const n of[this.byteStreamControllers,this.textStreamControllers])for(const i of n.values()){i.sendingParticipantIdentity===e&&(t+=1)}return t>=this.maxOpenStreamsPerParticipant}handleStreamHeader(t,n,i){var r;if(this.hasTooManyOpenStreams(n))this.log.error("Participant ".concat(n," already has ").concat(this.maxOpenStreamsPerParticipant," data streams open, dropping stream ").concat(t.streamId));else switch(t.contentHeader.case){case"byteHeader":{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 s;const a={id:t.streamId,name:null!==(r=t.contentHeader.value.name)&&void 0!==r?r:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Ua(t.timestamp),attributes:t.attributes,encryptionType:i};let c;switch(t.compression){case Si.DEFLATE_RAW:if(!Xa())return void wo.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));c=!0;break;case Si.NONE:c=!1;break;default:return void wo.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const d=t.inlineContent;if(void 0!==d)return void o(new ju(a,rh(t.streamId,c?eh(d,this.maxPayloadByteLength):d),Ua(t.totalLength)),{identity:n});const l=new ReadableStream({start:i=>{if(s=i,this.byteStreamControllers.has(t.streamId))throw new fs("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:s,startTime:Date.now(),sendingParticipantIdentity:n})},cancel:()=>{var e;(null===(e=this.byteStreamControllers.get(t.streamId))||void 0===e?void 0:e.controller)===s&&this.byteStreamControllers.delete(t.streamId)}});return void o(new ju(a,c?function(e,t,n){return e.pipeThrough(oh(t)).pipeThrough(sh()).pipeThrough($u()).pipeThrough(ah(t,n)).pipeThrough(function(e){let t=0;return new TransformStream({transform:(n,i)=>{n.byteLength>0&&(i.enqueue(new Ri({streamId:e,chunkIndex:Fa(t),content:n})),t+=1)}})}(t))}(l,t.streamId,this.maxPayloadByteLength):l.pipeThrough(oh(t.streamId)),Ua(t.totalLength)),{identity:n})}case"textHeader":{const r=this.textStreamHandlers.get(t.topic);if(!r)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let o;const s={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,attachedStreamIds:t.contentHeader.value.attachedStreamIds};let a;switch(t.compression){case Si.DEFLATE_RAW:if(!Xa())return void wo.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));a=!0;break;case Si.NONE:a=!1;break;default:return void wo.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const c=t.inlineContent;if(void 0!==c){const e=a?eh(c,this.maxPayloadByteLength):c;return void r(new Bu(s,rh(t.streamId,e),Ua(t.totalLength)),{identity:n})}const d=new ReadableStream({start:i=>{if(o=i,this.textStreamControllers.has(t.streamId))throw new fs("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:s,controller:o,startTime:Date.now(),sendingParticipantIdentity:n})},cancel:()=>{var e;(null===(e=this.textStreamControllers.get(t.streamId))||void 0===e?void 0:e.controller)===o&&this.textStreamControllers.delete(t.streamId)}});return void r(new Bu(s,a?function(t,n,i){return t.pipeThrough(oh(n)).pipeThrough(sh()).pipeThrough($u()).pipeThrough(ah(n,i)).pipeThrough(function(t){const n=new TextDecoder("utf-8"),i=new TextEncoder;let r=0;const o=i=>{try{return i?n.decode(i,{stream:!0}):n.decode()}catch(r){throw new fs("Cannot decode compressed data stream ".concat(t," as text: ").concat(r),e.DataStreamErrorReason.DecodeFailed)}};return new TransformStream({transform:(e,n)=>{const s=o(e);s.length>0&&(n.enqueue(new Ri({streamId:t,chunkIndex:Fa(r),content:i.encode(s)})),r+=1)},flush:e=>{const n=o();n.length>0&&(e.enqueue(new Ri({streamId:t,chunkIndex:Fa(r),content:i.encode(n)})),r+=1)}})}(n))}(d,t.streamId,this.maxPayloadByteLength):d.pipeThrough(oh(t.streamId)),Ua(t.totalLength)),{identity:n})}}}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new fs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):i.controller.enqueue(t));const r=this.textStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new fs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):r.controller.enqueue(t))}handleStreamTrailer(t,n){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new fs("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),t.reason?i.controller.error(new fs("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(t.streamId));const r=this.byteStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new fs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),t.attributes),t.reason?r.controller.error(new fs("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(t.streamId))}}function rh(e,t){return new ReadableStream({start:n=>Ao(this,void 0,void 0,(function*(){const i=yield t;n.enqueue(new Ri({streamId:e,chunkIndex:BigInt(0),content:i})),n.close()}))})}function oh(t){let n=-1;return new TransformStream({transform:(i,r)=>{const o=Ua(i.chunkIndex);if(o<=n)wo.warn("ignoring duplicate chunk ".concat(o," ").concat(i.version>0?"(version ".concat(i.version,")"):""," for data stream ").concat(t," (last processed: ").concat(n,")"));else{if(o>n+1)throw new fs("Missing chunk(s) ".concat(n+1,"..").concat(o-1," for data stream ").concat(t," - cannot reassemble payload"),e.DataStreamErrorReason.Incomplete);n=o,0!==i.content.length&&r.enqueue(i)}}})}function sh(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function ah(t,n){let i=0;return new TransformStream({transform:(r,o)=>{if(i+=r.byteLength,i>n)throw new fs("Data stream ".concat(t," exceeds the maximum payload size of ").concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge);o.enqueue(r)}})}class ch{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 Ao(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 dh extends ch{}class lh extends ch{}function uh(e,t,n){var i;return new wi({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Fa(e.timestamp),totalLength:Fa(e.size),attributes:e.attributes,compression:null!==(i=null==n?void 0:n.compression)&&void 0!==i?i:Si.NONE,inlineContent:null==n?void 0:n.inlineContent,contentHeader:{case:"textHeader",value:new Ei({version:null==t?void 0:t.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?Ti.UPDATE:Ti.CREATE})}})}function hh(e,t){var n;return new wi({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Fa(e.timestamp),totalLength:Fa(e.size),attributes:e.attributes,compression:null!==(n=null==t?void 0:t.compression)&&void 0!==n?n:Si.NONE,inlineContent:null==t?void 0:t.inlineContent,contentHeader:{case:"byteHeader",value:new Ci({name:e.name})}})}function ph(e,t){return new Yn({destinationIdentities:t,value:{case:"streamHeader",value:e}})}const mh=new TextEncoder;class gh{constructor(e,t,n,i,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=i,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r,o,s;const a=crypto.randomUUID(),c=mh.encode(e),d=c.byteLength,l=null===(n=null==t?void 0:t.compress)||void 0===n||n;let u={id:a,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:d,attributes:null==t?void 0:t.attributes,encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE};let h=l&&Xa()&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(null==t?void 0:t.destinationIdentities)?fh.fromStream(Ja(c).pipeThrough(Zu())):null;if((!(null==t?void 0:t.attachments)||0===t.attachments.length)&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)){let e=c,n=Si.NONE;if(h){const t=yield h.collect();t.byteLength<c.byteLength&&(e=t,n=Si.DEFLATE_RAW)}const i=ph(uh(u,void 0,{compression:n,inlineContent:e}),null==t?void 0:t.destinationIdentities);if(i.toBinary().byteLength<=nh)return yield this.engine.sendDataPacket(i,xd.RELIABLE),null===(o=null==t?void 0:t.onProgress)||void 0===o||o.call(t,1),u}const p=null===(s=null==t?void 0:t.attachments)||void 0===s?void 0:s.map((()=>crypto.randomUUID())),m=p?p.length+1:1,g=new Array(m).fill(0),f=(e,n)=>{var i;g[n]=e,null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,g.reduce(((e,t)=>e+t),0)/m)};if(h){u.attachedStreamIds=p;const e=ph(uh(u,void 0,{compression:Si.DEFLATE_RAW}),null==t?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(e,a,null==t?void 0:t.destinationIdentities,h.stream().pipeThrough(vh(c.length,(e=>f(e,0))))),0===c.length&&f(1,0)}else{const n=yield this.streamText({streamId:a,totalSize:d,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:p,attributes:null==t?void 0:t.attributes});yield n.write(e),f(1,0),yield n.close(),u=n.info}return(null==t?void 0:t.attachments)&&p&&(yield Promise.all(t.attachments.map(((e,n)=>Ao(this,void 0,void 0,(function*(){return this._sendFile(p[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{f(e,n+1)}})})))))),u}))}sendBytes(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r,o,s,a,c;const d=crypto.randomUUID(),l=null==t?void 0:t.destinationIdentities,u=null===(n=null==t?void 0:t.compress)||void 0===n||n,h={id:d,name:null!==(i=null==t?void 0:t.name)&&void 0!==i?i:"unknown",mimeType:null!==(r=null==t?void 0:t.mimeType)&&void 0!==r?r:"application/octet-stream",timestamp:Date.now(),topic:null!==(o=null==t?void 0:t.topic)&&void 0!==o?o:"",size:e.byteLength,attributes:null==t?void 0:t.attributes,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE},p=vh(e.length,null==t?void 0:t.onProgress);let m=u&&Xa()&&this.allRecipientsSupportV2(l)&&this.allRecipientsSupportCompression(l)?fh.fromStream(Ja(e).pipeThrough(p).pipeThrough(Zu())):null;if(this.allRecipientsSupportV2(l)){let n=e,i=Si.NONE;if(m){const t=yield m.collect();t.byteLength<e.byteLength&&(n=t,i=Si.DEFLATE_RAW)}const r=ph(hh(h,{compression:i,inlineContent:n}),l);if(r.toBinary().byteLength<=nh)return yield this.engine.sendDataPacket(r,xd.RELIABLE),null===(a=null==t?void 0:t.onProgress)||void 0===a||a.call(t,1),h}const g=ph(hh(h,{compression:m?Si.DEFLATE_RAW:Si.NONE}),l),f=m?m.stream():Ja(e).pipeThrough(p);return yield this.sendChunkedByteStream(g,d,l,f),0===e.length&&(null===(c=null==t?void 0:t.onProgress)||void 0===c||c.call(t,1)),h}))}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantClientProtocol(e)>=2))}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantCapabilities(e).includes(fi.CAP_COMPRESSION_DEFLATE_RAW)))}sendChunkedByteStream(e,t,n,i){return Ao(this,void 0,void 0,(function*(){var r,o,s,a;const c=this.engine;yield kh(c,e);let d=0;try{for(var l,u=!0,h=Uo(function(e,t){return xo(this,arguments,(function*(){const n=e.getReader();let i=new Uint8Array(0);try{for(;;){const e=yield No(n.read()),r=e.done,o=e.value;if(r)break;if(0===o.byteLength)continue;const s=new Uint8Array(i.byteLength+o.byteLength);for(s.set(i),s.set(o,i.byteLength),i=s;i.byteLength>=t;)yield yield No(i.slice(0,t)),i=i.slice(t)}i.byteLength>0&&(yield yield No(i))}finally{n.releaseLock()}}))}(i,nh));!(r=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=new Yn({destinationIdentities:n,value:{case:"streamChunk",value:new Ri({content:a,streamId:t,chunkIndex:Fa(d)})}});yield c.sendDataPacket(e,xd.RELIABLE),d+=1}}catch(p){o={error:p}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(o)throw o.error}}yield yh(t,n,c)}))}streamText(t){return Ao(this,void 0,void 0,(function*(){var n,i,r;const o=null!==(n=null==t?void 0:t.streamId)&&void 0!==n?n:crypto.randomUUID(),s=null==t?void 0:t.destinationIdentities,a={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===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE,attachedStreamIds:null==t?void 0:t.attachedStreamIds},c=ph(uh(a,t),s);yield kh(this.engine,c);let d=0;const l=this.engine,u=new WritableStream({write(e){return Ao(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,nh)){const e=new Ri({content:t,streamId:o,chunkIndex:Fa(d)}),n=new Yn({destinationIdentities:s,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(n,xd.RELIABLE),d+=1}}))},close(){return Ao(this,void 0,void 0,(function*(){yield yh(o,s,l)}))},abort(e){console.log("Sink error:",e)}});let h=()=>Ao(this,void 0,void 0,(function*(){yield p.close()}));l.once(e.EngineEvent.Closing,h);const p=new dh(u,a,(()=>this.engine.off(e.EngineEvent.Closing,h)));return p}))}sendFile(e,t){return Ao(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return Ao(this,void 0,void 0,(function*(){var i,r,o,s,a;const c=null==n?void 0:n.destinationIdentities,d=(null===(i=null==n?void 0:n.compress)||void 0===i||i)&&Xa()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),l={id:e,name:t.name,mimeType:null!==(r=null==n?void 0:n.mimeType)&&void 0!==r?r:t.type,topic:null!==(o=null==n?void 0:n.topic)&&void 0!==o?o:"",timestamp:Date.now(),size:t.size,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE},u=ph(hh(l,{compression:d?Si.DEFLATE_RAW:Si.NONE}),c),h=t.stream().pipeThrough(vh(t.size,null==n?void 0:n.onProgress)),p=d?h.pipeThrough(Zu()):h;return yield this.sendChunkedByteStream(u,e,c,p),0===t.size&&(null===(a=null==n?void 0:n.onProgress)||void 0===a||a.call(n,1)),l}))}streamBytes(e){return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;const s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:s,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!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown",encryptionType:(null===(o=this.engine.e2eeManager)||void 0===o?void 0:o.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE},d=ph(hh(c),a);yield kh(this.engine,d);let l=0;const u=new be,h=this.engine,p=this.log,m=new WritableStream({write(e){return Ao(this,void 0,void 0,(function*(){const t=yield u.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+nh),i=new Yn({destinationIdentities:a,value:{case:"streamChunk",value:new Ri({content:t,streamId:s,chunkIndex:Fa(l)})}});yield h.sendDataPacket(i,xd.RELIABLE),l+=1,n+=t.byteLength}}finally{t()}}))},close(){return Ao(this,void 0,void 0,(function*(){yield yh(s,a,h)}))},abort(e){p.error("Sink error:",e)}});return new lh(m,c)}))}}class fh{constructor(e){this.state=e}static fromStream(e){return new fh({type:"stream",stream:e})}collect(){return Ao(this,void 0,void 0,(function*(){switch(this.state.type){case"stream":const e=yield th(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}}))}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return Ja(this.state.bytes)}}}function vh(e,t){let n=0;return new TransformStream({transform(i,r){n+=i.byteLength,t&&"number"==typeof e&&e>0&&t(Math.min(n/e,1)),r.enqueue(i)}})}function kh(t,n){return Ao(this,void 0,void 0,(function*(){if(n.toBinary().byteLength>nh)throw new fs("data stream header exceeds the ".concat(nh,"-byte limit; reduce attribute size"),e.DataStreamErrorReason.HeaderTooLarge);yield t.sendDataPacket(n,xd.RELIABLE)}))}function yh(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=new Yn({destinationIdentities:t,value:{case:"streamTrailer",value:new Pi({streamId:e})}});yield n.sendDataPacket(i,xd.RELIABLE)}))}const bh=il("dataStreams",[],((t,n,i)=>{const r=new ih(null!=i?i:t.options.dataStream),o=new gh(t.engine,n.log,(e=>{var n,i;return null!==(i=null===(n=t.remoteParticipants.get(e))||void 0===n?void 0:n.clientProtocol)&&void 0!==i?i:0}),(e=>{var n,i;return null!==(i=null===(n=t.remoteParticipants.get(e))||void 0===n?void 0:n.capabilities)&&void 0!==i?i:[]}),(()=>Array.from(t.remoteParticipants.keys()))),s=(e,t,n)=>r.handleDataStreamPacket(t,n);return t.on(e.RoomEvent.ConnectionStateChanged,(t=>r.setConnected(t===e.ConnectionState.Connected))).on(e.RoomEvent.ParticipantDisconnected,(e=>r.validateParticipantHasNoActiveDataStreams(e.identity))),{incoming:r,outgoing:o,byteStreamOpener:e=>o.streamBytes(e),dataPackets:{streamHeader:s,streamChunk:s,streamTrailer:s},onEngineCreated:e=>o.setupEngine(e),onDisconnect:()=>r.clearControllers(),room:{registerTextStreamHandler:(e,t)=>r.registerTextStreamHandler(e,t),unregisterTextStreamHandler:e=>r.unregisterTextStreamHandler(e),registerByteStreamHandler:(e,t)=>r.registerByteStreamHandler(e,t),unregisterByteStreamHandler:e=>r.unregisterByteStreamHandler(e)},localParticipant:{sendText:(e,t)=>o.sendText(e,t),streamText:e=>o.streamText(e),sendFile:(e,t)=>o.sendFile(e,t),sendBytes:(e,t)=>o.sendBytes(e,t),streamBytes:e=>o.streamBytes(e)}}})),Th={deviceId:{ideal:"default"},resolution:ge.h720.resolution},Sh={simulcast:!0,screenShareEncoding:ve.h1080fps15.encoding,videoCodec:Od,backupCodec:!0},Eh={defaults:Th,createTrack:(e,t,n,i)=>new Lu(e,t,n,i)};function Ch(){vl(Eh)}function wh(e){return Ao(this,void 0,void 0,(function*(){Ch();return(yield yl({audio:!1,video:null==e||e}))[0]}))}function Rh(e,t){const n=e.localParticipant,i=e.options;return{prepare(r,o,s){return Ao(this,void 0,void 0,(function*(){var a,c,d,l;!function(){const e=zo(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&va(e.osVersion,t)>=0)||"Safari"===e.name&&va(e.version,t)>=0}()&&e.hasE2EESetup&&(t.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),o.simulcast=!1),r.source===Bs.Source.ScreenShare&&na()&&(o.simulcast=!1),"av1"!==o.videoCodec||Js()||(o.videoCodec=void 0),"vp9"!==o.videoCodec||Qs()||(o.videoCodec=void 0),void 0===o.videoCodec&&(o.videoCodec=Od),n.enabledPublishVideoCodecs.length>0&&(n.enabledPublishVideoCodecs.some((e=>o.videoCodec===As(e.mime)))||(o.videoCodec=As(n.enabledPublishVideoCodecs[0].mime)));const u=o.videoCodec;let h;try{h=yield r.waitForDimensions()}catch(ke){const n=null!==(c=null===(a=i.videoCaptureDefaults)||void 0===a?void 0:a.resolution)&&void 0!==c?c:ge.h720.resolution;h={width:n.width,height:n.height},t.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},Ns(r)),{dims:h}))}var p;s.width=h.width,s.height=h.height,!Zs(u,o)||!$s()&&((p=null===(d=e.engine)||void 0===d?void 0:d.serverVersion)&&va(p,"1.13.6")>0)||(o.simulcast=!1,t.info("SVC simulcast is not supported, disabling simulcast.",Ns(r)));const m=Zs(u,o);Ys(u)&&!m&&(r.source===Bs.Source.ScreenShare&&(o.scalabilityMode="L1T3","contentHint"in r.mediaStreamTrack&&(r.mediaStreamTrack.contentHint="motion",t.debug("forcing contentHint to motion for screenshare with SVC codecs",Ns(r)))),o.scalabilityMode=null!==(l=o.scalabilityMode)&&void 0!==l?l:"L3T3_KEY");const g=new ar({codec:u,cid:r.mediaStreamTrack.id});m&&(g.videoLayerMode=Qn.ONE_SPATIAL_LAYER_PER_STREAM),s.simulcastCodecs=[g],!0===o.backupCodec&&(o.backupCodec={codec:Od}),o.backupCodec&&u!==o.backupCodec.codec&&s.encryption===xn.NONE&&(i.dynacast||(i.dynacast=!0),s.simulcastCodecs.push(new ar({codec:o.backupCodec.codec,cid:""})));const f=Iu(r.source===Bs.Source.ScreenShare,s.width,s.height,o);return s.layers=Uu(s.width,s.height,f,Ys(o.videoCodec)&&!Zs(o.videoCodec,o)),f}))},senderCreated(t,n,i,r){var o,s;if(null!==(o=n.degradationPreference)&&void 0!==o||(n.degradationPreference=function(e){switch(e.source){case Bs.Source.Camera:return"maintain-framerate";case Bs.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}(t)),t.setDegradationPreference(n.degradationPreference),i&&t.codec&&Ma(t.codec)){const o=function(e,t,n){var i,r;return Ys(e)&&!Zs(e,t)?null!==(r=null===(i=n[0])||void 0===i?void 0:i.maxBitrate)&&void 0!==r?r:0:n.reduce(((e,t)=>{var n;return e+(null!==(n=t.maxBitrate)&&void 0!==n?n:0)}),0)}(t.codec,n,i);o>0&&(null===(s=e.engine.pcManager)||void 0===s||s.publisher.setTrackCodecBitrate({cid:r.cid,codec:t.codec,maxbr:o/1e3,isScreenShare:t.source===Bs.Source.ScreenShare}))}},serverCodecChanged(e,n,i,r){let o;if(i.codecs.forEach((e=>{void 0===o&&(o=e.mimeType)})),!o)return;const s=As(o);return s!==n.videoCodec?(t.debug("falling back to server selected codec",Object.assign(Object.assign({},Ns(e)),{codec:s})),n.videoCodec=s,Iu(e.source===Bs.Source.ScreenShare,r.width,r.height,n)):void 0},createScreenTracks:t=>Ph(e,t)}}function Ph(t,n){return Ao(this,void 0,void 0,(function*(){const i=t.localParticipant;if(void 0===n&&(n={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new cs("getDisplayMedia not supported");void 0!==n.resolution||ca()||(n.resolution=ve.h1080fps30.resolution);const r=Ms(n),o=yield navigator.mediaDevices.getDisplayMedia(r),s=o.getVideoTracks();if(0===s.length)throw new ds("no video track found");const a=new Lu(s[0],void 0,!1,i.trackLoggerOptions);a.source=Bs.Source.ScreenShare,n.contentHint&&(a.mediaStreamTrack.contentHint=n.contentHint);const c=[a];if(o.getAudioTracks().length>0){i.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new ul(o.getAudioTracks()[0],void 0,!1,i.audioContext,i.trackLoggerOptions);t.source=Bs.Source.ScreenShareAudio,c.push(t)}return c}))}function Ih(e,t,n,i,r){return Ao(this,void 0,void 0,(function*(){var o;const s=e.localParticipant;if(s.isE2EEEnabled)return;let a;if(s.trackPublications.forEach((e=>{e.track&&e.track===n&&(a=e)})),!a)throw new ds("track is not published");if(!Va(n))throw new ds("track is not a video track");const c=Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.publishDefaults),r),d=_u(n,i,c);if(!d)return void t.info("backup codec has been disabled, ignoring request to add additional codec for track",Ns(n));const l=n.addSimulcastTrack(i,d);if(!l)return;const u=s.normalizeRequestedFrameMetadataOptions(n,c),h=n.mediaStreamTrack.getSettings(),p=h.width,m=h.height,g=p&&m?{width:p,height:m}:void 0;g||t.warn("could not determine track dimensions, publishing backup codec without layers",Ns(n));const f=g?Uu(g.width,g.height,d):[],v=new cr({cid:l.mediaStreamTrack.id,type:Bs.kindToProto(n.kind),muted:n.isMuted,source:Bs.sourceToProto(n.source),sid:n.sid,width:null==g?void 0:g.width,height:null==g?void 0:g.height,packetTrailerFeatures:u,layers:f,simulcastCodecs:[{codec:c.videoCodec,cid:l.mediaStreamTrack.id,layers:f}]}),k=e.engine;if(!k||k.isClosed)throw new us("cannot publish track when not connected");const y=(yield Promise.all([k.addTrack(v),(()=>Ao(this,void 0,void 0,(function*(){yield k.createSimulcastSender(n,l,c,d),yield k.negotiate()})))()]))[0];t.debug("published ".concat(i," for track ").concat(n.sid),{encodings:d,trackInfo:y})}))}const _h={key:Symbol("lk.extension.video"),install(t,n){Ch(),t.options.videoCaptureDefaults=Object.assign(Object.assign({},Th),t.options.videoCaptureDefaults),t.options.publishDefaults=Object.assign(Object.assign({},Sh),t.options.publishDefaults);const i=t.localParticipant;return{videoPublisher:Rh(t,n.log),onEngineCreated:i=>{i.on(e.EngineEvent.SubscribedQualityUpdate,(e=>function(e,t,n){return Ao(this,void 0,void 0,(function*(){var i,r,o,s,a;if(!(null===(a=e.options)||void 0===a?void 0:a.dynacast))return;const c=e.localParticipant.videoTrackPublications.get(n.trackSid);if(!c)return void t.warn("received subscribed quality update for unknown track",{trackSid:n.trackSid});if(!c.videoTrack)return;const d=yield c.videoTrack.setPublishingCodecs(n.subscribedCodecs);try{for(var l,u=!0,h=Uo(d);!(i=(l=yield h.next()).done);u=!0){s=l.value,u=!1;const n=s;pe(n)&&(t.debug("publish ".concat(n," for ").concat(c.videoTrack.sid),Ns(c)),yield Ih(e,t,c.videoTrack,n,c.options))}}catch(p){r={error:p}}finally{try{u||i||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}))}(t,n.log,e)))},localParticipant:{setCameraEnabled:(e,t,n)=>i.setTrackEnabled(Bs.Source.Camera,e,t,n),setScreenShareEnabled:(e,t,n)=>i.setTrackEnabled(Bs.Source.ScreenShare,e,t,n),enableCameraAndMicrophone:()=>function(e){return Ao(this,void 0,void 0,(function*(){const t=e.localParticipant;if(!t.pendingPublishing.has(Bs.Source.Camera)&&!t.pendingPublishing.has(Bs.Source.Microphone)){t.pendingPublishing.add(Bs.Source.Camera),t.pendingPublishing.add(Bs.Source.Microphone);try{const e=yield t.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>t.publishTrack(e))))}finally{t.pendingPublishing.delete(Bs.Source.Camera),t.pendingPublishing.delete(Bs.Source.Microphone)}}}))}(t),createScreenTracks:e=>Ph(t,e),publishAdditionalCodecForTrack:(e,i,r)=>Ih(t,n.log,e,i,r)}}}},Oh=e=>function(e,t){const n=new Ll(e);return rl(n,null!=t?t:[]),n}(e,[bh,_h]);var Dh;e.CheckStatus=void 0,(Dh=e.CheckStatus||(e.CheckStatus={}))[Dh.IDLE=0]="IDLE",Dh[Dh.RUNNING=1]="RUNNING",Dh[Dh.SKIPPED=2]="SKIPPED",Dh[Dh.SUCCESS=3]="SUCCESS",Dh[Dh.FAILED=4]="FAILED";class Mh extends Vo.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=Oh(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return Ao(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(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.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 Ao(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 Ao(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 Ao(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 r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Ks(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 Ah extends Mh{get description(){return"Cloud regions"}perform(){return Ao(this,void 0,void 0,(function*(){const e=new tl(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let r=0;r<3;r++){const i=yield e.getNextBestRegionUrl();if(!i)break;if(n.has(i))continue;n.add(i);const r=yield this.checkCloudRegion(i);this.appendMessage("".concat(r.region," RTT: ").concat(r.rtt,"ms, duration: ").concat(r.duration,"ms")),t.push(r)}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 Ao(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 r=yield this.room.localParticipant.streamText({topic:"test"}),o="A".repeat(1e3),s=Date.now();for(let e=0;e<1e3;e++)yield r.write(o);yield r.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-s};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const Lh=1e4;class Nh extends Mh{get description(){return"Connection via UDP vs TCP"}perform(){return Ao(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 Ao(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 r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],s=(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((()=>Ao(this,void 0,void 0,(function*(){const e=yield s.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,Lh))),clearInterval(c),o.stop(),t.remove(),yield this.disconnect(),a}))}}class xh extends Mh{get description(){return"Can publish audio"}perform(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield bl();if(yield Is(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 r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class Uh extends Mh{get description(){return"Can publish video"}perform(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield wh();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 r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(r+=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}checkForVideo(e){return Ao(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,r,o,s;const a=document.createElement("canvas"),c=e.getSettings(),d=null!==(r=null!==(i=c.width)&&void 0!==i?i:n.videoWidth)&&void 0!==r?r:1280,l=null!==(s=null!==(o=c.height)&&void 0!==o?o:n.videoHeight)&&void 0!==s?s: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 Fh extends Mh{get description(){return"Resuming connection after interruption"}perform(){return Ao(this,void 0,void 0,(function*(){var t;const n=yield this.connect();let i,r=!1,o=!1;const s=new Promise((e=>{setTimeout(e,5e3),i=e})),a=()=>{r=!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 s,!r)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 jh extends Mh{get description(){return"Can connect via TURN"}perform(){return Ao(this,void 0,void 0,(function*(){var e,t,n;ha(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=null!==(e=yield new tl(this.url,this.token).getNextBestRegionUrl())&&void 0!==e?e:this.url);const i=new Jc,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,s=!1,a=!1;for(let c of r.iceServers)for(let e of c.urls)e.startsWith("turn:")?(s=!0,a=!0):e.startsWith("turns:")&&(s=!0,a=!0,o=!0),e.startsWith("stun:")&&(a=!0);a?s&&!o&&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===(n=null===(t=this.connectOptions)||void 0===t?void 0:t.rtcConfig)||void 0===n?void 0:n.iceServers)||s?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 Bh extends Mh{get description(){return"Establishing WebRTC connection"}perform(){return Ao(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{var e;const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(e,r)=>{if(e.candidate){const i=new RTCIceCandidate(e);let r="".concat(i.protocol," ").concat(i.address,":").concat(i.port," ").concat(i.type);i.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}(i.address)?"tcp"===i.protocol&&"passive"===i.tcpType?(t=!0,r+=" (passive)"):"udp"===i.protocol&&(n=!0):r+=" (private)"),this.appendMessage(r)}i&&i(e,r)},(null===(e=this.room.engine.pcManager)||void 0===e?void 0:e.subscriber)&&(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(),wo.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class qh extends Mh{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Ao(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,r=new Jc;try{i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(ke){if(ha(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(ke.message,". Retrying with region fallback"));const t=new tl(this.url,this.token),n=yield t.getNextBestRegionUrl();n&&(i=yield r.join(n,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}i?(this.appendMessage("Connected to server, version ".concat(i.serverVersion,".")),(null===(e=i.serverInfo)||void 0===e?void 0:e.edition)===pi.Cloud&&(null===(t=i.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=i.serverInfo)||void 0===n?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()}))}}class Vh extends Vo.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 Ao(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 r=yield n.run();return n.off("update",i),r}))}checkWebsocket(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(qh)}))}checkWebRTC(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Bh)}))}checkTURN(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(jh)}))}checkReconnect(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Fh)}))}checkPublishAudio(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(xh)}))}checkPublishVideo(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Uh)}))}checkConnectionProtocol(){return Ao(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(Nh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Ah)}))}}var Wh,Hh,Kh;e.KeyProviderEvent=void 0,(Wh=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",Wh.RatchetRequest="ratchetRequest",Wh.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Hh=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Hh.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class zh extends Vo.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(e,t,n)=>{wo.debug("key ratcheted event received",{participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},sc),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const r={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),r),void 0!==i&&(this.latestManuallySetKeyIndex=i),this.emit(e.KeyProviderEvent.SetKey,r,void 0!==i)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}e.CryptorErrorReason=void 0,(Kh=e.CryptorErrorReason||(e.CryptorErrorReason={}))[Kh.InvalidKey=0]="InvalidKey",Kh[Kh.MissingKey=1]="MissingKey",Kh[Kh.InternalError=2]="InternalError";class Gh extends Xo{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}}class Jh{}class Qh{}new TextEncoder;const Yh=new TextDecoder,Xh=new TextDecoder("utf-8",{fatal:!0});class Zh extends Error{constructor(e,t){var n;super(e,t),Ze(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}Ze(Zh,"code","ERR_JOSE_GENERIC");Ze(class extends Zh{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}}),Ze(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");Ze(class extends Zh{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}}),Ze(this,"code","ERR_JWT_EXPIRED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");Ze(class extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");Ze(class extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");Ze(class extends Zh{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),Ze(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");Ze(class extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");Ze(class extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class $h extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JWT_INVALID")}}Ze($h,"code","ERR_JWT_INVALID");Ze(class extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");Ze(class extends Zh{constructor(){super(...arguments),Ze(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");Ze(class extends Zh{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),Ze(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");Ze(class extends Zh{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),Ze(this,Symbol.asyncIterator,function(e){return function(){return new rt(e.apply(this,arguments))}}((function*(){}))),Ze(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");Ze(class extends Zh{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),Ze(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");Ze(class extends Zh{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),Ze(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function ep(e){try{return function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}const n=atob(e),i=new Uint8Array(n.length);for(let r=0;r<n.length;r++)i[r]=n.charCodeAt(r);return i}("string"==typeof e?e:Yh.decode(e),!0)}catch(t){throw new TypeError("The input to be decoded is not correctly encoded.",{cause:t})}}function tp(e){if("string"!=typeof e)throw new $h("JWTs must use Compact JWS serialization, JWT must be a string");const t=e.split("."),n=t[1],i=t.length;if(5===i)throw new $h("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new $h("Invalid JWT");if(!n)throw new $h("JWTs must contain a payload");let r,o;try{r=ep(n)}catch(s){throw new $h("Failed to base64url decode the payload")}try{o=JSON.parse(Xh.decode(r))}catch(a){throw new $h("Failed to parse the decoded payload as JSON")}if(!function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}(o))throw new $h("Invalid JWT Claims Set");return o}const np=1e3;function ip(e){const t=tp(e);t.roomConfig;const n=Mo(t,["roomConfig"]);return Object.assign(Object.assign({},n),{roomConfig:t.roomConfig?er.fromJson(t.roomConfig,{ignoreUnknownFields:!0}):void 0})}function rp(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const i of n)switch(i){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"agentName":case"agentMetadata":case"deployment":if(e[i]!==t[i])return!1;break;case"participantAttributes":if(!op(e[i],t[i]))return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0}function op(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),i=new Set(Object.keys(t));return n.length===i.size&&n.every((n=>i.has(n)&&e[n]===t[n]))}class sp extends Qh{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new be}isSameAsCachedFetchOptions(e){return!!this.cachedFetchOptions&&rp(e,this.cachedFetchOptions)}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=ip(e.participantToken);if(!(null==t?void 0:t.exp))return!1;const n=new Date;if(t.nbf){const e=t.nbf*np;if(new Date(e)>n)return!1}const i=t.exp*np;return new Date(i-6e4)>n}(this.cachedResponse)&&!!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?ip(this.cachedResponse.participantToken):null}fetch(e,t){return Ao(this,void 0,void 0,(function*(){const n=yield this.fetchMutex.lock();try{if(t&&(this.cachedResponse=null),this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();const n=yield this.update(e);return this.cachedFetchOptions=e,this.cachedResponse=n,n.toJson()}finally{n()}}))}}class ap extends Jh{constructor(e){super(),this.literalOrFn=e}fetch(){return Ao(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class cp extends sp{constructor(e){super(),this.customFn=e}update(e){return Ao(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,vo.fromJson(n,{ignoreUnknownFields:!0})}))}}class dp extends sp{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,r;const o=new fo;for(const s of Object.keys(e))switch(s){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":o[s]=e[s];break;case"participantAttributes":o.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":o.roomConfig=null!==(n=o.roomConfig)&&void 0!==n?n:new er,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Mi),o.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":o.roomConfig=null!==(i=o.roomConfig)&&void 0!==i?i:new er,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Mi),o.roomConfig.agents[0].metadata=e.agentMetadata;break;case"deployment":o.roomConfig=null!==(r=o.roomConfig)&&void 0!==r?r:new er,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Mi),o.roomConfig.agents[0].deployment=e.deployment;break;default:throw new Error("Options key ".concat(s," not being included in forming request!"))}return o}update(e){return Ao(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 r=yield i.json();return vo.fromJson(r,{ignoreUnknownFields:!0})}))}}class lp extends dp{constructor(e,t){const n=t.baseUrl,i=void 0===n?"https://cloud-api.livekit.io":n,r=Mo(t,["baseUrl"]);super("".concat(i,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},r),{headers:{"X-Sandbox-ID":e}}))}}class up extends lp{}const hp={literal:e=>new ap(e),custom:e=>new cp(e),endpoint(e){return new dp(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new up(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},developmentTokenServer(e){return new lp(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const pp=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),mp=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function gp(e){var t;const n=e.trim().toLowerCase();if(""!==n)return pp.has(n)?pp.get(n):null===(t=Array.from(mp.entries()).find((e=>{let t=tt(e,1)[0];return n.includes(t)})))||void 0===t?void 0:t[1]}const fp=Symbol.for("lk.serializer");function vp(e){return Object.assign(Object.assign({},e),{symbol:fp})}const kp={json:function(){return vp({parse:e=>JSON.parse(e),serialize:e=>JSON.stringify(e)})},raw:function(){return vp({parse:e=>e,serialize:e=>e})},custom:function(e){return vp(e)}};class yp extends Vo.EventEmitter{get logContext(){var e,t;return{room:null===(e=this.room)||void 0===e?void 0:e.name,participant:null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity}}constructor(t,n){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=Po(e.LoggerNames.E2EE,(()=>this.logContext)),this.onWorkerMessage=t=>{var n;const i=t.data,r=i.kind,o=i.data;switch(r){case"error":if(o.uuid){const e=this.decryptDataRequests.get(o.uuid);if(null==e?void 0:e.reject){e.reject(o.error);break}const t=this.encryptDataRequests.get(o.uuid);if(null==t?void 0:t.reject){t.reject(o.error);break}}this.log.error(o.error.message),this.emit(e.EncryptionEvent.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)}));break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)})),o.local)this.encryptionEnabled!==o.enabled&&(this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled);else if(o.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.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 i=this.encryptDataRequests.get(o.uuid);(null==i?void 0:i.resolve)&&i.resolve(o);break;case"packetTrailerMetadata":this.handleFrameMetadata(o.trackId,o.rtpTimestamp,o.ssrc,o.metadata);break;case"log":Io[o.level](o.msg,o.context)}},this.onWorkerError=t=>{this.log.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error,void 0)},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(!ac())throw new cs("tried to setup end-to-end encryption on an unsupported browser");if(this.log.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:Io.getLevel()}};this.worker&&(this.log.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var e;let t;if(null===(e=this.unsubscribeLogLevel)||void 0===e||e.call(this),yp.disposeRegistry){const e=new WeakRef(this.worker);t=Do((n=>{const i=e.deref();i?i.postMessage({kind:"setLogLevel",data:{level:n}}):null==t||t()})),yp.disposeRegistry.register(this,t,this)}else{const e=this.worker;t=Do((t=>{e.postMessage({kind:"setLogLevel",data:{level:t}})}))}this.unsubscribeLogLevel=t}dispose(){var t,n,i;null===(t=this.unsubscribeLogLevel)||void 0===t||t.call(this),this.unsubscribeLogLevel=void 0,yp.disposeRegistry&&yp.disposeRegistry.unregister(this);const r=new Gh("E2EEManager disposed",e.CryptorErrorReason.InternalError);for(const e of[...this.encryptDataRequests.values()])null===(n=e.reject)||void 0===n||n.call(e,r);for(const e of[...this.decryptDataRequests.values()])null===(i=e.reject)||void 0===i||i.call(e,r);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setLocalParticipantCryptorEnabled(e){var t,n;this.log.debug("set e2ee to ".concat(e," for the local participant")),this.postEnable(e,null!==(n=null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity)&&void 0!==n?n:"",!0)}setParticipantCryptorEnabled(e,t){this.setLocalParticipantCryptorEnabled(e)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):this.log.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,n,i){if(this.room)for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const o of r.trackPublications.values())if(o.track&&o.track.mediaStreamID===e&&o.track instanceof Pl&&o.track.frameMetadataExtractor)return void o.track.frameMetadataExtractor.storeMetadata(t,n,i)}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabledForPublication(e,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabledForPublication(t,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const r={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(r)})).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");const e=n.getLatestManuallySetKeyIndex();n.getKeys().forEach((t=>{var n;this.postKey(t,e===(null!==(n=t.keyIndex)&&void 0!==n?n:0))})),this.setLocalParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>Ao(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!qa(e.track)||!sa())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:As(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1,operation:"encode"}};this.worker.postMessage(t)})),n.on(e.KeyProviderEvent.SetKey,((e,t)=>this.postKey(e,null==t||t))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return Ao(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 Da;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 r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:i}},s=new Da;return s.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,s),this.worker.postMessage(o),s.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,i=e.participantIdentity,r=e.keyIndex;var o;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(o=this.room)||void 0===o?void 0:o.localParticipant.identity),key:n,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(s)}postEnable(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t,local:n}};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 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)}setParticipantCryptorEnabledForPublication(e,t){e.trackInfo?this.postEnable(e.trackInfo.encryption!==xn.NONE,t):this.log.warn("skipping e2ee enabled update for publication without trackInfo",{trackSid:e.trackSid})}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const i="video"===e.kind&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?As(n.mimeType):void 0,i,n.encryption!==xn.NONE)}setupE2EESender(e,t){var n;if(!ja(e)||!t)return void(t||this.log.warn("early return because sender is not ready"));const i=qa(e),r=i?null===(n=e.publishOptions)||void 0===n?void 0:n.videoCodec:void 0;this.handleSender(t,e.mediaStreamID,"h264"===r||"h265"===r?r:void 0,i?vc(e.publishOptions):void 0)}handleReceiver(e,t,n,i,r,o){return Ao(this,void 0,void 0,(function*(){if(this.worker){if(ra()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:i,hasPacketTrailer:r,encrypted:o};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(rc in e&&oc in e){const s={kind:"updateCodec",data:{trackId:t,previousTrackId:e[oc],codec:i,participantIdentity:n,hasPacketTrailer:r,encrypted:o}};return this.worker.postMessage(s),void(e[oc]=t)}let s=e.writableStream,a=e.readableStream;if(!s||!a){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,a=t.readable}const c={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:i,participantIdentity:n,hasPacketTrailer:r,encrypted:o}};this.worker.postMessage(c,[a,s])}e[rc]=!0,e[oc]=t}}))}handleSender(e,t,n,i){var r;if(!(rc in e)&&this.worker){if(!(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ra()){this.log.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:fc(i),packetTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{this.log.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:fc(i),packetTrailer:i}};this.worker.postMessage(o,[r.readable,r.writable])}e[rc]=!0}}}yp.disposeRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e()}));const bp=il("e2ee",[],((t,n,i)=>{const r=!t.options.e2ee,o=null!=i?i:t.options.encryption||t.options.e2ee;let s,a=()=>{};if(o){if("e2eeManager"in o)s=o.e2eeManager,s.isDataChannelEncryptionEnabled=r;else{const e=new yp(o,r);s=e,a=()=>{e.dispose(),o.worker.terminate()}}const n=(n,i)=>{Ga(i)&&(t.isE2EEEnabled=n),t.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,n,i)},i=(n,i)=>{const r=i?t.getParticipantByIdentity(i):void 0;t.emit(e.RoomEvent.EncryptionError,n,r)};if(s.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,n),s.on(e.EncryptionEvent.EncryptionError,i),"e2eeManager"in o){const t=s;a=()=>{t.off(e.EncryptionEvent.ParticipantEncryptionStatusChanged,n),t.off(e.EncryptionEvent.EncryptionError,i)}}s.setup(t),s.setupEngine(t.engine)}const c=new be;return{manager:s,e2eeManager:s,room:{setE2EEEnabled:e=>Ao(void 0,void 0,void 0,(function*(){const n=yield c.lock();try{if(!s)throw Error("e2ee not configured, please set e2ee settings within the room options");t.isE2EEEnabled!==e&&(yield t.localParticipant.setE2EEEnabled(e),s.setLocalParticipantCryptorEnabled?s.setLocalParticipantCryptorEnabled(e):""!==t.localParticipant.identity&&s.setParticipantCryptorEnabled(e,t.localParticipant.identity))}finally{n()}}))},dispose:a}})),Tp=il("frameMetadata",[],((e,t,n)=>{var i;const r=null!==(i=null!=n?n:e.options.frameMetadata)&&void 0!==i?i:e.options.packetTrailer,o=new Yu(r);return o.setup(e),{manager:o,frameMetadataOptions:r,dispose:()=>o.dispose()}})),Sp={key:Symbol("lk.extension.chat"),install(t,n){const i=t.localParticipant;i.on(e.ParticipantEvent.ChatMessage,(n=>{t.emit(e.RoomEvent.ChatMessage,n,i)}));const r=n=>Ao(this,void 0,void 0,(function*(){const r=new Yn({value:{case:"chatMessage",value:new si(Object.assign(Object.assign({},n),{timestamp:Ve.parse(n.timestamp),editTimestamp:void 0!==n.editTimestamp?Ve.parse(n.editTimestamp):void 0}))}});return yield t.engine.sendDataPacket(r,xd.RELIABLE),i.emit(e.ParticipantEvent.ChatMessage,n),n}));return{dataPackets:{chatMessage:(n,i,r,o)=>{t.emit(e.RoomEvent.ChatMessage,function(e){const t=e.id,n=e.timestamp,i=e.message,r=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}(n),o)}},localParticipant:{sendChatMessage:(e,t)=>r({id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments}),editChatMessage:(e,t)=>r(Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}))}}}},Ep=Po(e.LoggerNames.DataTracks);class Cp extends Zo{constructor(e,t,n,i){super(19,"Frame ".concat(n," dropped: ").concat(e),i),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=wp[t],this.frameNumber=n}static interrupted(e,t){return new Cp("Interrupted by the start of a new frame ".concat(t),wp.Interrupted,e)}static unknownFrame(e){return new Cp("Initial packet was never received.",wp.UnknownFrame,e)}static bufferFull(e){return new Cp("Reorder buffer is full.",wp.BufferFull,e)}static incomplete(e,t,n){return new Cp("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),wp.Incomplete,e)}}var wp,Rp;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(wp||(wp={}));class Pp{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case su.Single:return this.frameFromSingle(e,t);case su.Start:return this.beginPartial(e,t);case su.Inter:case su.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==su.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const i=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;if(this.partials.size>=i){const n=this.peekOldestPartialFrameNumber();if("number"!=typeof n)throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(n),null==t?void 0:t.throwOnInterruption)throw Cp.interrupted(n,e.header.frameNumber.value);Ep.warn("Data track frame ".concat(n," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var n;if(e.header.marker!==su.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const i=e.header.sequence,r=e.header.frameNumber.value,o={startSequence:i,extensions:e.header.extensions,payloads:new Map([[i.value,e.payload]])},s=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;for(;this.partials.size>=s;){const e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw Cp.interrupted(e,r);Ep.warn("Data track partials full (max ".concat(s,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,o),null}pushToPartial(e){if(e.header.marker!==su.Inter&&e.header.marker!==su.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),Cp.unknownFrame(t);if(n.payloads.size>=Pp.MAX_BUFFER_PACKETS)throw this.partials.delete(t),Cp.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Ep.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===su.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const i=t.payloads.size;let r=0;for(const c of t.payloads.values())r+=c.length;const o=new Uint8Array(r);let s=t.startSequence.clone(),a=0;for(;;){const i=t.payloads.get(s.value);if(!i)break;t.payloads.delete(s.value);const r=o.length-a;if(i.length>r)throw new Error("Depacketizer.finalize: Expected at least ".concat(i.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(o.set(i,a),a+=i.length,s.value==n)return this.partials.delete(e),{payload:o,extensions:t.extensions};s.increment()}throw this.partials.delete(e),Cp.incomplete(e,i,n-t.startSequence.value+1)}}Pp.MAX_BUFFER_PACKETS=128,function(e){e[e.Unpublished=0]="Unpublished",e[e.Timeout=1]="Timeout",e[e.Disconnected=2]="Disconnected",e[e.Cancelled=4]="Cancelled"}(Rp||(Rp={}));class Ip extends Zo{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Rp[t]}static unpublished(){return new Ip("The track has been unpublished and is no longer available",Rp.Unpublished)}static timeout(){return new Ip("Request to subscribe to data track timed-out",Rp.Timeout)}static disconnected(){return new Ip("Cannot subscribe to data track when disconnected",Rp.Disconnected)}static cancelled(){return new Ip("Subscription to data track cancelled by caller",Rp.Cancelled)}}const _p=Po(e.LoggerNames.DataTracks);class Op{constructor(e){var t,n;const i=null!==e.e2eeManager;if(e.info.usesE2ee!==i)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new Pp;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(n=e.pipelineOptions)&&void 0!==n?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return Ao(this,void 0,void 0,(function*(){const t=this.depacketize(e);if(!t)return null;const n=yield this.decryptIfNeeded(t);return n||null}))}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return _p.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return Ao(this,void 0,void 0,(function*(){var t,n;const i=this.e2eeManager;if(!i)return e;const r=null!==(n=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==n?n:null;if(!r)return _p.error("Missing E2EE meta"),null;let o;try{o=yield i.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(s){return _p.error("Error decrypting packet: ".concat(s)),null}return e.payload=o.payload,e}))}}const Dp=Po(e.LoggerNames.DataTracks);class Mp extends Vo.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const n=this.descriptors.get(e);n?(n.pipelineOptions=t,"active"===n.subscription.type&&n.subscription.pipeline.setOptions(t)):Dp.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,i=null;const r=new Da,o=this.descriptors.get(e),s=()=>{null==t||t.removeEventListener("abort",c)},a=()=>{s(),i?o&&this.descriptors.get(o.info.sid)===o?"active"===o.subscription.type?(o.subscription.streamControllers.delete(i),0===o.subscription.streamControllers.size&&this.unSubscribeRequest(o.info.sid)):Dp.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):Dp.warn("Unknown track ".concat(e,", skipping cancel...")):Dp.warn("ReadableStream subscribed to ".concat(e," was not started."))},c=()=>{var e;i&&("active"===(null==o?void 0:o.subscription.type)&&o.subscription.streamControllers.delete(i),i.error(Ip.cancelled()),null===(e=r.reject)||void 0===e||e.call(r,Ip.cancelled()),a())},d=new ReadableStream({start:n=>{i=n,this.subscribeRequest(e,t).then((()=>Ao(this,void 0,void 0,(function*(){var i,a,d;if(!o||this.descriptors.get(o.info.sid)!==o){Dp.error("Unknown track ".concat(e));const t=Ip.disconnected();return n.error(t),void(null===(i=r.reject)||void 0===i||i.call(r,t))}if("active"!==o.subscription.type){Dp.error("Subscription for track ".concat(e," is not active"));const t=Ip.disconnected();return n.error(t),void(null===(a=r.reject)||void 0===a||a.call(r,t))}(null==t?void 0:t.aborted)?c():(null==t||t.addEventListener("abort",c),o.subscription.streamControllers.set(n,s),null===(d=r.resolve)||void 0===d||d.call(r))})))).catch((e=>{var t;n.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{a()}},new CountQueuingStrategy({highWaterMark:n}));return[d,r.promise]}subscribeRequest(e,t){return Ao(this,void 0,void 0,(function*(){const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");const i=(t,n,i)=>Ao(this,void 0,void 0,(function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));const r=Cc([n,i].filter((e=>void 0!==e))),o=new Da;t.subscription.completionFuture.promise.then((()=>{var e;return null===(e=o.resolve)||void 0===e?void 0:e.call(o)})).catch((e=>{var t;return null===(t=o.reject)||void 0===t?void 0:t.call(o,e)}));const s=()=>{var e;"pending"===t.subscription.type&&(t.subscription.pendingRequestCount-=1,(null==i?void 0:i.aborted)||t.subscription.pendingRequestCount<=0?t.subscription.cancel():null===(e=o.reject)||void 0===e||e.call(o,Ip.cancelled()))};r.aborted&&s(),r.addEventListener("abort",s),yield o.promise,r.removeEventListener("abort",s)}));switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new Da,pendingRequestCount:1,cancel:()=>{var e,t;const i=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),"pending"===i.type&&(null===(t=(e=i.completionFuture).reject)||void 0===t||t.call(e,r.aborted?Ip.timeout():Ip.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=wc(1e4);return void(yield i(n,t,r))}case"pending":return n.subscription.pendingRequestCount+=1,void(yield i(n,t));case"active":return}}))}querySubscribed(){return Ao(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.subscription.type)).map((e=>[e.info,e.publisherIdentity]))}))}unSubscribeRequest(e){var t;const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if("active"!==n.subscription.type)return void Dp.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=n.subscription)||void 0===t?void 0:t.type));this.closeStreamControllers(n.subscription.streamControllers,e);const i=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(i.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var n=tt(r,2);const e=n[0];(0,n[1])();try{e.close()}catch(i){Dp.warn("Failed to close readable stream for track ".concat(t,": ").concat(i))}}}receiveSfuPublicationUpdates(e){return Ao(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const r of e.entries()){var n=tt(r,2);const e=n[0],i=n[1],o=new Set;for(const t of i)o.add(t.sid),this.descriptors.has(t.sid)||this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t));t.set(e,o)}for(const e of t.entries()){var i=tt(e,2);const t=i[0],n=i[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let n=tt(e,2);return n[0],n[1].publisherIdentity===t})).map((e=>tt(e,1)[0])).filter((e=>!n.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return Ao(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return Ao(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void Dp.error("Existing descriptor for track ".concat(t.sid));let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);const i=new Tu(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:i})}))}handleSidReassigned(e,t){const n=Array.from(this.descriptors.entries()).find((n=>{let i=tt(n,2);i[0];let r=i[1];return r.publisherIdentity===e&&r.info.pubHandle===t.pubHandle}));if(!n)return!1;const i=tt(n,2),r=i[0],o=i[1],s=o.info,a=s.name,c=s.usesE2ee;if(a!==t.name||c!==t.usesE2ee)return Dp.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;const d=t.sid;if(Dp.debug("SID reassigned: ".concat(r," -> ").concat(d)),!this.descriptors.delete(r))return!1;switch(o.info.sid=d,o.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:d,subscribe:!0})}return"active"===o.subscription.type&&this.subscriptionHandles.set(o.subscription.subcriptionHandle,d),this.descriptors.set(d,o),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):Dp.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=tt(n,2);const e=t[0],i=t[1];this.registerSubscriberHandle(e,i)}}registerSubscriberHandle(e,t){var n,i;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void Dp.warn("No subscription for ".concat(t));case"active":return this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{Dp.debug("data track subscription activated",{sid:t,handle:e});const o=new Op({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),s=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:o,streamControllers:new Map},this.subscriptionHandles.set(e,t),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}}else Dp.error("Unknown track ".concat(t))}packetReceived(e){return Ao(this,void 0,void 0,(function*(){let t;try{t=tt(uu.fromBinary(e),1)[0]}catch(o){return void Dp.error("Failed to deserialize packet: ".concat(o))}const n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void Dp.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const i=this.descriptors.get(n);if(!i)return void Dp.error("Missing descriptor for track ".concat(n));if("active"!==i.subscription.type)return void Dp.warn("Received packet for track ".concat(n," without active subscription"));const r=yield i.subscription.pipeline.processPacket(t);if(r)for(const e of i.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){Dp.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const t=eu.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=tt(t,2);const n=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(const i of this.descriptors.values())if(i.publisherIdentity===e)switch(i.subscription.type){case"none":break;case"pending":null===(n=(t=i.subscription.completionFuture).reject)||void 0===n||n.call(t,Ip.disconnected());break;case"active":this.unSubscribeRequest(i.info.sid)}}reset(){var e,t;for(const n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),"pending"===n.subscription.type&&(null===(t=(e=n.subscription.completionFuture).reject)||void 0===t||t.call(e,Ip.disconnected())),"active"===n.subscription.type&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Ap{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new pu(e.info.pubHandle,Ap.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return xo(this,arguments,(function*(){const t=yield No(this.encryptIfNeeded(e));try{yield No(yield*function(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,r){t[i]=e[i]?function(t){return(n=!n)?{value:No(e[i](t)),done:!1}:r?r(t):t}:r}}(Uo(this.packetizer.packetize(t))))}catch(n){if(n instanceof hu)throw fu.packetizer(n);throw n}}))}encryptIfNeeded(e){return Ao(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw fu.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new Zl(t.keyIndex,t.iv),e}))}}Ap.TRANSPORT_MTU_BYTES=16e3;const Lp=Po(e.LoggerNames.DataTracks),Np={pending:()=>({type:"pending",completionFuture:new Da}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new Ap({info:e,e2eeManager:t}),unpublishingFuture:new Da})};class xp extends Vo.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new ru,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}static withDescriptors(e){const t=new xp;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!==(t=this.descriptors.get(e))&&void 0!==t?t:null}tryProcessAndSend(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r,o,s;const a=this.getDescriptor(e);if("active"!==(null==a?void 0:a.type))throw gu.trackUnpublished();if("unpublished"===a.publishState)throw gu.trackUnpublished();if("republishing"===a.publishState)throw gu.dropped("Data track republishing");try{try{for(var c,d=!0,l=Uo(a.pipeline.processFrame(t));!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const t=o,n=null!==(s=this.inFlightPacketCounter.get(e))&&void 0!==s?s:0;this.inFlightPacketCounter.set(e,n+1),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:t.toBinary()})}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(h){throw gu.dropped(h)}}))}handlePacketSendComplete(e){var t;let n=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;n<0&&(Lp.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),n=0),this.inFlightPacketCounter.set(e,n),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return Ao(this,void 0,void 0,(function*(){const n=this.handleAllocator.get();if(!n)throw mu.limitReached();const i=wc(1e4),r=t?Cc([t,i]):i;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const o=Np.pending();this.descriptors.set(n,o);const s=()=>{var e,t;const r=this.descriptors.get(n);r?(this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,i.aborted?mu.timeout():mu.cancelled()))):Lp.warn("No descriptor for ".concat(n))};return r.aborted?(s(),o.completionFuture.promise.then((()=>n))):(r.addEventListener("abort",s),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:null!==this.e2eeManager}),yield o.completionFuture.promise,r.removeEventListener("abort",s),this.emit("trackPublished",{track:yu.withExplicitHandle(e,this,n)}),n)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return Ao(this,void 0,void 0,(function*(){const t=this.descriptors.get(e);t?"active"===t.type?(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):Lp.warn("Track ".concat(e," not active")):Lp.warn("No descriptor for ".concat(e))}))}receivedSfuPublishResponse(e,t){var n,i,r,o;const s=this.descriptors.get(e);if(s)switch(this.descriptors.delete(e),s.type){case"pending":if("ok"===t.type){const r=t.data;Lp.debug("SFU accepted publish request for handle ".concat(e),{sid:r.sid});const o=r.usesE2ee?this.e2eeManager:null;this.descriptors.set(r.pubHandle,Np.active(r,o)),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}else Lp.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),null===(o=(r=s.completionFuture).reject)||void 0===o||o.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void Lp.warn("Track ".concat(e," already active"));if("error"===t.type)return Lp.warn("Republish failed for track ".concat(e,": ").concat(t.error)),void(s.publishState="unpublished");Lp.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}else Lp.warn("No descriptor for ".concat(e))}receivedSfuUnpublishResponse(e){var t,n;const i=this.descriptors.get(e);i?(this.descriptors.delete(e),"active"===i.type?(i.publishState="unpublished",null===(n=(t=i.unpublishingFuture).resolve)||void 0===n||n.call(t)):Lp.warn("Track ".concat(e," not active"))):Lp.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const i of this.descriptors.entries()){var n=tt(i,2);const r=n[0],o=n[1];switch(o.type){case"pending":this.descriptors.delete(r),null===(t=(e=o.completionFuture).reject)||void 0===t||t.call(e,mu.disconnected());break;case"active":o.publishState="republishing",this.emit("sfuPublishRequest",{handle:o.info.pubHandle,name:o.info.name,usesE2ee:o.info.usesE2ee})}}}reset(){return Ao(this,void 0,void 0,(function*(){var e,t,n,i;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,mu.disconnected());break;case"active":null===(i=(n=r.unpublishingFuture).resolve)||void 0===i||i.call(n),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")}))}}const Up=e=>e.map((e=>bu.from(e))),Fp={key:Symbol("lk.extension.dataTracks"),install(t,n){const i=new Mp,r=new xp;i.on("sfuUpdateSubscription",(e=>{t.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)})).on("trackPublished",(n=>{var i;n.track.publisherIdentity!==t.localParticipant.identity&&(t.emit(e.RoomEvent.DataTrackPublished,n.track),null===(i=t.remoteParticipants.get(n.track.publisherIdentity))||void 0===i||i.addRemoteDataTrack(n.track))})).on("trackUnpublished",(n=>{var i;n.publisherIdentity!==t.localParticipant.identity&&(t.emit(e.RoomEvent.DataTrackUnpublished,n.sid),null===(i=t.remoteParticipants.get(n.publisherIdentity))||void 0===i||i.removeRemoteDataTrack(n.sid))})),r.on("sfuPublishRequest",(e=>{t.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)})).on("sfuUnpublishRequest",(e=>{t.engine.client.sendUnPublishDataTrackRequest(e.handle)})).on("trackPublished",(n=>{t.emit(e.RoomEvent.LocalDataTrackPublished,n.track)})).on("trackUnpublished",(n=>{t.emit(e.RoomEvent.LocalDataTrackUnpublished,n.sid)})).on("packetAvailable",(e=>{let n=e.handle,i=e.bytes;t.engine.sendDataTrackFrame(i).finally((()=>r.handlePacketSendComplete(n)))}));return t.on(e.RoomEvent.ParticipantDisconnected,(e=>i.handleRemoteParticipantDisconnected(e.identity))),{incoming:i,outgoing:r,onEngineCreated:t=>{var o;const s=null!==(o=n.slot("e2eeManager"))&&void 0!==o?o:null;i.updateE2eeManager(s),r.updateE2eeManager(s),t.on(e.EngineEvent.PublishDataTrackResponse,(e=>{e.info?r.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==xn.NONE}}):n.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.UnPublishDataTrackResponse,(e=>{e.info?r.receivedSfuUnpublishResponse(e.info.pubHandle):n.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.DataTrackSubscriberHandles,(e=>{const t=new Map(Object.entries(e.subHandles).map((e=>{let t=tt(e,2),n=t[0],i=t[1];return[parseInt(n,10),i.trackSid]})));i.receivedSfuSubscriberHandles(t)})).on(e.EngineEvent.DataTrackPacketReceived,(e=>{try{i.packetReceived(e)}catch(t){throw t}})).on(e.EngineEvent.Joined,(e=>{i.receiveSfuPublicationUpdates(new Map(e.otherParticipants.map((e=>[e.identity,Up(e.dataTracks)]))))})).on(e.EngineEvent.Restarted,(()=>{r.sfuWillRepublishTracks(),i.resendSubscriptionUpdates()})).on(e.EngineEvent.SignalRequestResponse,(e=>{if("publishDataTrack"!==e.request.case)return;let t;switch(e.reason){case co.NOT_ALLOWED:t=mu.notAllowed(e.message);break;case co.DUPLICATE_NAME:t=mu.duplicateName(e.message);break;case co.INVALID_NAME:t=mu.invalidName(e.message);break;case co.LIMIT_EXCEEDED:t=mu.limitReached(e.message);break;default:t=mu.unknown(e.reason,e.message)}r.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t})}))},onDisconnect:()=>{i.reset(),r.reset()},onParticipantCreated:(e,t)=>{for(const n of t.dataTracks)e.addRemoteDataTrack(new Tu(bu.from(n),i,{publisherIdentity:t.identity}))},onParticipantUpdates:e=>{i.receiveSfuPublicationUpdates(new Map(e.filter((e=>e.identity!==t.localParticipant.identity)).map((e=>[e.identity,Up(e.dataTracks)]))))},syncState:()=>r.queryPublished().map((e=>new lr({info:bu.toProtobuf(e)}))),localParticipant:{publishDataTrack:e=>Ao(this,void 0,void 0,(function*(){const t=new yu(e,r);return yield t.publish(),t}))}}}},jp={key:Symbol("lk.extension.rpc"),requires:[bh],install(t,n){const i=n.get(bh),r=i.incoming,o=i.outgoing,s=e=>{var n,i;return null!==(i=null===(n=t.remoteParticipants.get(e))||void 0===n?void 0:n.clientProtocol)&&void 0!==i?i:0},a=new Gu(n.log,o,s,(()=>{var e;return null===(e=t.engine)||void 0===e?void 0:e.serverVersion}));a.on("sendDataPacket",(e=>{let n=e.packet;var i;null===(i=t.engine)||void 0===i||i.sendDataPacket(n,xd.RELIABLE)}));const c=new Ju(n.log,o,s);c.on("sendDataPacket",(e=>{let n=e.packet;var i;null===(i=t.engine)||void 0===i||i.sendDataPacket(n,xd.RELIABLE)})),r.registerTextStreamHandler(Vu,((e,t)=>Ao(this,[e,t],void 0,(function(e,t){let n=t.identity;return function*(){var t;yield c.handleIncomingDataStream(e,n,null!==(t=e.info.attributes)&&void 0!==t?t:{})}()})))),r.registerTextStreamHandler(Wu,((e,t)=>Ao(this,[e,t],void 0,(function(e,t){let n=t.identity;return function*(){var t;yield a.handleIncomingDataStream(e,n,null!==(t=e.info.attributes)&&void 0!==t?t:{})}()})))),t.on(e.RoomEvent.ParticipantDisconnected,(e=>a.handleParticipantDisconnected(e.identity)));return{dataPackets:{rpcRequest:(e,t)=>{c.handleIncomingRpcRequest(t.participantIdentity,e)},rpcResponse:e=>{switch(e.value.case){case"payload":a.handleIncomingRpcResponseSuccess(e.requestId,e.value.value);break;case"error":a.handleIncomingRpcResponseFailure(e.requestId,qu.fromProto(e.value.value));break;default:n.log.warn("Unknown rpcResponse.value.case: ".concat(e.value.case))}},rpcAck:e=>a.handleIncomingRpcAck(e.requestId)},room:{registerRpcMethod:(e,t)=>c.registerRpcMethod(e,t),unregisterRpcMethod:e=>c.unregisterRpcMethod(e)},localParticipant:{performRpc:e=>a.performRpc(e).then((e=>{let t=tt(e,2);return t[0],t[1]}))}}}},Bp={key:Symbol("lk.extension.rpcLegacy"),requires:[jp],install(e,t){const n=t.get(jp).room;return{localParticipant:{registerRpcMethod:n.registerRpcMethod,unregisterRpcMethod:n.unregisterRpcMethod}}}},qp={key:Symbol("lk.extension.simulatedParticipants"),install:(t,n)=>({room:{simulateParticipants:i=>function(t,n,i){return Ao(this,void 0,void 0,(function*(){var r,o,s,a;const c=Object.assign({audio:!0,video:!0,useRealTracks:!1},i.publish),d=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},i.participants),l=t.localParticipant,u=l.trackLoggerOptions;if(n.simulateConnected(new _n({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ve.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),new Mn({identity:"simulated-local",name:"local-name"})),c.video){const t=new gl(Bs.Kind.Video,new Fn({source:bn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO,name:"video-dummy"}),kl().createTrack(c.useRealTracks&&(null===(r=window.navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Pa(160*(null!==(o=d.aspectRatios[0])&&void 0!==o?o:1),160,!0,!0),void 0,!1,u),u);l.addTrackPublication(t),l.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(c.audio){const t=new gl(Bs.Kind.Audio,new Fn({source:bn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO}),new ul(c.useRealTracks&&(null===(s=navigator.mediaDevices)||void 0===s?void 0:s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:n.acquireEmptyAudioStreamTrack(),void 0,!1,l.audioContext,u),u);l.addTrackPublication(t),l.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<d.count-1;e+=1){let t=new Mn({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:An.ACTIVE,tracks:[],joinedAt:Ve.parse(Date.now())});const i=n.getOrCreateParticipant(t.identity,t);if(d.video){const n=Pa(160*(null!==(a=d.aspectRatios[e%d.aspectRatios.length])&&void 0!==a?a:1),160,!1,!0),r=new Fn({source:bn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(d.audio){const e=n.acquireEmptyAudioStreamTrack(),r=new Fn({source:bn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO});i.addSubscribedMediaTrack(e,r.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}i.updateInfo(t)}}))}(t,n,i)}})};const Vp=[bh,jp,Bp,Fp,Tp,bp,_h,qp,Sp];Ch();const Wp=pe;e.BaseKeyProvider=zh,e.CLIENT_PROTOCOL_DATA_STREAM_RPC=1,e.CLIENT_PROTOCOL_DATA_STREAM_V2=2,e.CLIENT_PROTOCOL_DEFAULT=0,e.Checker=Mh,e.ConnectionCheck=Vh,e.ConnectionError=ss,e.CriticalTimers=ks,e.CryptorError=Gh,e.DataPacket_Kind=Xn,e.DataStreamError=fs,e.DataTrackPacket=uu,e.DefaultReconnectPolicy=_d,e.DeviceUnsupportedError=cs,e.DisconnectReason=Cn,e.Encryption_Type=xn,e.ExternalE2EEKeyProvider=class extends zh{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 Ao(this,void 0,void 0,(function*(){const t="string"==typeof e?yield lc(e):yield uc(e);this.onSetEncryptionKey(t)}))}},e.FrameMetadataManager=Yu,e.LivekitError=Xo,e.LivekitReasonedError=Zo,e.LocalAudioTrack=ul,e.LocalDataTrack=yu,e.LocalParticipant=El,e.LocalTrack=ll,e.LocalTrackPublication=gl,e.LocalTrackRecorder=dl,e.LocalVideoTrack=Lu,e.Mutex=be,e.NegotiationError=hs,e.PROTOCOL_NEGOTIATED_DATA_CHANNELS=18,e.PacketTrailerManager=Xu,e.Participant=Sl,e.ParticipantKind=Ln,e.PublishDataError=ps,e.PublishTrackError=ms,e.RemoteAudioTrack=pl,e.RemoteDataTrack=Tu,e.RemoteParticipant=Dl,e.RemoteTrack=hl,e.RemoteTrackPublication=Rl,e.RemoteVideoTrack=Pl,e.Room=class extends Ll{constructor(e){super(e),rl(this,Vp)}},e.RpcError=qu,e.ScreenSharePresets=ve,e.SignalReconnectError=vs,e.SignalRequestError=gs,e.SimulatedError=class extends Xo{constructor(){super(-1,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Simulated failure"),this.name="simulated"}},e.SubscriptionError=Rn,e.TokenSource=hp,e.TokenSourceConfigurable=Qh,e.TokenSourceFixed=Jh,e.Track=Bs,e.TrackInvalidError=ds,e.TrackPublication=ml,e.TrackType=yn,e.UnexpectedConnectionState=us,e.UnsupportedServer=ls,e.VideoPreset=de,e.VideoPresets=ge,e.VideoPresets43=fe,e.areTokenSourceFetchOptionsEqual=rp,e.asEncryptablePacket=pc,e.attachToElement=qs,e.attributes=Ul,e.audioCodecs=le,e.canFailOverToAnotherRegion=as,e.clientProtocol=2,e.compareVersions=va,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=_s();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,o=i.createMediaStreamSource(new MediaStream([r])),s=i.createAnalyser();s.minDecibels=n.minDecibels,s.maxDecibels=n.maxDecibels,s.fftSize=n.fftSize,s.smoothingTimeConstant=n.smoothingTimeConstant,o.connect(s);const a=new Uint8Array(s.frequencyBinCount);let c=!1;return{calculateVolume:()=>{s.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:s,cleanup:()=>Ao(this,void 0,void 0,(function*(){c||(c=!0,o.disconnect(),s.disconnect(),n.cloneTrack&&r.stop(),yield i.close())}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=uc,e.createKeyMaterialFromString=lc,e.createLocalAudioTrack=bl,e.createLocalScreenTracks=function(e){return Ao(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||ca()||(e.resolution=ve.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new cs("getDisplayMedia not supported");const t=Ms(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new ds("no video track found");const r=new Lu(i[0],void 0,!1);r.source=Bs.Source.ScreenShare;const o=[r];if(n.getAudioTracks().length>0){const e=new ul(n.getAudioTracks()[0],void 0,!1);e.source=Bs.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=yl,e.createLocalVideoTrack=wh,e.decodeTokenPayload=ip,e.deriveKeys=function(e,t){return Ao(this,void 0,void 0,(function*(){const n=hc(e.algorithm.name,t.ratchetSalt),i=yield crypto.subtle.deriveKey(n,e,{name:ic,length:t.keySize},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Vs,e.facingModeFromDeviceLabel=gp,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=ja(e)?e.mediaStreamTrack:e,r=i.getSettings();let o={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;wo.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)){wo.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=gp(i.label);void 0!==e&&(o=e)}return o},e.getBrowser=zo,e.getEmptyAudioStreamTrack=_a,e.getEmptyVideoStreamTrack=function(){return Ca||(Ca=Pa()),Ca.clone()},e.getLogger=Po,e.getVideoCapture=kl,e.importKey=function(e){return Ao(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:ic},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 le.includes(e)},e.isAudioTrack=Ba,e.isBackupCodec=Wp,e.isBackupVideoCodec=pe,e.isBrowserSupported=ta,e.isE2EESupported=ac,e.isInsertableStreamSupported=dc,e.isLocalParticipant=Ga,e.isLocalTrack=ja,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=Ha,e.isSVCCodec=Ys,e.isScriptTransformSupported=cc,e.isSerializer=function(e){return"object"==typeof e&&null!==e&&"symbol"in e&&e.symbol===fp},e.isVideoCodec=Ma,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=qa,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=18,e.ratchet=function(e,t){return Ao(this,void 0,void 0,(function*(){const n=hc(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.releaseEmptyAudioStreamTrack=Oa,e.serializers=kp,e.setLogExtension=function(t,n){(n?[n]:Ro).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,r,o)=>{const s=i(n,r,o),a=e.LogLevel[n],c=a>=r&&a<e.LogLevel.silent;return(e,n)=>{n?s(e,n):s(e),c&&t(a,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){if(t)Co.getLogger(t).setLevel(e);else for(const n of Ro)n.setLevel(e)},e.setVideoCapture=vl,e.supportsAV1=Js,e.supportsAdaptiveStream=function(){return"undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return ea()},e.supportsDynacast=function(){return zs()},e.supportsH265=function(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/h265"===n.mimeType.toLowerCase()){t=!0;break}return t},e.supportsVP9=Qs,e.version=Yo,e.videoCodecs=he,e.writeRbsp=function(e){const t=[];let n=0;for(let o=0;o<e.length;++o){const i=e[o];i<=3&&n>=2&&(t.push(o),n=0),n=0===i?n+1:0}if(0===t.length)return e;const i=new Uint8Array(e.length+t.length);let r=0;for(let o=0;o<t.length;++o)i.set(e.subarray(r,t[o]),r+o),i[t[o]+o]=3,r=t[o];return i.set(e.subarray(r),r+t.length),i}}));
|
|
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)}let n=!0,i=!0;function r(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function o(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable)return void c("Unable to polyfill events");const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.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),r.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 s(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(n=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function a(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(i=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function c(){if("object"==typeof window){if(n)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function d(e,t){i&&console.warn(e+" is deprecated, please use "+t+" instead.")}function l(e){return"[object Object]"===Object.prototype.toString.call(e)}function u(e){return l(e)?Object.keys(e).reduce((function(t,n){const i=l(e[n]),r=i?u(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})}),{}):e}function h(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?h(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{h(e,e.get(t),n)}))})))}function p(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;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&&h(e,n,r)}))})),r}const m=c;function g(e,t){if(t.version>=64)return;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 r=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[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(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 s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){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 s=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&n.length&&t.includes("back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),m("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return m("chrome: "+JSON.stringify(e)),r(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){r(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 r(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 f(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function v(e,t){if(!(t.version>102))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 r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),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 r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else o(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function k(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 r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};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 y(e,t){if(t.version>=67)return;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=>p(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}),o(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>p(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const n=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 n.apply(this,arguments)}}function b(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 r=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]})),r.apply(this,arguments)}}function T(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return b(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 r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.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||{},r.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 r=this._streams[n.id];if(r)r.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 s=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],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.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 S(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 E(e,t){t.version>102||o(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var C=Object.freeze({__proto__:null,fixNegotiationNeeded:E,shimAddTrackRemoveTrack:T,shimAddTrackRemoveTrackWithNative:b,shimGetSendersWithDtmf:k,shimGetUserMedia:g,shimMediaStream:f,shimOnTrack:v,shimPeerConnection:S,shimSenderReceiverGetStats:y});function w(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){d("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 R(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 P(e,t){"object"==typeof e&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!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]})))}function I(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;if(t.version>=151)return;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=Array.prototype.slice.call(arguments),r=e[0],o=e[1],s=e[2];return"closed"===this.signalingState?Promise.resolve(new Map):i.apply(this,[r||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(ke){if("TypeError"!==ke.name)throw ke;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(o,s)}}function _(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 O(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}),o(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function D(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){d("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function M(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function A(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const t=e.length>0;t&&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=n.apply(this,arguments);if(t){const t=i.sender,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 L(e,t){if("object"!=typeof e||!e.RTCRtpSender)return;if(t.version>=110)return;const n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){const e=n.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function N(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}function x(e,t){if("object"!=typeof e||!e.RTCPeerConnection)return;if(t.version>=110)return;const n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>n.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):n.apply(this,arguments)}}var U=Object.freeze({__proto__:null,shimAddTransceiver:A,shimCreateAnswer:x,shimCreateOffer:N,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in 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:L,shimGetStats:I,shimGetUserMedia:w,shimOnTrack:R,shimPeerConnection:P,shimRTCDataChannel:M,shimReceiverGetStats:O,shimRemoveStream:D,shimSenderGetStats:_});function F(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),r=1;r<n;r++)i[r-1]=arguments[r];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 j(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 B(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,n){const i=r.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=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function q(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(V(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function V(e){return e&&void 0!==e.video?Object.assign({},e,{video:u(e.video)}):e}function W(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?(d("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 H(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 K(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 z(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var G=Object.freeze({__proto__:null,shimAudioContext:z,shimCallbacksAPI:B,shimConstraints:V,shimCreateOfferLegacy:K,shimGetUserMedia:q,shimLocalStreamsAPI:F,shimRTCIceServerUrls:W,shimRemoteStreamsAPI:j,shimTrackEventTransceiver:H});function J(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Q,Y={exports:{}};var X=(Q||(Q=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 i=8;i<t.length;i+=2)switch(t[i]){case"raddr":n.relatedAddress=t[i+1];break;case"rport":n.relatedPort=parseInt(t[i+1],10);break;case"tcptype":n.tcpType=t[i+1];break;case"ufrag":n.ufrag=t[i+1],n.usernameFragment=t[i+1];break;default:void 0===n[t[i]]&&(n[t[i]]=t[i+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&&void 0!==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 r=0;r<i.length;r++)n=i[r].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],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.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 o=3;o<i.length;o++){const r=i[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const i=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(i.parameters=o.length?t.parseFmtp(o[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").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 r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.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 r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[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),r&&(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 r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.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 r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[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 r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=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:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},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 r;const o=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+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 t=0;t<i.length;t++)switch(i[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[t].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 t=0;t<n.length;t++)if(n[t].length<2||"="!==n[t].charAt(1))return!1;return!0},e.exports=t}(Y)),Y.exports),Z=J(X),$=t({__proto__:null,default:Z},[X]);function ee(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=Z.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,o(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function te(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||o(e,"icecandidate",(e=>{if(e.candidate){const t=Z.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ne(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>102)return;if("firefox"===t.browser&&t.version>=113)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){"plan-b"===this.getConfiguration().sdpSemantics&&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=Z.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Z.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 r=Z.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let r;r=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:()=>r}),this._sctp=o}return n.apply(this,arguments)}}function ie(e,t){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;if("chrome"===t.browser&&t.version>=149)return;if("firefox"===t.browser&&t.version>60)return;function n(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return n(e,this),e},o(e,"datachannel",(e=>(n(e.channel,e.target),e)))}function re(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 oe(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 se(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 ae(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 ce=Object.freeze({__proto__:null,removeExtmapAllowMixed:oe,shimAddIceCandidateNullOrEmpty:se,shimConnectionState:re,shimMaxMessageSize:ne,shimParameterlessSetLocalDescription:ae,shimRTCIceCandidate:ee,shimRTCIceCandidateRelayProtocol:te,shimSendThrowTypeError:ie});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=c,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 n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e){const t=parseInt(e.version,10);if(t>=90)return{browser:"chrome",version:t}}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(r(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(r(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(r(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=r(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),o={browserDetails:i,commonShim:ce,extractVersion:r,disableLog:s,disableWarnings:a,sdp:$};switch(i.browser){case"chrome":if(!C||!S||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),o;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),o;n("adapter.js shimming chrome."),o.browserShim=C,se(e,i),ae(e),g(e,i),f(e),S(e,i),v(e,i),T(e,i),k(e),y(e,i),E(e,i),ee(e),te(e),re(e),ne(e,i),ie(e,i),oe(e,i);break;case"firefox":if(!U||!P||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),o;n("adapter.js shimming firefox."),o.browserShim=U,se(e,i),ae(e),w(e,i),P(e,i),I(e,i),R(e),D(e),_(e),O(e),M(e),A(e,i),L(e,i),N(e,i),x(e,i),ee(e),re(e),ne(e,i),ie(e,i);break;case"safari":if(!G||!t.shimSafari)return n("Safari shim is not included in this adapter release."),o;n("adapter.js shimming safari."),o.browserShim=G,se(e,i),ae(e),W(e),K(e),B(e),F(e),j(e),H(e),q(e),z(e),ee(e),te(e),ne(e,i),ie(e,i),oe(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});class de{constructor(e,t,n,i,r){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:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const le=["opus","red"],ue=["vp8","h264"],he=["vp8","h264","vp9","av1","h265"];function pe(e){return!!ue.find((t=>t===e))}var me;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,(me=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},me.speech={maxBitrate:24e3},me.music={maxBitrate:48e3},me.musicStereo={maxBitrate:64e3},me.musicHighQuality={maxBitrate:96e3},me.musicHighQualityStereo={maxBitrate:128e3};const ge={h90:new de(160,90,9e4,20),h180:new de(320,180,16e4,20),h216:new de(384,216,18e4,20),h360:new de(640,360,45e4,20),h540:new de(960,540,8e5,25),h720:new de(1280,720,17e5,30),h1080:new de(1920,1080,3e6,30),h1440:new de(2560,1440,5e6,30),h2160:new de(3840,2160,8e6,30)},fe={h120:new de(160,120,7e4,20),h180:new de(240,180,125e3,20),h240:new de(320,240,14e4,20),h360:new de(480,360,33e4,20),h480:new de(640,480,5e5,20),h540:new de(720,540,6e5,25),h720:new de(960,720,13e5,30),h1080:new de(1440,1080,23e5,30),h1440:new de(1920,1440,38e5,30)},ve={h360fps3:new de(640,360,2e5,3,"medium"),h360fps15:new de(640,360,4e5,15,"medium"),h720fps5:new de(1280,720,8e5,5,"medium"),h720fps15:new de(1280,720,15e5,15,"medium"),h720fps30:new de(1280,720,2e6,30,"medium"),h1080fps15:new de(1920,1080,25e5,15,"medium"),h1080fps30:new de(1920,1080,5e6,30,"medium"),original:new de(0,0,7e6,30,"medium")};var ke=Object.defineProperty,ye=(e,t,n)=>((e,t,n)=>t in e?ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class be{constructor(){ye(this,"_locking"),ye(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 Te(e,t){if(!e)throw new Error(t)}function Se(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ee(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Ce(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const we=Symbol("@bufbuild/protobuf/enum-type");function Re(e){const t=e[we];return Te(t,"missing enum type on enum object"),t}function Pe(e,t,n,i){e[we]=Ie(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function Ie(e,t,n){const i=Object.create(null),r=Object.create(null),o=[];for(const s of t){const e=Oe(s);o.push(e),i[s.name]=e,r[s.no]=e}return{typeName:e,values:o,findName:e=>i[e],findNumber:e=>r[e]}}function _e(e,t,n){const i={};for(const r of t){const e=Oe(r);i[e.localName]=e.no,i[e.no]=e.localName}return Pe(i,e,t),i}function Oe(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class De{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,r=i.makeReadOptions(t);return i.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(ke){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(ke instanceof Error?ke.message:String(ke)))}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 Me(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,!(128&n))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Ae(e,t,n){for(let o=0;o<28;o+=7){const i=e>>>o,r=!(i>>>7==0&&0==t),s=255&(r?128|i:i);if(n.push(s),!r)return}const i=e>>>28&15|(7&t)<<4,r=!!(t>>3);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),o=255&(r?128|i:i);if(n.push(o),!r)return}n.push(t>>>31&1)}}const Le=4294967296;function Ne(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function o(t,o){const s=Number(e.slice(t,o));r*=n,i=i*n+s,i>=Le&&(r+=i/Le|0,i%=Le)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?Fe(i,r):Ue(i,r)}function xe(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(Le*t+e);const i=16777215&(e>>>24|t<<8),r=t>>16&65535;let o=(16777215&e)+6777216*i+6710656*r,s=i+8147497*r,a=2*r;const c=1e7;return o>=c&&(s+=Math.floor(o/c),o%=c),s>=c&&(a+=Math.floor(s/c),s%=c),a.toString()+je(s)+je(o)}function Ue(e,t){return{lo:0|e,hi:0|t}}function Fe(e,t){return t=~t,e?e=1+~e:t+=1,Ue(e,t)}const je=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Be(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 qe(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let n=5;128&e&&n<10;n++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Ve=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"),r=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>r||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=>Te(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>Te(/^[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),Ne(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),Ne(e)),dec:(e,t)=>function(e,t){let n=Ue(e,t);const i=2147483648&n.hi;i&&(n=Fe(n.lo,n.hi));const r=xe(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>xe(e,t)}}();var We,He,Ke;function ze(e,t,n){if(t===n)return!0;if(e==We.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 We.UINT64:case We.FIXED64:case We.INT64:case We.SFIXED64:case We.SINT64:return t==n}return!1}function Ge(e,t){switch(e){case We.BOOL:return!1;case We.UINT64:case We.FIXED64:case We.INT64:case We.SFIXED64:case We.SINT64:return 0==t?Ve.zero:"0";case We.DOUBLE:case We.FLOAT:return 0;case We.BYTES:return new Uint8Array(0);case We.STRING:return"";default:return 0}}function Je(e,t){switch(e){case We.BOOL:return!1===t;case We.STRING:return""===t;case We.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function Qe(e,t){this.v=e,this.k=t}function Ye(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Xe(e){if(Array.isArray(e))return e}function Ze(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}function $e(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function et(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function tt(e,t){return Xe(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||it(e,t)||$e()}function nt(e){return Xe(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||it(e)||$e()}function it(e,t){if(e){if("string"==typeof e)return Ye(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ye(e,t):void 0}}function rt(e){var t,n;function i(t,n){try{var o=e[t](n),s=o.value,a=s instanceof Qe;Promise.resolve(a?s.v:s).then((function(n){if(a){var c="return"===t&&s.k?t:"next";if(!s.k||n.done)return i(c,n);n=e[c](n).value}r(!!o.done,n)}),(function(e){i("throw",e)}))}catch(e){r(2,e)}}function r(e,r){2===e?t.reject(r):t.resolve({value:r,done:e}),(t=t.next)?i(t.key,t.arg):n=null}this._invoke=function(e,r){return new Promise((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};n?n=n.next=a:(t=n=a,i(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}!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"}(We||(We={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(He||(He={})),rt.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},rt.prototype.next=function(e){return this._invoke("next",e)},rt.prototype.throw=function(e){return this._invoke("throw",e)},rt.prototype.return=function(e){return this._invoke("return",e)},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"}(Ke||(Ke={}));class ot{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],n),n+=this.chunks[i].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(Ee(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Se(e),Be(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){Ce(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){Ee(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Se(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Se(e),Be(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=Ve.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=Ve.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=Ve.enc(e);return Ae(t.lo,t.hi,this.buf),this}sint64(e){let t=Ve.enc(e),n=t.hi>>31;return Ae(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Ve.uEnc(e);return Ae(t.lo,t.hi,this.buf),this}}class st{constructor(e,t){this.varint64=Me,this.uint32=qe,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 Ke.Varint:for(;128&this.buf[this.pos++];);break;case Ke.Bit64:this.pos+=4;case Ke.Bit32:this.pos+=4;break;case Ke.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Ke.StartGroup:for(;;){const e=tt(this.tag(),2),n=e[0],i=e[1];if(i===Ke.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(i,n)}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 Ve.dec(...this.varint64())}uint64(){return Ve.uDec(...this.varint64())}sint64(){let e=tt(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,Ve.dec(t,n)}bool(){let e=tt(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Ve.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ve.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 at(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 Ge(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 ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),dt=[];for(let Kp=0;Kp<ct.length;Kp++)dt[ct[Kp].charCodeAt(0)]=Kp;dt["-".charCodeAt(0)]=ct.indexOf("+"),dt["_".charCodeAt(0)]=ct.indexOf("/");const lt={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),r=0,o=0,s=0;for(let a=0;a<e.length;a++){if(n=dt[e.charCodeAt(a)],void 0===n)switch(e[a]){case"=":o=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(o){case 0:s=n,o=1;break;case 1:i[r++]=s<<2|(48&n)>>4,s=n,o=2;break;case 2:i[r++]=(15&s)<<4|(60&n)>>2,s=n,o=3;break;case 3:i[r++]=(3&s)<<6|n,o=0}}if(1==o)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let o=0;o<e.length;o++)switch(t=e[o],i){case 0:n+=ct[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=ct[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=ct[r|t>>6],n+=ct[63&t],i=0}return i&&(n+=ct[r],n+="=",1==i&&(n+="=")),n}};function ut(e,t,n){mt(t,e);const i=t.runtime.bin.makeReadOptions(n),r=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=tt(at(t),2),s=o[0],a=o[1];for(const c of r)t.runtime.bin.readField(s,i.readerFactory(c.data),t.field,c.wireType,i);return a()}function ht(e,t,n,i){mt(t,e);const r=t.runtime.bin.makeReadOptions(i),o=t.runtime.bin.makeWriteOptions(i);if(pt(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 s=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,s,o);const c=r.readerFactory(s.finish());for(;c.pos<c.len;){const t=tt(c.tag(),2),n=t[0],i=t[1],r=c.skip(i,n);e.getType().runtime.bin.onUnknownField(e,n,i,r)}}function pt(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 mt(e,t){Te(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function gt(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:!Je(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ft(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?Ge(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function vt(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(De.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 kt(e,t){return vt(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}We.DOUBLE,We.FLOAT,We.INT64,We.UINT64,We.INT32,We.UINT32,We.BOOL,We.STRING,We.BYTES;const yt={ignoreUnknownFields:!1},bt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Tt(e){return e?Object.assign(Object.assign({},yt),e):yt}function St(e){return e?Object.assign(Object.assign({},bt),e):bt}const Et=Symbol(),Ct=Symbol();function wt(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 Rt(e,t,n,i,r){let o=n.localName;if(n.repeated){if(Te("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t)));const s=e[o];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e)));switch(n.kind){case"message":s.push(n.T.fromJson(e,i));break;case"enum":const t=_t(n.T,e,i.ignoreUnknownFields,!0);t!==Ct&&s.push(t);break;case"scalar":try{s.push(It(n.T,e,n.L,!0))}catch(ke){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(e));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.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(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t)));const a=e[o];for(const e of Object.entries(t)){var s=tt(e,2);const o=s[0],c=s[1];if(null===c)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=Pt(n.K,o)}catch(ke){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.message)),new Error(i)}switch(n.V.kind){case"message":a[d]=n.V.T.fromJson(c,i);break;case"enum":const e=_t(n.V.T,c,i.ignoreUnknownFields,!0);e!==Ct&&(a[d]=e);break;case"scalar":try{a[d]=It(n.V.T,c,He.BIGINT,!0)}catch(ke){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:o},o="value"),n.kind){case"message":const s=n.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let a=e[o];vt(a)?a.fromJson(t,i):(e[o]=a=s.fromJson(t,i),s.fieldWrapper&&!n.oneof&&(e[o]=s.fieldWrapper.unwrapField(a)));break;case"enum":const c=_t(n.T,t,i.ignoreUnknownFields,!1);switch(c){case Et:ft(n,e);break;case Ct:break;default:e[o]=c}break;case"scalar":try{const i=It(n.T,t,n.L,!1);if(i===Et)ft(n,e);else e[o]=i}catch(ke){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(wt(t));throw ke instanceof Error&&ke.message.length>0&&(i+=": ".concat(ke.message)),new Error(i)}}}function Pt(e,t){if(e===We.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return It(e,t,He.BIGINT,!0).toString()}function It(e,t,n,i){if(null===t)return i?Ge(e,n):Et;switch(e){case We.DOUBLE:case We.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==We.FLOAT&&Ce(i),i;case We.INT32:case We.FIXED32:case We.SFIXED32:case We.SINT32:case We.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==We.UINT32||e==We.FIXED32?Ee(r):Se(r),r;case We.INT64:case We.SFIXED64:case We.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=Ve.parse(t);return n?o.toString():o;case We.FIXED64:case We.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=Ve.uParse(t);return n?s.toString():s;case We.BOOL:if("boolean"!=typeof t)break;return t;case We.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(ke){throw new Error("invalid UTF8")}return t;case We.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return lt.dec(t)}throw new Error}function _t(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:Et;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 Ct}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(wt(t)))}function Ot(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Dt(e,t,n){if("map"==e.kind){Te("object"==typeof t&&null!=t);const s={},a=Object.entries(t);switch(e.V.kind){case"scalar":for(const n of a){var i=tt(n,2);const t=i[0],r=i[1];s[t.toString()]=At(e.V.T,r)}break;case"message":for(const e of a){var r=tt(e,2);const t=r[0],i=r[1];s[t.toString()]=i.toJson(n)}break;case"enum":const t=e.V.T;for(const e of a){var o=tt(e,2);const i=o[0],r=o[1];s[i.toString()]=Mt(t,r,n.enumAsInteger)}}return n.emitDefaultValues||a.length>0?s:void 0}if(e.repeated){Te(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(At(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(Mt(e.T,t[r],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 At(e.T,t);case"enum":return Mt(e.T,t,n.enumAsInteger);case"message":return kt(e.T,t).toJson(n)}}function Mt(e,t,n){var i;if(Te("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function At(e,t){switch(e){case We.INT32:case We.SFIXED32:case We.SINT32:case We.FIXED32:case We.UINT32:return Te("number"==typeof t),t;case We.FLOAT:case We.DOUBLE:return Te("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case We.STRING:return Te("string"==typeof t),t;case We.BOOL:return Te("boolean"==typeof t),t;case We.UINT64:case We.FIXED64:case We.INT64:case We.SFIXED64:case We.SINT64:return Te("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case We.BYTES:return Te(t instanceof Uint8Array),lt.enc(t)}}const Lt=Symbol("@bufbuild/protobuf/unknown-fields"),Nt={readUnknownFields:!0,readerFactory:e=>new st(e)},xt={writeUnknownFields:!0,writerFactory:()=>new ot};function Ut(e){return e?Object.assign(Object.assign({},Nt),e):Nt}function Ft(e){return e?Object.assign(Object.assign({},xt),e):xt}function jt(e,t,n,i,r){let o=n.repeated,s=n.localName;switch(n.oneof&&((e=e[n.oneof.localName]).case!=s&&delete e.value,e.case=s,s="value"),n.kind){case"scalar":case"enum":const a="enum"==n.kind?We.INT32:n.T;let c=Vt;if("scalar"==n.kind&&n.L>0&&(c=qt),o){let n=e[s];if(i==Ke.LengthDelimited&&a!=We.STRING&&a!=We.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,a))}else n.push(c(t,a))}else e[s]=c(t,a);break;case"message":const d=n.T;o?e[s].push(Bt(t,new d,r,n)):vt(e[s])?Bt(t,e[s],r,n):(e[s]=Bt(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[s]=d.fieldWrapper.unwrapField(e[s])));break;case"map":let l=function(e,t,n){const i=t.uint32(),r=t.pos+i;let o,s;for(;t.pos<r;){switch(tt(t.tag(),1)[0]){case 1:o=Vt(t,e.K);break;case 2:switch(e.V.kind){case"scalar":s=Vt(t,e.V.T);break;case"enum":s=t.int32();break;case"message":s=Bt(t,new e.V.T,n,void 0)}}}void 0===o&&(o=Ge(e.K,He.BIGINT));"string"!=typeof o&&"number"!=typeof o&&(o=o.toString());if(void 0===s)switch(e.V.kind){case"scalar":s=Ge(e.V.T,He.BIGINT);break;case"enum":s=e.V.T.values[0].no;break;case"message":s=new e.V.T}return[o,s]}(n,t,r),u=tt(l,2),h=u[0],p=u[1];e[s][h]=p}}function Bt(e,t,n,i){const r=t.getType().runtime.bin,o=null==i?void 0:i.delimited;return r.readMessage(t,e,o?i.no:e.uint32(),n,o),t}function qt(e,t){const n=Vt(e,t);return"bigint"==typeof n?n.toString():n}function Vt(e,t){switch(t){case We.STRING:return e.string();case We.BOOL:return e.bool();case We.DOUBLE:return e.double();case We.FLOAT:return e.float();case We.INT32:return e.int32();case We.INT64:return e.int64();case We.UINT64:return e.uint64();case We.FIXED64:return e.fixed64();case We.BYTES:return e.bytes();case We.FIXED32:return e.fixed32();case We.SFIXED32:return e.sfixed32();case We.SFIXED64:return e.sfixed64();case We.SINT64:return e.sint64();case We.UINT32:return e.uint32();case We.SINT32:return e.sint32()}}function Wt(e,t,n,i){Te(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?We.INT32:e.T;if(r)if(Te(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,Ke.LengthDelimited).fork();let r=tt(Gt(t),2)[1];for(let o=0;o<i.length;o++)e[r](i[o]);e.join()}(n,s,e.no,t);else for(const i of t)zt(n,s,e.no,i);else zt(n,s,e.no,t);break;case"message":if(r){Te(Array.isArray(t));for(const r of t)Kt(n,i,e,r)}else Kt(n,i,e,t);break;case"map":Te("object"==typeof t&&null!=t);for(const r of Object.entries(t)){var o=tt(r,2);Ht(n,i,e,o[0],o[1])}}}function Ht(e,t,n,i,r){e.tag(n.no,Ke.LengthDelimited),e.fork();let o=i;switch(n.K){case We.INT32:case We.FIXED32:case We.UINT32:case We.SFIXED32:case We.SINT32:o=Number.parseInt(i);break;case We.BOOL:Te("true"==i||"false"==i),o="true"==i}switch(zt(e,n.K,1,o),n.V.kind){case"scalar":zt(e,n.V.T,2,r);break;case"enum":zt(e,We.INT32,2,r);break;case"message":Te(void 0!==r),e.tag(2,Ke.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Kt(e,t,n,i){const r=kt(n.T,i);n.delimited?e.tag(n.no,Ke.StartGroup).raw(r.toBinary(t)).tag(n.no,Ke.EndGroup):e.tag(n.no,Ke.LengthDelimited).bytes(r.toBinary(t))}function zt(e,t,n,i){Te(void 0!==i);let r=tt(Gt(t),2),o=r[0],s=r[1];e.tag(n,o)[s](i)}function Gt(e){let t=Ke.Varint;switch(e){case We.BYTES:case We.STRING:t=Ke.LengthDelimited;break;case We.DOUBLE:case We.FIXED64:case We.SFIXED64:t=Ke.Bit64;break;case We.FIXED32:case We.SFIXED32:case We.FLOAT:t=Ke.Bit32}return[t,We[e].toLowerCase()]}function Jt(e){if(void 0===e)return e;if(vt(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Qt(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Yt{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 Xt(e,t){const n=$t(e);return t?n:on(rn(n))}const Zt=$t;function $t(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}const en=new Set(["constructor","toString","toJSON","valueOf"]),tn=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),nn=e=>"".concat(e,"$"),rn=e=>tn.has(e)?nn(e):e,on=e=>en.has(e)?nn(e):e;class sn{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=Xt(e,!1)}addField(e){Te(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 an=(cn=e=>new Yt(e,(e=>function(e){var t,n,i,r,o,s;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Xt(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Zt(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(i=d.L)&&void 0!==i?i:He.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(o=d.req)&&void 0!==o&&o,e.opt=null!==(s=d.opt)&&void 0!==s&&s,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=We.BYTES&&d.T!=We.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new sn(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),dn=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]=Ge(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:Tt,makeWriteOptions:St,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(wt(t)));i=null!=i?i:new e;const r=new Map,o=n.typeRegistry;for(const a of Object.entries(t)){var s=tt(a,2);const t=s[0],c=s[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=r.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));r.set(d.oneof,t)}Rt(i,c,d,n,e)}else{let r=!1;if((null==o?void 0:o.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const s=o.findExtension(t.substring(1,t.length-1));if(s&&s.extendee.typeName==e.typeName){r=!0;const e=tt(at(s),2),t=e[0],o=e[1];Rt(t,c,s.field,n,s),ht(i,s,o(),n)}}if(!r&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!gt(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Ot(r))continue}const n=Dt(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const s=o.findExtensionFor(n.typeName,r.no);if(s&&pt(e,s)){const n=ut(e,s,t),r=Dt(s.field,n,t);void 0!==r&&(i[s.field.jsonName]=r)}}}catch(ke){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=ke instanceof Error?ke.message:String(ke);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>It(e,t,null!=n?n:He.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||Je(e,t)?At(e,t):void 0},debug:wt},bin:{makeReadOptions:Ut,makeWriteOptions:Ft,listUnknownFields(e){var t;return null!==(t=e[Lt])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Lt]},writeUnknownFields(e,t){const n=e[Lt];if(n)for(const i of n)t.tag(i.no,i.wireType).raw(i.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[Lt])||(r[Lt]=[]),r[Lt].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const o=e.getType(),s=r?t.len:t.pos+n;let a,c;for(;t.pos<s;){var d=tt(t.tag(),2);if(a=d[0],c=d[1],!0===r&&c==Ke.EndGroup)break;const n=o.fields.find(a);if(n)jt(e,t,n,c,i);else{const n=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,n)}}if(r&&(c!=Ke.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:jt,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(gt(r,e))Wt(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,n);else if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){void 0!==t&&Wt(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:Pe,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const r of n.fields.byMember()){const n=r.localName,o=t,s=e;if(null!=s[n])switch(r.kind){case"oneof":const e=s[n].case;if(void 0===e)continue;const t=r.findField(e);let a=s[n].value;t&&"message"==t.kind&&!vt(a,t.T)?a=new t.T(a):t&&"scalar"===t.kind&&t.T===We.BYTES&&(a=Qt(a)),o[n]={case:e,value:a};break;case"scalar":case"enum":let c=s[n];r.T===We.BYTES&&(c=r.repeated?c.map(Qt):Qt(c)),o[n]=c;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===We.BYTES)for(const t of Object.entries(s[n])){var i=tt(t,2);const e=i[0],r=i[1];o[n][e]=Qt(r)}else Object.assign(o[n],s[n]);break;case"message":const e=r.V.T;for(const t of Object.keys(s[n])){let i=s[n][t];e.fieldWrapper||(i=new e(i)),o[n][t]=i}}break;case"message":const d=r.T;if(r.repeated)o[n]=s[n].map((e=>vt(e,d)?e:new d(e)));else{const e=s[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?o[n]=Qt(e):o[n]=e:o[n]=vt(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],r=n[e.localName];if(e.repeated){if(i.length!==r.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,r[n])));case"scalar":return i.every(((t,n)=>ze(e.T,t,r[n])));case"enum":return i.every(((e,t)=>ze(We.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=i,n=r;return e.T.fieldWrapper&&(void 0===t||vt(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||vt(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return ze(We.INT32,i,r);case"scalar":return ze(e.T,i,r);case"oneof":if(i.case!==r.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,r.value);case"enum":return ze(We.INT32,i.value,r.value);case"scalar":return ze(o.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const s=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return s.every((e=>t.equals(i[e],r[e])));case"enum":return s.every((e=>ze(We.INT32,i[e],r[e])));case"scalar":const n=e.V.T;return s.every((e=>ze(n,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const o of t.fields.byMember()){const t=e[o.localName];let n;if(o.repeated)n=t.map(Jt);else if("map"==o.kind){n=i[o.localName];for(const e of Object.entries(t)){var r=tt(e,2);const t=r[0],i=r[1];n[t]=Jt(i)}}else n="oneof"==o.kind?o.findField(t.case)?{case:t.case,value:Jt(t.value)}:{case:void 0}:Jt(t);i[o.localName]=n}for(const o of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,o.no,o.wireType,o.data);return n}}),{newFieldList:cn,initFields:dn}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const o=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),s={[o]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[o];return Object.setPrototypeOf(s.prototype,new De),Object.assign(s,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new s).fromBinary(e,t),fromJson:(e,t)=>(new s).fromJson(e,t),fromJsonString:(e,t)=>(new s).fromJsonString(e,t),equals:(t,n)=>e.util.equals(s,t,n)}),s}(this,e,t,n)},makeEnum:_e,makeEnumType:Ie,getEnumType:Re,makeExtension(e,t,n){return function(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),r=e.util.newFieldList([n]).list()[0]}return r},runtime:e}}(this,e,t,n)}});var cn,dn;class ln extends De{constructor(e){super(),this.seconds=Ve.zero,this.nanos=0,an.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(an.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=Ve.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 ln.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ln({seconds:Ve.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new ln).fromBinary(e,t)}static fromJson(e,t){return(new ln).fromJson(e,t)}static fromJsonString(e,t){return(new ln).fromJsonString(e,t)}static equals(e,t){return an.util.equals(ln,e,t)}}ln.runtime=an,ln.typeName="google.protobuf.Timestamp",ln.fields=an.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const un=an.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ln},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:hn,repeated:!0},{no:5,name:"events",kind:"message",T:mn,repeated:!0}])),hn=an.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:pn,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),pn=an.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ln},{no:3,name:"value",kind:"scalar",T:2}])),mn=an.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:ln},{no:7,name:"normalized_end_timestamp",kind:"message",T:ln,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),gn=an.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),fn=an.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"}]),vn=an.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),kn=an.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),yn=an.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),bn=an.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Tn=an.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Sn=an.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),En=an.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Cn=an.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"},{no:16,name:"AGENT_ERROR"}]),wn=an.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"}]),Rn=an.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Pn=an.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"}]),In=an.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),_n=an.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:On,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:bi}])),On=an.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),Dn=an.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:an.getEnumType(bn),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8},{no:13,name:"can_manage_agent_session",kind:"scalar",T:8}])),Mn=an.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:an.getEnumType(An)},{no:4,name:"tracks",kind:"message",T:Fn,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:Dn},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:an.getEnumType(Ln)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:an.getEnumType(Cn)},{no:18,name:"kind_details",kind:"enum",T:an.getEnumType(Nn),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:jn,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:an.getEnumType(fi),repeated:!0}])),An=an.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ln=an.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),Nn=an.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),xn=an.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Un=an.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Jn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:an.getEnumType(Qn)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),Fn=an.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:an.getEnumType(yn)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:an.getEnumType(bn)},{no:10,name:"layers",kind:"message",T:Jn,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Un,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:an.getEnumType(xn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:bi},{no:19,name:"audio_features",kind:"enum",T:an.getEnumType(Pn),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:an.getEnumType(kn)},{no:21,name:"packet_trailer_features",kind:"enum",T:an.getEnumType(In),repeated:!0}])),jn=an.makeMessageType("livekit.DataTrackInfo",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:an.getEnumType(xn)},{no:5,name:"frame_encoding",kind:"message",T:Bn,opt:!0},{no:6,name:"schema",kind:"message",T:Hn,opt:!0}])),Bn=an.makeMessageType("livekit.DataTrackFrameEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:an.getEnumType(qn),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),qn=an.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),Vn=an.makeMessageType("livekit.DataTrackSchemaEncoding",(()=>[{no:1,name:"well_known",kind:"enum",T:an.getEnumType(Wn),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}])),Wn=an.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),Hn=an.makeMessageType("livekit.DataTrackSchemaId",(()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:Vn}])),Kn=an.makeMessageType("livekit.DataTrackSubscriptionOptions",(()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}])),zn=an.makeMessageType("livekit.DataBlobKey",(()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:Hn,oneof:"key"}])),Gn=an.makeMessageType("livekit.DataBlob",(()=>[{no:1,name:"key",kind:"message",T:zn},{no:2,name:"contents",kind:"scalar",T:12}])),Jn=an.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:an.getEnumType(Tn)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}])),Qn=an.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"}]),Yn=an.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:an.getEnumType(Xn)},{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:ni,oneof:"value"},{no:3,name:"speaker",kind:"message",T:ei,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ii,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ri,oneof:"value"},{no:8,name:"metrics",kind:"message",T:un,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:si,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:ai,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:ci,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:di,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:wi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Ri,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Pi,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Zn,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),Xn=an.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Zn=an.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:an.getEnumType(xn)},{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}])),$n=an.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:ni,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:si,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:ai,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:ci,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:di,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:wi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Ri,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Pi,oneof:"value"}])),ei=an.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:ti,repeated:!0}])),ti=an.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}])),ni=an.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}])),ii=an.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),ri=an.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:oi,repeated:!0}])),oi=an.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),si=an.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}])),ai=an.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13},{no:6,name:"compressed_payload",kind:"scalar",T:12}])),ci=an.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),di=an.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:li,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}])),li=an.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}])),ui=an.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),hi=an.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:an.getEnumType(pi)},{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}])),pi=an.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),mi=an.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:an.getEnumType(gi)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9},{no:12,name:"client_protocol",kind:"scalar",T:5},{no:13,name:"capabilities",kind:"enum",T:an.getEnumType(fi),repeated:!0}])),gi=an.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"},{no:15,name:"DOTNET"}]),fi=an.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),vi=an.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:ki},{no:2,name:"screen",kind:"message",T:ki},{no:3,name:"resume_connection",kind:"enum",T:an.getEnumType(En)},{no:4,name:"disabled_codecs",kind:"message",T:yi},{no:5,name:"force_relay",kind:"enum",T:an.getEnumType(En)}])),ki=an.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:an.getEnumType(En)}])),yi=an.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:On,repeated:!0},{no:2,name:"publish",kind:"message",T:On,repeated:!0}])),bi=an.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),Ti=an.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Si=an.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Ei=an.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:an.getEnumType(Ti)},{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"}),Ci=an.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),wi=an.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:an.getEnumType(xn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ei,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ci,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:an.getEnumType(Si)}]),{localName:"DataStream_Header"}),Ri=an.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"}),Pi=an.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"}),Ii=an.makeMessageType("livekit.FilterParams",(()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}])),_i=an.makeMessageType("livekit.WebhookConfig",(()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:Ii}])),Oi=an.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Di=an.makeEnum("livekit.JobRestartPolicy",[{no:0,name:"JRP_ON_FAILURE"},{no:1,name:"JRP_NEVER"}]),Mi=an.makeMessageType("livekit.RoomAgentDispatch",(()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9},{no:3,name:"restart_policy",kind:"enum",T:an.getEnumType(Di)},{no:4,name:"deployment",kind:"scalar",T:9},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Ai=an.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"},{no:8,name:"PASSTHROUGH"}]),Li=an.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),Ni=an.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"},{no:3,name:"WEBSOCKET"}]),xi=an.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),Ui=an.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),Fi=an.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),ji=an.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),Bi=an.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:an.getEnumType(gn)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:an.getEnumType(fn)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5}])),qi=an.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:an.getEnumType(Ni)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),Vi=an.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:an.getEnumType(xi)},{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:an.getEnumType(Ui)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Hi,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:7,name:"azure",kind:"message",T:zi,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),Wi=an.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:an.getEnumType(Fi)},{no:6,name:"image_codec",kind:"enum",T:an.getEnumType(vn)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Hi,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:10,name:"azure",kind:"message",T:zi,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),Hi=an.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:Ji}])),Ki=an.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:Ji}])),zi=an.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}])),Gi=an.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}])),Ji=an.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}])),Qi=an.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:an.getEnumType(Ai),oneof:"options"},{no:2,name:"advanced",kind:"message",T:Bi,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Zi,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Vi,repeated:!0}])),Yi=an.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:Hi,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:4,name:"azure",kind:"message",T:zi,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),Xi=an.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:an.getEnumType(ji)},{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:Zi,oneof:"output"},{no:7,name:"stream",kind:"message",T:qi,oneof:"output"},{no:10,name:"segments",kind:"message",T:Vi,oneof:"output"},{no:8,name:"preset",kind:"enum",T:an.getEnumType(Ai),oneof:"options"},{no:9,name:"advanced",kind:"message",T:Bi,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Zi,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:qi,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Vi,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:Wi,repeated:!0},{no:16,name:"webhooks",kind:"message",T:_i,repeated:!0}])),Zi=an.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:an.getEnumType(Li)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Hi,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Ki,oneof:"output"},{no:5,name:"azure",kind:"message",T:zi,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:Gi,oneof:"output"}])),$i=an.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:Xi},{no:3,name:"participant",kind:"message",T:Qi},{no:2,name:"tracks",kind:"message",T:Yi}])),er=an.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:$i},{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:Mi,repeated:!0},{no:12,name:"tags",kind:"map",K:9,V:{kind:"scalar",T:9}}])),tr=an.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),nr=an.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ir=an.makeEnum("livekit.NegotiatedDataChannelID",[{no:0,name:"NDCI_INVALID"},{no:100,name:"NDCI_RELIABLE"},{no:101,name:"NDCI_LOSSY"},{no:102,name:"NDCI_DATA_TRACK"}]),rr=an.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),or=an.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:Tr,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tr,oneof:"message"},{no:3,name:"trickle",kind:"message",T:gr,oneof:"message"},{no:4,name:"add_track",kind:"message",T:cr,oneof:"message"},{no:5,name:"mute",kind:"message",T:fr,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Er,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Or,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ar,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Nr,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Qr,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Zr,oneof:"message"},{no:13,name:"simulate",kind:"message",T:to,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:xr,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:no,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Dr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Mr,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:dr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:ur,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Cr,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:Rr,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:Ir,oneof:"message"}])),sr=an.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:vr,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tr,oneof:"message"},{no:3,name:"offer",kind:"message",T:Tr,oneof:"message"},{no:4,name:"trickle",kind:"message",T:gr,oneof:"message"},{no:5,name:"update",kind:"message",T:Sr,oneof:"message"},{no:6,name:"track_published",kind:"message",T:yr,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ar,oneof:"message"},{no:9,name:"mute",kind:"message",T:fr,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Fr,oneof:"message"},{no:11,name:"room_update",kind:"message",T:jr,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:qr,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Wr,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:zr,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Yr,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:br,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:kr,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:io,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:so,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ao,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:lo,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Xr,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:go,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Gr,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:lr,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:hr,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:pr,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:Pr,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:_r,oneof:"message"}])),ar=an.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:Jn,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:an.getEnumType(Qn)}])),cr=an.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:an.getEnumType(yn)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:an.getEnumType(bn)},{no:9,name:"layers",kind:"message",T:Jn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ar,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:an.getEnumType(xn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:an.getEnumType(kn)},{no:17,name:"audio_features",kind:"enum",T:an.getEnumType(Pn),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:an.getEnumType(In),repeated:!0}])),dr=an.makeMessageType("livekit.PublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:an.getEnumType(xn)},{no:4,name:"frame_encoding",kind:"message",T:Bn,opt:!0},{no:5,name:"schema",kind:"message",T:Hn,opt:!0}])),lr=an.makeMessageType("livekit.PublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:jn}])),ur=an.makeMessageType("livekit.UnpublishDataTrackRequest",(()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}])),hr=an.makeMessageType("livekit.UnpublishDataTrackResponse",(()=>[{no:1,name:"info",kind:"message",T:jn}])),pr=an.makeMessageType("livekit.DataTrackSubscriberHandles",(()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:mr}}])),mr=an.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",(()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}]),{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),gr=an.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:an.getEnumType(tr)},{no:3,name:"final",kind:"scalar",T:8}])),fr=an.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),vr=an.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:_n},{no:2,name:"participant",kind:"message",T:Mn},{no:3,name:"other_participants",kind:"message",T:Mn,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ur,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:vi},{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:hi},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:On,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),kr=an.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Ur,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:vi},{no:3,name:"server_info",kind:"message",T:hi},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),yr=an.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Fn}])),br=an.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Tr=an.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Sr=an.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:Mn,repeated:!0}])),Er=an.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:ui,repeated:!0}])),Cr=an.makeMessageType("livekit.UpdateDataSubscription",(()=>[{no:1,name:"updates",kind:"message",T:wr,repeated:!0}])),wr=an.makeMessageType("livekit.UpdateDataSubscription.Update",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Kn}]),{localName:"UpdateDataSubscription_Update"}),Rr=an.makeMessageType("livekit.StoreDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Gn}])),Pr=an.makeMessageType("livekit.StoreDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:zn}])),Ir=an.makeMessageType("livekit.GetDataBlobRequest",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:zn}])),_r=an.makeMessageType("livekit.GetDataBlobResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Gn}])),Or=an.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:an.getEnumType(Tn)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}])),Dr=an.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:an.getEnumType(Pn),repeated:!0}])),Mr=an.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}])),Ar=an.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:an.getEnumType(Cn)},{no:3,name:"action",kind:"enum",T:an.getEnumType(Lr)},{no:4,name:"regions",kind:"message",T:ro}])),Lr=an.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Nr=an.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Jn,repeated:!0}])),xr=an.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}])),Ur=an.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}])),Fr=an.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:ti,repeated:!0}])),jr=an.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:_n}])),Br=an.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:an.getEnumType(Sn)},{no:3,name:"score",kind:"scalar",T:2}])),qr=an.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Br,repeated:!0}])),Vr=an.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:an.getEnumType(nr)}])),Wr=an.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Vr,repeated:!0}])),Hr=an.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:an.getEnumType(Tn)},{no:2,name:"enabled",kind:"scalar",T:8}])),Kr=an.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Hr,repeated:!0}])),zr=an.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Hr,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Kr,repeated:!0}])),Gr=an.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Oi,repeated:!0}])),Jr=an.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}])),Qr=an.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Jr,repeated:!0}])),Yr=an.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}])),Xr=an.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:_n},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Mn},{no:4,name:"other_participants",kind:"message",T:Mn,repeated:!0}])),Zr=an.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:Tr},{no:2,name:"subscription",kind:"message",T:Er},{no:3,name:"publish_tracks",kind:"message",T:yr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:eo,repeated:!0},{no:5,name:"offer",kind:"message",T:Tr},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:$r,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:lr,repeated:!0},{no:9,name:"data_subscription",kind:"message",T:Cr}])),$r=an.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),eo=an.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:an.getEnumType(tr)}])),to=an.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:an.getEnumType(rr),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"}])),no=an.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),io=an.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),ro=an.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:oo,repeated:!0}])),oo=an.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}])),so=an.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:an.getEnumType(Rn)}])),ao=an.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:an.getEnumType(co)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:gr,oneof:"request"},{no:5,name:"add_track",kind:"message",T:cr,oneof:"request"},{no:6,name:"mute",kind:"message",T:fr,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:xr,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Dr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Mr,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:dr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:ur,oneof:"request"}])),co=an.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),lo=an.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),uo=an.makeMessageType("livekit.ConnectionSettings",(()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}])),ho=an.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:mi},{no:2,name:"connection_settings",kind:"message",T:uo},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:cr,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Tr},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:an.getEnumType(wn)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Zr}])),po=an.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:an.getEnumType(mo)},{no:2,name:"join_request",kind:"scalar",T:12}])),mo=an.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),go=an.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),fo=an.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:er,opt:!0}])),vo=an.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));var ko,yo={exports:{}},bo=yo.exports;var To,So,Eo=(ko||(ko=1,function(e){var t,n;t=bo,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"],r={},o=null;function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(ke){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(),r=0;r<i.length;r++){var o=i[r];this[o]=r<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,r,o){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?a:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var s,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(o){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.length+1))[1])}catch(o){}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:s},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(r){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(r){}}}(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&&(s=m(o.getLevel())),c.call(u),o===u)for(var e in r)r[e].rebuild()},s=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=r[e];return t||(t=r[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 r},o.default=o,o},e.exports?e.exports=n():t.log=n()}(yo)),yo.exports),Co=J(Eo);e.LogLevel=void 0,(To=e.LogLevel||(e.LogLevel={}))[To.trace=0]="trace",To[To.debug=1]="debug",To[To.info=2]="info",To[To.warn=3]="warn",To[To.error=4]="error",To[To.silent=5]="silent",e.LoggerNames=void 0,(So=e.LoggerNames||(e.LoggerNames={})).Default="livekit",So.Room="livekit-room",So.TokenSource="livekit-token-source",So.Participant="livekit-participant",So.Track="livekit-track",So.Publication="livekit-track-publication",So.Engine="livekit-engine",So.Signal="livekit-signal",So.PCManager="livekit-pc-manager",So.PCTransport="livekit-pc-transport",So.E2EE="lk-e2ee",So.DataTracks="livekit-data-tracks",So.Region="livekit-region",So.ICE="livekit-ice",So.Stats="livekit-stats";let wo=Co.getLogger(e.LoggerNames.Default);const Ro=Object.values(e.LoggerNames).map((e=>Co.getLogger(e)));function Po(e,t){const n=Co.getLogger(e);return n.setDefaultLevel(wo.getLevel()),t?function(e,t){const n=n=>(i,r)=>{const o=t(),s=o||r?Object.assign(Object.assign({},o),r):void 0;e[n](i,s)},i=Object.create(e);return i.trace=n("trace"),i.debug=n("debug"),i.info=n("info"),i.warn=n("warn"),i.error=n("error"),i}(n,t):n}wo.setDefaultLevel(e.LogLevel.info);const Io=Co.getLogger(e.LoggerNames.E2EE),_o=new Set,Oo=Io.setLevel.bind(Io);function Do(e){return _o.add(e),()=>{_o.delete(e)}}function Mo(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 r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]])}return n}function Ao(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(ke){o(ke)}}function a(e){try{c(i.throw(e))}catch(ke){o(ke)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function Lo(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 No(e){return this instanceof No?(this.v=e,this):new No(e)}function xo(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(e,t||[]),o=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",(function(e){return function(t){return Promise.resolve(t).then(e,d)}})),i[Symbol.asyncIterator]=function(){return this},i;function s(e,t){r[e]&&(i[e]=function(t){return new Promise((function(n,i){o.push([e,t,n,i])>1||a(e,t)}))},t&&(i[e]=t(i[e])))}function a(e,t){try{(n=r[e](t)).value instanceof No?Promise.resolve(n.value.v).then(c,d):l(o[0][2],n)}catch(ke){l(o[0][3],ke)}var n}function c(e){a("next",e)}function d(e){a("throw",e)}function l(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}}function Uo(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Lo(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,r){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,r,(t=e[n](t)).done,t.value)}))}}}Io.setLevel=(e,t)=>{Oo(e,t);const n=Io.getLevel();_o.forEach((e=>e(n)))},"function"==typeof SuppressedError&&SuppressedError;var Fo,jo={exports:{}};var Bo,qo,Vo=function(){if(Fo)return jo.exports;Fo=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 r(){r.init.call(this)}jo.exports=r,jo.exports.once=function(e,t){return new Promise((function(n,i){function r(n){e.removeListener(t,o),i(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",r),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,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function s(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?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,o,c,d;if(s(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),(r=a(e))>0&&c.length>r&&!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},r=d.bind(i);return r.listener=n,i.wrapFn=r,r}function u(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]: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}(r):p(r,r.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 r(o){i.once&&e.removeEventListener(t,r),n(o)}))}}return Object.defineProperty(r,"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}}),r.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},r.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},r.prototype.getMaxListeners=function(){return a(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,o=this._events;if(void 0!==o)r=r&&void 0===o.error;else if(!r)return!1;if(r){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,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},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return s(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,o,a;if(s(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(r=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,r=o;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},r.prototype.off=r.prototype.removeListener,r.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 r,o=Object.keys(n);for(i=0;i<o.length;++i)"removeListener"!==(r=o[i])&&this.removeAllListeners(r);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},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},jo.exports}();class Wo extends(qo=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}Bo=Wo,Wo.resolve=e=>Reflect.get(qo,"resolve",Bo).call(Bo,e);const Ho=/version\/(\d+(\.?_?\d+)+)/i;let Ko;function zo(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===Ko||t){const e=Go.find((e=>e.test.test(n)));Ko=null==e?void 0:e.describe(n)}return Ko}const Go=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Jo(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Qo(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Jo(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Qo(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Jo(Ho,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Qo(e)})}];function Jo(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 Qo(e){return e.includes("mac os")?Jo(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const Yo="2.24.1";class Xo extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}class Zo extends Xo{}var $o,es,ts,ns,is,rs,os;e.ConnectionErrorReason=void 0,($o=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[$o.NotAllowed=0]="NotAllowed",$o[$o.ServerUnreachable=1]="ServerUnreachable",$o[$o.InternalError=2]="InternalError",$o[$o.Cancelled=3]="Cancelled",$o[$o.LeaveRequest=4]="LeaveRequest",$o[$o.Timeout=5]="Timeout",$o[$o.WebSocket=6]="WebSocket",$o[$o.ServiceNotFound=7]="ServiceNotFound";class ss extends Zo{constructor(t,n,i,r){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=r,this.reasonName=e.ConnectionErrorReason[n]}static notAllowed(t,n,i){return new ss(t,e.ConnectionErrorReason.NotAllowed,n,i)}static timeout(t){return new ss(t,e.ConnectionErrorReason.Timeout)}static leaveRequest(t,n){return new ss(t,e.ConnectionErrorReason.LeaveRequest,void 0,n)}static internal(t,n){return new ss(t,e.ConnectionErrorReason.InternalError,void 0,n)}static cancelled(t){return new ss(t,e.ConnectionErrorReason.Cancelled)}static serverUnreachable(t,n){return new ss(t,e.ConnectionErrorReason.ServerUnreachable,n)}static websocket(t,n,i){return new ss(t,e.ConnectionErrorReason.WebSocket,n,i)}static serviceNotFound(t,n){return new ss(t,e.ConnectionErrorReason.ServiceNotFound,void 0,n)}}function as(t){return t.reason!==e.ConnectionErrorReason.Cancelled&&(t.reason!==e.ConnectionErrorReason.NotAllowed||403===t.status)}class cs extends Xo{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class ds extends Xo{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class ls extends Xo{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class us extends Xo{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class hs extends Xo{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class ps extends Xo{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class ms extends Xo{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class gs extends Zo{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName="string"==typeof t?t:co[t]}}e.DataStreamErrorReason=void 0,(es=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[es.AlreadyOpened=0]="AlreadyOpened",es[es.AbnormalEnd=1]="AbnormalEnd",es[es.DecodeFailed=2]="DecodeFailed",es[es.LengthExceeded=3]="LengthExceeded",es[es.Incomplete=4]="Incomplete",es[es.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",es[es.EncryptionTypeMismatch=8]="EncryptionTypeMismatch",es[es.HeaderTooLarge=9]="HeaderTooLarge",es[es.PayloadTooLarge=10]="PayloadTooLarge";class fs extends Zo{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}class vs extends Xo{constructor(e){super(18,e),this.name="SignalReconnectError"}}e.MediaDeviceFailure=void 0,(ts=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",ts.NotFound="NotFound",ts.DeviceInUse="DeviceInUse",ts.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={}));class ks{}function ys(e){const t={};for(const i of Object.entries(e)){var n=tt(i,2);const e=n[0],r=n[1];void 0!==r&&(t[e]=r)}return t}function bs(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function Ts(e){return Math.round(1e4*e)/1e4}function Ss(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?Ts(t/n):void 0}function Es(e,t){if(void 0!==e.playoutDelay)return Ts(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,i=null==t?void 0:t.totalSamplesCount;return void 0!==n&&i?Ts(n/i):void 0}function Cs(e){var t,n;const i=new Map,r=[],o=[],s=[];let a;e.forEach((e=>i.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=i.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?i.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");o.push(ys({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:bs(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:Ss(e),playoutDelay:Es(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");s.push(ys({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:bs(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:bs(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":a=e;break;case"candidate-pair":r.push(e)}}));const l=null==a?void 0:a.selectedCandidatePairId,u=null!==(n=null!==(t=l?i.get(l):void 0)&&void 0!==t?t:r.find((e=>e.selected)))&&void 0!==n?n:r.find((e=>e.nominated)),h=(null==u?void 0:u.localCandidateId)?i.get(u.localCandidateId):void 0,p=(null==u?void 0:u.remoteCandidateId)?i.get(u.remoteCandidateId):void 0,m=ys({ice:null==a?void 0:a.iceState,dtls:null==a?void 0:a.dtlsState,route:h&&p?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(p.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==u?void 0:u.currentRoundTripTime,availableOutgoingBitrate:null==u?void 0:u.availableOutgoingBitrate,availableIncomingBitrate:null==u?void 0:u.availableIncomingBitrate,bytesSent:null==u?void 0:u.bytesSent,bytesReceived:null==u?void 0:u.bytesReceived,candidatePairChanges:null==a?void 0:a.selectedCandidatePairChanges});return{connection:Object.keys(m).length>0?m:void 0,outbound:s.length>0?s:void 0,inbound:o.length>0?o:void 0}}function ws(e,t,n){var i,r,o,s;const a=xs(null!=e?e:{}),c=a.optionsWithoutProcessor,d=a.audioProcessor,l=a.videoProcessor,u=null==t?void 0:t.processor,h=null==n?void 0:n.processor,p=null!=c?c:{};return!0===p.audio&&(p.audio={}),!0===p.video&&(p.video={}),p.audio&&(Rs(p.audio,t),null!==(i=(o=p.audio).deviceId)&&void 0!==i||(o.deviceId={ideal:"default"}),(d||u)&&(p.audio.processor=null!=d?d:u)),p.video&&(Rs(p.video,n),null!==(r=(s=p.video).deviceId)&&void 0!==r||(s.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=null!=l?l:h)),p}function Rs(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Ps(e){var t,n,i,r;const o={};if(e.video)if("object"==typeof e.video){const n={},r=n,s=e.video;Object.keys(s).forEach((e=>{if("resolution"===e)Rs(r,s.resolution);else r[e]=s[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=(r=o.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"})):o.audio={deviceId:{ideal:"default"}}:o.audio=!1,o}function Is(e){return Ao(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=_s();if(!n)return!1;let i,r;try{r=n.createAnalyser(),r.fftSize=2048;const o=r.frequencyBinCount,s=new Uint8Array(o);i=n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])),i.connect(r);const a=()=>"running"===n.state;if(!a()){try{yield Promise.race([n.resume(),Ks(200)])}catch(Bo){}if(!a())return!1}yield Ks(t),r.getByteTimeDomainData(s);return!s.some((e=>128!==e&&0!==e))}finally{null==i||i.disconnect(),null==r||r.disconnect(),yield n.close().catch((()=>{}))}}()}))}function _s(){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=()=>Ao(this,void 0,void 0,(function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(ke){console.warn("Error trying to auto-resume audio context",ke)}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 Os(e){return"audioinput"===e?Bs.Source.Microphone:"videoinput"===e?Bs.Source.Camera:Bs.Source.Unknown}function Ds(e){return e===Bs.Source.Microphone?"audioinput":e===Bs.Source.Camera?"videoinput":void 0}function Ms(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=oa()?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 As(e){return e.split("/")[1].toLowerCase()}function Ls(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new yr({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Ns(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?Ns(e.track):{})}}function xs(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:(r=t,void 0===r?r:"function"==typeof structuredClone?"object"==typeof r&&null!==r?structuredClone(Object.assign({},r)):structuredClone(r):JSON.parse(JSON.stringify(r)))};var r}function Us(e,t){return e.width*e.height<t.width*t.height}ks.setTimeout=function(){return setTimeout(...arguments)},ks.setInterval=function(){return setInterval(...arguments)},ks.clearTimeout=function(){return clearTimeout(...arguments)},ks.clearInterval=function(){return clearInterval(...arguments)},e.RoomEvent=void 0,(ns=e.RoomEvent||(e.RoomEvent={})).Connected="connected",ns.Reconnecting="reconnecting",ns.SignalReconnecting="signalReconnecting",ns.Reconnected="reconnected",ns.Disconnected="disconnected",ns.ConnectionStateChanged="connectionStateChanged",ns.Moved="moved",ns.MediaDevicesChanged="mediaDevicesChanged",ns.ParticipantConnected="participantConnected",ns.ParticipantDisconnected="participantDisconnected",ns.TrackPublished="trackPublished",ns.TrackSubscribed="trackSubscribed",ns.TrackSubscriptionFailed="trackSubscriptionFailed",ns.TrackUnpublished="trackUnpublished",ns.TrackUnsubscribed="trackUnsubscribed",ns.TrackMuted="trackMuted",ns.TrackUnmuted="trackUnmuted",ns.LocalTrackPublished="localTrackPublished",ns.LocalTrackUnpublished="localTrackUnpublished",ns.LocalAudioSilenceDetected="localAudioSilenceDetected",ns.ActiveSpeakersChanged="activeSpeakersChanged",ns.ParticipantMetadataChanged="participantMetadataChanged",ns.ParticipantNameChanged="participantNameChanged",ns.ParticipantAttributesChanged="participantAttributesChanged",ns.ParticipantActive="participantActive",ns.RoomMetadataChanged="roomMetadataChanged",ns.DataReceived="dataReceived",ns.SipDTMFReceived="sipDTMFReceived",ns.TranscriptionReceived="transcriptionReceived",ns.ConnectionQualityChanged="connectionQualityChanged",ns.TrackStreamStateChanged="trackStreamStateChanged",ns.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",ns.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",ns.AudioPlaybackStatusChanged="audioPlaybackChanged",ns.VideoPlaybackStatusChanged="videoPlaybackChanged",ns.MediaDevicesError="mediaDevicesError",ns.ParticipantPermissionsChanged="participantPermissionsChanged",ns.SignalConnected="signalConnected",ns.RecordingStatusChanged="recordingStatusChanged",ns.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",ns.EncryptionError="encryptionError",ns.DCBufferStatusChanged="dcBufferStatusChanged",ns.ActiveDeviceChanged="activeDeviceChanged",ns.ChatMessage="chatMessage",ns.LocalTrackSubscribed="localTrackSubscribed",ns.MetricsReceived="metricsReceived",ns.DataTrackPublished="dataTrackPublished",ns.DataTrackUnpublished="dataTrackUnpublished",ns.LocalDataTrackPublished="localDataTrackPublished",ns.LocalDataTrackUnpublished="localDataTrackUnpublished",e.ParticipantEvent=void 0,(is=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",is.TrackSubscribed="trackSubscribed",is.TrackSubscriptionFailed="trackSubscriptionFailed",is.TrackUnpublished="trackUnpublished",is.TrackUnsubscribed="trackUnsubscribed",is.TrackMuted="trackMuted",is.TrackUnmuted="trackUnmuted",is.LocalTrackPublished="localTrackPublished",is.LocalTrackUnpublished="localTrackUnpublished",is.LocalTrackCpuConstrained="localTrackCpuConstrained",is.LocalSenderCreated="localSenderCreated",is.ParticipantMetadataChanged="participantMetadataChanged",is.ParticipantNameChanged="participantNameChanged",is.DataReceived="dataReceived",is.SipDTMFReceived="sipDTMFReceived",is.TranscriptionReceived="transcriptionReceived",is.IsSpeakingChanged="isSpeakingChanged",is.ConnectionQualityChanged="connectionQualityChanged",is.TrackStreamStateChanged="trackStreamStateChanged",is.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",is.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",is.TrackCpuConstrained="trackCpuConstrained",is.MediaDevicesError="mediaDevicesError",is.AudioStreamAcquired="audioStreamAcquired",is.ParticipantPermissionsChanged="participantPermissionsChanged",is.PCTrackAdded="pcTrackAdded",is.AttributesChanged="attributesChanged",is.LocalTrackSubscribed="localTrackSubscribed",is.ChatMessage="chatMessage",is.Active="active",e.EngineEvent=void 0,(rs=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",rs.Connected="connected",rs.Disconnected="disconnected",rs.Resuming="resuming",rs.Resumed="resumed",rs.Restarting="restarting",rs.Restarted="restarted",rs.SignalResumed="signalResumed",rs.SignalRestarted="signalRestarted",rs.Closing="closing",rs.MediaTrackAdded="mediaTrackAdded",rs.ActiveSpeakersUpdate="activeSpeakersUpdate",rs.DataPacketReceived="dataPacketReceived",rs.RTPVideoMapUpdate="rtpVideoMapUpdate",rs.DCBufferStatusChanged="dcBufferStatusChanged",rs.ParticipantUpdate="participantUpdate",rs.RoomUpdate="roomUpdate",rs.SpeakersChanged="speakersChanged",rs.StreamStateChanged="streamStateChanged",rs.ConnectionQualityUpdate="connectionQualityUpdate",rs.SubscriptionError="subscriptionError",rs.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",rs.RemoteMute="remoteMute",rs.SubscribedQualityUpdate="subscribedQualityUpdate",rs.LocalTrackUnpublished="localTrackUnpublished",rs.LocalTrackSubscribed="localTrackSubscribed",rs.Offline="offline",rs.SignalRequestResponse="signalRequestResponse",rs.SignalConnected="signalConnected",rs.RoomMoved="roomMoved",rs.PublishDataTrackResponse="publishDataTrackResponse",rs.UnPublishDataTrackResponse="unPublishDataTrackResponse",rs.DataTrackSubscriberHandles="dataTrackSubscriberHandles",rs.DataTrackPacketReceived="dataTrackPacketReceived",rs.Joined="joined",rs.TokenRefreshed="tokenRefreshed",rs.ServerRegionsReported="serverRegionsReported",rs.RequestSubscribedCodecRefresh="requestSubscribedCodecRefresh",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=[];var js;e.VideoQuality=void 0,(js=e.VideoQuality||(e.VideoQuality={}))[js.LOW=0]="LOW",js[js.MEDIUM=1]="MEDIUM",js[js.HIGH=2]="HIGH";class Bs extends Vo.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Bs.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=wo,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=i.loggerContextCb,this.log=Po(null!==(r=i.loggerName)&&void 0!==r?r:e.LoggerNames.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=Bs.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Ns(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===Bs.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===Bs.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Fs.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Fs.splice(Fs.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),qs(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),r=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(r?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(r?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:n}),r&&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){Vs(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=>{Vs(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.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",Cs(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=Po(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Fs.forEach((e=>{e.parentElement||(t=!1)})),t&&Fs.push(e)}}handleAppVisibilityChanged(){return Ao(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Bs.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){la()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){la()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function qs(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)),oa()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(oa()||na())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Vs(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;"audio"===e.kind&&ia()&&(t.srcObject=null),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 yn.AUDIO;case t.Video:return yn.VIDEO;default:return yn.DATA}},e.kindFromProto=function(e){switch(e){case yn.AUDIO:return t.Audio;case yn.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return bn.CAMERA;case n.Microphone:return bn.MICROPHONE;case n.ScreenShare:return bn.SCREEN_SHARE;case n.ScreenShareAudio:return bn.SCREEN_SHARE_AUDIO;default:return bn.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case bn.CAMERA:return n.Camera;case bn.MICROPHONE:return n.Microphone;case bn.SCREEN_SHARE:return n.ScreenShare;case bn.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case nr.ACTIVE:return i.Active;case nr.PAUSED:return i.Paused;default:return i.Unknown}}}(Bs||(Bs={}));const Ws="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Hs(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}function Ks(e){return new Wo((t=>ks.setTimeout(t,e)))}function zs(){return"addTransceiver"in RTCPeerConnection.prototype}function Gs(){return"addTrack"in RTCPeerConnection.prototype}function Js(){if(!("getCapabilities"in RTCRtpSender))return!1;if(oa()||na())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 Qs(){if(!("getCapabilities"in RTCRtpSender))return!1;if(na())return!1;if(oa()){const e=zo();if((null==e?void 0:e.version)&&va(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&va(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 Ys(e){return"av1"===e||"vp9"===e}function Xs(e){var t;const n=null===(t=e.getHeaderExtensionsToNegotiate)||void 0===t?void 0:t.call(e);if(!n||!e.setHeaderExtensionsToNegotiate)return!1;const i=n.find((e=>e.uri===Ws));if(!i)return!1;if("stopped"!==i.direction)return!0;i.direction="sendrecv";try{return e.setHeaderExtensionsToNegotiate(n),!0}catch(ke){return!1}}function Zs(e,t){var n;return Ys(e)&&!!(null==t?void 0:t.simulcast)&&!!(null===(n=t.scalabilityMode)||void 0===n?void 0:n.startsWith("L1T"))}function $s(){const e=zo();return sa()||ua()||"Chrome"===(null==e?void 0:e.name)&&va(e.version,"113")<0}function ea(e){return!(!document||sa())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function ta(){return"undefined"!=typeof RTCPeerConnection&&(zs()||Gs())}function na(){var e;return"Firefox"===(null===(e=zo())||void 0===e?void 0:e.name)}function ia(){const e=zo();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function ra(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform&&!ia()}function oa(){var e;return"Safari"===(null===(e=zo())||void 0===e?void 0:e.name)}function sa(){const e=zo();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function aa(){var e;return"iOS"===(null===(e=zo())||void 0===e?void 0:e.os)||function(){if(!la())return!1;const e=zo();return"Safari"===(null==e?void 0:e.name)&&"macOS"===(null==e?void 0:e.os)&&navigator.maxTouchPoints>1}()}function ca(){const e=zo();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)&&va(e.osVersion,"17")>=0}function da(){var e,t;return!!la()&&(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 la(){return"undefined"!=typeof document}function ua(){return"ReactNative"==navigator.product}function ha(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function pa(e){return ha(e)?e.hostname.split(".")[0]:null}function ma(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ga(){if(!ua())return;let e=ma();return e?e.platform:void 0}function fa(){if(la())return window.devicePixelRatio;if(ua()){let e=ma();if(e)return e.devicePixelRatio}return 1}function va(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let o=0;o<r;++o){const e=parseInt(n[o],10),t=parseInt(i[o],10);if(e>t)return 1;if(e<t)return-1;if(o===r-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function ka(e){for(const t of e)t.target.handleResize(t)}function ya(e){for(const t of e)t.target.handleVisibilityChanged(t)}let ba=null;const Ta=()=>(ba||(ba=new ResizeObserver(ka)),ba);let Sa=null;const Ea=()=>(Sa||(Sa=new IntersectionObserver(ya,{root:null,rootMargin:"0px"})),Sa);let Ca,wa,Ra;function Pa(){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 r=document.createElement("canvas");r.width=e,r.height=t;const o=r.getContext("2d");null==o||o.fillRect(0,0,r.width,r.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 s=tt(r.captureStream().getTracks(),1)[0];if(!s)throw Error("Could not get empty media stream video track");return s.enabled=n,s}const Ia=new Set;function _a(){if(!wa){const t=new AudioContext,n=t.createOscillator(),i=t.createGain();i.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();n.connect(i),i.connect(r),n.start();var e=tt(r.stream.getAudioTracks(),1);if(wa=e[0],!wa)throw t.close().catch((()=>{})),Error("Could not get empty media stream audio track");wa.enabled=!1,Ra=t}const t=wa.clone();return Ia.add(t),t}function Oa(e){return Ao(this,void 0,void 0,(function*(){if(!Ia.delete(e))return;if(e.stop(),Ia.size>0)return;const t=Ra;null==wa||wa.stop(),wa=void 0,Ra=void 0,yield null==t?void 0:t.close()}))}class Da{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>Ao(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 Ma(e){return he.includes(e)}function Aa(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")}const La=new WeakSet;function Na(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function xa(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return Cn.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return Cn.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return Cn.JOIN_FAILURE;default:return Cn.UNKNOWN_REASON}}function Ua(e){return void 0!==e?Number(e):void 0}function Fa(e){return void 0!==e?BigInt(e):void 0}function ja(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Ba(e){return!!e&&e.kind==Bs.Kind.Audio}function qa(e){return!!e&&e.kind==Bs.Kind.Video}function Va(e){return ja(e)&&qa(e)}function Wa(e){return ja(e)&&Ba(e)}function Ha(e){return!!e&&!e.isLocal}function Ka(e){return!!e&&!e.isLocal}function za(e){return Ha(e)&&qa(e)}function Ga(e){return e.isLocal}function Ja(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Qa(){return"undefined"!=typeof CompressionStream}let Ya=null;function Xa(){return"boolean"!=typeof Ya&&(Ya=function(){if("undefined"==typeof CompressionStream||"undefined"==typeof DecompressionStream)return!1;try{return new CompressionStream("deflate-raw"),new DecompressionStream("deflate-raw"),!0}catch(Bo){return!1}}()),Ya}function Za(e,t){const n=tt(Hs(t.id),2)[1];return(null==n?void 0:n.startsWith("TR"))?n:e.id.startsWith("TR")?e.id:void 0}function $a(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const i=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)})),tc(n,"rtc")}(e,t);return n?i:tc(i,"v1")}function ec(e){return e.endsWith("/")?e:"".concat(e,"/")}function tc(e,t){return e.pathname="".concat(ec(e.pathname)).concat(t),e}function nc(e){if("string"==typeof e)return sr.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return sr.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const ic="AES-GCM",rc="lk_e2ee",oc="lk_e2ee_track_id",sc={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function ac(){return dc()||cc()}function cc(){return"undefined"!=typeof window&&void 0!==window.RTCRtpScriptTransform}function dc(){return"undefined"!=typeof window&&void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function lc(e){return Ao(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 uc(e){return Ao(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function hc(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"))}}function pc(e){var t,n,i,r,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===(r=e.value)||void 0===r?void 0:r.case)&&"encryptedPacket"!==(null===(o=e.value)||void 0===o?void 0:o.case))return new $n({value:e.value})}function mc(){return ra()}function gc(e){return!!(null==e?void 0:e.worker)&&(dc()||mc())}function fc(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}function vc(e){var t;return null!==(t=null==e?void 0:e.frameMetadata)&&void 0!==t?t:null==e?void 0:e.packetTrailer}function kc(e,t){e.frameMetadata=t,e.packetTrailer=t}class yc{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new yc),this._instance}addFailedConnectionAttempt(e){var t;const n=pa(new URL(e));if(!n)return;let i=null!==(t=this.failedConnectionAttempts.get(n))&&void 0!==t?t:0;this.failedConnectionAttempts.set(n,i+1),this.backOffPromises.set(n,Ks(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&pa(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&pa(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}yc._instance=null;const bc="default";class Tc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Tc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Ao(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=Tc.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){wo.debug("awaiting getUserMedia promise");try{e?yield Tc.userMediaPromiseMap.get(e):yield Promise.all(Tc.userMediaPromiseMap.values())}catch(ke){wo.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(n&&(!oa()||!t.hasDeviceInUse(e))){if(0===r.filter((t=>!e||t.kind===e)).length||r.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);r=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=r,e&&(r=r.filter((t=>t.kind===e))),r}()}))}normalizeDeviceId(e,t,n){return Ao(this,void 0,void 0,(function*(){if(t!==bc)return t;const i=yield this.getDevices(e),r=i.find((e=>e.deviceId===bc));if(!r)return void wo.warn("could not reliably determine default device");const o=i.find((e=>e.deviceId!==bc&&e.groupId===(null!=n?n:r.groupId)));if(o)return null==o?void 0:o.deviceId;wo.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Tc.userMediaPromiseMap.has(e):Tc.userMediaPromiseMap.size>0}}var Sc;Tc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Tc.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Sc||(Sc={}));class Ec{constructor(){this.pendingTasks=new Map,this.taskMutex=new be,this.nextTaskIndex=0}run(e){return Ao(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Sc.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Sc.RUNNING,yield e()}finally{t.status=Sc.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return Ao(this,void 0,void 0,(function*(){return this.run((()=>Ao(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function Cc(e){if(0===e.length){return(new AbortController).signal}if(1===e.length)return e[0];for(const i of e)if(i.aborted)return i;const t=new AbortController,n=Array(e.length);return e.forEach(((e,i)=>{const r=()=>{t.abort(e.reason),(()=>{for(const e of n)e()})()};e.addEventListener("abort",r),n[i]=()=>e.removeEventListener("abort",r)})),t.signal}function wc(e){const t=new AbortController;return setTimeout((()=>{t.abort(new DOMException("signal timed out after ".concat(e," ms"),"TimeoutError"))}),e),t.signal}const Rc=["client"],Pc="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.target=e}deref(){return this.target}};var Ic=class{constructor(){Ze(this,"listeners",new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){const n=this.listeners.get("*");if(n)for(const r of n)r(e,t);const i=this.listeners.get(e);if(i)for(const r of i)r(t)}clear(){this.listeners.clear()}},_c=class extends Error{constructor(e,t){super("non-serializable value at ".concat(e," (").concat(t,")")),this.path=e,this.label=t}};const Oc=(e,t,n)=>{if(null===e)return null;switch(typeof e){case"string":case"boolean":return e;case"number":if(!Number.isFinite(e))throw new _c(t,Mc(e));return e;case"object":return Dc(e,t,n);default:throw new _c(t,typeof e)}},Dc=(e,t,n)=>{var i,r;if(n.has(e))throw new _c(t,"circular reference");if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new _c(t,"sparse array or array with non-index properties");n.add(e);const i=e.map(((e,i)=>Oc(e,"".concat(t,"[").concat(i,"]"),n)));return n.delete(e),i}const o=Object.getPrototypeOf(e);if(o!==Object.prototype&&null!==o)throw new _c(t,null!==(i=null===(r=e.constructor)||void 0===r?void 0:r.name)&&void 0!==i?i:"object");n.add(e);const s={};for(const a of Object.keys(e)){const i=Oc(e[a],"".concat(t,".").concat(a),n);Object.defineProperty(s,a,{value:i,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),s},Mc=e=>Number.isNaN(e)?"NaN":e>0?"Infinity":"-Infinity",Ac=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Set;if(null===e||"object"!=typeof e)return e;if(t.has(e))return e;if(Array.isArray(e)){t.add(e);const n=e.map((e=>Ac(e,t)));return t.delete(e),n}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&null!==n)return e;t.add(e);const i={};for(const r of Object.keys(e)){const n=Ac(e[r],t);Object.defineProperty(i,r,{value:n,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),i},Lc=Symbol("machina.type");var Nc=class{constructor(e){Ze(this,"id",void 0),Ze(this,"initialState",void 0),Ze(this,Lc,"BehavioralFsm"),Ze(this,"states",void 0),Ze(this,"emitter",new Ic),Ze(this,"clients",new WeakMap),Ze(this,"knownClients",new Set),Ze(this,"childSubscriptions",[]),Ze(this,"disposed",!1),Ze(this,"transitionDepth",0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){var n;if(this.disposed)return;const i=this.getOrCreateClientMeta(e);for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];i.currentActionArgs=o;const a=null===(n=this.states[i.state])||void 0===n?void 0:n._child;if(a&&a.canHandle(e,t))try{a.handle(e,t,...o)}finally{i.currentActionArgs=void 0}else this.handleLocally(e,t,o,i)}canHandle(e,t){var n,i,r;if(this.disposed)return!1;const o=null!==(n=null===(i=this.clients.get(e))||void 0===i?void 0:i.state)&&void 0!==n?n:this.initialState,s=this.states[o];if(null!==(r=null==s?void 0:s[t])&&void 0!==r?r:null==s?void 0:s["*"])return!0;const a=null==s?void 0:s._child;return!!a&&a.canHandle(e,t)}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){var t;return null===(t=this.clients.get(e))||void 0===t?void 0:t.state}transition(e,t){if(this.disposed)return;const n=this.getOrCreateClientMeta(e),i=n.state;if(t!==i)if(Object.prototype.hasOwnProperty.call(this.states,t)){if(this.transitionDepth++,this.transitionDepth>20)throw this.transitionDepth=0,new Error("Max transition depth (".concat(20,') exceeded in FSM "').concat(this.id,'". Likely an infinite _onEnter → transition loop.'));try{const r=this.states[i],o=this.states[t];if(null!=r&&r._onExit&&"function"==typeof r._onExit){const t=this.buildHandlerArgs(e,"",n);r._onExit(t)}n.state=t;const s={fromState:i,toState:t,client:e};let a;if(this.emitter.emit("transitioning",s),null!=o&&o._onEnter&&"function"==typeof o._onEnter){const t=this.buildHandlerArgs(e,"",n);a=o._onEnter(t)}this.emitter.emit("transitioned",s);const c=null==o?void 0:o._child;c&&c.reset(e),this.processQueue(e,n),"string"==typeof a&&n.state===t&&this.transition(e,a)}finally{this.transitionDepth--}}else this.emitter.emit("invalidstate",{stateName:t,client:e})}compositeState(e){var t;const n=this.clients.get(e);if(!n)return"";const i=null===(t=this.states[n.state])||void 0===t?void 0:t._child;if(i){const t=i.compositeState(e);if(t)return"".concat(n.state,".").concat(t)}return n.state}rehydrate(e,t){if(this.disposed)return;if("string"==typeof t)return void this.rehydrateCompositePath(e,t);const n=this.planSnapshotWrites(e,t);for(const i of n)i()}dehydrate(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.clients.get(e);if(!n)return;const i={state:n.state,deferred:n.deferredQueue.map((e=>this.snapshotDeferredInput(e)))},r=this.collectChildSnapshots(e,n.state,t);return r&&(i.children=r),i}planSnapshotWrites(e,t){if(this.disposed)return[];const n=t.state,i=t.deferred,r=t.children;if(!Object.prototype.hasOwnProperty.call(this.states,n))throw new Error('rehydrate: unknown state "'.concat(n,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));const o=[];if(r)for(const c of Object.keys(r)){var s;if(!Object.prototype.hasOwnProperty.call(this.states,c))throw new Error('rehydrate: unknown state "'.concat(c,'" in FSM "').concat(this.id,'" referenced by snapshot.children.'));const t=null===(s=this.states[c])||void 0===s?void 0:s._child;if(!t)throw new Error('rehydrate: state "'.concat(c,'" in FSM "').concat(this.id,'" has no _child, but the snapshot has a children["').concat(c,'"] entry.'));o.push(...t.planRehydrate(e,r[c]))}const a=i.map((e=>function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?et(Object(n),!0).forEach((function(t){Ze(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):et(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({inputName:e.inputName,args:Ac(e.args)},void 0!==e.untilState?{untilState:e.untilState}:{})));return o.push((()=>{this.clients.has(e)||this.knownClients.add(new Pc(e)),this.clients.set(e,{state:n,deferredQueue:a})})),o}rehydrateCompositePath(e,t){const n=nt(t.split(".")),i=n[0],r=Ye(n).slice(1);if(!Object.prototype.hasOwnProperty.call(this.states,i))throw new Error('rehydrate: unknown state "'.concat(i,'" in FSM "').concat(this.id,'". Valid states: ').concat(Object.keys(this.states).join(", ")));if(r.length>0){var o;const n=r.join("."),s=null===(o=this.states[i])||void 0===o?void 0:o._child;if(!s)throw new Error('rehydrate: state "'.concat(i,'" in FSM "').concat(this.id,'" has no _child, but composite path "').concat(t,'" requires one.'));s.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new Pc(e)),this.clients.set(e,{state:i,deferredQueue:[]})}collectChildSnapshots(e,t,n){const i=new Map;for(const s of Object.keys(this.states)){var r;const e=null===(r=this.states[s])||void 0===r?void 0:r._child;if(!e)continue;const t=i.get(e.instance);t?t.stateNames.push(s):i.set(e.instance,{childLink:e,stateNames:[s]})}let o;for(const s of i.values()){const i=s.childLink,r=s.stateNames,a=n&&r.includes(t);if("Fsm"===i.instance[Lc]&&!a)continue;const c=i.dehydrate(e,a);if(c){null!=o||(o={});for(const e of r)o[e]=c}}return o}snapshotDeferredInput(e){let t;try{n=e.args,t=Oc(n,"args",new Set)}catch(r){if(!(r instanceof _c))throw r;const t=e.untilState?' (until "'.concat(e.untilState,'")'):"";throw new Error('dehydrate: deferred input "'.concat(e.inputName,'"').concat(t,' in FSM "').concat(this.id,'" has a non-serializable value at ').concat(r.path," (").concat(r.label,")"))}var n;const i={inputName:e.inputName,args:t};return void 0!==e.untilState&&(i.untilState=e.untilState),i}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(const n of this.childSubscriptions)n.off();if(null==e||!e.preserveChildren){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;i&&!e.has(i.instance)&&(e.add(i.instance),i.dispose())}}this.emitter.clear()}wrapChildLinks(){for(const e of Object.keys(this.states)){const t=this.states[e],n=null==t?void 0:t._child;if(n){if("object"!=typeof n)throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got ').concat(String(n)));if(!(Lc in n))throw new Error('State "'.concat(e,'"._child: expected an Fsm or BehavioralFsm instance, got a plain object'));t._child=xc(n)}}}setupChildSubscriptions(){const e=new Set;for(const n of Object.keys(this.states)){var t;const i=null===(t=this.states[n])||void 0===t?void 0:t._child;if(!i||e.has(i.instance))continue;e.add(i.instance);const r=i.onAny(((e,t)=>{if("nohandler"===e){var n;const e=t;if(void 0!==e.client)this.bubbleNohandler(e.client,i,e.inputName,null!==(n=e.args)&&void 0!==n?n:[]);else for(const t of this.knownClients){var r;const n=t.deref();void 0!==n?this.bubbleNohandler(n,i,e.inputName,null!==(r=e.args)&&void 0!==r?r:[]):this.knownClients.delete(t)}return}const o=t;if(o&&"object"==typeof o&&"client"in o)this.isChildActiveForClient(o.client,i)&&this.emitter.emit(e,t);else for(const s of this.knownClients){const n=s.deref();if(n){if(this.isChildActiveForClient(n,i)){this.emitter.emit(e,t);break}}else this.knownClients.delete(s)}}));this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,i){if(!this.isChildActiveForClient(e,t))return;const r=this.clients.get(e);r.currentActionArgs=i,this.handleLocally(e,n,i,r)}isChildActiveForClient(e,t){var n;const i=this.clients.get(e);return!!i&&(null===(n=this.states[i.state])||void 0===n||null===(n=n._child)||void 0===n?void 0:n.instance)===t.instance}handleLocally(e,t,n,i){var r;const o=this.states[i.state],s=null!==(r=null==o?void 0:o[t])&&void 0!==r?r:null==o?void 0:o["*"];if(!s)return this.emitter.emit("nohandler",{inputName:t,args:n,client:e}),void(i.currentActionArgs=void 0);try{this.emitter.emit("handling",{inputName:t,client:e});const r=this.buildHandlerArgs(e,t,i);let o;"string"==typeof s?o=s:"function"==typeof s&&(o=s(r,...n)),this.emitter.emit("handled",{inputName:t,client:e}),"string"==typeof o&&this.transition(e,o)}finally{i.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new Pc(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:i=>{if(!n.currentActionArgs)return;const r={inputName:t,args:[...n.currentActionArgs],untilState:null==i?void 0:i.until};n.deferredQueue.push(r),this.emitter.emit("deferred",{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){const n=[],i=[];for(const r of t.deferredQueue)void 0===r.untilState||r.untilState===t.state?n.push(r):i.push(r);t.deferredQueue=i;for(const r of n)this.handle(e,r.inputName,...r.args)}};function xc(e){if(!e||"object"!=typeof e)throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got ".concat(String(e)));const t=e[Lc];if("BehavioralFsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(t,n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(t),rehydrate(t,n){e.rehydrate(t,n)},dehydrate:(t,n)=>e.dehydrate(t,n),planRehydrate:(t,n)=>e.planSnapshotWrites(t,n),dispose(){e.dispose()}};if("Fsm"===t)return{instance:e,canHandle:(t,n)=>e.canHandle(n),handle(t,n){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];e.handle(n,...r)},reset(t){e.reset()},onAny:t=>e.on("*",t),compositeState:t=>e.compositeState(),rehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dehydrate(e,t){throw new Error("dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.")},planRehydrate(e,t){throw new Error("rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.")},dispose(){e.dispose()}};throw new Error("createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ".concat(String(null!=t?t:"undefined")))}var Uc=class{constructor(e){var t;Ze(this,"id",void 0),Ze(this,"initialState",void 0),Ze(this,Lc,"Fsm"),Ze(this,"states",void 0),Ze(this,"bfsm",void 0),Ze(this,"context",void 0),Ze(this,"emitter",new Ic),Ze(this,"disposed",!1),this.id=e.id,this.initialState=e.initialState,this.context=null!==(t=e.context)&&void 0!==t?t:{},this.bfsm=new Nc(e),this.states=e.states,this.bfsm.on("*",((e,t)=>{if(t&&"object"==typeof t&&"client"in t){t.client;const n=function(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)n=o[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}(t,Rc);this.emitter.emit(e,n)}else this.emitter.emit(e,t)})),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];this.bfsm.handle(this.context,e,...n)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function Fc(e,t){return t.attemptId===e.attemptId}const jc=(e,t)=>{if(Fc(e.ctx,t))return"connected"},Bc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"connecting"},qc=e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,"reconnecting"},Vc=(e,t)=>(e.ctx.closeReason=t.reason,"disconnecting"),Wc={new:{connect:Bc,close:Vc},connecting:{connectComplete:jc,connectFailed:(e,t)=>(e.ctx.lastError=t.error,"closed"),close:Vc},connected:{reconnect:qc,transportFailed:(e,t)=>{let n=e.ctx;if(Fc(n,t))return n.lastError=t.reason,"offline"},close:Vc},offline:{connect:Bc,reconnect:qc,close:Vc},reconnecting:{reconnectComplete:jc,reconnectFailed:(e,t)=>(e.ctx.lastError=t.error,t.recoverable?"offline":"closed"),close:Vc},disconnecting:{closeComplete:"closed"},closed:{connect:Bc,reconnect:qc}};function Hc(){return new Uc({id:"signal",initialState:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"new",context:{attemptId:0},states:Wc})}class Kc{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(null===(n=t.signal)||void 0===n?void 0:n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,null!==(i=t.protocols)&&void 0!==i?i:[]);let o,s;r.binaryType="arraybuffer",this.ws=r;const a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};r.readyState===WebSocket.CONNECTING&&(o=e,s(ss.websocket("Websocket closed before the connection opened")));const t=e.closeCode,n=e.reason;r.close(t,void 0===n?void 0:function(e){const t=new TextEncoder;if(t.encode(e).length<=zc)return e;let n="",i=0;for(const r of e){if(i+=t.encode(r).length,i>zc)break;n+=r}return n}(n))};this.opened=new Wo(((e,t)=>{s=t;const n=()=>{t(ss.websocket("Encountered websocket error during connection establishment"))},i=e=>{t(ss.websocket("Websocket closed during connection establishment with code ".concat(e.code).concat(e.reason?": ".concat(e.reason):"")))};r.onopen=()=>{o?a(o):(e({readable:new ReadableStream({start(e){r.onmessage=t=>{let n=t.data;r.readyState===WebSocket.OPEN&&e.enqueue(n)},r.onerror=t=>{return e.error(ss.websocket((i="websocket",(n=t)instanceof Error?n.name&&n.message?"".concat(n.name,": ").concat(n.message):n.name:"Encountered unknown ".concat(i," error: ").concat(String(n)))));var n,i},r.onclose=t=>{t.wasClean||1e3===t.code?e.close():e.error(ss.websocket("WS closed unexpectedly with code ".concat(t.code)))}},cancel:a}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",n),r.removeEventListener("close",i))},r.addEventListener("error",n),r.addEventListener("close",i)})),this.closed=new Wo(((e,t)=>{const n=()=>Ao(this,void 0,void 0,(function*(){const n=new Wo((e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield Wo.race([Ks(250),n]);i?e(i):t(ss.websocket("Encountered unspecified websocket error without a timely close event"))}));r.addEventListener("close",(t=>{let i=t.code,o=t.reason;e({closeCode:i,reason:o}),r.removeEventListener("error",n)})),r.addEventListener("error",n)})),t.signal&&(t.signal.onabort=()=>a()),this.close=a}}const zc=123;const Gc=["syncState","trickle","offer","answer","simulate","leave"];var Jc;!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"}(Jc||(Jc={}));class Qc{get currentState(){return function(e){switch(e){case"connected":return Jc.CONNECTED;case"connecting":return Jc.CONNECTING;case"reconnecting":return Jc.RECONNECTING;case"disconnecting":return Jc.DISCONNECTING;default:return Jc.DISCONNECTED}}(this.lifecycleState)}get isDisconnected(){const e=this.currentState;return e===Jc.DISCONNECTING||e===Jc.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){const t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return Ao(this,void 0,void 0,(function*(){this.log.debug("waiting for an in-flight close to settle before establishing a session"),(yield this.closingLock.lock())()}))}get isEstablishingConnection(){return"connecting"===this.lifecycleState||"reconnecting"===this.lifecycleState}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.log=wo,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=n.loggerContextCb,this.log=Po(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal,(()=>this.logContext)),this.useJSON=t,this.requestQueue=new Ec,this.queuedRequests=[],this.closingLock=new be,this.connectionLock=new be,this.machine=Hc(),this.machine.on("transitioned",(e=>{let t=e.fromState,n=e.toState;this.log.debug("signal lifecycle: ".concat(t," -> ").concat(n))})),this.machine.on("nohandler",(e=>{let t=e.inputName;this.log.debug("ignoring signal lifecycle input ".concat(t," in state ").concat(this.lifecycleState))})),this.machine}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 Ao(this,arguments,void 0,(function(e,t,n,i){var r=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){if("disconnecting"===r.lifecycleState&&(yield r.settleInFlightClose()),!r.sendLifecycleInput({type:"connect"}))throw ss.internal("cannot establish a signal session from '".concat(r.lifecycleState,"', close the current one first"));r.options=n;try{return yield r.connect(e,t,n,i,o,s)}catch(ke){throw r.sendLifecycleInput({type:"connectFailed",error:ke}),ke}}()}))}reconnect(t,n,i,r){return Ao(this,void 0,void 0,(function*(){if(this.options){if("disconnecting"===this.lifecycleState&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:"reconnect"}))throw ss.internal("cannot resume the signal session from '".concat(this.lifecycleState,"'"));this.clearPingInterval();try{return yield this.connect(t,n,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(ke){throw this.sendLifecycleInput({type:"reconnectFailed",error:ke,recoverable:(o=ke,!(o instanceof ss)||o.reason!==e.ConnectionErrorReason.LeaveRequest&&o.reason!==e.ConnectionErrorReason.NotAllowed)}),ke}var o}else this.log.warn("attempted to reconnect without signal options being set, ignoring")}))}connect(e,t,n,i){return Ao(this,arguments,void 0,(function(e,t,n,i){var r=this;let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5?arguments[5]:void 0;return function*(){const a=yield r.connectionLock.lock();let c,d;try{r.connectOptions=n,r.useV0SignalPath=o;const i=function(e){var t;const n=new mi({capabilities:e,sdk:ua()?gi.REACT_NATIVE:gi.JS,protocol:18,clientProtocol:2,version:Yo});return ua()&&(n.os=null!==(t=ga())&&void 0!==t?t:""),n}(n.clientInfoCapabilities),a=o?function(e,t,n){var i;const r=new URLSearchParams;r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid));r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",ua()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),r.set("client_protocol",t.clientProtocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel);t.os&&r.set("os",t.os);t.osVersion&&r.set("os_version",t.osVersion);t.browser&&r.set("browser",t.browser);t.browserVersion&&r.set("browser_version",t.browserVersion);n.adaptiveStream&&r.set("adaptive_stream","1");n.disableIceLite&&r.set("disable_ice_lite","1");void 0!==n.subscriberAllowPause&&r.set("subscriber_allow_pause",n.subscriberAllowPause?"1":"0");n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type);return r}(t,i,n):yield function(e,t,n,i){return Ao(this,void 0,void 0,(function*(){const r=new URLSearchParams;r.set("access_token",e);const o=new ho({clientInfo:t,connectionSettings:new uo({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream,disableIceLite:!!n.disableIceLite,subscriberAllowPause:n.subscriberAllowPause}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:i});n.reconnectReason&&(o.reconnectReason=n.reconnectReason);const s=o.toBinary();let a,c;if(Qa()){const e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new Uint8Array(s)),t.close();const n=[],i=e.readable.getReader();for(;;){const e=yield i.read(),t=e.done,r=e.value;if(t)break;n.push(r)}const r=n.reduce(((e,t)=>e+t.length),0),o=new Uint8Array(r);let d=0;for(const s of n)o.set(s,d),d+=s.length;a=o,c=mo.GZIP}else a=s,c=mo.NONE;const d=new po({joinRequest:a,compression:c}).toBinary(),l=e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)};return r.set("join_request",l(d).replace(/\+/g,"-").replace(/\//g,"_")),r}))}(t,i,n,s);c=$a(e,a,o).toString(),d=(l=c,tc(new URL(Na(l)),"validate")).toString()}catch(ke){throw a(),ke}var l;if(null==i?void 0:i.aborted)throw a(),r.log.debug("signal connect abandoned before opening a transport"),ss.cancelled("Connection aborted");return new Promise(((e,t)=>Ao(r,void 0,void 0,(function*(){var r,o,s,l,u;try{let a=!1;const h=e=>Ao(this,void 0,void 0,(function*(){if(a)return;a=!0;const n=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;const n=e.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:t;default:return"toString"in n?n.toString():t}}("undefined"!=typeof Event&&e instanceof Event?e.currentTarget:e,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(!0,n))).catch((e=>{this.log.error(e),this.close(!0,n)})):this.close(!0,n),p(),t(e instanceof ss?e:ss.cancelled(n))}));null==i||i.addEventListener("abort",h);const p=()=>{clearTimeout(m),null==i||i.removeEventListener("abort",h)},m=setTimeout((()=>{h(ss.timeout("room connection has timed out (signal)"))}),n.websocketTimeout),g=new URL(c);if(g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.ws){const e=performance.now();yield this.teardownTransport("replaced by a new connection attempt"),this.log.debug("closed previous ws connection in ".concat(performance.now()-e,"ms"))}if(a)return void this.log.debug("signal connect abandoned after tearing down the previous transport");const f=this.attemptId;this.log.info("signal connecting to ".concat(g),{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws=new Kc(c);let v=!1;this.ws.opened.catch((()=>{v=!0}));try{this.ws.closed.then((e=>{this.isEstablishingConnection&&!v&&t(ss.internal("Websocket got closed during a (re)connection attempt: ".concat(e.reason))),this.log.debug("websocket closed",{reason:e.reason,code:e.closeCode,attemptId:f,state:this.lifecycleState}),this.handleOnClose(e.reason||(1e3===e.closeCode?"server closed the signal connection":"Unexpected WS error"),f)})).catch((e=>{this.isEstablishingConnection&&!v&&t(ss.internal("Websocket error during a (re)connection attempt: ".concat(e)))}));const i=yield this.ws.opened.catch((e=>Ao(this,void 0,void 0,(function*(){if(a)this.log.debug("signal connect abandoned while the websocket was opening");else if("connected"===this.lifecycleState)this.handleWSError(e),t(e);else{clearTimeout(m);const n=yield this.handleConnectionError(e,d);t(n)}}))));if(clearTimeout(m),!i)return;const c=i.readable.getReader();let h;this.streamWriter=i.writable.getWriter();try{const e=Date.now()+5e3;for(;;){const t=e-Date.now();if(t<=0)throw ss.timeout("signal connection timed out while waiting for the first message");let n;const i=yield Promise.race([c.read(),new Promise(((e,i)=>{n=setTimeout((()=>{i(ss.timeout("signal connection timed out while waiting for the first message"))}),t)}))]);if(clearTimeout(n),!i.value)throw ss.internal("no message received as first message");const a=nc(i.value);if("reconnecting"!==this.lifecycleState||"reconnect"===(null===(r=a.message)||void 0===r?void 0:r.case)||"leave"===(null===(o=a.message)||void 0===o?void 0:o.case)){h=a;break}this.log.warn("dropping signal message while awaiting reconnect response",{messageCase:null===(s=a.message)||void 0===s?void 0:s.case})}}catch(ke){return c.releaseLock(),t(ke),void this.close()}if(c.releaseLock(),a)return void this.log.debug("signal connect abandoned while waiting for the first message");const p=this.validateFirstMessage(h,null!==(l=n.reconnect)&&void 0!==l&&l);if(!p.isValid)return void t(p.error);"join"===(null===(u=h.message)||void 0===u?void 0:u.case)&&(this.pingTimeoutDuration=h.message.value.pingTimeout,this.pingIntervalDuration=h.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(h.message.value)),this.handleSignalConnected(i,m,f),e(p.response)}catch(ke){t(ke)}finally{p()}}finally{a()}}))))}()}))}startReadingLoop(e){return Ao(this,void 0,void 0,(function*(){const t=this.attemptId;for(;;){this.signalLatency&&(yield Ks(this.signalLatency));try{const t=yield e.read(),n=t.done,i=t.value;if(n)break;const r=nc(i);this.handleSignalResponse(r)}catch(ke){yield this.handleOnClose("error in reading loop",t,void 0,ke);break}}}))}close(){return Ao(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){const i=t&&e.sendLifecycleInput({type:"close",reason:n}),r=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{i&&e.sendLifecycleInput({type:"closeComplete"}),r()}}()}))}teardownTransport(e){return Ao(this,void 0,void 0,(function*(){try{this.clearPingInterval();const t=this.ws;t&&(this.ws=void 0,this.streamWriter=void 0,t.close({closeCode:1e3,reason:e}),yield Promise.race([t.closed,Ks(250)]))}catch(ke){this.log.debug("websocket error while closing",{error:ke})}}))}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Xc(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Xc(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new gr({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new fr({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Ao(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const r=n.getNextRequestId();return yield n.sendRequest({case:"updateMetadata",value:new xr({requestId:r,metadata:e,name:t,attributes:i})}),r}()}))}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 Nr({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Qr({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ve.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new no({timestamp:Ve.parse(Date.now()),rtt:Ve.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Dr({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ar({reason:Cn.CLIENT_INITIATED,action:Lr.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new dr({pubHandle:e,name:t,encryption:n?xn.GCM:xn.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new ur({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Cr({updates:[new wr({trackSid:e,subscribe:t})]})})}sendRequest(e){return Ao(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=Gc.indexOf(e.case)>=0;return wo.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e),r="reconnecting"===t.lifecycleState||t.queuedRequests.length>0;if(i&&r)return void t.queuedRequests.push((()=>Ao(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Ks(t.signalLatency));const o="leave"===e.case&&!!t.streamWriter;if(t.isDisconnected&&!o)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case));const s=new or({message:e});try{t.useJSON?yield t.streamWriter.write(s.toJsonString()):yield t.streamWriter.write(s.toBinary().buffer)}catch(ke){t.log.error("error sending signal message",{error:ke})}}()}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message");let r=!1;if("answer"===i.case){const e=Yc(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=Yc(i.value);this.onOffer&&this.onOffer(e,i.value.id,i.value.midToTrackId)}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(),r=!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)):"mediaSectionsRequirement"===i.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(i.value):"publishDataTrackResponse"===i.case?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(i.value):"unpublishDataTrackResponse"===i.case?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(i.value):"dataTrackSubscriberHandles"===i.case?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(i.value):this.log.debug("unsupported message",{msgCase:i.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.attemptId,i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0;return function*(){const o=t.onClose;t.sendLifecycleInput({type:"transportFailed",attemptId:n,reason:e})?(void 0!==r&&t.log.error("error reading from signal stream",{error:r}),yield t.teardownTransport(e),t.log.info("websocket connection closed: ".concat(e),{reason:e}),i&&(t.log.info("waiting for ".concat(i,"ms until reconnecting signal")),yield Ks(i)),o&&o(e)):t.log.debug("ignoring transport close in state ".concat(t.lifecycleState),Object.assign({reason:e,attemptId:n,currentAttemptId:t.attemptId},void 0!==r?{error:r}:{}))}()}))}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){this.clearPingTimeout(),this.isDisconnected||(this.pingTimeoutDuration?this.pingTimeout=ks.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString())),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set"))}clearPingTimeout(){this.pingTimeout&&ks.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval"),this.pingInterval=ks.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set")}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ks.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){clearTimeout(t);this.sendLifecycleInput("reconnecting"===this.lifecycleState?{type:"reconnectComplete",attemptId:n}:{type:"connectComplete",attemptId:n})?(this.log.info("signal connected"),this.startPingInterval(),this.startReadingLoop(e.readable.getReader())):this.log.debug("discarding a connection whose attempt no longer owns the session",{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState})}validateFirstMessage(e,t){var n,i,r,o;return"join"===(null===(n=e.message)||void 0===n?void 0:n.case)||"reconnecting"===this.lifecycleState&&"reconnect"===(null===(i=e.message)||void 0===i?void 0:i.case)?{isValid:!0,response:e.message.value}:this.isEstablishingConnection&&"leave"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!1,error:ss.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:ss.internal("Unexpected first message")}:{isValid:!1,error:ss.internal("did not receive join response, got ".concat(null===(o=e.message)||void 0===o?void 0:o.case," instead"))}}handleConnectionError(e,t){return Ao(this,void 0,void 0,(function*(){try{const n=yield fetch(t,{signal:wc(3e3)});switch(n.status){case 404:const e=yield n.text();return e.includes("requested room does not exist")?ss.notAllowed(e,n.status):ss.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const t=yield n.text();return ss.notAllowed(t,n.status)}return e instanceof ss?e:ss.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(ke){return ke instanceof ss?ke:ss.serverUnreachable(ke instanceof Error?ke.message:"server was not reachable")}}))}}function Yc(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 Xc(e,t){return new Tr({sdp:e.sdp,type:e.type,id:t})}class Zc{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 n of this._map.entries()){var t=tt(n,2);const i=t[0];t[1].expiresAt<e&&this._map.delete(i)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const n of this._map.entries()){var t=tt(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,i,this.asValueMap())}}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const r of n.entries()){var i=tt(r,2);const o=i[0],s=i[1];t.push(e(s,o,n))}return t}asValueMap(){const e=new Map;for(const n of this._map.entries()){var t=tt(n,2);const i=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(i,r.value)}return e}}var $c,ed,td,nd,id,rd={},od={},sd={exports:{}};function ad(){if($c)return sd.exports;$c=1;var e=sd.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")}))})),sd.exports}function cd(){return ed||(ed=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var r=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:r&&!n[e.name]&&(n[e.name]={});var o=e.push?{}:r?n[e.name]:n;!function(e,n,i,r){if(r&&!i)n[r]=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=ad(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(r))return n(c,s,r)}})),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),r=0;r<i.length;r+=3)n.push({component:i[r],ip:i[r+1],port:i[r+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}}))}))}}(od)),od}function dd(){if(nd)return td;nd=1;var e=ad(),t=/%[sdv%]/g,n=function(e){var n=1,i=arguments,r=i.length;return e.replace(t,(function(e){if(n>=r)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 r=[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 s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return td=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 s=n.outerOrder||r,a=n.innerOrder||o,c=[];return s.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"},td}var ld=function(){if(id)return rd;id=1;var e=cd(),t=dd(),n=ad();return rd.grammar=n,rd.write=t,rd.parse=e.parse,rd.parseParams=e.parseParams,rd.parseFmtpConfig=e.parseFmtpConfig,rd.parsePayloads=e.parsePayloads,rd.parseRemoteCandidates=e.parseRemoteCandidates,rd.parseImageAttributes=e.parseImageAttributes,rd.parseSimulcastStreamList=e.parseSimulcastStreamList,rd}();function ud(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i,r;let o;const s=null!==(i=n.isImmediate)&&void 0!==i&&i,a=null!==(r=n.callback)&&void 0!==r&&r,c=n.maxWait;let d=Date.now(),l=[];const u=function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];const u=this;return new Promise(((n,r)=>{const h=s&&void 0===o;if(void 0!==o&&ks.clearTimeout(o),o=ks.setTimeout((function(){if(o=void 0,d=Date.now(),!s){const t=e.apply(u,i);a&&a(t),l.forEach((e=>(0,e.resolve)(t))),l=[]}}),function(){if(void 0!==c){const e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){const t=e.apply(u,i);return a&&a(t),n(t)}l.push({resolve:n,reject:r})}))};return u.cancel=function(e){void 0!==o&&ks.clearTimeout(o),l.forEach((t=>(0,t.reject)(e))),l=[]},u}const hd=1e3,pd=300,md=1500;function gd(e,t,n){var i,r,o;if(null===(i=e.msid)||void 0===i?void 0:i.includes(t))return null!==(o=null===(r=e.rtp.find((e=>e.codec.toUpperCase()===n.toUpperCase())))||void 0===r?void 0:r.payload)&&void 0!==o?o:0}function fd(e,t){if(e.maxbr<300)return;const n=Math.min(Math.round(.9*e.maxbr),e.maxbr);if(e.isScreenShare)return n;const i=Math.min(function(e){if(void 0===e)return hd;const t=Math.min(Math.max((e-md)/2e3,0),1);return Math.round(hd-700*t)}(t),function(){const e="undefined"!=typeof navigator?navigator.connection:void 0;switch(null==e?void 0:e.effectiveType){case"slow-2g":case"2g":return pd;case"3g":return 500;default:return hd}}());return Math.min(n,i)}const vd="negotiationStarted",kd="negotiationComplete",yd="offerAnswered",bd="rtpVideoPayloadTypes";class Td extends Vo.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=wo,this.iceLog=wo,this.ddExtID=0,this.latestOfferId=0,this.answeredOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.hasAppliedVideoStartBitrate=!1,this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=ud((e=>Ao(this,void 0,void 0,(function*(){this.emit(vd);try{yield this.createAndSendOffer()}catch(ke){if(!e)throw ke;e(ke)}}))),20),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.loggerOptions=n,this.log=Po(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport,(()=>this.logContext)),this.iceLog=Po(e.LoggerNames.ICE,(()=>this.logContext)),this.config=t,this._pc=this.createPC(),this.offerLock=new be}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:e.candidate.candidate}),null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug("ICE candidate error",{event:e}),null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug("data channel opened by peer",{label:e.channel.label,id:e.channel.id}),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 Ao(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)}))}isStaleAnswer(e){return this.latestOfferId>0&&e>0&&e!==this.latestOfferId}setRemoteDescription(e,t){return Ao(this,void 0,void 0,(function*(){var n;if("answer"===e.type&&this.isStaleAnswer(t))return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;if("answer"===e.type){if(function(e,t,n,i,r){return t===e||(e>0?e===n:"stable"===i&&!r)}(t,this.answerInFlight,this.answeredOfferId,null===(n=this._pc)||void 0===n?void 0:n.signalingState,void 0!==this.pendingInitialOffer))return this.log.warn("ignoring duplicate answer",{offerId:t}),!1;this.answerInFlight=t}try{return yield this.applyRemoteDescription(e,t)}finally{"answer"===e.type&&(this.answerInFlight=void 0)}}))}applyRemoteDescription(e,t){return Ao(this,void 0,void 0,(function*(){var n,i;let r;if("offer"===e.type){let t=function(e){var t;const n=[],i=[],r=ld.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let o=0;return r.media.forEach((e=>{var t;const r=Pd(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(o=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===o&&"nack"===e.type)))&&i.push(r),e.fmtp.some((e=>e.payload===o&&(Ed(e.config,"sprop-stereo=1")&&n.push(r),!0))))})),{stereoMids:n,nackMids:i}}(e),n=t.stereoMids,i=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=i}else if("answer"===e.type){if(this.pendingInitialOffer&&this._pc){const e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const t=ld.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{Rd(e)})),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(e,ld.write(t))}const t=ld.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach((e=>{const t=Pd(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 r=!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)),r=!0;break}return r||n.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*n.maxbr)}),!0}))}));const o=this.getPlaceholderMids();o.size>0&&wd(t.media,(e=>o.has(Pd(e.mid)))),r=ld.write(t)}if(yield this.setMungedSDP(e,r,!0),"answer"===e.type&&t>0&&(this.answeredOfferId=t),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,"answer"===e.type&&(this.latestAcknowledgedOfferId=t,this.emit(yd,t)),this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(kd),e.sdp)){ld.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(bd,e.rtp)}))}return!0}))}createInitialOffer(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.offerLock.lock();try{if("stable"!==this.pc.signalingState)return void this.log.warn("signaling state is not stable, cannot create initial offer");const t=this.latestOfferId+1;this.latestOfferId=t;const n=yield this.pc.createOffer();this.pendingInitialOffer={sdp:n.sdp,type:n.type};const i=ld.parse(null!==(e=n.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{Rd(e)})),n.sdp=ld.write(i),{offer:n,offerId:t}}finally{t()}}))}createAndSendOffer(e){return Ao(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.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&("have-local-offer"===this._pc.signalingState||this.pendingInitialOffer)){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t){if(null==e?void 0:e.iceRestart)throw new hs("ICE restart requested without a remote description, peer connection must be recreated");return this.renegotiate=!0,void this.log.debug("requesting renegotiation")}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.log.debug("starting to negotiate");const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:i.sdp});const r=ld.parse(null!==(t=i.sdp)&&void 0!==t?t:""),o=this.hasAppliedVideoStartBitrate?void 0:function(e,t,n){let i;for(const r of e)if("video"===r.type&&"recvonly"!==r.direction&&"inactive"!==r.direction)for(const e of t){if(!e.cid)continue;const t=gd(r,e.cid,e.codec);if(void 0===t)continue;const o=t>0?fd(e,n):void 0;void 0!==o&&(void 0===i||o>i)&&(i=o);break}return i}(r.media,this.trackBitrates,this.connectionSetupTimeEstimateMs());let s=!1;r.media.forEach((e=>{Rd(e),"audio"===e.type?Cd(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!t.cid)return!1;const n=gd(e,t.cid,t.codec);return void 0!==n&&(n>0&&(void 0!==o&&(s=function(e,t,n){const i=e.fmtp.find((e=>e.payload===t));return i?i.config.includes("x-google-start-bitrate")||(i.config+=";x-google-start-bitrate=".concat(n)):e.fmtp.push({payload:t,config:"x-google-start-bitrate=".concat(n)}),!0}(e,n,o)||s),Ys(t.codec)&&!oa()&&(this.ddExtID=function(e,t,n){var i,r;const o=function(e,t){const n=function(e,t){var n;for(const i of e.media){const e=null===(n=i.ext)||void 0===n?void 0:n.find((e=>e.uri===t));if(e)return e.value}return}(e,Ws);if(void 0!==n)return Sd(e,n,Ws)?void 0:n;if(0!==t&&!Sd(e,t,Ws))return t;return function(e){let t=0;return e.media.forEach((e=>{var n;null===(n=e.ext)||void 0===n||n.forEach((e=>{e.value>t&&(t=e.value)}))})),t+1===15?16:t+1}(e)}(t,n);if(void 0===o)return n;(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Ws)))||(null!==(r=e.ext)&&void 0!==r||(e.ext=[]),e.ext.push({value:o,uri:Ws}));return o}(e,r,this.ddExtID))),!0)}))}));const a=this.getPlaceholderMids();if(a.size>0&&wd(r.media,(e=>a.has(Pd(e.mid)))),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:n});const c=ld.write(r);yield this.setMungedSDP(i,c),s&&i.sdp===c&&(this.hasAppliedVideoStartBitrate=!0,this.log.info("applied x-google-start-bitrate",{startBitrateKbps:o,connectionSetupTimeMs:this.connectionSetupTimeEstimateMs()})),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=ld.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Rd(e),"audio"===e.type&&Cd(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,ld.write(n)),t}))}getPlaceholderMids(){var e,t;return function(e){const t=new Set;for(const n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}(null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new us("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConnectionSetupTime(e){this.connectionSetupTimeMs=e}setConnectionStartedAt(e){this.connectionStartedAt=e}connectionSetupTimeEstimateMs(){return void 0!==this.connectionSetupTimeMs?this.connectionSetupTimeMs:void 0!==this.connectionStartedAt?Math.round(performance.now()-this.connectionStartedAt):void 0}setConfiguration(e){var t;if(!this._pc)throw new us("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(){var e;return null===(e=this._pc)||void 0===e?void 0:e.getStats()}getMaxMessageSize(){var e,t;return null===(t=null===(e=this._pc)||void 0===e?void 0:e.sctp)||void 0===t?void 0:t.maxMessageSize}getConnectedAddress(){return Ao(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 r=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==r?i.get(r):void 0}))}setMungedSDP(e,t,n){return Ao(this,void 0,void 0,(function*(){var i,r;const o=e.sdp;if(t){e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description")),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(ke){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),{error:ke,mungedSdp:t,originalSdp:o}),e.sdp=o}}try{n?yield null===(i=this._pc)||void 0===i?void 0:i.setRemoteDescription(e):yield null===(r=this._pc)||void 0===r?void 0:r.setLocalDescription(e)}catch(ke){let r="unknown error";ke instanceof Error?r=ke.message:"string"==typeof ke&&(r=ke);const s={error:r,sdp:e.sdp};throw t&&t!==o&&(s.mungedSdp=t),!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:s}),new hs(r)}}))}}function Sd(e,t,n){return e.media.some((e=>{var i;return null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.value===t&&e.uri!==n))}))}function Ed(e,t){return e.split(";").some((e=>e.trim()===t))}function Cd(e,t,n){const i=Pd(e.mid);let r=0;e.rtp.some((e=>"opus"===e.codec.toLowerCase()&&(r=e.payload,!0))),r>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(i)&&!e.rtcpFb.some((e=>e.payload===r&&"nack"===e.type))&&e.rtcpFb.push({payload:r,type:"nack"}),(t.includes(i)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===r&&(Ed(e.config,"stereo=1")||(e.config+=";stereo=1"),!0))))}function wd(e,t){var n,i,r,o,s,a,c,d;const l=new Map;for(const u of e){const e=t(u);for(const t of null!==(n=u.rtp)&&void 0!==n?n:[]){const n=t.payload,s=null!==(o=null===(r=null===(i=u.fmtp)||void 0===i?void 0:i.find((e=>e.payload===n)))||void 0===r?void 0:r.config)&&void 0!==o?o:"";e&&l.has(n)||l.set(n,s)}}for(const u of e)if(t(u))for(const e of null!==(s=u.rtp)&&void 0!==s?s:[]){const t=e.payload,n=l.get(t),i=null===(a=u.fmtp)||void 0===a?void 0:a.find((e=>e.payload===t));""===n?u.fmtp=(null!==(c=u.fmtp)&&void 0!==c?c:[]).filter((e=>e.payload!==t)):i?i.config=n:u.fmtp=[...null!==(d=u.fmtp)&&void 0!==d?d:[],{payload:t,config:n}]}}function Rd(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Pd(e){return"number"==typeof e?e.toFixed(0):e}const Id=7e3,_d=[0,300,1200,2700,4800,Id,Id,Id,Id,Id];class Od{constructor(e){this._retryDelays=void 0!==e?[...e]:_d}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return 0===e.retryCount&&0===t?500*Math.random():Math.round(t*(.5+Math.random()))}}const Dd="vp8",Md={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,stopMicTrackOnMute:!1,preConnectBuffer:!1},Ad={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Ld={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Od,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Nd={autoSubscribe:!0,disableIceLite:!1,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var xd,Ud;!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"}(xd||(xd={}));class Fd{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=i.rtcConfig,o=i.peerConnectionTimeout,s=void 0===o?Nd.peerConnectionTimeout:o;var a;this.log=wo,this.iceLog=wo,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=xd.CONNECTED:i.some((e=>"failed"===e))?this.state=xd.FAILED:i.some((e=>"connecting"===e))?this.state=xd.CONNECTING:i.every((e=>"closed"===e))?this.state=xd.CLOSED:i.some((e=>"closed"===e))?this.state=xd.CLOSING:i.every((e=>"new"===e))&&(this.state=xd.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(xd[n]," to ").concat(xd[this.state])),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.loggerOptions=n,this.peerConnectionTimeout=s,this.log=Po(null!==(a=n.loggerName)&&void 0!==a?a:e.LoggerNames.PCManager,(()=>this.logContext)),this.iceLog=Po(e.LoggerNames.ICE,(()=>this.logContext)),this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new Td(r,n),this._mode=t,"publisher-only"!==t&&(this.subscriber=new Td(r,n),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tr.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.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tr.PUBLISHER)},this.publisher.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=xd.NEW,this.connectionLock=new be,this.remoteOfferLock=new be}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()}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 Ao(this,void 0,void 0,(function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(ke){this.log.warn("could not removeTrack",{error:ke})}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return Ao(this,void 0,void 0,(function*(){this.iceLog.warn("triggering ICE restart"),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Ao(this,void 0,void 0,(function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===tr.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()});const o=yield this.remoteOfferLock.lock();try{if(!(yield null===(i=this.subscriber)||void 0===i?void 0:i.setRemoteDescription(e,t)))return;return yield null===(r=this.subscriber)||void 0===r?void 0:r.createAndSetAnswer()}finally{o()}}))}updateConfiguration(e,t){var n;this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Ao(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.publisher.negotiate().catch((e=>{this.log.error(e)}))),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 Ao(this,void 0,void 0,(function*(){return new Wo(((t,n)=>{const i=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>i)return this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),void t();let r=!1;const o=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(yd,s),e.signal.removeEventListener("abort",a))},s=e=>{e>i&&(o(),t())},a=()=>{o(),n(new hs("negotiation aborted"))},c=setTimeout((()=>{o(),n(new hs("negotiation timed out"))}),this.peerConnectionTimeout);e.signal.addEventListener("abort",a),this.publisher.on(yd,s),this.publisher.negotiate((e=>{o(),e instanceof Error?n(e):n(new Error(String(e)))}))}))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getTransceiverForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((t=>t.receiver===e))}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===tr.PUBLISHER||e===tr.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Ao(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,r)=>Ao(n,void 0,void 0,(function*(){const n=()=>{this.log.warn("abort transport connection"),ks.clearTimeout(s),r(ss.cancelled("room connection has been cancelled"))};let o=!1;const s=ks.setTimeout((()=>{o=!0,null==t||t.signal.removeEventListener("abort",n),r(ss.internal("could not establish pc connection"))}),i);for((null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);this.state!==xd.CONNECTED;){if(yield Ks(50),o)return;if(null==t?void 0:t.signal.aborted)return void r(ss.cancelled("room connection has been cancelled"))}ks.clearTimeout(s),null==t||t.signal.removeEventListener("abort",n),e()}))))}()}))}}class jd{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new be,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){const t=this.handle;this.handle=e,t&&t!==e&&this.release(t,"data channel replaced")}detach(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"data channel torn down";const t=this.handle;this.handle=void 0,t&&this.release(t,e)}release(e,t){this.invalidateWaiters(t),e.close()}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(e){return Ao(this,void 0,void 0,(function*(){const t=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock(e)}finally{t()}}))}waitForHeadroomWithoutLock(e){return Ao(this,void 0,void 0,(function*(){if(this.isEngineClosed())throw new us("engine closed");if("open"!==e.readyState)throw new us("DataChannel ".concat(this.kind," is ").concat(e.readyState));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new Wo(((n,i)=>{const r=()=>{a(),n()},o=()=>{a(),i(new us("DataChannel ".concat(this.kind," closed while draining the buffer")))},s=()=>{a(),i(new us("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},a=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",o),t.removeEventListener("abort",s)};t.aborted?s():(e.addEventListener("bufferedamountlow",r),e.addEventListener("close",o),t.addEventListener("abort",s))}))}))}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,null===(e=this.onBufferStatusChanged)||void 0===e||e.call(this,n))}}class Bd extends jd{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return Ao(this,void 0,void 0,(function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":if(!this.isBelowHighWaterMark(t))try{yield this.waitForHeadroomWithLock(t)}catch(n){if(this.isEngineClosed())throw n;return}break;case"drop":if(!this.isBelowLowWaterMark(t))return this.dropCount+=1,void(this.dropCount%100==0&&wo.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount)))}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(!(n instanceof TypeError))throw n;wo.error(n)}}}))}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=ks.setInterval((()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}}),1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(ks.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class qd{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter((e=>!e.sent))}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(!t.sent)break;if(this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Vd extends jd{constructor(e){super(e),this.messageBuffer=new qd,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return Ao(this,void 0,void 0,(function*(){if(this.isDeferringSends())return void this.messageBuffer.push({data:e,sequence:t,sent:!1});const n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock(n)}catch(i){if(this.isEngineClosed())throw i;return void this.messageBuffer.push({data:e,sequence:t,sent:!1})}this.isDeferringSends()?this.messageBuffer.push({data:e,sequence:t,sent:!1}):(this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus())}}))}replay(e){return Ao(this,void 0,void 0,(function*(){if(!this.getChannel())return;this.messageBuffer.popToSequence(e);const t=yield this.lockHeadroom();try{const e=this.getChannel();if(!e)throw new us("DataChannel not found, kind: ".concat(this.kind));this.messageBuffer.markAllUnsent();for(let t=this.messageBuffer.getUnsent();t.length>0;t=this.messageBuffer.getUnsent())for(const n of t)yield this.waitForHeadroomWithoutLock(e),e.send(n.data),this.messageBuffer.markSent(n)}finally{t()}this.refreshBufferStatus()}))}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new qd,this.sequence=1}}!function(e){e[e.RELIABLE=0]="RELIABLE",e[e.LOSSY=1]="LOSSY",e[e.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"}(Ud||(Ud={}));function Wd(e){return e===Ud.RELIABLE?65536:8192}function Hd(e){return e===Ud.RELIABLE?1048576:262144}const Kd="_lossy",zd="_reliable",Gd="_data_track";function Jd(e){e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null}class Qd{constructor(e){this.negotiated=!1,this.opts=e;const t=t=>({kind:t,lowWaterMark:Wd(t),highWaterMark:Hd(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new Vd(Object.assign(Object.assign({},t(Ud.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new Bd(Object.assign(Object.assign({},t(Ud.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new Bd(Object.assign(Object.assign({},t(Ud.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case Ud.RELIABLE:return this.reliable;case Ud.LOSSY:return this.lossy;case Ud.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&void 0!==arguments[1]&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case Ud.RELIABLE:return this.reliableSub;case Ud.LOSSY:return this.lossySub;case Ud.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return Boolean(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}get publisherChannelsNegotiated(){return this.hasPublisherChannels&&this.negotiated}createPublisherChannels(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];for(const r of[this.lossy,this.reliable,this.dataTrack]){const e=r.channelHandle;e&&Jd(e)}const n=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)},i=e=>t?{negotiated:t,id:e}:{};n(this.lossy,e.createPublisherDataChannel(Kd,Object.assign({ordered:!1,maxRetransmits:0},i(ir.NDCI_LOSSY))),this.opts.onDataMessage),n(this.reliable,e.createPublisherDataChannel(zd,Object.assign({ordered:!0},i(ir.NDCI_RELIABLE))),this.opts.onDataMessage),n(this.dataTrack,e.createPublisherDataChannel(Gd,Object.assign({ordered:!1,maxRetransmits:0},i(ir.NDCI_DATA_TRACK))),this.opts.onDataTrackMessage),this.negotiated=t,this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===zd)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===Kd)this.lossySub=e,t=this.opts.onDataMessage;else{if(e.label!==Gd)return!1;this.dataTrackSub=e,t=this.opts.onDataTrackMessage}return e.onmessage=t,!0}teardown(){const e=[this.lossy,this.reliable,this.dataTrack],t=[this.lossySub,this.reliableSub,this.dataTrackSub];for(const n of e){const e=n.channelHandle;e&&Jd(e),n.detach("peer connections cleaned up")}for(const n of t)n&&(Jd(n),n.close());this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const Yd="leave-reconnect";var Xd;!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"}(Xd||(Xd={}));class Zd extends Vo.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get serverVersion(){var e,t,n;return(null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.serverInfo)||void 0===t?void 0:t.version)||(null===(n=this.latestJoinResponse)||void 0===n?void 0:n.serverVersion)||void 0}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Nd.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Xd.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=wo,this.reliableReceivedState=new Zc(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.pendingNegotiationAborts=new Set,this.handleDataChannel=e=>Ao(this,[e],void 0,(function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug("on data channel ".concat(n.id,", ").concat(n.label))}()})),this.handleDataMessage=t=>Ao(this,void 0,void 0,(function*(){var n,i,r,o;const s=yield this.dataProcessLock.lock();try{const s=yield this.decodeDataMessage(t);if(!s)return;const c=Yn.fromBinary(s);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");let t;try{t=yield this.e2eeManager.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex)}catch(a){return void this.log.debug("failed to decrypt data packet",{error:a,participantIdentity:c.participantIdentity})}const n=$n.fromBinary(t.payload),i=new Yn({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(r=i.value)||void 0===r?void 0:r.case)&&$d(i,i.value.value),this.emit(e.EngineEvent.DataPacketReceived,i,c.value.value.encryptionType)}else"user"===(null===(o=c.value)||void 0===o?void 0:o.case)&&$d(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,xn.NONE)}finally{s()}})),this.handleDataTrackMessage=e=>Ao(this,void 0,void 0,(function*(){const t=yield this.decodeDataMessage(e);t&&this.emit("dataTrackPacketReceived",t)})),this.handleDataError=e=>{if(this._isClosed)return;const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if("undefined"!=typeof RTCErrorEvent&&e instanceof RTCErrorEvent&&e.error){const n=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(n.message),{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(t),{event:e})},this.handleDataChannelClose=e=>()=>{var t;this._isClosed||"connected"!==(null===(t=this.pcManager)||void 0===t?void 0:t.publisher.getConnectionState())||this.log.error("publisher data channel '".concat(Ud[e],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected")),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.emit(e.EngineEvent.Disconnected),this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms"))},r=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(null===o)return void i(r);if(t===Yd&&(o=this.getNextRetryDelay({elapsedMs:r,retryCount:0}),null===o))return void i(r);this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(e.EngineEvent.TokenRefreshed,this.token);const s=ks.setTimeout((()=>this.attemptReconnect(n).finally((()=>{this.reconnectTimeout===s&&(this.reconnectTimeout=void 0)}))),o);this.reconnectTimeout=s},this.waitForRestarted=t=>new Promise((n=>{if(t.aborted)return void n(!1);const i=()=>{t.removeEventListener("abort",r),n(!0)},r=()=>{t.removeEventListener("abort",r),this.off(e.EngineEvent.Restarted,i),n(!1)};this.once(e.EngineEvent.Restarted,i),t.addEventListener("abort",r)})),this.onRtpMapAvailable=t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();Ma(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)},this.handleBrowserOnLine=()=>Ao(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(Na(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===Jc.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Jc.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(wn.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Ao(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Na(this.url),{method:"HEAD"}),Ks(4e3).then((()=>Promise.reject()))])}catch(ke){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=Po(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine,(()=>this.logContext)),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new Qc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new be,this.dataProcessLock=new be,this.dataChannels=new Qd({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(t,n)=>this.emit(e.EngineEvent.DCBufferStatusChanged,n,t)}),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>{this.handleLocalConnectionQuality(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),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onJoined=t=>this.emit(e.EngineEvent.Joined,t);const i=()=>{for(const e of Array.from(this.pendingNegotiationAborts))e()};this.on(e.EngineEvent.Closing,i),this.on(e.EngineEvent.Restarting,i)}get logContext(){var e,t,n,i,r,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===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===o?void 0:o.identity,participantID:this.participantSid}}join(t,n,i,r){return Ao(this,arguments,void 0,(function(t,n,i,r){var o=this;let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];return function*(){var a,c,d,l;o._isNewlyCreated=!1,o.url=t,o.token=n,o.signalOpts=i,o.maxJoinAttempts=i.maxRetries;try{o.joinAttempts+=1,o.joinStartedAt=performance.now(),o.setupSignalClientCallbacks();const u=!s&&Qa()&&!na();let h;if(u){o.pcManager||(yield o.configure(),o.applyInitialPublisherLayout(!0));const e=yield null===(a=o.pcManager)||void 0===a?void 0:a.publisher.createInitialOffer();e&&(h=Xc(e.offer,e.offerId))}if(null==r?void 0:r.aborted)throw ss.cancelled("Connection aborted");if(!s&&o.shouldFailOnV1Path)throw o.shouldFailOnV1Path=!1,ss.serviceNotFound("Simulated v1 path failure","v0-rtc");const p=yield o.client.join(t,n,i,r,s,h);if(null==r?void 0:r.aborted)throw o.log.info("join cancelled after the signal join response"),ss.cancelled("Connection aborted");if(o._isClosed=!1,o.latestJoinResponse=p,o.participantSid=null===(c=p.participant)||void 0===c?void 0:c.sid,o.subscriberPrimary=p.subscriberPrimary,u)null===(d=o.pcManager)||void 0===d||d.updateConfiguration(o.makeRTCConfiguration(p)),o.dataChannels.publisherChannelsNegotiated&&!o.useNegotiatedDataChannels()&&(o.log.debug("server does not support negotiated data channels, using in-band ones"),o.createDataChannels(!1));else{if(!o.pcManager){if(yield o.configure(p,!s),null==r?void 0:r.aborted)throw o.log.info("join cancelled after configuring peer connections"),ss.cancelled("Connection aborted");s||o.applyInitialPublisherLayout()}o.subscriberPrimary&&!p.fastPublish||o.negotiate().catch((e=>{o.log.error(e)}))}void 0!==o.joinStartedAt&&(null===(l=o.pcManager)||void 0===l||l.publisher.setConnectionStartedAt(o.joinStartedAt)),o.registerOnLineListener(),o.clientConfiguration=p.clientConfiguration,o.emit(e.EngineEvent.SignalConnected,p);let m=p.serverInfo;return m||(m={version:p.serverVersion,region:p.serverRegion}),o.log.info("connected to Livekit Server ".concat(Object.entries(m).map((e=>{let t=tt(e,2),n=t[0],i=t[1];return"".concat(n,": ").concat(i)})).join(", "))),{joinResponse:p,serverInfo:m}}catch(ke){if(ke instanceof ss)if(ke.reason===e.ConnectionErrorReason.ServerUnreachable){if(o.log.warn("Couldn't connect to server, attempt ".concat(o.joinAttempts," of ").concat(o.maxJoinAttempts)),o.joinAttempts<o.maxJoinAttempts)return o.join(t,n,i,r,s)}else if(ke.reason===e.ConnectionErrorReason.ServiceNotFound)return o.log.warn("Initial connection failed: ".concat(ke.message," – Retrying")),o.pcManager&&(o.pcManager.onStateChange=void 0,yield o.cleanupPeerConnections()),o.join(t,n,i,r,!0);throw ke}}()}))}close(t){return Ao(this,void 0,void 0,(function*(){var n,i;null===(n=this.reconnectAbortController)||void 0===n||n.abort(),this.reconnectAbortController=void 0,null===(i=this.restartAttemptController)||void 0===i||i.abort(),this.restartAttemptController=void 0;const r=yield this.closingLock.lock();if(this.isClosed)r();else try{this._isClosed=!0,this.joinAttempts=0,this.joinStartedAt=void 0,this.emit(e.EngineEvent.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(t)}finally{r()}}))}cleanupPeerConnections(){return Ao(this,void 0,void 0,(function*(){var e;this.dataChannels.teardown(),yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()}))}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return Ao(this,void 0,void 0,(function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new ds("a track with the same ID has already been published");return new Promise(((t,n)=>{const i=ks.setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],n(ss.timeout("publication of local track timed out, no response from server"))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{ks.clearTimeout(i),t(e)},reject:()=>{ks.clearTimeout(i),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(ke){this.log.warn("failed to remove track",{error:ke})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.dataChannelForKind(Ud.RELIABLE,!0))||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Ao(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionStrategy(e){this.regionStrategy=e}configure(t,n){return Ao(this,void 0,void 0,(function*(){var i;if(!this.pcManager||this.pcManager.currentState===xd.NEW){if(t){this.participantSid=null===(i=t.participant)||void 0===i?void 0:i.sid;const e=this.makeRTCConfiguration(t);this.pcManager=new Fd(n?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,{rtcConfig:e,peerConnectionTimeout:this.peerConnectionTimeout})}else{const e=this.makeRTCConfiguration();this.pcManager=new Fd("publisher-only",this.loggerOptions,{rtcConfig:e,peerConnectionTimeout:this.peerConnectionTimeout})}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=(t,n,i)=>Ao(this,void 0,void 0,(function*(){var r;if(this.log.debug("primary PC state changed ".concat(t)),t===xd.CONNECTING?this.transportConnectingSince=Date.now():this.transportConnectingSince=void 0,["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===xd.CONNECTED){if(void 0!==this.joinStartedAt){const e=Math.round(performance.now()-this.joinStartedAt);this.joinStartedAt=void 0,this.log.info("connection setup took ".concat(e," ms")),null===(r=this.pcManager)||void 0===r||r.publisher.setConnectionSetupTime(e)}const t=this.pcState===Xd.New;this.pcState=Xd.Connected,t&&this.emit(e.EngineEvent.Connected,this.latestJoinResponse)}else t===xd.FAILED&&(this.pcState!==Xd.Connected&&this.pcState!==Xd.Reconnecting||(this.pcState=Xd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?wn.RR_SUBSCRIBER_FAILED:wn.RR_PUBLISHER_FAILED)));const o=this.client.isDisconnected||this.client.currentState===Jc.RECONNECTING,s=[xd.FAILED,xd.CLOSING,xd.CLOSED].includes(t);o&&s&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)}}}))}setupSignalClientCallbacks(){this.client.onAnswer=(t,n,i)=>Ao(this,void 0,void 0,(function*(){this.pcManager&&(this.pcManager.publisher.isStaleAnswer(n)?this.log.warn("ignoring answer for old offer",{offerId:n,latestOfferId:this.pcManager.publisher.latestOfferId}):(this.log.debug("received server answer",{RTCSdpType:t.type,sdp:t.sdp,midToTrackId:i}),"publisher-only"===this.pcManager.mode&&Object.keys(i).length>0&&(this.midToTrackId=i),yield this.pcManager.setPublisherAnswer(t,n),this.emit(e.EngineEvent.RequestSubscribedCodecRefresh)))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>Ao(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;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",{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),{cid:e.cid});const n=this.pendingTrackResolvers[e.cid].resolve;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=t=>{this.token=t,this.emit(e.EngineEvent.TokenRefreshed,t)},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.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate().catch((e=>{this.log.error(e)}))},this.client.onPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.PublishDataTrackResponse,t)},this.client.onUnPublishDataTrackResponse=t=>{this.emit(e.EngineEvent.UnPublishDataTrackResponse,t)},this.client.onDataTrackSubscriberHandles=t=>{this.emit(e.EngineEvent.DataTrackSubscriberHandles,t)},this.client.onClose=()=>{this.handleDisconnect("signal",wn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{var n;switch(this.log.info("client leave request received (action=".concat(null==t?void 0:t.action,")"),{reason:null==t?void 0:t.reason}),t.regions&&(this.log.debug("updating regions"),this.emit(e.EngineEvent.ServerRegionsReported,t.regions)),t.action){case Lr.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close("server leave: ".concat(null!==(n=Cn[t.reason])&&void 0!==n?n:t.reason));break;case Lr.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Yd);break;case Lr.RESUME:this.handleDisconnect(Yd)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!mc())&&dc()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){const 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===En.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(e){this.createDataChannels(e),ua()||this.addMediaSections(3,3)}addMediaSections(e,t){var n,i,r;const o={direction:"recvonly"};for(let a=0;a<e;a++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("audio",o);const s="publisher-only"===(null===(i=this.pcManager)||void 0===i?void 0:i.mode);for(let a=0;a<t;a++){const e=null===(r=this.pcManager)||void 0===r?void 0:r.addPublisherTransceiverOfKind("video",o);if(s&&e){const t=Xs(e);this.log.debug("dependency descriptor negotiated for received video",{negotiated:t})}}}useNegotiatedDataChannels(){var e,t,n,i;return"publisher-only"===(null===(e=this.pcManager)||void 0===e?void 0:e.mode)&&(null!==(i=null===(n=null===(t=this.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===n?void 0:n.protocol)&&void 0!==i?i:0)>=18}createDataChannels(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.useNegotiatedDataChannels();this.pcManager&&(this.dataChannels.hasPublisherChannels&&(this.publisherConnectionPromise=void 0),this.dataChannels.createPublisherChannels(this.pcManager,e))}decodeDataMessage(e){return Ao(this,void 0,void 0,(function*(){return e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data instanceof Blob?new Uint8Array(yield e.data.arrayBuffer()):void this.log.error("unsupported data type",{data:e.data})}))}createSender(e,t,n){return Ao(this,void 0,void 0,(function*(){let i;if(zs())i=yield this.createTransceiverRTCRtpSender(e,t,n);else{if(!Gs())throw new us("Required webRTC APIs not supported on this device");this.log.warn("using add-track fallback"),i=yield this.createRTCRtpSender(e.mediaStreamTrack)}return this.setupFrameMetadataSender(i,t),i}))}createSimulcastSender(e,t,n,i){return Ao(this,void 0,void 0,(function*(){let r;if(zs())r=yield this.createSimulcastTransceiverSender(e,t,n,i);else{if(!Gs())throw new us("Cannot stream on this device");this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack)}return r&&this.setupFrameMetadataSender(r,n),r}))}get frameMetadataWorker(){var e;return null===(e=this.frameMetadataOptions)||void 0===e?void 0:e.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=this.frameMetadataWorker;if(!i||(null===(n=this.signalOpts)||void 0===n?void 0:n.e2eeEnabled))return;const r=vc(t),o=fc(r);if(mc())return void(o&&(e.transform=new RTCRtpScriptTransform(i,{kind:"encode",packetTrailer:r})));if(!gc(this.frameMetadataOptions)||!("createEncodedStreams"in e))return void(o&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext));const s=e.createEncodedStreams(),a=s.readable,c=s.writable;o?i.postMessage({kind:"encode",data:{readableStream:a,writableStream:c,packetTrailer:r}},[a,c]):a.pipeTo(c)}createTransceiverRTCRtpSender(e,t,n){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),qa(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};n&&(r.sendEncodings=n);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender}))}createSimulcastTransceiverSender(e,t,n,i){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const o=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,o.sender),o.sender}))}createRTCRtpSender(e){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}handleLocalConnectionQuality(e){if(!this.participantSid)return;const t=e.updates.find((e=>e.participantSid===this.participantSid));t&&(t.quality===Sn.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||(this.lostQualityTimeout=ks.setTimeout((()=>{this.lostQualityTimeout=void 0,this._isClosed||this.pcState!==Xd.Connected||this.attemptingReconnect||this.hasActivePublisherSenders()&&(this.log.warn("local connection quality lost while publishing, triggering full reconnect",this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect("connection quality lost",wn.RR_PUBLISHER_FAILED))}),1e4))}clearLostQualityTimeout(){this.lostQualityTimeout&&(ks.clearTimeout(this.lostQualityTimeout),this.lostQualityTimeout=void 0)}hasActivePublisherSenders(){var e,t;return null!==(t=null===(e=this.pcManager)||void 0===e?void 0:e.publisher.getSenders().some((e=>!!e.track&&"live"===e.track.readyState)))&&void 0!==t&&t}reconnect(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:wn.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect("reconcile",e)}attemptReconnect(t){return Ao(this,void 0,void 0,(function*(){var n,i,r;if(this._isClosed)return;if(this.attemptingReconnect)return void this.log.warn("already attempting reconnect, returning early");this.clearLostQualityTimeout(),(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==En.DISABLED&&(null!==(r=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==r?r:xd.NEW)!==xd.NEW||(this.fullReconnectOnNext=!0);const o=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let s=!1;const a=new AbortController;this.reconnectAbortController=a;try{if(this.attemptingReconnect=!0,o?yield this.restartConnection(a.signal):yield this.resumeConnection(t),a.signal.aborted)return void this.log.info("reconnect attempt cancelled, not marking it as succeeded");this.clearPendingReconnect(),s=!0}catch(ke){if(a.signal.aborted)return void this.log.info("reconnect attempt cancelled, not retrying",{error:ke});this.reconnectAttempts+=1;let n=!0;ke instanceof us?(this.log.debug("received unrecoverable error",{error:ke}),n=!1):!o&&ke instanceof vs||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",wn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(e.EngineEvent.Disconnected),yield this.close("gave up reconnecting after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms")))}finally{this.reconnectAbortController===a&&(this.reconnectAbortController=void 0),this.attemptingReconnect=!1,s&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug("full reconnect requested during in-progress attempt, dispatching"),this.handleDisconnect("reconnect"))}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(ke){this.log.warn("encountered error in reconnect policy",{error:ke})}return null}restartConnection(t,n){return Ao(this,void 0,void 0,(function*(){var i,r,o,s;try{if(t.aborted)return void this.log.info("full reconnect cancelled before starting",{regionUrl:n});if(!this.url||!this.token)throw new us("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),null===(i=this.restartAttemptController)||void 0===i||i.abort();const o=new AbortController;if(this.restartAttemptController=o,this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient(),t.aborted)return void this.log.info("full reconnect cancelled after cleaning up the previous session",{regionUrl:n});let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new vs;s=(yield this.join(null!=n?n:this.url,this.token,this.signalOpts,t,!this.options.singlePeerConnection)).joinResponse}catch(ke){if(ke instanceof ss&&ke.reason===e.ConnectionErrorReason.NotAllowed)throw new us("could not reconnect, token might be expired");throw new vs}if(t.aborted)return void this.log.info("full reconnect cancelled after the signal join response",{regionUrl:n});if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,s,o.signal),yield this.waitForPCReconnected(),t.aborted)return void this.log.info("full reconnect cancelled after peer connections reconnected",{regionUrl:n});if(this.client.currentState!==Jc.CONNECTED)throw new vs("Signal connection got severed during reconnect");null===(r=this.regionStrategy)||void 0===r||r.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(a){if(t.aborted)return void this.log.info("full reconnect cancelled after a failed attempt",{regionUrl:n});const e=yield null===(o=this.regionStrategy)||void 0===o?void 0:o.getNextUrl(t);if(t.aborted)return void this.log.info("full reconnect cancelled during region selection",{regionUrl:n});if(e)return void(yield this.restartConnection(t,e));throw null===(s=this.regionStrategy)||void 0===s||s.resetAttempts(),a}}))}resumeConnection(t){return Ao(this,void 0,void 0,(function*(){if(!this.url||!this.token)throw new us("could not reconnect, url or token not saved");if(!this.pcManager)throw new us("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(r){let t="";if(r instanceof Error&&(t=r.message,this.log.error(r.message,{error:r})),r instanceof ss&&r.reason===e.ConnectionErrorReason.NotAllowed)throw new us("could not reconnect, token might be expired");if(r instanceof ss&&r.reason===e.ConnectionErrorReason.LeaveRequest)throw r;throw new vs(t)}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");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Jc.CONNECTED)throw new vs("Signal connection got severed during reconnect");this.client.setReconnected();const i=this.dataChannelForKind(Ud.RELIABLE);"open"===(null==i?void 0:i.readyState)&&null===i.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq).catch((e=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:e}))})),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(t,n){return Ao(this,void 0,void 0,(function*(){if(!this.pcManager)throw new us("PC manager is closed");let i=!1;const r=()=>{i=!0};let o,s,a,c;const d=new Promise(((i,r)=>{o=i,s=()=>r(ss.internal("could not establish pc connection")),a=()=>r(ss.cancelled("room connection has been cancelled")),this.once(e.EngineEvent.Restarted,o),this.once(e.EngineEvent.Closing,s),null==n||n.signal.addEventListener("abort",a),c=ks.setTimeout(s,null!=t?t:this.peerConnectionTimeout)}));this.once(e.EngineEvent.Restarting,r);try{yield Promise.race([this.pcManager.ensurePCTransportConnection(n,t),d]),i&&(yield d)}finally{ks.clearTimeout(c),null==n||n.signal.removeEventListener("abort",a),this.off(e.EngineEvent.Restarting,r),this.off(e.EngineEvent.Restarted,o),this.off(e.EngineEvent.Closing,s)}}))}waitForPCReconnected(){return Ao(this,void 0,void 0,(function*(){this.pcState=Xd.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Ks(2e3),!this.pcManager)throw new us("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Xd.Connected}catch(ke){throw this.pcState=Xd.Disconnected,ss.internal("could not establish PC connection, ".concat(ke.message))}}))}publishRpcAck(e,t){return Ao(this,void 0,void 0,(function*(){const n=new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcAck",value:new ci({requestId:t})}});yield this.sendDataPacket(n,Ud.RELIABLE)}))}sendDataPacket(e,t){return Ao(this,void 0,void 0,(function*(){var n,i;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=pc(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Zn({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===Ud.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const r=e.toBinary(),o=Math.min(null!==(i=null===(n=this.pcManager)||void 0===n?void 0:n.getMaxPublisherMessageSize())&&void 0!==i?i:64e3,64e3);if(void 0!==o&&0!==o&&r.byteLength>o)throw new ps("cannot publish data packet larger than ".concat(o," bytes (got ").concat(r.byteLength,")"));t===Ud.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)}))}sendDataTrackFrame(e){return Ao(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Ud.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)}))}resendReliableMessagesForResume(e){return Ao(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(Ud.RELIABLE),yield this.reliableChannel.replay(e)}))}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return Ao(this,void 0,void 0,(function*(){const t=this.dataChannelForKind(e);if(!t)throw new us("DataChannel not found, kind: ".concat(e));return this.flowControlFor(e).waitForHeadroomWithLock(t)}))}ensureDataTransportConnected(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var i;if(!t.pcManager)throw new us("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,o=n?"Subscriber":"Publisher";if(!r)throw ss.internal("".concat(o," connection not set"));let s=!1;n||t.dataChannelForKind(e,n)||(t.createDataChannels(),s=!0),s||n||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(s=!0),s&&t.negotiate().catch((e=>{t.log.error(e)}));const a=t.dataChannelForKind(e,n);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(r.isICEConnected&&"open"===(null===(i=t.dataChannelForKind(e,n))||void 0===i?void 0:i.readyState))return;yield Ks(50)}throw ss.internal("could not establish ".concat(o," connection, state: ").concat(r.getICEConnectionState()))}()}))}ensurePublisherConnected(e){return Ao(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){if(!this.pcManager)return!1;const e=this.pcManager.currentState;return!![xd.CONNECTING,xd.CONNECTED].includes(e)&&(!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)&&(!(e===xd.CONNECTING&&void 0!==this.transportConnectingSince&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout)||(this.log.warn("transport stuck in connecting state",this.logContext),!1)))}negotiate(){return Ao(this,void 0,void 0,(function*(){return new Wo(((e,t)=>Ao(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new hs("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.dataChannels.hasPublisherChannels||this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new hs("cannot negotiate on closed engine")),this.pendingNegotiationAborts.add(i),this.pcManager.publisher.off(bd,this.onRtpMapAvailable),this.pcManager.publisher.once(bd,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(ke){if(n.signal.aborted)return void e();ke instanceof hs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",wn.RR_UNKNOWN),ke instanceof Error?t(ke):t(new Error(String(ke)))}finally{this.pendingNegotiationAborts.delete(i)}}))))}))}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var i,r,o,s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup");const a=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getRemoteDescription(),l=null===(r=this.pcManager.subscriber)||void 0===r?void 0:r.getLocalDescription(),u=null===(s=null===(o=this.signalOpts)||void 0===o?void 0:o.autoSubscribe)||void 0===s||s,h=new Array,p=new Array;e.forEach((e=>{e.isDesired!==u&&h.push(e.trackSid),e.isEnabled||p.push(e.trackSid)})),this.client.sendSyncState(new Zr({answer:"publisher-only"===this.pcManager.mode?c?Xc({sdp:c.sdp,type:c.type}):void 0:l?Xc({sdp:l.sdp,type:l.type}):void 0,offer:"publisher-only"===this.pcManager.mode?a?Xc({sdp:a.sdp,type:a.type}):void 0:d?Xc({sdp:d.sdp,type:d.type}):void 0,subscription:new Er({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ls(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new $r({publisherSid:t,lastSeq:e}))),publishDataTracks:n}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new eo({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(Ud.LOSSY),tr.PUBLISHER),t(this.dataChannelForKind(Ud.RELIABLE),tr.PUBLISHER),t(this.dataChannelForKind(Ud.LOSSY,!0),tr.SUBSCRIBER),t(this.dataChannelForKind(Ud.RELIABLE,!0),tr.SUBSCRIBER),t(this.dataChannelForKind(Ud.DATA_TRACK_LOSSY),tr.PUBLISHER),t(this.dataChannelForKind(Ud.DATA_TRACK_LOSSY,!0),tr.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&(ks.clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){la()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){la()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t,n;const i=null===(n=null===(t=this.pcManager)||void 0===t?void 0:t.getTransceiverForReceiver(e))||void 0===n?void 0:n.mid;if(i){const e=Object.entries(this.midToTrackId).find((e=>tt(e,1)[0]===i));if(e)return e[1]}}}function $d(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}const el=Po(e.LoggerNames.Region),tl=5e3;class nl{static fetchRegionSettings(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=yield nl.fetchLock.lock();try{const i=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(i.ok){const e=function(e){var t;const n=e.get("Cache-Control");if(n){const e=null===(t=n.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(i.headers),t=e?1e3*e:tl;return{regionSettings:yield i.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw 401===i.status?ss.notAllowed("Could not fetch region settings: ".concat(i.statusText),i.status):ss.internal("Could not fetch region settings: ".concat(i.statusText))}catch(ke){throw ke instanceof ss?ke:(null==n?void 0:n.aborted)?ss.cancelled("Region fetching was aborted"):ss.serverUnreachable("Could not fetch region settings, ".concat(ke instanceof Error?"".concat(ke.name,": ").concat(ke.message):ke))}finally{i()}}))}static scheduleRefetch(t,n,i){return Ao(this,void 0,void 0,(function*(){const r=nl.settingsTimeouts.get(t.hostname);clearTimeout(r),nl.settingsTimeouts.set(t.hostname,setTimeout((()=>Ao(this,void 0,void 0,(function*(){try{const e=yield nl.fetchRegionSettings(t,n);nl.updateCachedRegionSettings(t,n,e)}catch(r){if(r instanceof ss&&r.reason===e.ConnectionErrorReason.NotAllowed)return void el.debug("token is not valid, cancelling auto region refresh");el.debug("auto refetching of region settings failed",{error:r}),nl.scheduleRefetch(t,n,i)}}))),i))}))}static updateCachedRegionSettings(e,t,n){nl.cache.set(e.hostname,n),nl.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=nl.settingsTimeouts.get(e);t&&(clearTimeout(t),nl.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=nl.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout((()=>{const t=nl.connectionTrackers.get(e);t&&0===t.connectionCount&&(el.debug("stopping region refetch after disconnect delay",{hostname:e}),nl.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)}),3e4))}static cancelCleanup(e){const t=nl.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=nl.connectionTrackers.get(e);t||(t={connectionCount:0},nl.connectionTrackers.set(e,t)),t.connectionCount++,nl.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=nl.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&nl.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const n=this.getServerUrl(),i=nl.cache.get(n.hostname);nl.scheduleRefetch(this.serverUrl,this.token,null!==(t=null==i?void 0:i.maxAgeInMs)&&void 0!==t?t:tl)}isCloud(){return ha(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Ao(this,void 0,void 0,(function*(){return nl.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return Ao(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=nl.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),nl.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(n.length>0){const e=n[0];return this.attemptedRegions.push(e),el.info("switching to region: ".concat(e.region),{region:e.region}),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){nl.updateCachedRegionSettings(this.serverUrl,this.token,e)}}nl.cache=new Map,nl.settingsTimeouts=new Map,nl.connectionTrackers=new Map,nl.fetchLock=new be;const il=["e2eeManager","frameMetadataOptions","byteStreamOpener","videoPublisher"];function rl(e,t,n){const i=Symbol("lk.extension.".concat(e)),r=e=>({key:i,requires:t,install:(t,i)=>n(t,i,"function"==typeof e?e():e)});return Object.assign((e=>r(e)),r())}function ol(e,t){const n=new Map;for(const s of t){if(n.has(s.key))throw new Error("extension '".concat(String(s.key),"' is listed twice"));n.set(s.key,s)}const i=[],r=new Set,o=(e,t)=>{var s,a;const c=null!==(s=n.get(e.key))&&void 0!==s?s:e;if(t.includes(c.key))throw new Error("extension '".concat(String(c.key),"' depends on itself"));r.has(c.key)||(r.add(c.key),null===(a=c.requires)||void 0===a||a.forEach((e=>o(e,[...t,c.key]))),i.push(c))};t.forEach((e=>o(e,[]))),e.installExtensions(i)}const sl=2e3;function al(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 cl="undefined"!=typeof MediaRecorder;const dl=cl?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class ll extends dl{constructor(e,t){if(!cl)throw new Error("MediaRecorder is not available in this environment");let n,i;super(new MediaStream([e.mediaStreamTrack]),t);const r=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),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",r),this.removeEventListener("error",o),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>Ao(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:()=>{r()}}),this.addEventListener("stop",r),this.addEventListener("error",o)}}class ul extends Bs{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 r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=ud((()=>Ao(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Ao(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 be,this.pauseUpstreamLock=new be,this.trackChangeLock=new be,this.trackChangeLock.lock().then((e=>Ao(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!==Bs.Kind.Video)return;const e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;return t&&n?{width:t,height:n}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get isStopped(){return this.manuallyStopped}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,n){return Ao(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let r;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Vs(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,audioContext:this.audioContext,localTrack:this}),r=this.processor.processedTrack}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=r?r:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!!n||!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{qs(null!=r?r:e,t)}))),yield this.onMediaStreamTrackChanged()}))}onMediaStreamTrackChanged(){return Ao(this,void 0,void 0,(function*(){}))}waitForDimensions(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){if(e.kind===Bs.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");const n=Date.now();for((aa()||ia()&&e.source===Bs.Source.ScreenShare)&&(yield function(e,t){return Ao(this,arguments,void 0,(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return function*(){var i;if("undefined"==typeof document)return!1;if("ended"===e.readyState||e.muted||!e.enabled)return!1;const r="function"==typeof HTMLVideoElement.prototype.requestVideoFrameCallback,o=n.find((t=>t instanceof HTMLVideoElement&&t.srcObject instanceof MediaStream&&t.srcObject.getVideoTracks().includes(e)&&(r||t.readyState<2))),s=null!=o?o:document.createElement("video");let a,c,d;o||(s.playsInline=!0,s.muted=!0,s.srcObject=new MediaStream([e]),s.play().catch((e=>{wo.debug("could not play element while waiting for the first video frame",{error:e})})));try{return yield new Promise((e=>{a=setTimeout((()=>e(!1)),t),r?c=s.requestVideoFrameCallback((()=>e(!0))):(d=()=>e(!0),s.addEventListener("loadeddata",d))}))}finally{clearTimeout(a),void 0!==c&&(null===(i=s.cancelVideoFrameCallback)||void 0===i||i.call(s,c)),d&&s.removeEventListener("loadeddata",d),o||(s.pause(),s.srcObject=null)}}()}))}(e._mediaStreamTrack,t,e.attachedElements));;){const i=e.dimensions;if(i)return i;if(Date.now()-n>=t)break;yield Ks(50)}throw new ds("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Ao(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Aa(e)&&"live"===this._mediaStreamTrack.readyState||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Aa(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Ao(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===Bs.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),i=n.deviceId,r=n.groupId,o=e.kind===Bs.Kind.Audio?"audioinput":"videoinput";return t?Tc.getInstance().normalizeDeviceId(o,i,r):i}()}))}mute(){return Ao(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Ao(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Ao(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new ds("unable to replace an unpublished track");let n,i;"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())}finally{n()}return yield this.onSenderTrackSwapped(),this}))}onSenderTrackSwapped(){return Ao(this,void 0,void 0,(function*(){}))}restart(t,n){return Ao(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const i=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const i=t,r=i.deviceId,o=i.facingMode,s=Mo(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const a={audio:!1,video:!1};let c;this.kind===Bs.Kind.Video?a.video=!r&&!o||{deviceId:r,facingMode:o}:a.audio=!r||Object.assign({deviceId:r},s),this.attachedElements.forEach((e=>{Vs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();try{c=yield navigator.mediaDevices.getUserMedia(a)}catch(ke){throw function(e){"object"==typeof e&&null!==e&&La.add(e)}(ke),ke}const d=c.getTracks()[0];try{this.kind===Bs.Kind.Video&&(yield d.applyConstraints(s)),d.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(d,!1,n)}catch(ke){throw this._mediaStreamTrack!==d&&d.stop(),ke}return this._constraints=t,this.pendingDeviceChange=!1,this.emit(e.TrackEvent.Restarted,this),this}finally{this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),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 Ao(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),da()&&(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().catch((e=>{this.log.error("failed to destroy processor",Object.assign(Object.assign({},this.logContext),{error:e}))})),this.processor=void 0}pauseUpstream(){return Ao(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=zo();if("Safari"===(null==n?void 0:n.name)&&va(n.version,"12.0")<0)throw new cs("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 Ao(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 Ao(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 Ao(this,arguments,void 0,(function(t){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r;const o=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),s={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext,localTrack:n};if(yield t.init(s),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(qs(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&&(Vs(n._mediaStreamTrack,e),qs(n.processor.processedTrack,e));yield null===(r=n.sender)||void 0===r?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(e.TrackEvent.TrackProcessorUpdate,n.processor)}finally{o()}yield n.onSenderTrackSwapped()}()}))}getProcessor(){return this.processor}stopProcessor(){return Ao(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()}yield e.onSenderTrackSwapped()}()}))}internalStopProcessor(){return Ao(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r;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===(r=t.processorElement)||void 0===r||r.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(cl)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 ll(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 hl extends ul{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;super(t,Bs.Kind.Audio,n,i,o),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Ao(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(ke){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:ke}))}e&&this.prevStats&&(this._currentBitrate=al(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,Pn.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,Pn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Ao(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===Bs.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 Ao(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Bs.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!this.pendingDeviceChange||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}restartTrack(e){return Ao(this,void 0,void 0,(function*(){let t;if(e){const n=Ps({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}applyConstraints(e){return Ao(this,void 0,void 0,(function*(){const t=yield this.trackChangeLock.lock();try{const t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}}))}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return Ao(this,void 0,void 0,(function*(){const i=yield n.restart.call(this,e,t);return this.checkForSilence(),i}))}startMonitor(){la()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),sl)))}observeProcessedTrack(e){this.observedProcessedTrack!==e&&(this.observedProcessedTrack&&(this.observedProcessedTrack.removeEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.observedProcessedTrack.removeEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable),this.observedProcessedTrack=void 0,this.isKrispNoiseFilterEnabled&&this.handleKrispNoiseFilterDisable()),e&&(e.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),e.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable),this.observedProcessedTrack=e))}setProcessor(t){return Ao(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!ua()&&!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,localTrack:this};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.observeProcessedTrack(this.processor.processedTrack)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}onMediaStreamTrackChanged(){return Ao(this,void 0,void 0,(function*(){var e;this.observeProcessedTrack(null===(e=this.processor)||void 0===e?void 0:e.processedTrack)}))}internalStopProcessor(){const e=Object.create(null,{internalStopProcessor:{get:()=>super.internalStopProcessor}});return Ao(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){t.observeProcessedTrack(void 0),yield e.internalStopProcessor.call(t,n)}()}))}stop(){this.observeProcessedTrack(void 0),super.stop()}setAudioContext(t){return Ao(this,void 0,void 0,(function*(){var n;if(this.audioContext===t)return;const i=yield this.trackChangeLock.lock();try{if(this.audioContext=t,!this.processor||ua())return;if(!t)return this.log.debug("stopping audio processor, audio context has been removed",this.logContext),void(yield this.internalStopProcessor());this.log.debug("restarting audio processor on new audio context",this.logContext),yield this.processor.restart({kind:this.kind,track:this._mediaStreamTrack,audioContext:t,localTrack:this}),this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack),this.observeProcessedTrack(this.processor.processedTrack)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}getSenderStats(){return Ao(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach((e=>{if("outbound-rtp"===e.type){n={type:"audio",streamId:e.id,packetsSent:e.packetsSent,bytesSent:e.bytesSent,timestamp:e.timestamp};const i=t.get(e.remoteId);i&&(n.packetsLost=i.packetsLost,n.jitter=i.jitter,n.roundTripTime=i.roundTripTime)}})),n}))}checkForSilence(){return Ao(this,void 0,void 0,(function*(){const t=yield Is(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}class pl extends Bs{constructor(t,n,i,r,o){super(t,i,o),this.timeSyncLoop=()=>{var t;if(0===this.listenerCount(e.TrackEvent.TimeSyncUpdate))return void(this.timeSyncHandle=void 0);this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);const n=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(n){const t=n.timestamp,i=n.rtpTimestamp;i&&this.rtpTimestamp!==i&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:i}),this.rtpTimestamp=i)}},this.onTimeSyncListenerAdded=t=>{t===e.TrackEvent.TimeSyncUpdate&&void 0===this.timeSyncHandle&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(t){this.isMuted!==t&&(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?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 Ao(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()),sl)),"undefined"!=typeof RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.prototype.getSynchronizationSources&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off("newListener",this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){this.off("newListener",this.onTimeSyncListenerAdded),this.on("newListener",this.onTimeSyncListenerAdded),void 0===this.timeSyncHandle&&this.timeSyncLoop()}}class ml extends pl{constructor(e,t,n,i,r,o){super(e,t,Bs.Kind.Audio,n,o),this.connectedNodes=[],this.monitorReceiver=()=>Ao(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=al(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;if(this.audioContext)null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1);else for(const n of this.attachedElements)n.volume=e;ua()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(void 0!==this.elementVolume)return this.elementVolume;if(ua())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Ao(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(ea(t))return t.setSinkId(e)})))}))}attach(e){const t=!this.sourceNode;return e?super.attach(e):e=super.attach(),this.sinkId&&ea(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)})),this.audioContext&&(e.volume=0,e.muted=!0,t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e))),void 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){var t;if(this.audioContext!==e)if(this.audioContext=e,e){for(const e of this.attachedElements)e.volume=0,e.muted=!0;this.attachedElements.length>0&&this.connectWebAudio(e,this.attachedElements[0])}else{this.disconnectWebAudio();for(const e of this.attachedElements)e.muted=!1,e.volume=null!==(t=this.elementVolume)&&void 0!==t?t:1}}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.connectedNodes=[this.sourceNode],this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e,this.connectedNodes.push(e)})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.connectedNodes.push(this.gainNode),this.gainNode.connect(t.destination),void 0!==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;for(let i=0;i<this.connectedNodes.length-1;i+=1)try{this.connectedNodes[i].disconnect(this.connectedNodes[i+1])}catch(n){}this.connectedNodes=[],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 Ao(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 gl extends Vo.EventEmitter{constructor(t,n,i,r){var o;super(),this.metadataMuted=!1,this.encryption=xn.NONE,this.log=wo,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=Po(null!==(o=null==r?void 0:r.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=Bs.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)),Ns(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==xn.NONE}get audioTrack(){if(Ba(this.track))return this.track}get videoTrack(){if(qa(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Bs.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Bs.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"}(gl||(gl={}));class fl extends gl{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,r){super(t,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&qa(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 Ao(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Ao(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Ao(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Ao(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Ba(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Pn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Pn.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Pn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Pn.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(Pn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Pn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}let vl;function kl(e){vl=e}function yl(){if(!vl)throw new ds("video capture is not available in this build, add the video extension");return vl}function bl(e,t){return Ao(this,void 0,void 0,(function*(){null!=e||(e={});let n=!1;const i=xs(e),r=i.audioProcessor,o=i.videoProcessor,s=i.optionsWithoutProcessor;let a=s.audio,c=s.video;if(r&&"object"==typeof s.audio&&(s.audio.processor=r),o&&"object"==typeof s.video&&(s.video.processor=o),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){const e=s.audio.deviceId;s.audio.deviceId={exact:e},n=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:e}})}if(s.video&&"object"==typeof s.video&&"string"==typeof s.video.deviceId){const e=s.video.deviceId;s.video.deviceId={exact:e},n=!0,c=Object.assign(Object.assign({},s.video),{deviceId:{ideal:e}})}!0===s.audio?s.audio={deviceId:"default"}:"object"==typeof s.audio&&null!==s.audio&&(s.audio=Object.assign(Object.assign({},s.audio),{deviceId:s.audio.deviceId||"default"})),!0===s.video?s.video={deviceId:"default"}:"object"!=typeof s.video||s.video.deviceId||(s.video.deviceId="default");const d=Ps(ws(s,Ad,s.video?yl().defaults:void 0)),l=navigator.mediaDevices.getUserMedia(d);s.audio&&(Tc.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Tc.userMediaPromiseMap.delete("audioinput")))),s.video&&(Tc.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Tc.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((n=>Ao(this,void 0,void 0,(function*(){let i;const s="audio"===n.kind?d.audio:d.video;"boolean"!=typeof s&&(i=s);const a=n.getSettings().deviceId;(null==i?void 0:i.deviceId)&&Aa(i.deviceId)!==a?i.deviceId=a:i||(i={deviceId:a});const c="audio"===n.kind?new hl(n,i,!1,void 0,t):yl().createTrack(n,i,!1,t);return c.kind===Bs.Kind.Video?c.source=Bs.Source.Camera:c.kind===Bs.Kind.Audio&&(c.source=Bs.Source.Microphone),c.mediaStream=e,Ba(c)&&r?yield c.setProcessor(r):qa(c)&&o&&(yield c.setProcessor(o)),c})))))}catch(ke){if(!n)throw ke;return bl(Object.assign(Object.assign({},e),{audio:a,video:c}),t)}}))}function Tl(e){return Ao(this,void 0,void 0,(function*(){return(yield bl({audio:null==e||e,video:!1}))[0]}))}var Sl;e.ConnectionQuality=void 0,(Sl=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Sl.Good="good",Sl.Poor="poor",Sl.Lost="lost",Sl.Unknown="unknown";class El extends Vo.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===Ln.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===An.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,r,o,s){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Ln.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=wo,this.loggerOptions=s,this.log=Po(null!==(c=null==s?void 0:s.loggerName)&&void 0!==c?c:e.LoggerNames.Participant,(()=>this.logContext)),this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=o?o:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const t of this.trackPublications){const n=tt(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(const t of this.trackPublications){const n=tt(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Da,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(Bs.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Bs.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Bs.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}isOlderSession(e){const t=this.participantInfo;return!(!t||t.sid===e.sid)&&(e.joinedAt!==t.joinedAt?e.joinedAt<t.joinedAt:e.joinedAtMs&&t.joinedAtMs&&e.joinedAtMs!==t.joinedAtMs?e.joinedAtMs<t.joinedAtMs:e.sid<t.sid)}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===An.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==An.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)],r={};for(const o of i)e[o]!==t[o]&&(r[o]=null!==(n=t[o])&&void 0!==n?n:"");return r}(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,n)}setPermissions(t){var n,i,r,o,s,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===(r=this.permissions)||void 0===r?void 0:r.canPublishData)||t.hidden!==(null===(o=this.permissions)||void 0===o?void 0:o.hidden)||t.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.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 Sn.EXCELLENT:return e.ConnectionQuality.Excellent;case Sn.GOOD:return e.ConnectionQuality.Good;case Sn.POOR:return e.ConnectionQuality.Poor;case Sn.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){return Ao(this,void 0,void 0,(function*(){this.audioContext=e,yield Promise.all(Array.from(this.audioTrackPublications.values()).map((e=>e.track)).filter(Ba).map((t=>t.setAudioContext(e))))}))}addTrackPublication(t){this.log.debug("adding track publication",{trackSid:t.trackSid,source:t.source,kind:t.kind}),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 Bs.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case Bs.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Cl extends El{constructor(t,n,i,r){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};super(t,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=xn.NONE,this.e2eeStateMutex=new be,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Da)},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,r,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(i=(n=this.signalConnectedFuture).reject)||void 0===i||i.call(n,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),null===(o=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===o||o.call(r,new Error("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 Da),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const t=e.requestId,n=e.reason,i=e.message,r=this.pendingSignalRequests.get(t);r&&(n!==co.OK&&r.reject(new gs(i,n)),this.pendingSignalRequests.delete(t))},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",{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 Jr({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",Ns(e))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Ns(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Ns(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.onTrackCpuConstrained=(t,n)=>{this.log.debug("track cpu constrained",Ns(n)),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",{trackSid:e.trackSid})},this.handleTrackEnded=e=>Ao(this,void 0,void 0,(function*(){if(e.source===Bs.Source.ScreenShare||e.source===Bs.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Ns(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Wa(e)||Va(e))try{if(la())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===Bs.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Ns(e)),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(ke){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Ns(e)),Wa(e)?yield this.restartOnDefaultAudioDevice(e):yield e.restartTrack())}catch(ke){this.log.warn("could not restart track, muting instead",Ns(e)),yield e.mute()}})),this.slots=o,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==xn.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.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return Ao(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Ao(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Ao(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=e.metadata,i=e.name,r=e.attributes;return function*(){return new Wo(((e,o)=>Ao(t,void 0,void 0,(function*(){var t,s;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(s=null!=i?i:this.name)&&void 0!==s?s:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{o(e),a=!0},values:{name:i,metadata:n,attributes:r}});performance.now()-d<5e3&&!a;){if((!i||this.name===i)&&(!n||this.metadata===n)&&(!r||Object.entries(r).every((e=>{let t=tt(e,2),n=t[0],i=t[1];return this.attributes[n]===i||""===i&&!this.attributes[n]}))))return this.pendingSignalRequests.delete(c),void e();yield Ks(50)}o(new gs("Request to update local metadata timed out","TimeoutError"))}catch(ke){ke instanceof Error?o(ke):o(new Error(String(ke)))}}))))}()}))}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Bs.Source.Microphone,e,t,n)}setE2EEEnabled(e){return Ao(this,void 0,void 0,(function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?xn.GCM:xn.NONE,yield Promise.all(this.pendingPublishPromises.values()),0===this.trackPublications.size||Array.from(this.trackPublications.values()).every((t=>t.isEncrypted===e)))return;yield this.republishAllTracks(void 0,!1)}finally{t()}}))}setTrackEnabled(t,n,i,r){return Ao(this,void 0,void 0,(function*(){var o,s;this.log.debug("setTrackEnabled",{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",{source:t}),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case Bs.Source.Camera:n=yield this.createTracks({video:null===(o=i)||void 0===o||o});break;case Bs.Source.Microphone:n=yield this.createTracks({audio:null===(s=i)||void 0===s||s});break;case Bs.Source.ScreenShare:n=yield this.requireVideoPublisher().createScreenTracks(Object.assign({},i));break;default:throw new ds(t)}}catch(ke){throw null==n||n.forEach((e=>{e.stop()})),ke instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,ke,Ds(t)),this.pendingPublishing.delete(t),ke}for(const e of n){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),r);t===Bs.Source.Microphone&&Ba(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),e.startPreConnectBuffer())}try{const e=[];for(const t of n)this.log.info("publishing track",Ns(t)),e.push(this.publishTrack(t,r));a=tt(yield Promise.all(e),1)[0]}catch(ke){throw null==n||n.forEach((e=>{e.stop()})),ke}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",{source:t})),a&&a.track)if(t===Bs.Source.ScreenShare){const e=[this.unpublishTrack(a.track)],t=this.getTrackPublication(Bs.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),a=tt(yield Promise.all(e),1)[0]}else yield a.mute();return a}))}createTracks(t){return Ao(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const r=ws(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 bl(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return yield Promise.all(t.map((t=>Ao(this,void 0,void 0,(function*(){return Ba(t)&&(this.microphoneError=void 0,yield t.setAudioContext(this.audioContext),t.source=Bs.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),qa(t)&&(this.cameraError=void 0,t.source=Bs.Source.Camera),t})))))}catch(o){throw o instanceof Error&&(t.audio&&(this.microphoneError=o),t.video&&(this.cameraError=o)),o}}))}get trackLoggerOptions(){return{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext}}requireVideoPublisher(){if(!this.slots.videoPublisher)throw new ds("video publishing is not available in this build, add the video extension");return this.slots.videoPublisher}publishTrack(e,t){return Ao(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}waitForNextEngineRestart(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15e3;return new Promise(((n,i)=>{const r=()=>{clearTimeout(a),this.engine.off(e.EngineEvent.Restarted,o),this.engine.off(e.EngineEvent.Closing,s)},o=()=>{r(),n()},s=()=>{r(),i(new Error("engine closed before restart completed"))},a=setTimeout((()=>{r(),i(new Error("timed out waiting for engine restart"))}),t);this.engine.once(e.EngineEvent.Restarted,o),this.engine.once(e.EngineEvent.Closing,s)}))}publishOrRepublishTrack(e,t){return Ao(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return function*(){var o,s,a,c;let d,l;if(Wa(e)&&(yield e.setAudioContext(n.audioContext)),yield null===(o=n.reconnectFuture)||void 0===o?void 0:o.promise,n.republishPromise&&!i&&(yield n.republishPromise),ja(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)d=e.getConstraints();else{let t;switch(d=e.constraints,e.source){case Bs.Source.Microphone:t="audioinput";break;case Bs.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(d=Object.assign(Object.assign({},d),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new hl(e,d,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=yl().createTrack(e,d,!0,n.trackLoggerOptions);break;default:throw new ds("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&&(l=t)})),l)return n.log.warn("track has already been published, skipping",Ns(l)),l;const u=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),h="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,p=null!==(s=u.forceStereo)&&void 0!==s?s:h;p&&(void 0===u.dtx&&n.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Ns(e)),void 0===u.red&&n.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(a=u.dtx)&&void 0!==a||(u.dtx=!1),null!==(c=u.red)&&void 0!==c||(u.red=!1)),u.source&&(e.source=u.source);const m=new Promise(((t,i)=>Ao(n,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Jc.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:Ns(e)});let n=!1;const r=setTimeout((()=>{n=!0,e.stop(),i(new ms("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),n)return;const o=yield this.publish(e,u,p);t(o)}else try{const n=yield this.publish(e,u,p);t(n)}catch(ke){i(ke)}}catch(ke){i(ke)}}))));n.pendingPublishPromises.set(e,m);try{return yield m}catch(ke){if(!r&&ke instanceof hs)return n.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:ke}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,i,!0);throw ke}finally{n.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Da),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Ns(e)),!1;const t=this.permissions,n=t.canPublish,i=t.canPublishSources;return!(!n||0!==i.length&&!i.map((e=>function(e){switch(e){case bn.CAMERA:return Bs.Source.Camera;case bn.MICROPHONE:return Bs.Source.Microphone;case bn.SCREEN_SHARE:return Bs.Source.ScreenShare;case bn.SCREEN_SHARE_AUDIO:return Bs.Source.ScreenShareAudio;default:return Bs.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Ns(e)),!1)}publish(t,n,i){return Ao(this,void 0,void 0,(function*(){var r,o,s,a,c,d,l,u;if(!this.hasPermissionsToPublish(t))throw new ms("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>ja(t)&&e.source===t.source))&&t.source!==Bs.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Ns(t)),n.stopMicTrackOnMute&&Ba(t)&&(t.stopOnMute=!0),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 h=[],p=!(null===(r=n.dtx)||void 0===r||r),m=t.getSourceTrackSettings();m.autoGainControl&&h.push(Pn.TF_AUTO_GAIN_CONTROL),m.echoCancellation&&h.push(Pn.TF_ECHO_CANCELLATION),m.noiseSuppression&&h.push(Pn.TF_NOISE_SUPPRESSION),m.channelCount&&m.channelCount>1&&h.push(Pn.TF_STEREO),p&&h.push(Pn.TF_NO_DTX),Wa(t)&&t.hasPreConnectBuffer&&h.push(Pn.TF_PRECONNECT_BUFFER);const g=this.normalizeRequestedFrameMetadataOptions(t,n),f=new cr({cid:t.mediaStreamTrack.id,name:n.name,type:Bs.kindToProto(t.kind),muted:t.isMuted,source:Bs.sourceToProto(t.source),disableDtx:p,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:h,packetTrailerFeatures:g});let v;if(Va(t)?v=yield this.requireVideoPublisher().prepare(t,n,f):t.kind===Bs.Kind.Audio&&(v=[{maxBitrate:null===(s=n.audioPreset)||void 0===s?void 0:s.maxBitrate,priority:null!==(c=null===(a=n.audioPreset)||void 0===a?void 0:a.priority)&&void 0!==c?c:"high",networkPriority:null!==(l=null===(d=n.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high"}]),!this.engine||this.engine.isClosed)throw new us("cannot publish track when not connected");const k=()=>Ao(this,void 0,void 0,(function*(){var i;if(!this.engine.pcManager)throw new us("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,v),Va(t)&&(t.publishOptions=n),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Va(t)&&this.requireVideoPublisher().senderCreated(t,n,v,f),v&&na()&&t.kind===Bs.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===(i=v[0])||void 0===i?void 0:i.maxBitrate)?v[0].maxBitrate/1e3:0})}yield this.engine.negotiate()}));let y;const b=new Promise(((e,n)=>Ao(this,void 0,void 0,(function*(){var i;try{y=yield this.engine.addTrack(f),e(y)}catch(r){if(t.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)){try{this.engine.pcManager.publisher.removeTrack(t.sender)}catch(ke){this.log.error(ke)}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({},Ns(t)),{error:e}))}))}n(r)}}))));if(this.enabledPublishVideoCodecs.length>0&&0===g.length){const e=yield Promise.all([b,k()]);y=e[0]}else y=yield b,Va(t)&&(v=null!==(u=this.requireVideoPublisher().serverCodecChanged(t,n,y,f))&&void 0!==u?u:v),yield k();const T=new fl(t.kind,y,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(T.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,T))),T.options=n,t.sid=y.sid,Va(t)&&(t.publishOptions=n,f.width&&f.height&&(t.lastEncodedDimensions={width:f.width,height:f.height})),this.log.debug("publishing ".concat(t.kind," with encodings"),{encodings:v,trackInfo:y}),Va(t)?t.startMonitor(this.engine.client):Wa(t)&&t.startMonitor(),this.addTrackPublication(T),this.emit(e.ParticipantEvent.LocalTrackPublished,T),Wa(t)&&y.audioFeatures.includes(Pn.TF_PRECONNECT_BUFFER)){const n=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===y.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed");this.log.debug("finished recording preconnect buffer",Ns(t)),t.stopPreConnectBuffer()}})),n){const e=new Promise(((e,r)=>Ao(this,void 0,void 0,(function*(){var o,s,a,c,d,l;try{this.log.debug("waiting for agent",Ns(t));const f=setTimeout((()=>{r(new Error("agent not active within 10 seconds"))}),1e4),v=yield this.waitUntilActiveAgentPresent();if(clearTimeout(f),this.log.debug("sending preconnect buffer",Ns(t)),!this.slots.byteStreamOpener)throw new Error("the dataStreams extension is required to send the preconnect buffer");const k=yield this.slots.byteStreamOpener({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[v.identity],attributes:{trackId:T.trackSid,sampleRate:String(null!==(d=m.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=m.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Uo(n);!(o=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield k.write(e)}}catch(g){s={error:g}}finally{try{h||o||!(a=p.return)||(yield a.call(p))}finally{if(s)throw s.error}}yield k.close(),e()}catch(ke){r(ke)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Ns(t))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},Ns(t)),{error:e}))}))}}return T}))}canPublishFrameMetadata(){return!!this.engine.e2eeManager||gc(this.engine.frameMetadataOptions)}normalizeRequestedFrameMetadataOptions(e,t){const n=vc(t);if(e.kind!==Bs.Kind.Video||!fc(n))return kc(t,void 0),[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),Ns(e))),kc(t,void 0),[];const i=function(e){const t=[];return(null==e?void 0:e.timestamp)&&t.push(In.PTF_USER_TIMESTAMP),(null==e?void 0:e.frameId)&&t.push(In.PTF_FRAME_ID),t}(n),r=function(e){if(!e||0===e.length)return;const t={};return e.includes(In.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(In.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}(i);return kc(t,r),i}get isLocal(){return!0}unpublishTrack(t,n){return Ao(this,void 0,void 0,(function*(){var i,r;if(ja(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.debug("awaiting publish promise before attempting to unpublish",Ns(t)),yield e)}const o=this.getPublicationForTrack(t),s=o?Ns(o):void 0;if(this.log.info("unpublishing track",s),!o||!o.track)return void this.log.warn("track was not unpublished because no publication was found",s);(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===(r=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===r||r),n?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<xd.FAILED&&c)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===c&&(e.direction="inactive",a=!0);try{a=this.engine.removeTrack(c)}catch(ke){this.log.warn(ke),a=!0}if(Va(t)){for(const e of t.simulcastCodecs){const t=tt(e,2)[1];if(t.sender){try{a=this.engine.removeTrack(t.sender)}catch(ke){this.log.warn(ke),a=!0}t.sender=void 0}}t.simulcastCodecs.clear()}}catch(ke){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},s),{error:ke}))}switch(this.trackPublications.delete(o.trackSid),o.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(o.trackSid);break;case Bs.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 Ao(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Ao(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 Wo(((i,r)=>Ao(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=>Ao(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===Bs.Source.ScreenShare||t.source===Bs.Source.ScreenShareAudio||!Wa(t)&&!Va(t)||t.isUserProvided||(this.log.debug("restarting existing track",{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(t){t instanceof Error?r(t):r(new Error(String(t)))}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Ao(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?Ud.RELIABLE:Ud.LOSSY,r=n.reliable?Xn.RELIABLE:Xn.LOSSY,o=n.destinationIdentities,s=n.topic;let a=new ni({participantIdentity:t.identity,payload:e,destinationIdentities:o,topic:s});const c=new Yn({kind:r,value:{case:"user",value:a}});yield t.engine.sendDataPacket(c,i)}()}))}publishDtmf(e,t){return Ao(this,void 0,void 0,(function*(){const n=new Yn({kind:Xn.RELIABLE,value:{case:"sipDtmf",value:new ii({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Ud.RELIABLE)}))}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()}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 r=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},Ns(i)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}})),!0)}setActiveAgent(e){var t,n,i,r;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===(r=null===(i=this.activeAgentFuture)||void 0===i?void 0:i.reject)||void 0===r||r.call(i,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Da),this.activeAgentFuture.promise)}restartOnDefaultAudioDevice(e){return Ao(this,void 0,void 0,(function*(){var t,n;try{ia()?yield e.setDeviceId({exact:"default"}):yield e.restartTrack()}catch(ke){if(!function(e){return"object"==typeof e&&null!==e&&La.has(e)}(ke)||function(e){return"object"==typeof e&&null!==e&&"name"in e&&("NotAllowedError"===e.name||"SecurityError"===e.name||"PermissionDeniedError"===e.name||"PermissionDismissedError"===e.name)}(ke)||e.isStopped)throw ke;this.log.debug("could not reacquire the audio device, retrying with an enumerated device",Ns(e));const r=yield Tc.getInstance().getDevices("audioinput",!1);yield e.setDeviceId(null!==(n=null===(t=null==r?void 0:r[0])||void 0===t?void 0:t.deviceId)&&void 0!==n?n:"default")}}))}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(Wa(i)||Va(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return Ao(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>tt(t,1)[0].source===e));if(t)return t[1];yield Ks(20)}}))}}class wl extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class Rl extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,i;super.set(e,t);const r=null===(n=this.pending)||void 0===n?void 0:n.get(e);if(r){for(const e of r)e.isResolved||null===(i=e.resolve)||void 0===i||i.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return Ao(this,void 0,void 0,(function*(){const n=this.get(e);if(void 0!==n)return n;if(null==t?void 0:t.aborted)throw new wl("The operation was aborted.",t.reason);const i=new Da(void 0,(()=>{const t=this.pending.get(e);if(!t)return;const n=t.indexOf(i);-1!==n&&t.splice(n,1),0===t.length&&this.pending.delete(e)})),r=this.pending.get(e);if(r?r.push(i):this.pending.set(e,[i]),t){const e=()=>{var e;i.isResolved||null===(e=i.reject)||void 0===e||e.call(i,new wl("The operation was aborted.",t.reason))};t.addEventListener("abort",e,{once:!0});const n=()=>{t.removeEventListener("abort",e)};i.promise.then(n,n)}return i.promise}))}}class Pl extends gl{constructor(t,n,i,r){super(t,n.sid,n.name,r),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 r=new Er({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ui({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?gl.SubscriptionStatus.Unsubscribed:super.isSubscribed?gl.SubscriptionStatus.Subscribed:gl.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?gl.PermissionStatus.Allowed:gl.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||(za(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&za(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,r=this.track;r!==t&&(r&&(r.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),r.off(e.TrackEvent.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,r)),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 za(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Or({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Bs.Kind.Video){let n=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(n){Us(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=function(e,t){var n;return null===(n=e.layers)||void 0===n?void 0:n.find((e=>e.quality===t))}(this.trackInfo,this.requestedMaxQuality);e&&Us(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(t.width=Math.ceil(n.width),t.height=Math.ceil(n.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)}this.emit(e.TrackEvent.UpdateSettings,t)}}class Il extends pl{constructor(e,t,n,i,r){super(e,t,Bs.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>Ao(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=al(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=ud((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return null===(n=this.frameMetadataExtractor)||void 0===n?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===Bs.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Vs(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 _l(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 n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);const t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Ao(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 n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ao(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var n,i;const r=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,s=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!o||s;(this.lastVisible!==a||t)&&(!a&&Date.now()-r<100?ks.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,n;let i=0,r=0;const o=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*o,n=e.height()*o;t+n>i+r&&(i=t,r=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},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 fa();if(!t){return fa()>2?2:1}return t}}class _l{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const n=e.target,i=e.isIntersecting;n===this.element&&(this.isIntersecting=i,this.isPiP=Ol(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),queueMicrotask((()=>{requestAnimationFrame((()=>{var e;this.isPiP=Ol(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)}))}))},this.onLeavePiP=()=>{var e;this.isPiP=Ol(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Dl(e),this.isPiP=la()&&Ol(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Dl(this.element),this.isPiP=Ol(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ea().observe(this.element),Ta().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,r;null===(e=Ea())||void 0===e||e.unobserve(this.element),null===(t=Ta())||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===(r=null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function Ol(e){var t;if(document.pictureInPictureElement===e)return!0;const n=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window;return!!n&&(function(e,t){var n,i,r;if((null===(n=e.defaultView)||void 0===n?void 0:n.top)===t)return!0;let o=e;for(;o;){if(o===t.document)return!0;try{o=null===(r=null===(i=o.defaultView)||void 0===i?void 0:i.frameElement)||void 0===r?void 0:r.ownerDocument}catch(s){return!1}}return!1}(e.ownerDocument,n)&&Dl(e,n))}function Dl(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const o=e.offsetWidth,s=e.offsetHeight,a=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+s>n.pageYOffset&&r+o>n.pageXOffset&&!a&&"none"!==c}class Ml extends El{static fromParticipantInfo(e,t,n){return new Ml(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,[],t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,o,s){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:Ln.STANDARD,c=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,l=arguments.length>10&&void 0!==arguments[10]?arguments[10]:[];super(t,n||"",i,r,o,s,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Rl(c.map((e=>[e.info.name,e]))),this.volumeMap=new Map,this.clientProtocol=d,this.capabilities=l}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),Ns(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]:Bs.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]:Bs.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,r,o,s){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===s?(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===s&&(s=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,r,o,s-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),Ns(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Il(t,n,r,o):new ml(t,n,r,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)&&Ha(c)&&Ba(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,r;let o=this.getTrackPublicationBySid(e.sid);if(o)o.updateInfo(e);else{const n=Bs.kindFromProto(e.type);if(!n)return;o=new Pl(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),o.updateInfo(e),i.set(e.sid,o);const s=Array.from(this.trackPublications.values()).find((e=>e.source===(null==o?void 0:o.source)));s&&o.source!==Bs.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:Ns(s),newTrack:Ns(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),Ns(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 r=i.track;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case Bs.Kind.Audio:this.audioTrackPublications.delete(t);break;case Bs.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return Ao(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;Ba(n.track)&&Ha(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const n of this.dataTracks.entries()){var t=tt(n,2);const i=t[0];e===t[1].info.sid&&this.dataTracks.delete(i)}}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 Al;e.ConnectionState=void 0,(Al=e.ConnectionState||(e.ConnectionState={})).Disconnected="disconnected",Al.Connecting="connecting",Al.Connected="connected",Al.Reconnecting="reconnecting",Al.SignalReconnecting="signalReconnecting";let Ll;class Nl extends Vo.EventEmitter{get hasE2EESetup(){return void 0!==this.slots.e2eeManager}constructor(t){var n,i,r,o,s;if(super(),n=this,this.state=e.ConnectionState.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.ownsAudioContext=!1,this.audioContextReleased=!1,this.audioContextMutex=new be,this.acquiredEmptyAudioTracks=new Set,this.isVideoPlaybackBlocked=!1,this.log=wo,this.statsLog=wo,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.installedExtensions=new Map,this.slots={},this.extensionDisposers=[],this.dataPacketHandlers=new Map,this.disposed=!1,this.connect=(t,n,i)=>Ao(this,void 0,void 0,(function*(){var r;if(this.disposed)throw new us("room has been disposed");if(!ta())throw ua()?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.disposed)throw o(),new us("room has been disposed");if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name)),o(),Promise.resolve();if(this.connectFuture)return o(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.getServerUrl().toString())!==ec(t)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ha(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new nl(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",{error:e})})));const s=(r,a,c)=>Ao(this,void 0,void 0,(function*(){this.abortController&&this.abortController.abort();const d=new AbortController;this.abortController=d,null==o||o();const l=(e,t)=>{this.abortController===d&&this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),a(e)};try{if(yield yc.getInstance().getBackOffPromise(t),d.signal.aborted)throw ss.cancelled("Connection attempt aborted");yield this.attemptConnection(null!=c?c:t,n,i,d),this.abortController=void 0,r()}catch(u){if(this.regionUrlProvider&&u instanceof ss&&as(u)){let n=null;try{this.log.debug("Fetching next region"),n=yield this.regionUrlProvider.getNextBestRegionUrl(d.signal)}catch(h){if(h instanceof ss&&(401===h.status||h.reason===e.ConnectionErrorReason.Cancelled))return void l(h)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(u.reason)&&(this.log.debug("Adding failed connection attempt to back off"),yc.getInstance().addFailedConnectionAttempt(t)),n&&!d.signal.aborted?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(n)),this.recreateEngine(!0),yield s(r,a,n)):l(u,xa(u))}else{let e=Cn.UNKNOWN_REASON;u instanceof ss&&(e=xa(u)),l(u,e)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Da(((e,t)=>{s(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,r,o)=>Ao(this,void 0,void 0,(function*(){const s=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,disableIceLite:i.disableIceLite,subscriberAllowPause:i.subscriberAllowPause,clientInfoCapabilities:this.getClientInfoCapabilities(),maxRetries:i.maxRetries,e2eeEnabled:!!this.slots.e2eeManager,websocketTimeout:i.websocketTimeout},o.signal,!r.singlePeerConnection),a=s.joinResponse,c=s.serverInfo;if(this.serverInfo=c,!c.version)throw new ls("unknown server version");return"0.15.1"===c.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),r.dynacast=!1),a})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.slots.e2eeManager)try{this.slots.e2eeManager.setSifTrailer(e.sifTrailer)}catch(ke){this.log.error(ke instanceof Error?ke.message:"Could not set SifTrailer",{error:ke})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,r)=>Ao(this,void 0,void 0,(function*(){var o,s;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.recreateEngine(!0)):this.maybeCreateEngine();const a=this.engine;(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&a.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(!0).catch((e=>this.log.warn("Could not acquire audio context",Object.assign(Object.assign({},this.logContext),{error:e})))),this.connOptions=Object.assign(Object.assign({},Nd),i),this.connOptions.rtcConfig&&(a.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(a.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,a,this.connOptions,this.options,r);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(c){yield a.close(),this.recreateEngine(!1,a);const e=r.signal.aborted?ss.cancelled("Signal connection aborted"):ss.serverUnreachable("could not establish signal connection");throw c instanceof Error&&(e.message="".concat(e.message,": ").concat(c.message)),c instanceof ss&&(e.reason=c.reason,e.status=c.status),this.log.debug("error trying to establish signal connection",{error:c}),e}if(r.signal.aborted)throw yield a.close(),this.recreateEngine(!1,a),ss.cancelled("Connection attempt aborted");try{yield a.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(ke){throw yield a.close(),this.recreateEngine(!1,a),ke}la()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),la()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),yc.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Ao(n,[...i],void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,r,o;const s=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected");if(t.log.info("disconnect from room"),t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming){const e="Abort connection attempt due to user initiated disconnect";t.log.warn(e),null===(i=t.abortController)||void 0===i||i.abort(e),null===(o=null===(r=t.connectFuture)||void 0===r?void 0:r.reject)||void 0===o||o.call(r,ss.cancelled("Client initiated disconnect")),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(n,Cn.CLIENT_INITIATED),t.engine=void 0}finally{s()}}()}))},this.onPageLeave=()=>Ao(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()})),this.startAudio=()=>Ao(this,void 0,void 0,(function*(){const e=[],t=zo();t&&"iOS"===t.os&&!this.audioContextReleased&&e.push(this.acquireDummyAudioElement()),this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([...this.audioContextReleased?[]:[this.acquireAudioContext()],...e.map((e=>(this.options.webAudioMix||(e.muted=!1),e.play())))]),this.handleAudioPlaybackStarted()}catch(n){throw this.handleAudioPlaybackFailed(n),n}})),this.startVideo=()=>Ao(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.handleRestarting=()=>{var t;this.clearConnectionReconcile(),this.isResuming=!1,null!==(t=this.roomInfoBeforeRestart)&&void 0!==t||(this.roomInfoBeforeRestart=this.roomInfo),this.roomInfo=this.roomInfoBeforeRestart,this.bufferedEvents=[];for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);!this.connectFuture&&this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=(t,n)=>Ao(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),{region:t.serverRegion}),this.bufferedEvents=[];const i=void 0!==this.connectFuture,r=this.engine.waitForRestarted(n);this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",{error:o})}(yield r)&&!n.aborted&&(this.log.debug("fully reconnected to server",{region:t.serverRegion}),this.roomInfoBeforeRestart=void 0,i?this.bufferedEvents=[]:(this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()))})),this.handleParticipantUpdates=e=>{var t;const n=[];for(const i of e){if(i.identity===this.localParticipant.identity){this.localParticipant.updateInfo(i),n.push(i);continue}""===i.identity&&(i.identity=null!==(t=this.sidToIdentity.get(i.sid))&&void 0!==t?t:"");let e=this.remoteParticipants.get(i.identity);(null==e?void 0:e.isOlderSession(i))?this.log.debug("ignoring update from an older participant session",{remoteIdentity:i.identity,staleSid:i.sid,currentSid:e.sid}):(i.state===An.DISCONNECTED?this.handleParticipantDisconnected(i.identity,e,i.disconnectReason===Cn.UNKNOWN_REASON?void 0:i.disconnectReason):this.getOrCreateParticipant(i.identity,i),n.push(i))}this.extensionResults.forEach((e=>{var t;return null===(t=e.onParticipantUpdates)||void 0===t?void 0:t.call(e,n)}))},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 r=Bs.streamStateFromProto(t.state),o=i.track.streamState;i.track.setStreamState(r),r!==o&&(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=>{this.cancelPendingTrackAdded(e.trackSid);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)=>{var n;const i=this.remoteParticipants.get(e.participantIdentity);"user"===e.value.case?this.handleUserPacket(i,e.value.value,e.kind,t,e.participantIdentity):"transcription"===e.value.case?this.handleTranscription(i,e.value.value):"sipDtmf"===e.value.case?this.handleSipDtmf(i,e.value.value):"metrics"===e.value.case?this.handleMetrics(e.value.value,i):e.value.case&&(null===(n=this.dataPacketHandlers.get(e.value.case))||void 0===n||n(e,t,i))},this.handleUserPacket=(t,n,i,r,o)=>{this.emit(e.RoomEvent.DataReceived,n.payload,t,i,n.topic,r,o),null==t||t.emit(e.ParticipantEvent.DataReceived,n.payload,i,r)},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),r=null==i?void 0:i.trackPublications.get(n.trackId),o=function(e,t){return e.segments.map((e=>{let n=e.id,i=e.text,r=e.language,o=e.startTime,s=e.endTime,a=e.final;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(s.toString()),final:a,language:r,firstReceivedTime:d,lastReceivedTime:l}}))}(n,this.transcriptionReceivedTimes);null==r||r.emit(e.TrackEvent.TranscriptionReceived,o),null==i||i.emit(e.ParticipantEvent.TranscriptionReceived,o,r),this.emit(e.RoomEvent.TranscriptionReceived,o,i,r)},this.handleMetrics=(t,n)=>{this.emit(e.RoomEvent.MetricsReceived,t,n)},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",{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=()=>Ao(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=zo())||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.logWebRTCStats=()=>Ao(this,void 0,void 0,(function*(){var e,t,n,i;const r=null===(e=this.engine)||void 0===e?void 0:e.pcManager;if(r)try{const e=tt(yield Promise.all([r.publisher.getStats(),null===(t=r.subscriber)||void 0===t?void 0:t.getStats()]),2),o=e[0],s=e[1],a=o&&Cs(o),c=s&&Cs(s);this.statsLog.info("webrtc stats",{publisher:null==a?void 0:a.connection,subscriber:null==c?void 0:c.connection,inbound:[...null!==(n=null==a?void 0:a.inbound)&&void 0!==n?n:[],...null!==(i=null==c?void 0:c.inbound)&&void 0!==i?i:[]],outbound:null==a?void 0:a.outbound})}catch(o){this.statsLog.debug("could not collect webrtc stats",{error:o})}})),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=>Ao(this,void 0,void 0,(function*(){var n,i,r,o,s,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===(s=null===(o=null===(r=t.track)||void 0===r?void 0:r.getProcessor())||void 0===o?void 0:o.onPublish)||void 0===s||s.call(o,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),Wa(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=Ds(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=>Ao(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=Ds(t.source);i&&n&&n!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(n," active")),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.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Ld),t),this.log=Po(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room,(()=>this.logContext)),this.statsLog=Po(e.LoggerNames.Stats,(()=>this.logContext)),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ad),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign({},null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Md),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new be,this.localParticipant=new Cl("","",this.engine,this.options,this.slots),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Aa(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Aa(this.options.audioCaptureDefaults.deviceId)),(null===(r=this.options.audioOutput)||void 0===r?void 0:r.deviceId)&&this.switchActiveDevice("audiooutput",Aa(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message)))),la()){const e=new AbortController;let t;this.cleanupController=e;const n=this.constructor.cleanupRegistry;n?(t=Nl.createWeakDeviceChangeListener(new WeakRef(this)),n.register(this,e)):t=this.handleDeviceChange,null===(s=null===(o=navigator.mediaDevices)||void 0===o?void 0:o.addEventListener)||void 0===s||s.call(o,"devicechange",t,{signal:e.signal})}}installExtensions(e){var t;const n={log:this.log,get:e=>{const t=this.installedExtensions.get(e.key);if(!t)throw new Error("extension '".concat(String(e.key),"' is not installed"));return t},slot:e=>this.slots[e],getOrCreateParticipant:(e,t)=>this.getOrCreateParticipant(e,t),simulateConnected:(e,t)=>this.simulateConnected(e,t),acquireEmptyAudioStreamTrack:()=>this.acquireEmptyAudioStreamTrack()},i=[];for(const o of e){if(this.installedExtensions.has(o.key))throw new Error("extension '".concat(String(o.key),"' is already installed"));const e=o.install(this,n);this.installedExtensions.set(o.key,e),i.push(e);for(const n of Object.entries(null!==(t=e.dataPackets)&&void 0!==t?t:{})){var r=tt(n,2);const e=r[0],t=r[1];if(this.dataPacketHandlers.has(e))throw new Error("data packet case '".concat(e,"' is already handled by another extension"));this.dataPacketHandlers.set(e,((e,n,i)=>t(e.value.value,e,n,i)))}for(const t of il)void 0!==e[t]&&(this.slots[t]=e[t]);Ul(this,Nl.prototype,e.room,o),Ul(this.localParticipant,Cl.prototype,e.localParticipant,o),e.dispose&&this.extensionDisposers.push(e.dispose)}this.applySlotsToEngine(),i.forEach((e=>{var t;return null===(t=e.onEngineCreated)||void 0===t?void 0:t.call(e,this.engine)}))}applySlotsToEngine(){this.engine.e2eeManager=this.slots.e2eeManager,this.engine.frameMetadataOptions=this.slots.frameMetadataOptions}get extensionResults(){return Array.from(this.installedExtensions.values())}dispose(){return Ao(this,void 0,void 0,(function*(){var t;if(!this.disposed){this.disposed=!0,this.state!==e.ConnectionState.Disconnected&&(yield this.disconnect());for(const e of this.extensionDisposers.reverse())e();null===(t=this.cleanupController)||void 0===t||t.abort()}}))}get logContext(){var e,t,n;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:null===(t=this.localParticipant)||void 0===t?void 0:t.identity,participantID:null===(n=this.localParticipant)||void 0===n?void 0:n.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 this.state===e.ConnectionState.Disconnected?Wo.resolve(""):this.roomInfo&&""!==this.roomInfo.sid?Wo.resolve(this.roomInfo.sid):new Wo(((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(new us("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.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new Zd(this.options),this.applySlotsToEngine(),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=>{var t;null===(t=this.abortController)||void 0===t||t.abort("room disconnected by the server during connection attempt"),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.debug("Resuming signal connection"),!this.connectFuture&&this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.connectFuture?this.bufferedEvents=[]:(this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected),this.emitBufferedEvents())})).on(e.EngineEvent.SignalResumed,(()=>{(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Restarted,(()=>{this.state===e.ConnectionState.Connected&&this.emitBufferedEvents()})).on(e.EngineEvent.Offline,(()=>{!this.connectFuture&&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,(e=>{this.handleLocalTrackSubscribed(e)})).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)})).on(e.EngineEvent.TokenRefreshed,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)})).on(e.EngineEvent.ServerRegionsReported,(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:tl})})).on(e.EngineEvent.RequestSubscribedCodecRefresh,(()=>{for(const e of this.localParticipant.videoTrackPublications.values())Va(e.track)&&e.track.refreshSubscribedCodecs()})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.slots.e2eeManager&&this.slots.e2eeManager.setupEngine(this.engine),this.extensionResults.forEach((e=>{var t;return null===(t=e.onEngineCreated)||void 0===t?void 0:t.call(e,this.engine)})))}createRegionStrategy(){return{getNextUrl:e=>Ao(this,void 0,void 0,(function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null})),resetAttempts:()=>{var e;return null===(e=this.regionUrlProvider)||void 0===e?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Tc.getInstance().getDevices(e,t)}static createWeakDeviceChangeListener(e){return()=>{var t;null===(t=e.deref())||void 0===t||t.handleDeviceChange()}}prepareConnection(t,n){return Ao(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t));try{if(ha(new URL(t))&&n){this.regionUrlProvider=new nl(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(Na(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i)))}else yield fetch(Na(t),{method:"HEAD"})}catch(ke){this.log.warn("could not prepare connection",{error:ke})}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Ao(this,void 0,void 0,(function*(){let n,i=()=>Ao(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":const r="number"==typeof t?t:0;yield this.engine.client.handleOnClose("simulate disconnect",void 0,r);break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":n=new to({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new to({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new to({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new to({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=()=>Ao(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new to({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Ao(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new to({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 to({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Ao(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Ar({reason:Cn.CLIENT_INITIATED,action:Lr.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new to({scenario:{case:"subscriberBandwidth",value:Fa(t)}});break;case"leave-full-reconnect":n=new to({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}acquireDummyAudioElement(){Ll||(Ll=function(){const e=document.createElement("audio");e.id="livekit-dummy-audio-el",e.autoplay=!0,e.hidden=!0;const t=_a();t.enabled=!0;const n=new MediaStream([t]);return e.srcObject=n,document.body.append(e),{element:e,stream:n,track:t,refCount:0}}());const e=Ll;if(this.releaseDummyAudioElement)return e.element;e.refCount+=1;const t=()=>{e.element.srcObject=document.hidden?null:e.stream,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio().catch((e=>this.log.warn("Could not restart audio on page becoming visible",Object.assign(Object.assign({},this.logContext),{error:e})))))};return document.addEventListener("visibilitychange",t),this.releaseDummyAudioElement=()=>{this.releaseDummyAudioElement=void 0,document.removeEventListener("visibilitychange",t),e.refCount-=1,e.refCount>0||(e.element.srcObject=null,e.element.remove(),Ll=void 0,Oa(e.track).catch((e=>this.log.warn("Could not release the dummy audio element track",Object.assign(Object.assign({},this.logContext),{error:e})))))},e.element}acquireEmptyAudioStreamTrack(){const e=_a();return this.acquiredEmptyAudioTracks.add(e),e}releaseAcquiredEmptyAudioTrack(e){this.acquiredEmptyAudioTracks.delete(e)&&Oa(e).catch((e=>this.log.warn("Could not release empty audio stream track",Object.assign(Object.assign({},this.logContext),{error:e}))))}releaseAcquiredEmptyAudioTracks(){for(const e of this.acquiredEmptyAudioTracks)this.releaseAcquiredEmptyAudioTrack(e)}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,n){return Ao(this,arguments,void 0,(function(t,n){var i=this;let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var o,s,a,c,d,l,u;let h=!0,p=!1;const m=r?{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===Bs.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(ke){throw i.options.audioCaptureDefaults.deviceId=e,ke}const r=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&&r&&(p=!0)}else if("videoinput"===t){p=0===i.localParticipant.videoTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===Bs.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(ke){throw i.options.videoCaptureDefaults.deviceId=e,ke}const r=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&&r&&(p=!0)}else if("audiooutput"===t){if(p=!0,!ea()&&!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 Tc.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(ke){throw i.options.audioOutput.deviceId=e,ke}}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.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally((()=>t.close())):null==t||t.close(),t===this.engine&&(this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine())}onTrackAdded(t,n,i){var r,o;if([e.ConnectionState.Connecting,e.ConnectionState.Reconnecting].includes(this.state)){const o=Za(t,n);this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))});const s=()=>{a(),n.getTracks().includes(t)?this.onTrackAdded(t,n,i):this.log.debug("skipping deferred track, the server no longer sends it",{mediaTrackId:t.id,mediaStreamId:n.id})},a=()=>{if(this.off(e.RoomEvent.Reconnected,s),this.off(e.RoomEvent.Connected,s),this.off(e.RoomEvent.Disconnected,a),o){const e=this.pendingTrackAddedCallbacks.get(o);null==e||e.delete(a),0===(null==e?void 0:e.size)&&this.pendingTrackAddedCallbacks.delete(o)}};if(this.once(e.RoomEvent.Reconnected,s),this.once(e.RoomEvent.Connected,s),this.once(e.RoomEvent.Disconnected,a),o){const e=null!==(r=this.pendingTrackAddedCallbacks.get(o))&&void 0!==r?r:new Set;e.add(a),this.pendingTrackAddedCallbacks.set(o,e)}return}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected");if("ended"===t.readyState)return void this.log.debug("skipping incoming track as it already ended");const s=Hs(n.id),a=s[0],c=s[1];let d=null!==(o=Za(t,n))&&void 0!==o?o:t.id;if(a===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant");const l=Array.from(this.remoteParticipants.values()).find((e=>e.sid===a));if(!l)return void(a.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a)));if(!d.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a));d=e}let u;d.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(c,", trackId: ").concat(d),{remoteParticipantID:a,streamId:c,trackId:d}),this.options.adaptiveStream&&(u="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const h=l.addSubscribedMediaTrack(t,d,n,i,u);(null==h?void 0:h.isEncrypted)&&!this.slots.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(h.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}cancelPendingTrackAdded(e){var t;null===(t=this.pendingTrackAddedCallbacks.get(e))||void 0===t||t.forEach((e=>e()))}handleLocalTrackSubscribed(t){const n=()=>this.localParticipant.getTrackPublications().find((e=>e.trackSid===t)),i=n();if(i)return void this.emitLocalTrackSubscribed(i);this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:t});let r;const o=e=>{e.trackSid===t&&(s(),this.emitLocalTrackSubscribed(e))},s=()=>{clearTimeout(r),this.localParticipant.off(e.ParticipantEvent.LocalTrackPublished,o),this.off(e.RoomEvent.Disconnected,s)};this.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,o),this.once(e.RoomEvent.Disconnected,s),r=setTimeout((()=>{s();const e=n();e?this.emitLocalTrackSubscribed(e):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:t})}),1e4)}emitLocalTrackSubscribed(t){this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,t),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,t,this.localParticipant)}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i,r,o;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.roomInfoBeforeRestart=void 0,this.transcriptionReceivedTimes.clear(),this.extensionResults.forEach((e=>{var t;return null===(t=e.onDisconnect)||void 0===t?void 0:t.call(e)})),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{const n=t?[]:Array.from(this.localParticipant.audioTrackPublications.values()).map((e=>e.track)).filter(Wa);this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var n,i,r;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===(r=e.track)||void 0===r||r.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.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],null===(i=this.releaseDummyAudioElement)||void 0===i||i.call(this),this.releaseAcquiredEmptyAudioTracks(),this.releaseAudioContext(n).catch((e=>this.log.warn("Could not release audio context",Object.assign(Object.assign({},this.logContext),{error:e})))),la()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(o=null===(r=navigator.mediaDevices)||void 0===r?void 0:r.removeEventListener)||void 0===o||o.call(r,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n,i){this.remoteParticipants.delete(t),n&&(n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n,i),n.setDisconnected())}selectDefaultDevices(){return Ao(this,void 0,void 0,(function*(){var t,n,i;const r=Tc.getInstance().previousDevices,o=yield Tc.getInstance().getDevices(void 0,!1),s=zo();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let c of o){const t=r.find((e=>e.deviceId===c.deviceId));t&&""!==t.label&&t.kind===c.kind&&t.label!==c.label&&"default"===this.getActiveDevice(c.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,c.kind,c.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let e of a){const s=Os(e),a=this.localParticipant.getTrackPublication(s);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=r.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&&!sa()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&sa()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return Ao(this,arguments,void 0,(function(){var t=this;let n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function*(){var i,r;const o=yield t.audioContextMutex.lock();try{if(t.audioContextReleased&&!n)return;t.audioContextReleased=!1;const o="boolean"!=typeof t.options.webAudioMix?t.options.webAudioMix.audioContext:void 0;if(o?yield t.setRoomAudioContext(o,!1):t.audioContext&&"closed"!==t.audioContext.state||(yield t.setRoomAudioContext(null!==(i=_s())&&void 0!==i?i:void 0,!0)),t.audioContext&&"suspended"===t.audioContext.state)try{yield Promise.race([t.audioContext.resume(),Ks(200)])}catch(ke){t.log.warn("Could not resume audio context",{error:ke})}const s="running"===(null===(r=t.audioContext)||void 0===r?void 0:r.state);s!==t.canPlaybackAudio&&(t.audioEnabled=s,t.emit(e.RoomEvent.AudioPlaybackStatusChanged,s))}finally{o()}}()}))}setRoomAudioContext(e,t){return Ao(this,void 0,void 0,(function*(){const n=!!e&&t;if(this.audioContext===e)return void(this.ownsAudioContext=n);const i=this.ownsAudioContext?this.audioContext:void 0;this.audioContext=e,this.ownsAudioContext=n;try{this.options.webAudioMix&&(yield Promise.all(Array.from(this.remoteParticipants.values()).map((t=>t.setAudioContext(e))))),yield this.localParticipant.setAudioContext(e)}catch(r){this.log.warn("Could not move audio tracks to the new audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}finally{if(i&&"closed"!==i.state)try{yield i.close()}catch(r){this.log.warn("Could not close audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}}}))}releaseAudioContext(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return function*(){e.audioContextReleased=!0;const n=e.audioContext,i=yield e.audioContextMutex.lock();try{if(!e.audioContextReleased||e.audioContext!==n)return;if(!e.ownsAudioContext)return;try{yield Promise.all(t.map((e=>e.setAudioContext(void 0))))}catch(r){e.log.warn("Could not detach retained audio tracks from the audio context",Object.assign(Object.assign({},e.logContext),{error:r}))}yield e.setRoomAudioContext(void 0,!1)}finally{i()}}()}))}createParticipant(e,t){var n;let i;return t?(i=Ml.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.extensionResults.forEach((e=>{var n;return null===(n=e.onParticipantCreated)||void 0===n?void 0:n.call(e,i,t)}))):i=new Ml(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext).catch((e=>this.log.warn("Could not set audio context",Object.assign(Object.assign({},this.logContext),{error:e})))),(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)))),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===Bs.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===Bs.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.cancelPendingTrackAdded(t.trackSid),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===Ln.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(),n=[].concat(...this.extensionResults.map((e=>{var t,n;return null!==(n=null===(t=e.syncState)||void 0===t?void 0:t.call(e))&&void 0!==n?n:[]})));this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Ka(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t){const n=this.remoteParticipants.get(t);if((null==n?void 0:n.sid)===e)return n}}getClientInfoCapabilities(){const e=[];return(gc(this.slots.frameMetadataOptions)||this.slots.e2eeManager)&&e.push(fi.CAP_PACKET_TRAILER),Xa()&&e.push(fi.CAP_COMPRESSION_DEFLATE_RAW),e}setStatsLogging(e){e?this.statsLogInterval||(this.statsLogInterval=ks.setInterval((()=>{this.logWebRTCStats()}),3e4)):this.statsLogInterval&&(ks.clearInterval(this.statsLogInterval),this.statsLogInterval=void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ks.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn("detected connection state mismatch, attempting full reconnect"),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Cn.STATE_MISMATCH))))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&ks.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.log.info("connection state changed: ".concat(this.state," -> ").concat(t)),this.state=t,this.setStatsLogging(t===e.ConnectionState.Connected),this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let t=tt(e,2),n=t[0],i=t[1];this.emit(n,...i)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===e.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}simulateConnected(t,n){this.handleDisconnect(),this.roomInfo=t,this.localParticipant.updateInfo(n),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected),this.emit(e.RoomEvent.Connected),this.setAndEmitConnectionState(e.ConnectionState.Connected)}emit(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(t!==e.RoomEvent.ActiveSpeakersChanged&&t!==e.RoomEvent.TranscriptionReceived){const n=xl(i).filter((e=>void 0!==e));t!==e.RoomEvent.TrackSubscribed&&t!==e.RoomEvent.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),{event:t,args:n}),this.log.debug("room event ".concat(t),{event:t,args:n})}return super.emit(t,...i)}}function xl(e){return e.map((e=>{if(e)return Array.isArray(e)?xl(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}function Ul(e,t,n,i){if(!n)return;const r=Object.getOwnPropertyDescriptors(n);for(const o of Object.keys(r)){if(Object.getOwnPropertyDescriptor(e,o)||o in t)throw new Error("extension '".concat(String(i.key),"' redefines '").concat(o,"'"));o in e&&delete r[o]}Object.defineProperties(e,r)}Nl.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e.abort()}));var Fl=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)}}});const jl=65535,Bl=4294967295;class ql{static u16(e){return new ql(e,jl)}static u32(e){return new ql(e,Bl)}constructor(e,t){if(this.value=e,e<0)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0");if(t>Number.MAX_SAFE_INTEGER)throw new Error("WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.");this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new ql(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t+e))}decrement(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.update((t=>t-e))}getThenIncrement(){const e=this.value;return this.increment(),new ql(e,this.maxSize)}isBefore(e){const t=this.value>>>0,n=(e.value>>>0)-t>>>0;return 0!==n&&n<this.maxSize+1}}class Vl{static fromRtpTicks(e){return new Vl(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Bl);return Vl.fromRtpTicks(e)}constructor(e,t){this.timestamp=ql.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new Vl(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Wl{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new Wl(t,new Date,e)}static startingAtTime(e,t,n){return new Wl(n,e,t)}static rtpStartingNow(e){return Wl.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Wl.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=Wl.durationInMsToTicks(t,this.rateInHz),i=this.base.clone();return i.wrappingAdd(n),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(1e6*e*t+5e8)/1e9;return Math.round(n)}}function Hl(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw new Error("Error coercing ".concat(e," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Kl,zl,Gl;!function(e){e[e.TooShort=0]="TooShort",e[e.HeaderOverrun=1]="HeaderOverrun",e[e.MissingExtWords=2]="MissingExtWords",e[e.UnsupportedVersion=3]="UnsupportedVersion",e[e.InvalidHandle=4]="InvalidHandle",e[e.MalformedExt=5]="MalformedExt"}(Kl||(Kl={}));class Jl extends Zo{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=Kl[t]}static tooShort(){return new Jl("Too short to contain a valid header",Kl.TooShort)}static headerOverrun(){return new Jl("Header exceeds total packet length",Kl.HeaderOverrun)}static missingExtWords(){return new Jl("Extension word indicator is missing",Kl.MissingExtWords)}static unsupportedVersion(e){return new Jl("Unsupported version ".concat(e),Kl.UnsupportedVersion)}static invalidHandle(e){return new Jl("invalid track handle: ".concat(e.message),Kl.InvalidHandle,{cause:e})}static malformedExt(e){return new Jl("Extension with tag ".concat(e," is malformed"),Kl.MalformedExt)}}!function(e){e[e.TooSmallForHeader=0]="TooSmallForHeader",e[e.TooSmallForPayload=1]="TooSmallForPayload"}(zl||(zl={}));class Ql extends Zo{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=zl[t]}static tooSmallForHeader(){return new Ql("Buffer cannot fit header",zl.TooSmallForHeader)}static tooSmallForPayload(){return new Ql("Buffer cannot fit payload",zl.TooSmallForPayload)}}class Yl{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),i=this.toBinaryInto(n);if(e!==i)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(i," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}!function(e){e[e.UserTimestamp=2]="UserTimestamp",e[e.E2ee=1]="E2ee"}(Gl||(Gl={}));class Xl extends Yl{}class Zl extends Xl{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+Zl.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,Zl.tag),t+=1,e.setUint8(t,Zl.lengthBytes),t+=1,e.setBigUint64(t,this.timestamp),t+=8;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:Zl.tag,lengthBytes:Zl.lengthBytes,timestamp:this.timestamp}}}Zl.tag=Gl.UserTimestamp,Zl.lengthBytes=8;class $l extends Xl{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+$l.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,$l.tag),t+=1,e.setUint8(t,$l.lengthBytes),t+=1,e.setUint8(t,this.keyIndex),t+=1;for(let i=0;i<this.iv.length;i+=1)e.setUint8(t,this.iv[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:$l.tag,lengthBytes:$l.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}$l.tag=Gl.E2ee,$l.lengthBytes=13;class eu extends Yl{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){t+=this.e2ee.toBinaryInto(e)}if(this.userTimestamp){t+=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t))}const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){const t=Hl(e);let n,i,r=0;for(;t.byteLength-r>=2;){const e=t.getUint8(r);r+=1;const o=t.getUint8(r);if(r+=1,0!==e)switch(e){case Gl.UserTimestamp:if(t.byteLength-r<Zl.lengthBytes)throw Jl.malformedExt(e);n=new Zl(t.getBigUint64(r)),r+=o;break;case Gl.E2ee:if(t.byteLength-r<$l.lengthBytes)throw Jl.malformedExt(e);const s=t.getUint8(r),a=new Uint8Array(12);for(let e=0;e<a.length;e+=1){let n=r;n+=1,n+=1*e,a[e]=t.getUint8(n)}i=new $l(s,a),r+=o;break;default:if(t.byteLength-r<o)throw Jl.malformedExt(e);r+=o}}return[new eu({userTimestamp:n,e2ee:i}),t.byteLength]}toJSON(){var e,t,n,i;return{userTimestamp:null!==(t=null===(e=this.userTimestamp)||void 0===e?void 0:e.toJSON())&&void 0!==t?t:null,e2ee:null!==(i=null===(n=this.e2ee)||void 0===n?void 0:n.toJSON())&&void 0!==i?i:null}}}const tu={from:e=>({payload:e.payload,extensions:new eu({userTimestamp:e.userTimestamp?new Zl(e.userTimestamp):void 0})}),lossyIntoFrame(e){var t;return{payload:e.payload,userTimestamp:null===(t=e.extensions.userTimestamp)||void 0===t?void 0:t.timestamp}}};var nu;!function(e){e[e.Reserved=0]="Reserved",e[e.TooLarge=1]="TooLarge"}(nu||(nu={}));class iu extends Zo{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=nu[t]}isReason(e){return this.reason===e}static tooLarge(){return new iu("Value too large to be a valid track handle",nu.TooLarge)}static reserved(e){return new iu("0x".concat(e.toString(16)," is a reserved value."),nu.Reserved)}}const ru={fromNumber(e){if(0===e)throw iu.reserved(e);if(e>jl)throw iu.tooLarge();return e}};class ou{constructor(){this.value=0}get(){return this.value+=1,this.value>jl?null:this.value}reset(){this.value=0}}class su extends Yl{constructor(e){var t;super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=null!==(t=e.extensions)&&void 0!==t?t:new eu}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((2+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:4*t-2-e}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes;let i=12;return t>0&&(i+=2+t+n),i}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Ql.tooSmallForHeader();let t,n=0;switch(this.marker){case au.Inter:t=0;break;case au.Final:t=1;break;case au.Start:t=2;break;case au.Single:t=3}n|=t<<3;const i=this.extensionsMetrics(),r=i.lengthBytes,o=i.lengthWords,s=i.paddingLengthBytes;r>0&&(n|=4);let a=0;if(e.setUint8(a,n),a+=1,e.setUint8(a,0),a+=1,e.setUint16(a,this.trackHandle),a+=2,e.setUint16(a,this.sequence.value),a+=2,e.setUint16(a,this.frameNumber.value),a+=2,e.setUint32(a,this.timestamp.asTicks()),a+=4,r>0){const t=o-1;e.setUint16(a,t),a+=2;a+=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+a));for(let n=0;n<s;n+=1)e.setUint8(a,0),a+=1}const c=this.toBinaryLengthBytes();if(a!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(a," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){const t=Hl(e);if(t.byteLength<12)throw Jl.tooShort();let n=0;const i=t.getUint8(n);n+=1;const r=i>>5&7;if(r>0)throw Jl.unsupportedVersion(r);let o;switch(i>>3&3){case 2:o=au.Start;break;case 1:o=au.Final;break;case 3:o=au.Single;break;default:o=au.Inter}const s=(i>>2&1)>0;let a;n+=1;try{a=ru.fromNumber(t.getUint16(n))}catch(ke){throw ke instanceof iu&&(ke.isReason(nu.Reserved)||ke.isReason(nu.TooLarge))?Jl.invalidHandle(ke):ke}n+=2;const c=ql.u16(t.getUint16(n));n+=2;const d=ql.u16(t.getUint16(n));n+=2;const l=Vl.fromRtpTicks(t.getUint32(n));n+=4;let u=new eu;if(s){if(t.byteLength-n<2)throw Jl.missingExtWords();let e=t.getUint16(n);n+=2;let i=4*(e+1)-2;if(n+i>t.byteLength)throw Jl.headerOverrun();let r=new DataView(t.buffer,t.byteOffset+n,i);const o=tt(eu.fromBinary(r),2);u=o[0],n+=o[1]}return[new su({marker:o,trackHandle:a,sequence:c,frameNumber:d,timestamp:l,extensions:u}),n]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}}var au,cu,du,lu,uu;!function(e){e[e.Start=0]="Start",e[e.Inter=1]="Inter",e[e.Final=2]="Final",e[e.Single=3]="Single"}(au||(au={}));class hu extends Yl{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;if(t+=this.header.toBinaryInto(e),e.byteLength-t<this.payload.byteLength)throw Ql.tooSmallForPayload();for(let i=0;i<this.payload.length;i+=1)e.setUint8(t,this.payload[i]),t+=1;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return n}static fromBinary(e){const t=Hl(e),n=tt(su.fromBinary(t),2),i=n[0],r=n[1],o=t.buffer.slice(t.byteOffset+r,t.byteOffset+t.byteLength);return[new hu(i,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}class pu extends Zo{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=cu[t]}static mtuTooShort(){return new pu("MTU is too short to send frame",cu.MtuTooShort)}}!function(e){e[e.MtuTooShort=0]="MtuTooShort"}(cu||(cu={}));class mu{constructor(e,t){this.sequence=ql.u16(0),this.frameNumber=ql.u16(0),this.clock=Wl.rtpStartingNow(Vl.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?au.Single:0===e?au.Start:e===t-1?au.Final:au.Inter}*packetize(e,t){var n;const i=this.frameNumber.getThenIncrement(),r={marker:au.Inter,trackHandle:this.handle,sequence:ql.u16(0),frameNumber:i,timestamp:null!==(n=null==t?void 0:t.now)&&void 0!==n?n:this.clock.now(),extensions:e.extensions},o=new su(r).toBinaryLengthBytes();if(o>=this.mtuSizeBytes)throw pu.mtuTooShort();const s=this.mtuSizeBytes-o,a=Math.ceil(e.payload.byteLength/s);for(let d=0,l=0;l<e.payload.byteLength;d=(c=[d+1,l+s])[0],l=c[1],c){var c;const t=this.sequence.getThenIncrement(),n=new su(Object.assign(Object.assign({},r),{marker:mu.computeFrameMarker(d,a),sequence:t})),i=Math.min(s,e.payload.byteLength-l),o=new Uint8Array(e.payload.buffer,e.payload.byteOffset+l,i);yield new hu(n,o)}}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.DuplicateName=1]="DuplicateName",e[e.Timeout=2]="Timeout",e[e.LimitReached=3]="LimitReached",e[e.Disconnected=4]="Disconnected",e[e.Cancelled=5]="Cancelled",e[e.InvalidName=6]="InvalidName",e[e.Unknown=7]="Unknown"}(du||(du={}));class gu extends Zo{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=du[t],this.rawMessage=null==n?void 0:n.rawMessage}static notAllowed(e){return new gu("Data track publishing unauthorized",du.NotAllowed,{rawMessage:e})}static duplicateName(e){return new gu("Track name already taken",du.DuplicateName,{rawMessage:e})}static invalidName(e){return new gu("Track name is invalid",du.InvalidName,{rawMessage:e})}static timeout(){return new gu("Publish data track timed-out. Does the LiveKit server support data tracks?",du.Timeout)}static limitReached(e){return new gu("Data track publication limit reached",du.LimitReached,{rawMessage:e})}static unknown(e,t){return new gu("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),du.Unknown)}static disconnected(){return new gu("Room disconnected",du.Disconnected)}static cancelled(){return new gu("Publish data track cancelled by caller",du.Cancelled)}}!function(e){e[e.TrackUnpublished=0]="TrackUnpublished",e[e.Dropped=1]="Dropped"}(lu||(lu={}));class fu extends Zo{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=lu[t]}static trackUnpublished(){return new fu("Track is no longer published",lu.TrackUnpublished)}static dropped(e){return new fu("Frame was dropped",lu.Dropped,{cause:e})}}!function(e){e[e.Packetizer=0]="Packetizer",e[e.Encryption=1]="Encryption"}(uu||(uu={}));class vu extends Zo{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=uu[t]}static packetizer(e){return new vu("Error packetizing frame",uu.Packetizer,{cause:e})}static encryption(e){return new vu("Error encrypting frame",uu.Encryption,{cause:e})}}const ku=Symbol.for("lk.track"),yu=Symbol.for("lk.data-track");class bu{constructor(t,n){this.trackSymbol=ku,this.isLocal=!0,this.typeSymbol=yu,this.handle=null,this.log=wo,this.flushedFuture=new Da,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;null===(t=(e=this.flushedFuture).resolve)||void 0===t||t.call(e),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&(null===(n=(t=this.flushedFuture).resolve)||void 0===n||n.call(t),this.flushedFuture=new Da)},this.options=t,this.manager=n,this.log=Po(e.LoggerNames.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const i=new bu(e,t);return i.handle=n,i}get info(){const e=this.descriptor;return"active"===(null==e?void 0:e.type)?e.info:void 0}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return Ao(this,void 0,void 0,(function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}}))}isPublished(){var e;return"active"===(null===(e=this.descriptor)||void 0===e?void 0:e.type)&&"unpublished"!==this.descriptor.publishState}tryPush(e){if(!this.handle)throw fu.trackUnpublished();const t=tu.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return Ao(this,void 0,void 0,(function*(){if(!this.isFlushed)return this.flushedFuture.promise}))}unpublish(){return Ao(this,void 0,void 0,(function*(){if(this.handle)try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}else wo.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'))}))}}const Tu={from:e=>({sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==xn.NONE}),toProtobuf:e=>new jn({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?xn.GCM:xn.NONE})};class Su{constructor(e,t,n){this.trackSymbol=ku,this.isLocal=!1,this.typeSymbol=yu,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=tt(this.manager.openSubscriptionStream(this.info.sid,null==e?void 0:e.signal,null==e?void 0:e.bufferSize),2),n=t[0];return t[1].catch((()=>{})),n}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}const Eu=Object.values(ge),Cu=Object.values(fe),wu=Object.values(ve),Ru=[ge.h180,ge.h360],Pu=[fe.h180,fe.h360],Iu=["q","h","f"];function _u(e,t,n,i){var r,o;let s=null==i?void 0:i.videoEncoding;e&&(s=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,l=Zs(d,i);if(!s&&!a&&!c||!t||!n)return[{}];s||(s=function(e,t,n,i){const r=function(e,t,n){if(e)return wu;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)<Math.abs(i-4/3))return Eu;return Cu}(e,t,n);let o=r[0].encoding;const s=Math.max(t,n);for(let a=0;a<r.length;a+=1){const e=r[a];if(o=e.encoding,e.width>=s)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),wo.debug("using video encoding",s));const u=s.maxFramerate,h=new de(t,n,s.maxBitrate,s.maxFramerate,s.priority);if(c&&Ys(d)&&!l){const e=new Lu(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=zo();if($s()){const i="h"==e.suffix?2:3,r=function(e){return e||(e=zo()),"Safari"===(null==e?void 0:e.name)&&va(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&va(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:Iu[2-n],maxBitrate:s.maxBitrate/Math.pow(i,n),maxFramerate:h.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:s.maxBitrate,maxFramerate:h.encoding.maxFramerate,scalabilityMode:c});return h.encoding.priority&&(t[0].priority=h.encoding.priority,t[0].networkPriority=h.encoding.priority),wo.debug("using svc encoding",{encodings:t}),t}if(!a)return[s];const p=e=>(l&&e.forEach((e=>{e.scalabilityMode=c})),e);let m,g;if(m=e?null!==(r=Au(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:Du(e,h):null!==(o=Au(null==i?void 0:i.videoSimulcastLayers))&&void 0!==o?o:Du(e,h),m.length>0){const e=m[0];if(m.length>1)g=tt(m,2)[1];const i=Math.max(t,n);if(i>=960&&g)return p(Mu(t,n,[e,g,h],u));if(i>=480)return p(Mu(t,n,[e,h],u))}return p(Mu(t,n,[h]))}function Ou(e,t,n){var i,r,o,s;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&wo.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===(r=e.dimensions)||void 0===r?void 0:r.width,d=null!==(o=a.height)&&void 0!==o?o:null===(s=e.dimensions)||void 0===s?void 0:s.height;e.source===Bs.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1);return _u(e.source===Bs.Source.ScreenShare,c,d,n)}function Du(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(n=t).encoding.maxFramerate}].map((e=>{var t,i;return new de(Math.floor(n.width/e.scaleResolutionDownBy),Math.floor(n.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=n.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(i=e.fps)&&void 0!==i?i:30))))),e.fps,n.encoding.priority)}));var n;const i=t.width,r=t.height,o=i>r?i/r:r/i;return Math.abs(o-16/9)<Math.abs(o-4/3)?Ru:Pu}function Mu(e,t,n,i){const r=[];if(n.forEach(((n,o)=>{if(o>=Iu.length)return;const s=Math.min(e,t),a={rid:Iu[o],scaleResolutionDownBy:Math.max(1,s/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=zo(),l="Firefox"===(null==d?void 0:d.name)&&"iOS"!==d.os||0===o;n.encoding.priority&&l&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),r.push(a)})),ua()&&"ios"===ga()){let e;r.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;r.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,wo.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),wo.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return r}function Au(e){if(e)return e.slice().sort(((e,t)=>{const n=e.encoding,i=t.encoding;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 Lu{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 Nu extends ul{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],r=arguments.length>3?arguments[3]:void 0;super(t,Bs.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Ao(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(ke){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:ke}))}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 r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=al(t,r)})),this._currentBitrate=e}this.prevStats=n})),this.senderLock=new be}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;this.signalClient=e;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),la()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),sl)))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;yield e.pauseUpstream.call(this);try{for(var s,a=!0,c=Uo(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);a=!0){r=s.value,a=!1;const e=r;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(null)}}catch(d){n={error:d}}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 Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;yield e.resumeUpstream.call(this);try{for(var s,a=!0,c=Uo(this.simulcastCodecs.values());!(t=(s=yield c.next()).done);a=!0){r=s.value,a=!1;const e=r;yield null===(o=e.sender)||void 0===o?void 0:o.replaceTrack(e.mediaStreamTrack)}}catch(d){n={error:d}}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 Ao(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!==Bs.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 Ao(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==Bs.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Ao(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 r={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&&(r.jitter=o.jitter,r.packetsLost=o.packetsLost,r.roundTripTime=o.roundTripTime),t.push(r)}})),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}))}isSvcPublish(e){return Ys(e)&&!Zs(e,this.publishOptions)}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new Hr({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(this.isSvcPublish(this.codec),n)}restartTrack(e){return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;let s;if(e){const t=Ps({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Uo(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){r=a.value,c=!1;const e=r;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(l){n={error:l}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()}))}onSenderTrackSwapped(){return Ao(this,void 0,void 0,(function*(){yield this.refreshSenderEncodings()}))}refreshSenderEncodings(){return Ao(this,void 0,void 0,(function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let t;try{t=yield this.waitForDimensions()}catch(ke){return void this.log.warn("could not determine new track dimensions, skipping encoding recompute",Object.assign(Object.assign({},this.logContext),{error:ke}))}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===t.width&&this.lastEncodedDimensions.height===t.height)return;const i=_u(this.source===Bs.Source.ScreenShare,t.width,t.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,i),this.encodings=i,this.lastEncodedDimensions=t;for(const r of this.simulcastCodecs){var n=tt(r,2);const t=n[0],i=n[1];if(!i.sender||"closed"===(null===(e=i.sender.transport)||void 0===e?void 0:e.state))continue;if(!pe(t))continue;const o=Ou(this,t,Object.assign({},this.publishOptions));o&&(yield this.applyEncodingsToSender(i.sender,o),i.encodings=o)}}catch(ke){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:ke}))}finally{t()}}))}applyEncodingsToSender(e,t){return Ao(this,void 0,void 0,(function*(){const n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach(((e,n)=>{if(!1===e.active)return;const i=t[n];void 0!==i.scaleResolutionDownBy&&(e.scaleResolutionDownBy=i.scaleResolutionDownBy),void 0!==i.maxBitrate&&(e.maxBitrate=i.maxBitrate),void 0!==i.maxFramerate&&(e.maxFramerate=i.maxFramerate),void 0!==i.priority&&(e.priority=i.priority,e.networkPriority=i.priority)})),this.log.debug("updating sender encodings after track restart",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Ao(this,arguments,void 0,(function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,o,s,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=Uo(n.simulcastCodecs.values());!(r=(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(p){o={error:p}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(o)throw o.error}}}()}))}setDegradationPreference(e){return Ao(this,void 0,void 0,(function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(const e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)}))}applyDegradationPreference(e){return Ao(this,void 0,void 0,(function*(){if(e)try{this.log.debug("setting degradationPreference to ".concat(this.degradationPreference),this.logContext);const t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(ke){this.log.warn("failed to set degradationPreference",Object.assign({error:ke},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){return Ao(this,void 0,void 0,(function*(){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout((()=>{this.refreshSubscribedCodecs()}),5e3))}))}refreshSubscribedCodecs(){return Ao(this,void 0,void 0,(function*(){if(this.subscribedCodecs)return this.setPublishingCodecs(this.subscribedCodecs).catch((e=>this.log.warn("failed to refresh codec for track",Object.assign(Object.assign({},this.logContext),{error:e}))))}))}setPublishingCodecs(e){return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o,s,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(this.isSvcPublish(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=Uo(e);!(r=(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 xu(t.sender,t.encodings,e.qualities,this.senderLock,this.isSvcPublish(e.codec),this.log,this.logContext));else for(const n of e.qualities)if(n.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(this.isSvcPublish(e.codec),e.qualities)}}catch(d){o={error:d}}finally{try{t||r||!(s=n.return)||(yield s.call(n))}finally{if(o)throw o.error}}return c}))}setPublishingLayers(e,t){return Ao(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 xu(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Ao(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&&Ys(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(ke){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:ke})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Ao(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),da()&&this.isInBackground&&this.source===Bs.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function xu(e,t,n,i,r,o,s){return Ao(this,void 0,void 0,(function*(){const a=yield i.lock();o.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),a=i.encodings;if(!a)return;if(a.length!==t.length)return void o.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(r){n.some((e=>e.enabled))&&n.forEach((e=>e.enabled=!0))}a.forEach(((e,i)=>{var r;let a=null!==(r=e.rid)&&void 0!==r?r:"";""===a&&(a="q");const d=Uu(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"),s),na()&&(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({},s),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}}))}function Uu(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Fu(t,n,i,r){if(!i)return[new Jn({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(r){const r=i[0].scalabilityMode,o=new Lu(r),s=[],a="h"==o.suffix?1.5:2,c="h"==o.suffix?2:3;for(let d=0;d<o.spatial;d+=1)s.push(new Jn({quality:Math.min(e.VideoQuality.HIGH,o.spatial-1)-d,width:Math.ceil(t/Math.pow(a,d)),height:Math.ceil(n/Math.pow(a,d)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return s}return i.map((e=>{var i,r,o;const s=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let a=Uu(null!==(r=e.rid)&&void 0!==r?r:"");return new Jn({quality:a,width:Math.ceil(t/s),height:Math.ceil(n/s),bitrate:null!==(o=e.maxBitrate)&&void 0!==o?o:0,ssrc:0})}))}class ju{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 fs("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 fs("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}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)}}class Bu extends ju{[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch((()=>{}));const t=t=>{e.cancel(t).catch((()=>{})),e.releaseLock(),this.signal=void 0};return{next:()=>Ao(this,void 0,void 0,(function*(){var n;try{const t=this.signal;if(null==t?void 0:t.aborted)throw t.reason;const i=yield new Promise(((n,i)=>{if(t){const r=()=>i(t.reason);t.addEventListener("abort",r,{once:!0}),e.read().then(n,i).finally((()=>{t.removeEventListener("abort",r)}))}else e.read().then(n,i)}));return i.done?(this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(n=this.onProgress)||void 0===n||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(i.value),{done:!1,value:i.value.content})}catch(i){throw t(i),i}})),return(){return Ao(this,void 0,void 0,(function*(){return t(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,o;let s=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Uo(a);!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const e=o;s.add(e)}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return Array.from(s)}()}))}}class qu extends ju{[Symbol.asyncIterator](){const t=this.reader.getReader();t.closed.catch((()=>{}));const n=new TextDecoder("utf-8"),i=this.signal,r=e=>{t.cancel(e).catch((()=>{})),t.releaseLock(),this.signal=void 0};return{next:()=>Ao(this,void 0,void 0,(function*(){var o;try{if(null==i?void 0:i.aborted)throw i.reason;const r=yield new Promise(((e,n)=>{if(i){const r=()=>n(i.reason);i.addEventListener("abort",r,{once:!0}),t.read().then(e,n).finally((()=>{i.removeEventListener("abort",r)}))}else t.read().then(e,n)}));if(r.done)return this.validateBytesReceived(!0),"number"==typeof this.totalByteSize&&(null===(o=this.onProgress)||void 0===o||o.call(this,1)),{done:!0,value:void 0};{let t;this.handleChunkReceived(r.value);try{t=n.decode(r.value.content)}catch(s){throw new fs("Cannot decode datastream chunk ".concat(r.value.chunkIndex," as text: ").concat(s),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(s){throw r(s),s}})),return(){return Ao(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Ao(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,r,o;let s="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Uo(a);!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;s+=o}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}return s}()}))}}class Vu extends Error{constructor(e,t,n,i){super(t),this.code=e,this.message=Gu(t,Vu.MAX_MESSAGE_BYTES),this.data=n?Gu(n,Vu.MAX_DATA_BYTES):void 0,void 0!==(null==i?void 0:i.cause)&&(this.cause=null==i?void 0:i.cause)}static fromProto(e){return new Vu(e.code,e.message,e.data)}toProto(){return new li({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new Vu(Vu.ErrorCode[e],Vu.ErrorMessage[e],t,n)}}Vu.MAX_MESSAGE_BYTES=256,Vu.MAX_DATA_BYTES=15360,Vu.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,CONNECTION_CLOSED:1506,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Vu.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",CONNECTION_CLOSED:"Connection closed",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Wu="lk.rpc_request",Hu="lk.rpc_response";var Ku;!function(e){e.RPC_REQUEST_ID="lk.rpc_request_id",e.RPC_REQUEST_METHOD="lk.rpc_request_method",e.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",e.RPC_REQUEST_VERSION="lk.rpc_request_version"}(Ku||(Ku={}));function zu(e){return(new TextEncoder).encode(e).length}function Gu(e,t){if(zu(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const o=Math.floor((n+i+1)/2);r.encode(e.slice(0,o)).length<=t?n=o:i=o-1}const o=n>0?e.charCodeAt(n-1):0;return o>=55296&&o<=56319&&(n-=1),e.slice(0,n)}class Ju extends Vo.EventEmitter{constructor(e,t,n,i){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=i}performRpc(e){return Ao(this,arguments,void 0,(function(e){var t=this;let n=e.destinationIdentity,i=e.method,r=e.payload,o=e.responseTimeout,s=void 0===o?15e3:o;return function*(){const e=t.getRemoteParticipantClientProtocol(n);if(zu(r)>15360&&e<1)throw Vu.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const o=t.getServerVersion();if(o&&va(o,"1.8.0")<0)throw Vu.builtIn("UNSUPPORTED_SERVER");const a=Math.max(s,8e3),c=crypto.randomUUID(),d=new Da;let l=null;const u=setTimeout((()=>{var e;t.pendingAcks.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Vu.builtIn("CONNECTION_TIMEOUT")),t.pendingResponses.delete(c),null!==l&&clearTimeout(l)}),7e3);t.pendingAcks.set(c,{resolve:()=>{clearTimeout(u)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:d,participantIdentity:n});const h=d.promise.finally((()=>{null!==l&&clearTimeout(l),t.pendingAcks.has(c)&&(t.log.warn("RPC response received before ack",c),t.pendingAcks.delete(c),clearTimeout(u))}));h.catch((()=>{}));try{yield t.publishRpcRequest(n,c,i,r,a,e)}catch(ke){throw clearTimeout(u),t.pendingAcks.delete(c),t.pendingResponses.delete(c),ke}return t.pendingResponses.has(c)&&(l=setTimeout((()=>{var e;t.pendingResponses.delete(c),null===(e=d.reject)||void 0===e||e.call(d,Vu.builtIn("RESPONSE_TIMEOUT"))}),s)),[c,h]}()}))}publishRpcRequest(e,t,n,i,r,o){return Ao(this,void 0,void 0,(function*(){o>=1?yield this.outgoingDataStreamManager.sendText(i,{topic:Wu,destinationIdentities:[e],attributes:{[Ku.RPC_REQUEST_ID]:t,[Ku.RPC_REQUEST_METHOD]:n,[Ku.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[Ku.RPC_REQUEST_VERSION]:"".concat(2)}}):this.emit("sendDataPacket",{packet:new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcRequest",value:new ai({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}})})}))}handleIncomingDataStream(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=n[Ku.RPC_REQUEST_ID];if(!i)return void this.log.warn("RPC data stream malformed: ".concat(Ku.RPC_REQUEST_ID," not set."));const r=this.pendingResponses.get(i);if(r&&r.participantIdentity!==t)return void this.log.warn("RPC response stream for ".concat(i," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));let o;try{o=yield e.readAll()}catch(ke){return this.log.warn("Error reading RPC response payload: ".concat(ke)),void this.handleIncomingRpcResponseFailure(i,Vu.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:ke}))}this.handleIncomingRpcResponseSuccess(i,o)}))}handleIncomingRpcResponseSuccess(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).resolve)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,i;const r=this.pendingResponses.get(e);r?(null===(i=(n=r.completionFuture).reject)||void 0===i||i.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const o of this.pendingAcks){var n=tt(o,2);const t=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(t)}for(const o of this.pendingResponses){var i=tt(o,2);const n=i[0];var r=i[1];const s=r.participantIdentity,a=r.completionFuture;s===e&&(null===(t=a.reject)||void 0===t||t.call(a,Vu.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}}handleRoomDisconnected(){var e;for(const t of this.pendingAcks.values()){(0,t.resolve)()}this.pendingAcks.clear();for(const t of this.pendingResponses.values()){const n=t.completionFuture;null===(e=n.reject)||void 0===e||e.call(n,Vu.builtIn("CONNECTION_CLOSED"))}this.pendingResponses.clear()}}class Qu extends Vo.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return Ao(this,void 0,void 0,(function*(){var n;if(this.publishRpcAck(e,t.id),1!==t.version)return void this.publishRpcResponsePacket(e,t.id,null,Vu.builtIn("UNSUPPORTED_VERSION"));const i=this.rpcHandlers.get(t.method);if(!i)return void this.publishRpcResponsePacket(e,t.id,null,Vu.builtIn("UNSUPPORTED_METHOD"));let r;try{r=yield i({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(o){let i;return o instanceof Vu?i=o:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),o),i=Vu.builtIn("APPLICATION_ERROR","Uncaught error: ".concat(null!==(n=null==o?void 0:o.message)&&void 0!==n?n:o),{cause:o})),void this.publishRpcResponsePacket(e,t.id,null,i)}yield this.publishRpcResponse(e,t.id,null!=r?r:"")}))}handleIncomingDataStream(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=n[Ku.RPC_REQUEST_ID],r=n[Ku.RPC_REQUEST_METHOD],o=parseInt(n[Ku.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),s=parseInt(n[Ku.RPC_REQUEST_VERSION],10);if(!i||!r||Number.isNaN(o)||Number.isNaN(s))return this.log.warn("RPC data stream malformed: ".concat(Ku.RPC_REQUEST_ID," / ").concat(Ku.RPC_REQUEST_METHOD," / ").concat(Ku.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(Ku.RPC_REQUEST_VERSION," not set.")),void this.publishRpcResponsePacket(t,i,null,Vu.builtIn("APPLICATION_ERROR","RPC data stream malformed"));if(this.publishRpcAck(t,i),2!==s)return void this.publishRpcResponsePacket(t,i,null,Vu.builtIn("UNSUPPORTED_VERSION"));let a;try{a=yield e.readAll()}catch(ke){return this.log.warn("Error reading RPC request payload: ".concat(ke)),void this.publishRpcResponsePacket(t,i,null,Vu.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:ke}))}const c=this.rpcHandlers.get(r);if(!c)return void this.publishRpcResponsePacket(t,i,null,Vu.builtIn("UNSUPPORTED_METHOD"));let d;try{d=yield c({requestId:i,callerIdentity:t,payload:a,responseTimeout:o})}catch(l){let e;return l instanceof Vu?e=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),l),e=Vu.builtIn("APPLICATION_ERROR")),void this.publishRpcResponsePacket(t,i,null,e)}yield this.publishRpcResponse(t,i,null!=d?d:"")}))}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcAck",value:new ci({requestId:t})}})})}publishRpcResponsePacket(e,t,n,i){this.emit("sendDataPacket",{packet:new Yn({destinationIdentities:[e],kind:Xn.RELIABLE,value:{case:"rpcResponse",value:new di({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}})})}publishRpcResponse(e,t,n){return Ao(this,void 0,void 0,(function*(){if(this.getRemoteParticipantClientProtocol(e)>=1)return void(yield this.outgoingDataStreamManager.sendText(n,{topic:Hu,destinationIdentities:[e],attributes:{[Ku.RPC_REQUEST_ID]:t}}));if(zu(n)>15360)return this.log.warn("RPC Response payload too large for request ".concat(t,". To send larger responses, consider updating the sending client.")),void this.publishRpcResponsePacket(e,t,null,Vu.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));this.publishRpcResponsePacket(e,t,n,null)}))}}class Yu{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(0!==this.activeSsrc&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=300;){const e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class Xu{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{const t=e.data;if("metadata"===t.kind){const e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{wo.error("frame metadata worker encountered an error:",{error:e.error})},this.worker=null==e?void 0:e.worker}setup(t){t!==this.room&&(this.room=t,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:"init"})),t.on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{"video"===e.kind&&this.setupReceiver(e,t.trackInfo)})).on(e.RoomEvent.TrackUnsubscribed,(e=>{this.teardownTrack(e)})).on(e.RoomEvent.Disconnected,(()=>{this.cleanup()})))}setupReceiver(e,t){var n,i,r;const o=e.receiver;if(!o)return;if(!(!!(null==t?void 0:t.packetTrailerFeatures)&&t.packetTrailerFeatures.length>0))return void((null===(n=this.room)||void 0===n?void 0:n.hasE2EESetup)||this.setupPassthroughReceiver(o,e.mediaStreamID));if(!gc(this.worker?{worker:this.worker}:void 0)&&!(null===(i=this.room)||void 0===i?void 0:i.hasE2EESetup))return void wo.warn("frame metadata transform not supported; skipping extraction");const s=new Yu,a=e.mediaStreamID;this.extractors.set(a,s),e.frameMetadataExtractor=s,(null===(r=this.room)||void 0===r?void 0:r.hasE2EESetup)||this.setupWorkerReceiver(o,a,!0)}setupPassthroughReceiver(e,t){mc()?"transform"in e&&(e.transform=null):(this.worker&&gc({worker:this.worker})&&!this.workerPipelines.has(e)||this.worker&&this.workerPipelines.has(e))&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];const i=this.worker;if(!i)return;if(mc())return void(e.transform=new RTCRtpScriptTransform(i,{kind:"decode",trackId:t}));const r=this.workerPipelines.get(e);if(r){const o={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:n}};return i.postMessage(o),void this.workerPipelines.set(e,t)}if(!("createEncodedStreams"in e))return void wo.warn("createEncodedStreams not supported");let o;try{o=e.createEncodedStreams()}catch(a){return void wo.warn("failed to create encoded streams",{error:a})}const s={kind:"decode",data:{readableStream:o.readable,writableStream:o.writable,trackId:t,hasPacketTrailer:n}};i.postMessage(s,[o.readable,o.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof Il&&(e.frameMetadataExtractor=void 0)}cleanup(){for(const e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear()}dispose(){var e;this.cleanup(),null===(e=this.worker)||void 0===e||e.terminate()}}const Zu=Xu;function $u(){return new CompressionStream("deflate-raw")}function eh(){return new DecompressionStream("deflate-raw")}function th(e,t){return Ao(this,void 0,void 0,(function*(){const n=new DecompressionStream("deflate-raw"),i=n.writable.getWriter();return i.write(e).catch((()=>{})),i.close().catch((()=>{})),nh(n.readable,t)}))}function nh(t,n){return Ao(this,void 0,void 0,(function*(){const i=t.getReader(),r=[];let o=0;for(;;){const t=yield i.read(),s=t.done,a=t.value;if(s)break;if(r.push(a),o+=a.byteLength,"number"==typeof n&&o>n)throw yield i.cancel(),new fs("Decompressed payload exceeds the maximum payload size of ".concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge)}const s=new Uint8Array(o);let a=0;for(const e of r)s.set(e,a),a+=e.byteLength;return s}))}const ih=15e3;class rh{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.maxPayloadByteLength,n=void 0===t?5e9:t,i=e.maxOpenStreamsPerParticipant,r=void 0===i?500:i;this.log=wo,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=n,this.maxOpenStreamsPerParticipant=r}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new fs('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 fs('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)}clearControllers(){const t=new fs("Room disconnected in the middle of receiving data",e.DataStreamErrorReason.AbnormalEnd);for(const e of this.byteStreamControllers.values()){e.controller.error(t)}for(const e of this.textStreamControllers.values()){e.controller.error(t)}this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(t){const n=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),i=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(n.length>0||i.length>0){const s=new fs("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const e of i){var r=tt(e,2);const t=r[0];r[1].controller.error(s),this.byteStreamControllers.delete(t)}for(const e of n){var o=tt(e,2);const t=o[0];o[1].controller.error(s),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(this.isConnected)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!'))}else this.bufferedPackets.push({packet:e,encryptionType:t})}hasTooManyOpenStreams(e){let t=0;for(const n of[this.byteStreamControllers,this.textStreamControllers])for(const i of n.values()){i.sendingParticipantIdentity===e&&(t+=1)}return t>=this.maxOpenStreamsPerParticipant}handleStreamHeader(t,n,i){var r;if(this.hasTooManyOpenStreams(n))this.log.error("Participant ".concat(n," already has ").concat(this.maxOpenStreamsPerParticipant," data streams open, dropping stream ").concat(t.streamId));else switch(t.contentHeader.case){case"byteHeader":{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 s;const a={id:t.streamId,name:null!==(r=t.contentHeader.value.name)&&void 0!==r?r:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Ua(t.timestamp),attributes:t.attributes,encryptionType:i};let c;switch(t.compression){case Si.DEFLATE_RAW:if(!Xa())return void wo.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));c=!0;break;case Si.NONE:c=!1;break;default:return void wo.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const d=t.inlineContent;if(void 0!==d)return void o(new Bu(a,oh(t.streamId,c?th(d,this.maxPayloadByteLength):d),Ua(t.totalLength)),{identity:n});const l=new ReadableStream({start:i=>{if(s=i,this.byteStreamControllers.has(t.streamId))throw new fs("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:s,startTime:Date.now(),sendingParticipantIdentity:n})},cancel:()=>{var e;(null===(e=this.byteStreamControllers.get(t.streamId))||void 0===e?void 0:e.controller)===s&&this.byteStreamControllers.delete(t.streamId)}});return void o(new Bu(a,c?function(e,t,n){return e.pipeThrough(sh(t)).pipeThrough(ah()).pipeThrough(eh()).pipeThrough(ch(t,n)).pipeThrough(function(e){let t=0;return new TransformStream({transform:(n,i)=>{n.byteLength>0&&(i.enqueue(new Ri({streamId:e,chunkIndex:Fa(t),content:n})),t+=1)}})}(t))}(l,t.streamId,this.maxPayloadByteLength):l.pipeThrough(sh(t.streamId)),Ua(t.totalLength)),{identity:n})}case"textHeader":{const r=this.textStreamHandlers.get(t.topic);if(!r)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let o;const s={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,attachedStreamIds:t.contentHeader.value.attachedStreamIds};let a;switch(t.compression){case Si.DEFLATE_RAW:if(!Xa())return void wo.warn("Data stream ".concat(t.streamId," received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping..."));a=!0;break;case Si.NONE:a=!1;break;default:return void wo.warn("Data stream ".concat(t.streamId," received with unknown compression type ").concat(t.compression,", dropping..."))}const c=t.inlineContent;if(void 0!==c){const e=a?th(c,this.maxPayloadByteLength):c;return void r(new qu(s,oh(t.streamId,e),Ua(t.totalLength)),{identity:n})}const d=new ReadableStream({start:i=>{if(o=i,this.textStreamControllers.has(t.streamId))throw new fs("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:s,controller:o,startTime:Date.now(),sendingParticipantIdentity:n})},cancel:()=>{var e;(null===(e=this.textStreamControllers.get(t.streamId))||void 0===e?void 0:e.controller)===o&&this.textStreamControllers.delete(t.streamId)}});return void r(new qu(s,a?function(t,n,i){return t.pipeThrough(sh(n)).pipeThrough(ah()).pipeThrough(eh()).pipeThrough(ch(n,i)).pipeThrough(function(t){const n=new TextDecoder("utf-8"),i=new TextEncoder;let r=0;const o=i=>{try{return i?n.decode(i,{stream:!0}):n.decode()}catch(r){throw new fs("Cannot decode compressed data stream ".concat(t," as text: ").concat(r),e.DataStreamErrorReason.DecodeFailed)}};return new TransformStream({transform:(e,n)=>{const s=o(e);s.length>0&&(n.enqueue(new Ri({streamId:t,chunkIndex:Fa(r),content:i.encode(s)})),r+=1)},flush:e=>{const n=o();n.length>0&&(e.enqueue(new Ri({streamId:t,chunkIndex:Fa(r),content:i.encode(n)})),r+=1)}})}(n))}(d,t.streamId,this.maxPayloadByteLength):d.pipeThrough(sh(t.streamId)),Ua(t.totalLength)),{identity:n})}}}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new fs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):i.controller.enqueue(t));const r=this.textStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new fs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):r.controller.enqueue(t))}handleStreamTrailer(t,n){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new fs("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),t.reason?i.controller.error(new fs("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):i.controller.close()),this.textStreamControllers.delete(t.streamId));const r=this.byteStreamControllers.get(t.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new fs("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),t.attributes),t.reason?r.controller.error(new fs("Data stream ".concat(t.streamId," closed abnormally: ").concat(t.reason),e.DataStreamErrorReason.AbnormalEnd)):r.controller.close()),this.byteStreamControllers.delete(t.streamId))}}function oh(e,t){return new ReadableStream({start:n=>Ao(this,void 0,void 0,(function*(){const i=yield t;n.enqueue(new Ri({streamId:e,chunkIndex:BigInt(0),content:i})),n.close()}))})}function sh(t){let n=-1;return new TransformStream({transform:(i,r)=>{const o=Ua(i.chunkIndex);if(o<=n)wo.warn("ignoring duplicate chunk ".concat(o," ").concat(i.version>0?"(version ".concat(i.version,")"):""," for data stream ").concat(t," (last processed: ").concat(n,")"));else{if(o>n+1)throw new fs("Missing chunk(s) ".concat(n+1,"..").concat(o-1," for data stream ").concat(t," - cannot reassemble payload"),e.DataStreamErrorReason.Incomplete);n=o,0!==i.content.length&&r.enqueue(i)}}})}function ah(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function ch(t,n){let i=0;return new TransformStream({transform:(r,o)=>{if(i+=r.byteLength,i>n)throw new fs("Data stream ".concat(t," exceeds the maximum payload size of ").concat(n," bytes"),e.DataStreamErrorReason.PayloadTooLarge);o.enqueue(r)}})}class dh{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 Ao(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 lh extends dh{}class uh extends dh{}function hh(e,t,n){var i;return new wi({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Fa(e.timestamp),totalLength:Fa(e.size),attributes:e.attributes,compression:null!==(i=null==n?void 0:n.compression)&&void 0!==i?i:Si.NONE,inlineContent:null==n?void 0:n.inlineContent,contentHeader:{case:"textHeader",value:new Ei({version:null==t?void 0:t.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?Ti.UPDATE:Ti.CREATE})}})}function ph(e,t){var n;return new wi({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:Fa(e.timestamp),totalLength:Fa(e.size),attributes:e.attributes,compression:null!==(n=null==t?void 0:t.compression)&&void 0!==n?n:Si.NONE,inlineContent:null==t?void 0:t.inlineContent,contentHeader:{case:"byteHeader",value:new Ci({name:e.name})}})}function mh(e,t){return new Yn({destinationIdentities:t,value:{case:"streamHeader",value:e}})}const gh=new TextEncoder;class fh{constructor(e,t,n,i,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=i,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r,o,s;const a=crypto.randomUUID(),c=gh.encode(e),d=c.byteLength,l=null===(n=null==t?void 0:t.compress)||void 0===n||n;let u={id:a,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:d,attributes:null==t?void 0:t.attributes,encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE};let h=l&&Xa()&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)&&this.allRecipientsSupportCompression(null==t?void 0:t.destinationIdentities)?vh.fromStream(Ja(c).pipeThrough($u())):null;if((!(null==t?void 0:t.attachments)||0===t.attachments.length)&&this.allRecipientsSupportV2(null==t?void 0:t.destinationIdentities)){let e=c,n=Si.NONE;if(h){const t=yield h.collect();t.byteLength<c.byteLength&&(e=t,n=Si.DEFLATE_RAW)}const i=mh(hh(u,void 0,{compression:n,inlineContent:e}),null==t?void 0:t.destinationIdentities);if(i.toBinary().byteLength<=ih)return yield this.engine.sendDataPacket(i,Ud.RELIABLE),null===(o=null==t?void 0:t.onProgress)||void 0===o||o.call(t,1),u}const p=null===(s=null==t?void 0:t.attachments)||void 0===s?void 0:s.map((()=>crypto.randomUUID())),m=p?p.length+1:1,g=new Array(m).fill(0),f=(e,n)=>{var i;g[n]=e,null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,g.reduce(((e,t)=>e+t),0)/m)};if(h){u.attachedStreamIds=p;const e=mh(hh(u,void 0,{compression:Si.DEFLATE_RAW}),null==t?void 0:t.destinationIdentities);yield this.sendChunkedByteStream(e,a,null==t?void 0:t.destinationIdentities,h.stream().pipeThrough(kh(c.length,(e=>f(e,0))))),0===c.length&&f(1,0)}else{const n=yield this.streamText({streamId:a,totalSize:d,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:p,attributes:null==t?void 0:t.attributes});yield n.write(e),f(1,0),yield n.close(),u=n.info}return(null==t?void 0:t.attachments)&&p&&(yield Promise.all(t.attachments.map(((e,n)=>Ao(this,void 0,void 0,(function*(){return this._sendFile(p[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{f(e,n+1)}})})))))),u}))}sendBytes(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r,o,s,a,c;const d=crypto.randomUUID(),l=null==t?void 0:t.destinationIdentities,u=null===(n=null==t?void 0:t.compress)||void 0===n||n,h={id:d,name:null!==(i=null==t?void 0:t.name)&&void 0!==i?i:"unknown",mimeType:null!==(r=null==t?void 0:t.mimeType)&&void 0!==r?r:"application/octet-stream",timestamp:Date.now(),topic:null!==(o=null==t?void 0:t.topic)&&void 0!==o?o:"",size:e.byteLength,attributes:null==t?void 0:t.attributes,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE},p=kh(e.length,null==t?void 0:t.onProgress);let m=u&&Xa()&&this.allRecipientsSupportV2(l)&&this.allRecipientsSupportCompression(l)?vh.fromStream(Ja(e).pipeThrough(p).pipeThrough($u())):null;if(this.allRecipientsSupportV2(l)){let n=e,i=Si.NONE;if(m){const t=yield m.collect();t.byteLength<e.byteLength&&(n=t,i=Si.DEFLATE_RAW)}const r=mh(ph(h,{compression:i,inlineContent:n}),l);if(r.toBinary().byteLength<=ih)return yield this.engine.sendDataPacket(r,Ud.RELIABLE),null===(a=null==t?void 0:t.onProgress)||void 0===a||a.call(t,1),h}const g=mh(ph(h,{compression:m?Si.DEFLATE_RAW:Si.NONE}),l),f=m?m.stream():Ja(e).pipeThrough(p);return yield this.sendChunkedByteStream(g,d,l,f),0===e.length&&(null===(c=null==t?void 0:t.onProgress)||void 0===c||c.call(t,1)),h}))}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantClientProtocol(e)>=2))}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every((e=>this.getRemoteParticipantCapabilities(e).includes(fi.CAP_COMPRESSION_DEFLATE_RAW)))}sendChunkedByteStream(e,t,n,i){return Ao(this,void 0,void 0,(function*(){var r,o,s,a;const c=this.engine;yield yh(c,e);let d=0;try{for(var l,u=!0,h=Uo(function(e,t){return xo(this,arguments,(function*(){const n=e.getReader();let i=new Uint8Array(0);try{for(;;){const e=yield No(n.read()),r=e.done,o=e.value;if(r)break;if(0===o.byteLength)continue;const s=new Uint8Array(i.byteLength+o.byteLength);for(s.set(i),s.set(o,i.byteLength),i=s;i.byteLength>=t;)yield yield No(i.slice(0,t)),i=i.slice(t)}i.byteLength>0&&(yield yield No(i))}finally{n.releaseLock()}}))}(i,ih));!(r=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=new Yn({destinationIdentities:n,value:{case:"streamChunk",value:new Ri({content:a,streamId:t,chunkIndex:Fa(d)})}});yield c.sendDataPacket(e,Ud.RELIABLE),d+=1}}catch(p){o={error:p}}finally{try{u||r||!(s=h.return)||(yield s.call(h))}finally{if(o)throw o.error}}yield bh(t,n,c)}))}streamText(t){return Ao(this,void 0,void 0,(function*(){var n,i,r;const o=null!==(n=null==t?void 0:t.streamId)&&void 0!==n?n:crypto.randomUUID(),s=null==t?void 0:t.destinationIdentities,a={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===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE,attachedStreamIds:null==t?void 0:t.attachedStreamIds},c=mh(hh(a,t),s);yield yh(this.engine,c);let d=0;const l=this.engine,u=new WritableStream({write(e){return Ao(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,ih)){const e=new Ri({content:t,streamId:o,chunkIndex:Fa(d)}),n=new Yn({destinationIdentities:s,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(n,Ud.RELIABLE),d+=1}}))},close(){return Ao(this,void 0,void 0,(function*(){yield bh(o,s,l)}))},abort(e){console.log("Sink error:",e)}});let h=()=>Ao(this,void 0,void 0,(function*(){yield p.close()}));l.once(e.EngineEvent.Closing,h);const p=new lh(u,a,(()=>this.engine.off(e.EngineEvent.Closing,h)));return p}))}sendFile(e,t){return Ao(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return Ao(this,void 0,void 0,(function*(){var i,r,o,s,a;const c=null==n?void 0:n.destinationIdentities,d=(null===(i=null==n?void 0:n.compress)||void 0===i||i)&&Xa()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),l={id:e,name:t.name,mimeType:null!==(r=null==n?void 0:n.mimeType)&&void 0!==r?r:t.type,topic:null!==(o=null==n?void 0:n.topic)&&void 0!==o?o:"",timestamp:Date.now(),size:t.size,encryptionType:(null===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE},u=mh(ph(l,{compression:d?Si.DEFLATE_RAW:Si.NONE}),c),h=t.stream().pipeThrough(kh(t.size,null==n?void 0:n.onProgress)),p=d?h.pipeThrough($u()):h;return yield this.sendChunkedByteStream(u,e,c,p),0===t.size&&(null===(a=null==n?void 0:n.onProgress)||void 0===a||a.call(n,1)),l}))}streamBytes(e){return Ao(this,void 0,void 0,(function*(){var t,n,i,r,o;const s=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:s,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!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown",encryptionType:(null===(o=this.engine.e2eeManager)||void 0===o?void 0:o.isDataChannelEncryptionEnabled)?xn.GCM:xn.NONE},d=mh(ph(c),a);yield yh(this.engine,d);let l=0;const u=new be,h=this.engine,p=this.log,m=new WritableStream({write(e){return Ao(this,void 0,void 0,(function*(){const t=yield u.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+ih),i=new Yn({destinationIdentities:a,value:{case:"streamChunk",value:new Ri({content:t,streamId:s,chunkIndex:Fa(l)})}});yield h.sendDataPacket(i,Ud.RELIABLE),l+=1,n+=t.byteLength}}finally{t()}}))},close(){return Ao(this,void 0,void 0,(function*(){yield bh(s,a,h)}))},abort(e){p.error("Sink error:",e)}});return new uh(m,c)}))}}class vh{constructor(e){this.state=e}static fromStream(e){return new vh({type:"stream",stream:e})}collect(){return Ao(this,void 0,void 0,(function*(){switch(this.state.type){case"stream":const e=yield nh(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}}))}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return Ja(this.state.bytes)}}}function kh(e,t){let n=0;return new TransformStream({transform(i,r){n+=i.byteLength,t&&"number"==typeof e&&e>0&&t(Math.min(n/e,1)),r.enqueue(i)}})}function yh(t,n){return Ao(this,void 0,void 0,(function*(){if(n.toBinary().byteLength>ih)throw new fs("data stream header exceeds the ".concat(ih,"-byte limit; reduce attribute size"),e.DataStreamErrorReason.HeaderTooLarge);yield t.sendDataPacket(n,Ud.RELIABLE)}))}function bh(e,t,n){return Ao(this,void 0,void 0,(function*(){const i=new Yn({destinationIdentities:t,value:{case:"streamTrailer",value:new Pi({streamId:e})}});yield n.sendDataPacket(i,Ud.RELIABLE)}))}const Th=rl("dataStreams",[],((t,n,i)=>{const r=new rh(null!=i?i:t.options.dataStream),o=new fh(t.engine,n.log,(e=>{var n,i;return null!==(i=null===(n=t.remoteParticipants.get(e))||void 0===n?void 0:n.clientProtocol)&&void 0!==i?i:0}),(e=>{var n,i;return null!==(i=null===(n=t.remoteParticipants.get(e))||void 0===n?void 0:n.capabilities)&&void 0!==i?i:[]}),(()=>Array.from(t.remoteParticipants.keys()))),s=(e,t,n)=>r.handleDataStreamPacket(t,n);return t.on(e.RoomEvent.ConnectionStateChanged,(t=>r.setConnected(t===e.ConnectionState.Connected))).on(e.RoomEvent.ParticipantDisconnected,(e=>r.validateParticipantHasNoActiveDataStreams(e.identity))),{incoming:r,outgoing:o,byteStreamOpener:e=>o.streamBytes(e),dataPackets:{streamHeader:s,streamChunk:s,streamTrailer:s},onEngineCreated:e=>o.setupEngine(e),onDisconnect:()=>r.clearControllers(),room:{registerTextStreamHandler:(e,t)=>r.registerTextStreamHandler(e,t),unregisterTextStreamHandler:e=>r.unregisterTextStreamHandler(e),registerByteStreamHandler:(e,t)=>r.registerByteStreamHandler(e,t),unregisterByteStreamHandler:e=>r.unregisterByteStreamHandler(e)},localParticipant:{sendText:(e,t)=>o.sendText(e,t),streamText:e=>o.streamText(e),sendFile:(e,t)=>o.sendFile(e,t),sendBytes:(e,t)=>o.sendBytes(e,t),streamBytes:e=>o.streamBytes(e)}}})),Sh={deviceId:{ideal:"default"},resolution:ge.h720.resolution},Eh={simulcast:!0,screenShareEncoding:ve.h1080fps15.encoding,videoCodec:Dd,backupCodec:!0},Ch={defaults:Sh,createTrack:(e,t,n,i)=>new Nu(e,t,n,i)};function wh(){kl(Ch)}function Rh(e){return Ao(this,void 0,void 0,(function*(){wh();return(yield bl({audio:!1,video:null==e||e}))[0]}))}function Ph(e,t){const n=e.localParticipant,i=e.options;return{prepare(r,o,s){return Ao(this,void 0,void 0,(function*(){var a,c,d,l;!function(){const e=zo(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&va(e.osVersion,t)>=0)||"Safari"===e.name&&va(e.version,t)>=0}()&&e.hasE2EESetup&&(t.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2"),o.simulcast=!1),r.source===Bs.Source.ScreenShare&&na()&&(o.simulcast=!1),"av1"!==o.videoCodec||Js()||(o.videoCodec=void 0),"vp9"!==o.videoCodec||Qs()||(o.videoCodec=void 0),void 0===o.videoCodec&&(o.videoCodec=Dd),n.enabledPublishVideoCodecs.length>0&&(n.enabledPublishVideoCodecs.some((e=>o.videoCodec===As(e.mime)))||(o.videoCodec=As(n.enabledPublishVideoCodecs[0].mime)));const u=o.videoCodec;let h;try{h=yield r.waitForDimensions()}catch(ke){const n=null!==(c=null===(a=i.videoCaptureDefaults)||void 0===a?void 0:a.resolution)&&void 0!==c?c:ge.h720.resolution;h={width:n.width,height:n.height},t.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},Ns(r)),{dims:h}))}var p;s.width=h.width,s.height=h.height,!Zs(u,o)||!$s()&&((p=null===(d=e.engine)||void 0===d?void 0:d.serverVersion)&&va(p,"1.13.6")>0)||(o.simulcast=!1,t.info("SVC simulcast is not supported, disabling simulcast.",Ns(r)));const m=Zs(u,o);Ys(u)&&!m&&(r.source===Bs.Source.ScreenShare&&(o.scalabilityMode="L1T3","contentHint"in r.mediaStreamTrack&&(r.mediaStreamTrack.contentHint="motion",t.debug("forcing contentHint to motion for screenshare with SVC codecs",Ns(r)))),o.scalabilityMode=null!==(l=o.scalabilityMode)&&void 0!==l?l:"L3T3_KEY");const g=new ar({codec:u,cid:r.mediaStreamTrack.id});m&&(g.videoLayerMode=Qn.ONE_SPATIAL_LAYER_PER_STREAM),s.simulcastCodecs=[g],!0===o.backupCodec&&(o.backupCodec={codec:Dd}),o.backupCodec&&u!==o.backupCodec.codec&&s.encryption===xn.NONE&&(i.dynacast||(i.dynacast=!0),s.simulcastCodecs.push(new ar({codec:o.backupCodec.codec,cid:""})));const f=_u(r.source===Bs.Source.ScreenShare,s.width,s.height,o);return s.layers=Fu(s.width,s.height,f,Ys(o.videoCodec)&&!Zs(o.videoCodec,o)),f}))},senderCreated(t,n,i,r){var o,s;if(null!==(o=n.degradationPreference)&&void 0!==o||(n.degradationPreference=function(e){switch(e.source){case Bs.Source.Camera:return"maintain-framerate";case Bs.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}(t)),t.setDegradationPreference(n.degradationPreference),i&&t.codec&&Ma(t.codec)){const o=function(e,t,n){var i,r;return Ys(e)&&!Zs(e,t)?null!==(r=null===(i=n[0])||void 0===i?void 0:i.maxBitrate)&&void 0!==r?r:0:n.reduce(((e,t)=>{var n;return e+(null!==(n=t.maxBitrate)&&void 0!==n?n:0)}),0)}(t.codec,n,i);o>0&&(null===(s=e.engine.pcManager)||void 0===s||s.publisher.setTrackCodecBitrate({cid:r.cid,codec:t.codec,maxbr:o/1e3,isScreenShare:t.source===Bs.Source.ScreenShare}))}},serverCodecChanged(e,n,i,r){let o;if(i.codecs.forEach((e=>{void 0===o&&(o=e.mimeType)})),!o)return;const s=As(o);return s!==n.videoCodec?(t.debug("falling back to server selected codec",Object.assign(Object.assign({},Ns(e)),{codec:s})),n.videoCodec=s,_u(e.source===Bs.Source.ScreenShare,r.width,r.height,n)):void 0},createScreenTracks:t=>Ih(e,t)}}function Ih(t,n){return Ao(this,void 0,void 0,(function*(){const i=t.localParticipant;if(void 0===n&&(n={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new cs("getDisplayMedia not supported");void 0!==n.resolution||ca()||(n.resolution=ve.h1080fps30.resolution);const r=Ms(n),o=yield navigator.mediaDevices.getDisplayMedia(r),s=o.getVideoTracks();if(0===s.length)throw new ds("no video track found");const a=new Nu(s[0],void 0,!1,i.trackLoggerOptions);a.source=Bs.Source.ScreenShare,n.contentHint&&(a.mediaStreamTrack.contentHint=n.contentHint);const c=[a];if(o.getAudioTracks().length>0){i.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new hl(o.getAudioTracks()[0],void 0,!1,i.audioContext,i.trackLoggerOptions);t.source=Bs.Source.ScreenShareAudio,c.push(t)}return c}))}function _h(e,t,n,i,r){return Ao(this,void 0,void 0,(function*(){var o;const s=e.localParticipant;if(s.isE2EEEnabled)return;let a;if(s.trackPublications.forEach((e=>{e.track&&e.track===n&&(a=e)})),!a)throw new ds("track is not published");if(!Va(n))throw new ds("track is not a video track");const c=Object.assign(Object.assign({},null===(o=e.options)||void 0===o?void 0:o.publishDefaults),r),d=Ou(n,i,c);if(!d)return void t.info("backup codec has been disabled, ignoring request to add additional codec for track",Ns(n));const l=n.addSimulcastTrack(i,d);if(!l)return;const u=s.normalizeRequestedFrameMetadataOptions(n,c),h=n.mediaStreamTrack.getSettings(),p=h.width,m=h.height,g=p&&m?{width:p,height:m}:void 0;g||t.warn("could not determine track dimensions, publishing backup codec without layers",Ns(n));const f=g?Fu(g.width,g.height,d):[],v=new cr({cid:l.mediaStreamTrack.id,type:Bs.kindToProto(n.kind),muted:n.isMuted,source:Bs.sourceToProto(n.source),sid:n.sid,width:null==g?void 0:g.width,height:null==g?void 0:g.height,packetTrailerFeatures:u,layers:f,simulcastCodecs:[{codec:c.videoCodec,cid:l.mediaStreamTrack.id,layers:f}]}),k=e.engine;if(!k||k.isClosed)throw new us("cannot publish track when not connected");const y=(yield Promise.all([k.addTrack(v),(()=>Ao(this,void 0,void 0,(function*(){yield k.createSimulcastSender(n,l,c,d),yield k.negotiate()})))()]))[0];t.debug("published ".concat(i," for track ").concat(n.sid),{encodings:d,trackInfo:y})}))}const Oh={key:Symbol("lk.extension.video"),install(t,n){wh(),t.options.videoCaptureDefaults=Object.assign(Object.assign({},Sh),t.options.videoCaptureDefaults),t.options.publishDefaults=Object.assign(Object.assign({},Eh),t.options.publishDefaults);const i=t.localParticipant;return{videoPublisher:Ph(t,n.log),onEngineCreated:i=>{i.on(e.EngineEvent.SubscribedQualityUpdate,(e=>function(e,t,n){return Ao(this,void 0,void 0,(function*(){var i,r,o,s,a;if(!(null===(a=e.options)||void 0===a?void 0:a.dynacast))return;const c=e.localParticipant.videoTrackPublications.get(n.trackSid);if(!c)return void t.warn("received subscribed quality update for unknown track",{trackSid:n.trackSid});if(!c.videoTrack)return;const d=yield c.videoTrack.setPublishingCodecs(n.subscribedCodecs);try{for(var l,u=!0,h=Uo(d);!(i=(l=yield h.next()).done);u=!0){s=l.value,u=!1;const n=s;pe(n)&&(t.debug("publish ".concat(n," for ").concat(c.videoTrack.sid),Ns(c)),yield _h(e,t,c.videoTrack,n,c.options))}}catch(p){r={error:p}}finally{try{u||i||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}))}(t,n.log,e)))},localParticipant:{setCameraEnabled:(e,t,n)=>i.setTrackEnabled(Bs.Source.Camera,e,t,n),setScreenShareEnabled:(e,t,n)=>i.setTrackEnabled(Bs.Source.ScreenShare,e,t,n),enableCameraAndMicrophone:()=>function(e){return Ao(this,void 0,void 0,(function*(){const t=e.localParticipant;if(!t.pendingPublishing.has(Bs.Source.Camera)&&!t.pendingPublishing.has(Bs.Source.Microphone)){t.pendingPublishing.add(Bs.Source.Camera),t.pendingPublishing.add(Bs.Source.Microphone);try{const e=yield t.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>t.publishTrack(e))))}finally{t.pendingPublishing.delete(Bs.Source.Camera),t.pendingPublishing.delete(Bs.Source.Microphone)}}}))}(t),createScreenTracks:e=>Ih(t,e),publishAdditionalCodecForTrack:(e,i,r)=>_h(t,n.log,e,i,r)}}}},Dh=e=>function(e,t){const n=new Nl(e);return ol(n,null!=t?t:[]),n}(e,[Th,Oh]);var Mh;e.CheckStatus=void 0,(Mh=e.CheckStatus||(e.CheckStatus={}))[Mh.IDLE=0]="IDLE",Mh[Mh.RUNNING=1]="RUNNING",Mh[Mh.SKIPPED=2]="SKIPPED",Mh[Mh.SUCCESS=3]="SUCCESS",Mh[Mh.FAILED=4]="FAILED";class Ah extends Vo.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=Dh(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return Ao(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(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.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 Ao(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 Ao(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 Ao(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 r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield Ks(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 Lh extends Ah{get description(){return"Cloud regions"}perform(){return Ao(this,void 0,void 0,(function*(){const e=new nl(this.url,this.token);if(!e.isCloud())return void this.skip();const t=[],n=new Set;for(let r=0;r<3;r++){const i=yield e.getNextBestRegionUrl();if(!i)break;if(n.has(i))continue;n.add(i);const r=yield this.checkCloudRegion(i);this.appendMessage("".concat(r.region," RTT: ").concat(r.rtt,"ms, duration: ").concat(r.duration,"ms")),t.push(r)}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 Ao(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 r=yield this.room.localParticipant.streamText({topic:"test"}),o="A".repeat(1e3),s=Date.now();for(let e=0;e<1e3;e++)yield r.write(o);yield r.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-s};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const Nh=1e4;class xh extends Ah{get description(){return"Connection via UDP vs TCP"}perform(){return Ao(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 Ao(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 r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],s=(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((()=>Ao(this,void 0,void 0,(function*(){const e=yield s.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,Nh))),clearInterval(c),o.stop(),t.remove(),yield this.disconnect(),a}))}}class Uh extends Ah{get description(){return"Can publish audio"}perform(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Tl();if(yield Is(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 r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(r=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," audio packets"))}))}}class Fh extends Ah{get description(){return"Can publish video"}perform(){return Ao(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Rh();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 r=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(r+=e.packetsSent)})),0===r)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))}))}checkForVideo(e){return Ao(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,r,o,s;const a=document.createElement("canvas"),c=e.getSettings(),d=null!==(r=null!==(i=c.width)&&void 0!==i?i:n.videoWidth)&&void 0!==r?r:1280,l=null!==(s=null!==(o=c.height)&&void 0!==o?o:n.videoHeight)&&void 0!==s?s: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 jh extends Ah{get description(){return"Resuming connection after interruption"}perform(){return Ao(this,void 0,void 0,(function*(){var t;const n=yield this.connect();let i,r=!1,o=!1;const s=new Promise((e=>{setTimeout(e,5e3),i=e})),a=()=>{r=!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 s,!r)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 Bh extends Ah{get description(){return"Can connect via TURN"}perform(){return Ao(this,void 0,void 0,(function*(){var e,t,n;ha(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=null!==(e=yield new nl(this.url,this.token).getNextBestRegionUrl())&&void 0!==e?e:this.url);const i=new Qc,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let o=!1,s=!1,a=!1;for(let c of r.iceServers)for(let e of c.urls)e.startsWith("turn:")?(s=!0,a=!0):e.startsWith("turns:")&&(s=!0,a=!0,o=!0),e.startsWith("stun:")&&(a=!0);a?s&&!o&&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===(n=null===(t=this.connectOptions)||void 0===t?void 0:t.rtcConfig)||void 0===n?void 0:n.iceServers)||s?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 qh extends Ah{get description(){return"Establishing WebRTC connection"}perform(){return Ao(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{var e;const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(e,r)=>{if(e.candidate){const i=new RTCIceCandidate(e);let r="".concat(i.protocol," ").concat(i.address,":").concat(i.port," ").concat(i.type);i.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}(i.address)?"tcp"===i.protocol&&"passive"===i.tcpType?(t=!0,r+=" (passive)"):"udp"===i.protocol&&(n=!0):r+=" (private)"),this.appendMessage(r)}i&&i(e,r)},(null===(e=this.room.engine.pcManager)||void 0===e?void 0:e.subscriber)&&(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(),wo.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class Vh extends Ah{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Ao(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,r=new Qc;try{i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(ke){if(ha(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(ke.message,". Retrying with region fallback"));const t=new nl(this.url,this.token),n=yield t.getNextBestRegionUrl();n&&(i=yield r.join(n,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}i?(this.appendMessage("Connected to server, version ".concat(i.serverVersion,".")),(null===(e=i.serverInfo)||void 0===e?void 0:e.edition)===pi.Cloud&&(null===(t=i.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=i.serverInfo)||void 0===n?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()}))}}class Wh extends Vo.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 Ao(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 r=yield n.run();return n.off("update",i),r}))}checkWebsocket(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Vh)}))}checkWebRTC(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(qh)}))}checkTURN(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Bh)}))}checkReconnect(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(jh)}))}checkPublishAudio(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Uh)}))}checkPublishVideo(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Fh)}))}checkConnectionProtocol(){return Ao(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(xh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return Ao(this,void 0,void 0,(function*(){return this.createAndRunCheck(Lh)}))}}var Hh,Kh,zh;e.KeyProviderEvent=void 0,(Hh=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",Hh.RatchetRequest="ratchetRequest",Hh.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(Kh=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Kh.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";class Gh extends Vo.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(e,t,n)=>{wo.debug("key ratcheted event received",{participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},sc),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const r={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),r),void 0!==i&&(this.latestManuallySetKeyIndex=i),this.emit(e.KeyProviderEvent.SetKey,r,void 0!==i)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}e.CryptorErrorReason=void 0,(zh=e.CryptorErrorReason||(e.CryptorErrorReason={}))[zh.InvalidKey=0]="InvalidKey",zh[zh.MissingKey=1]="MissingKey",zh[zh.InternalError=2]="InternalError";class Jh extends Xo{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}}class Qh{}class Yh{}new TextEncoder;const Xh=new TextDecoder,Zh=new TextDecoder("utf-8",{fatal:!0});class $h extends Error{constructor(e,t){var n;super(e,t),Ze(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}Ze($h,"code","ERR_JOSE_GENERIC");Ze(class extends $h{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}}),Ze(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");Ze(class extends $h{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}}),Ze(this,"code","ERR_JWT_EXPIRED"),Ze(this,"claim",void 0),Ze(this,"reason",void 0),Ze(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");Ze(class extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");Ze(class extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");Ze(class extends $h{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),Ze(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");Ze(class extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");Ze(class extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class ep extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JWT_INVALID")}}Ze(ep,"code","ERR_JWT_INVALID");Ze(class extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");Ze(class extends $h{constructor(){super(...arguments),Ze(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");Ze(class extends $h{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),Ze(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");Ze(class extends $h{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),Ze(this,Symbol.asyncIterator,function(e){return function(){return new rt(e.apply(this,arguments))}}((function*(){}))),Ze(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");Ze(class extends $h{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),Ze(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");Ze(class extends $h{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),Ze(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function tp(e){try{return function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw new TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}const n=atob(e),i=new Uint8Array(n.length);for(let r=0;r<n.length;r++)i[r]=n.charCodeAt(r);return i}("string"==typeof e?e:Xh.decode(e),!0)}catch(t){throw new TypeError("The input to be decoded is not correctly encoded.",{cause:t})}}function np(e){if("string"!=typeof e)throw new ep("JWTs must use Compact JWS serialization, JWT must be a string");const t=e.split("."),n=t[1],i=t.length;if(5===i)throw new ep("Only JWTs using Compact JWS serialization can be decoded");if(3!==i)throw new ep("Invalid JWT");if(!n)throw new ep("JWTs must contain a payload");let r,o;try{r=tp(n)}catch(s){throw new ep("Failed to base64url decode the payload")}try{o=JSON.parse(Zh.decode(r))}catch(a){throw new ep("Failed to parse the decoded payload as JSON")}if(!function(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}(o))throw new ep("Invalid JWT Claims Set");return o}const ip=1e3;function rp(e){const t=np(e);t.roomConfig;const n=Mo(t,["roomConfig"]);return Object.assign(Object.assign({},n),{roomConfig:t.roomConfig?er.fromJson(t.roomConfig,{ignoreUnknownFields:!0}):void 0})}function op(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const i of n)switch(i){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"agentName":case"agentMetadata":case"deployment":if(e[i]!==t[i])return!1;break;case"participantAttributes":if(!sp(e[i],t[i]))return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0}function sp(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),i=new Set(Object.keys(t));return n.length===i.size&&n.every((n=>i.has(n)&&e[n]===t[n]))}class ap extends Yh{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new be}isSameAsCachedFetchOptions(e){return!!this.cachedFetchOptions&&op(e,this.cachedFetchOptions)}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=rp(e.participantToken);if(!(null==t?void 0:t.exp))return!1;const n=new Date;if(t.nbf){const e=t.nbf*ip;if(new Date(e)>n)return!1}const i=t.exp*ip;return new Date(i-6e4)>n}(this.cachedResponse)&&!!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?rp(this.cachedResponse.participantToken):null}fetch(e,t){return Ao(this,void 0,void 0,(function*(){const n=yield this.fetchMutex.lock();try{if(t&&(this.cachedResponse=null),this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();const n=yield this.update(e);return this.cachedFetchOptions=e,this.cachedResponse=n,n.toJson()}finally{n()}}))}}class cp extends Qh{constructor(e){super(),this.literalOrFn=e}fetch(){return Ao(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class dp extends ap{constructor(e){super(),this.customFn=e}update(e){return Ao(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,vo.fromJson(n,{ignoreUnknownFields:!0})}))}}class lp extends ap{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,r;const o=new fo;for(const s of Object.keys(e))switch(s){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":o[s]=e[s];break;case"participantAttributes":o.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":o.roomConfig=null!==(n=o.roomConfig)&&void 0!==n?n:new er,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Mi),o.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":o.roomConfig=null!==(i=o.roomConfig)&&void 0!==i?i:new er,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Mi),o.roomConfig.agents[0].metadata=e.agentMetadata;break;case"deployment":o.roomConfig=null!==(r=o.roomConfig)&&void 0!==r?r:new er,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Mi),o.roomConfig.agents[0].deployment=e.deployment;break;default:throw new Error("Options key ".concat(s," not being included in forming request!"))}return o}update(e){return Ao(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 r=yield i.json();return vo.fromJson(r,{ignoreUnknownFields:!0})}))}}class up extends lp{constructor(e,t){const n=t.baseUrl,i=void 0===n?"https://cloud-api.livekit.io":n,r=Mo(t,["baseUrl"]);super("".concat(i,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},r),{headers:{"X-Sandbox-ID":e}}))}}class hp extends up{}const pp={literal:e=>new cp(e),custom:e=>new dp(e),endpoint(e){return new lp(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new hp(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},developmentTokenServer(e){return new up(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const mp=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),gp=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function fp(e){var t;const n=e.trim().toLowerCase();if(""!==n)return mp.has(n)?mp.get(n):null===(t=Array.from(gp.entries()).find((e=>{let t=tt(e,1)[0];return n.includes(t)})))||void 0===t?void 0:t[1]}const vp=Symbol.for("lk.serializer");function kp(e){return Object.assign(Object.assign({},e),{symbol:vp})}const yp={json:function(){return kp({parse:e=>JSON.parse(e),serialize:e=>JSON.stringify(e)})},raw:function(){return kp({parse:e=>e,serialize:e=>e})},custom:function(e){return kp(e)}};class bp extends Vo.EventEmitter{get logContext(){var e,t;return{room:null===(e=this.room)||void 0===e?void 0:e.name,participant:null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity}}constructor(t,n){super(),this.keysPostedToWorker=new WeakSet,this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=Po(e.LoggerNames.E2EE,(()=>this.logContext)),this.onWorkerMessage=t=>{var n;const i=t.data,r=i.kind,o=i.data;switch(r){case"error":if(o.uuid){const e=this.decryptDataRequests.get(o.uuid);if(null==e?void 0:e.reject){e.reject(o.error);break}const t=this.encryptDataRequests.get(o.uuid);if(null==t?void 0:t.reject){t.reject(o.error);break}}this.log.error(o.error.message),this.emit(e.EncryptionEvent.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e,!1)}));break;case"enable":if(o.local)this.encryptionEnabled!==o.enabled&&(this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled);else if(o.participantIdentity){const t=null===(n=this.room)||void 0===n?void 0:n.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 i=this.encryptDataRequests.get(o.uuid);(null==i?void 0:i.resolve)&&i.resolve(o);break;case"packetTrailerMetadata":this.handleFrameMetadata(o.trackId,o.rtpTimestamp,o.ssrc,o.metadata);break;case"log":Io[o.level](o.msg,o.context)}},this.onWorkerError=t=>{this.log.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error,void 0)},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(!ac())throw new cs("tried to setup end-to-end encryption on an unsupported browser");if(this.log.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:Io.getLevel()}};this.worker&&(this.log.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var e;let t;if(null===(e=this.unsubscribeLogLevel)||void 0===e||e.call(this),bp.disposeRegistry){const e=new WeakRef(this.worker);t=Do((n=>{const i=e.deref();i?i.postMessage({kind:"setLogLevel",data:{level:n}}):null==t||t()})),bp.disposeRegistry.register(this,t,this)}else{const e=this.worker;t=Do((t=>{e.postMessage({kind:"setLogLevel",data:{level:t}})}))}this.unsubscribeLogLevel=t}dispose(){var t,n,i;null===(t=this.unsubscribeLogLevel)||void 0===t||t.call(this),this.unsubscribeLogLevel=void 0,bp.disposeRegistry&&bp.disposeRegistry.unregister(this);const r=new Jh("E2EEManager disposed",e.CryptorErrorReason.InternalError);for(const e of[...this.encryptDataRequests.values()])null===(n=e.reject)||void 0===n||n.call(e,r);for(const e of[...this.decryptDataRequests.values()])null===(i=e.reject)||void 0===i||i.call(e,r);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setLocalParticipantCryptorEnabled(e){var t,n;this.log.debug("set e2ee to ".concat(e," for the local participant")),this.postEnable(e,null!==(n=null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity)&&void 0!==n?n:"",!0)}setParticipantCryptorEnabled(e,t){this.setLocalParticipantCryptorEnabled(e)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):this.log.warn("ignoring server sent trailer as it's empty")}handleFrameMetadata(e,t,n,i){if(this.room)for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const o of r.trackPublications.values())if(o.track&&o.track.mediaStreamID===e&&o.track instanceof Il&&o.track.frameMetadataExtractor)return void o.track.frameMetadataExtractor.storeMetadata(t,n,i)}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabledForPublication(e,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabledForPublication(t,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const r={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(r)})).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");const e=n.getLatestManuallySetKeyIndex();n.getKeys().filter((e=>!this.keysPostedToWorker.has(e))).forEach((t=>{var n;this.postKey(t,e===(null!==(n=t.keyIndex)&&void 0!==n?n:0))})),this.setLocalParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>Ao(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!qa(e.track)||!sa())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:As(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1,operation:"encode"}};this.worker.postMessage(t)})),n.on(e.KeyProviderEvent.SetKey,((e,t)=>this.postKey(e,null==t||t))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return Ao(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 Da;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 r=crypto.randomUUID(),o={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:i}},s=new Da;return s.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,s),this.worker.postMessage(o),s.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){var n;if(!this.worker)throw Error("could not set key, worker is missing");const i=e.key,r=e.participantIdentity,o=e.keyIndex,s={kind:"setKey",data:{participantIdentity:r,isPublisher:r===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity),key:i,keyIndex:o,updateCurrentKeyIndex:t}};this.worker.postMessage(s),this.keysPostedToWorker.add(e)}postEnable(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t,local:n}};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 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)}setParticipantCryptorEnabledForPublication(e,t){e.trackInfo?this.postEnable(e.trackInfo.encryption!==xn.NONE,t):this.log.warn("skipping e2ee enabled update for publication without trackInfo",{trackSid:e.trackSid})}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const i="video"===e.kind&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?As(n.mimeType):void 0,i,n.encryption!==xn.NONE)}setupE2EESender(e,t){var n;if(!ja(e)||!t)return void(t||this.log.warn("early return because sender is not ready"));const i=qa(e),r=i?null===(n=e.publishOptions)||void 0===n?void 0:n.videoCodec:void 0;this.handleSender(t,e.mediaStreamID,"h264"===r||"h265"===r?r:void 0,i?vc(e.publishOptions):void 0)}handleReceiver(e,t,n,i,r,o){return Ao(this,void 0,void 0,(function*(){if(this.worker){if(ra()){const s={kind:"decode",participantIdentity:n,trackId:t,codec:i,hasPacketTrailer:r,encrypted:o};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(rc in e&&oc in e){const s={kind:"updateCodec",data:{trackId:t,previousTrackId:e[oc],codec:i,participantIdentity:n,hasPacketTrailer:r,encrypted:o}};return this.worker.postMessage(s),void(e[oc]=t)}let s=e.writableStream,a=e.readableStream;if(!s||!a){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,a=t.readable}const c={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:i,participantIdentity:n,hasPacketTrailer:r,encrypted:o}};this.worker.postMessage(c,[a,s])}e[rc]=!0,e[oc]=t}}))}handleSender(e,t,n,i){var r;if(!(rc in e)&&this.worker){if(!(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ra()){this.log.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:fc(i),packetTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{this.log.info("initialize encoded streams");const r=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:fc(i),packetTrailer:i}};this.worker.postMessage(o,[r.readable,r.writable])}e[rc]=!0}}}bp.disposeRegistry="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef&&new FinalizationRegistry((e=>{e()}));const Tp=rl("e2ee",[],((t,n,i)=>{const r=!t.options.e2ee,o=null!=i?i:t.options.encryption||t.options.e2ee;let s,a=()=>{};if(o){if("e2eeManager"in o)s=o.e2eeManager,s.isDataChannelEncryptionEnabled=r;else{const e=new bp(o,r);s=e,a=()=>{e.dispose(),o.worker.terminate()}}const n=(n,i)=>{Ga(i)&&(t.isE2EEEnabled=n),t.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,n,i)},i=(n,i)=>{const r=i?t.getParticipantByIdentity(i):void 0;t.emit(e.RoomEvent.EncryptionError,n,r)};if(s.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,n),s.on(e.EncryptionEvent.EncryptionError,i),"e2eeManager"in o){const t=s;a=()=>{t.off(e.EncryptionEvent.ParticipantEncryptionStatusChanged,n),t.off(e.EncryptionEvent.EncryptionError,i)}}s.setup(t),s.setupEngine(t.engine)}const c=new be;return{manager:s,e2eeManager:s,room:{setE2EEEnabled:e=>Ao(void 0,void 0,void 0,(function*(){const n=yield c.lock();try{if(!s)throw Error("e2ee not configured, please set e2ee settings within the room options");t.isE2EEEnabled!==e&&(yield t.localParticipant.setE2EEEnabled(e),s.setLocalParticipantCryptorEnabled?s.setLocalParticipantCryptorEnabled(e):""!==t.localParticipant.identity&&s.setParticipantCryptorEnabled(e,t.localParticipant.identity))}finally{n()}}))},dispose:a}})),Sp=rl("frameMetadata",[],((e,t,n)=>{var i;const r=null!==(i=null!=n?n:e.options.frameMetadata)&&void 0!==i?i:e.options.packetTrailer,o=new Xu(r);return o.setup(e),{manager:o,frameMetadataOptions:r,dispose:()=>o.dispose()}})),Ep={key:Symbol("lk.extension.chat"),install(t,n){const i=t.localParticipant;i.on(e.ParticipantEvent.ChatMessage,(n=>{t.emit(e.RoomEvent.ChatMessage,n,i)}));const r=n=>Ao(this,void 0,void 0,(function*(){const r=new Yn({value:{case:"chatMessage",value:new si(Object.assign(Object.assign({},n),{timestamp:Ve.parse(n.timestamp),editTimestamp:void 0!==n.editTimestamp?Ve.parse(n.editTimestamp):void 0}))}});return yield t.engine.sendDataPacket(r,Ud.RELIABLE),i.emit(e.ParticipantEvent.ChatMessage,n),n}));return{dataPackets:{chatMessage:(n,i,r,o)=>{t.emit(e.RoomEvent.ChatMessage,function(e){const t=e.id,n=e.timestamp,i=e.message,r=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}(n),o)}},localParticipant:{sendChatMessage:(e,t)=>r({id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments}),editChatMessage:(e,t)=>r(Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}))}}}},Cp=Po(e.LoggerNames.DataTracks);class wp extends Zo{constructor(e,t,n,i){super(19,"Frame ".concat(n," dropped: ").concat(e),i),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Rp[t],this.frameNumber=n}static interrupted(e,t){return new wp("Interrupted by the start of a new frame ".concat(t),Rp.Interrupted,e)}static unknownFrame(e){return new wp("Initial packet was never received.",Rp.UnknownFrame,e)}static bufferFull(e){return new wp("Reorder buffer is full.",Rp.BufferFull,e)}static incomplete(e,t,n){return new wp("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),Rp.Incomplete,e)}}var Rp,Pp;!function(e){e[e.Interrupted=0]="Interrupted",e[e.UnknownFrame=1]="UnknownFrame",e[e.BufferFull=2]="BufferFull",e[e.Incomplete=3]="Incomplete"}(Rp||(Rp={}));class Ip{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case au.Single:return this.frameFromSingle(e,t);case au.Start:return this.beginPartial(e,t);case au.Inter:case au.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==au.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const i=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;if(this.partials.size>=i){const n=this.peekOldestPartialFrameNumber();if("number"!=typeof n)throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(n),null==t?void 0:t.throwOnInterruption)throw wp.interrupted(n,e.header.frameNumber.value);Cp.warn("Data track frame ".concat(n," was interrupted by single-packet frame ").concat(e.header.frameNumber.value,", dropping."))}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){var n;if(e.header.marker!==au.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const i=e.header.sequence,r=e.header.frameNumber.value,o={startSequence:i,extensions:e.header.extensions,payloads:new Map([[i.value,e.payload]])},s=null!==(n=null==t?void 0:t.maxPartialFrames)&&void 0!==n?n:1;for(;this.partials.size>=s;){const e=this.peekOldestPartialFrameNumber();if("number"!=typeof e)break;if(this.partials.delete(e),null==t?void 0:t.throwOnInterruption)throw wp.interrupted(e,r);Cp.warn("Data track partials full (max ".concat(s,"), evicted oldest frame ").concat(e," to make room for new frame ").concat(r,"."))}return this.partials.set(r,o),null}pushToPartial(e){if(e.header.marker!==au.Inter&&e.header.marker!==au.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),wp.unknownFrame(t);if(n.payloads.size>=Ip.MAX_BUFFER_PACKETS)throw this.partials.delete(t),wp.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Cp.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===au.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const i=t.payloads.size;let r=0;for(const c of t.payloads.values())r+=c.length;const o=new Uint8Array(r);let s=t.startSequence.clone(),a=0;for(;;){const i=t.payloads.get(s.value);if(!i)break;t.payloads.delete(s.value);const r=o.length-a;if(i.length>r)throw new Error("Depacketizer.finalize: Expected at least ".concat(i.length," more bytes left in the payload buffer, only got ").concat(r," bytes."));if(o.set(i,a),a+=i.length,s.value==n)return this.partials.delete(e),{payload:o,extensions:t.extensions};s.increment()}throw this.partials.delete(e),wp.incomplete(e,i,n-t.startSequence.value+1)}}Ip.MAX_BUFFER_PACKETS=128,function(e){e[e.Unpublished=0]="Unpublished",e[e.Timeout=1]="Timeout",e[e.Disconnected=2]="Disconnected",e[e.Cancelled=4]="Cancelled"}(Pp||(Pp={}));class _p extends Zo{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Pp[t]}static unpublished(){return new _p("The track has been unpublished and is no longer available",Pp.Unpublished)}static timeout(){return new _p("Request to subscribe to data track timed-out",Pp.Timeout)}static disconnected(){return new _p("Cannot subscribe to data track when disconnected",Pp.Disconnected)}static cancelled(){return new _p("Subscription to data track cancelled by caller",Pp.Cancelled)}}const Op=Po(e.LoggerNames.DataTracks);class Dp{constructor(e){var t,n;const i=null!==e.e2eeManager;if(e.info.usesE2ee!==i)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new Ip;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=null!==(t=e.e2eeManager)&&void 0!==t?t:null,this.depacketizer=r,this.options=null!==(n=e.pipelineOptions)&&void 0!==n?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return Ao(this,void 0,void 0,(function*(){const t=this.depacketize(e);if(!t)return null;const n=yield this.decryptIfNeeded(t);return n||null}))}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return Op.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return Ao(this,void 0,void 0,(function*(){var t,n;const i=this.e2eeManager;if(!i)return e;const r=null!==(n=null===(t=e.extensions)||void 0===t?void 0:t.e2ee)&&void 0!==n?n:null;if(!r)return Op.error("Missing E2EE meta"),null;let o;try{o=yield i.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(s){return Op.error("Error decrypting packet: ".concat(s)),null}return e.payload=o.payload,e}))}}const Mp=Po(e.LoggerNames.DataTracks);class Ap extends Vo.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.subscription.type&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const n=this.descriptors.get(e);n?(n.pipelineOptions=t,"active"===n.subscription.type&&n.subscription.pipeline.setOptions(t)):Mp.warn("Unknown track ".concat(e,", cannot set pipeline options."))}openSubscriptionStream(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16,i=null;const r=new Da,o=this.descriptors.get(e),s=()=>{null==t||t.removeEventListener("abort",c)},a=()=>{s(),i?o&&this.descriptors.get(o.info.sid)===o?"active"===o.subscription.type?(o.subscription.streamControllers.delete(i),0===o.subscription.streamControllers.size&&this.unSubscribeRequest(o.info.sid)):Mp.warn("Subscription for track ".concat(e," is not active, skipping cancel...")):Mp.warn("Unknown track ".concat(e,", skipping cancel...")):Mp.warn("ReadableStream subscribed to ".concat(e," was not started."))},c=()=>{var e;i&&("active"===(null==o?void 0:o.subscription.type)&&o.subscription.streamControllers.delete(i),i.error(_p.cancelled()),null===(e=r.reject)||void 0===e||e.call(r,_p.cancelled()),a())},d=new ReadableStream({start:n=>{i=n,this.subscribeRequest(e,t).then((()=>Ao(this,void 0,void 0,(function*(){var i,a,d;if(!o||this.descriptors.get(o.info.sid)!==o){Mp.error("Unknown track ".concat(e));const t=_p.disconnected();return n.error(t),void(null===(i=r.reject)||void 0===i||i.call(r,t))}if("active"!==o.subscription.type){Mp.error("Subscription for track ".concat(e," is not active"));const t=_p.disconnected();return n.error(t),void(null===(a=r.reject)||void 0===a||a.call(r,t))}(null==t?void 0:t.aborted)?c():(null==t||t.addEventListener("abort",c),o.subscription.streamControllers.set(n,s),null===(d=r.resolve)||void 0===d||d.call(r))})))).catch((e=>{var t;n.error(e),null===(t=r.reject)||void 0===t||t.call(r,e)}))},cancel:()=>{a()}},new CountQueuingStrategy({highWaterMark:n}));return[d,r.promise]}subscribeRequest(e,t){return Ao(this,void 0,void 0,(function*(){const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");const i=(t,n,i)=>Ao(this,void 0,void 0,(function*(){if("active"===t.subscription.type)return;if("pending"!==t.subscription.type)throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(t.subscription.type));const r=Cc([n,i].filter((e=>void 0!==e))),o=new Da;t.subscription.completionFuture.promise.then((()=>{var e;return null===(e=o.resolve)||void 0===e?void 0:e.call(o)})).catch((e=>{var t;return null===(t=o.reject)||void 0===t?void 0:t.call(o,e)}));const s=()=>{var e;"pending"===t.subscription.type&&(t.subscription.pendingRequestCount-=1,(null==i?void 0:i.aborted)||t.subscription.pendingRequestCount<=0?t.subscription.cancel():null===(e=o.reject)||void 0===e||e.call(o,_p.cancelled()))};r.aborted&&s(),r.addEventListener("abort",s),yield o.promise,r.removeEventListener("abort",s)}));switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new Da,pendingRequestCount:1,cancel:()=>{var e,t;const i=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),"pending"===i.type&&(null===(t=(e=i.completionFuture).reject)||void 0===t||t.call(e,r.aborted?_p.timeout():_p.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=wc(1e4);return void(yield i(n,t,r))}case"pending":return n.subscription.pendingRequestCount+=1,void(yield i(n,t));case"active":return}}))}querySubscribed(){return Ao(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.subscription.type)).map((e=>[e.info,e.publisherIdentity]))}))}unSubscribeRequest(e){var t;const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if("active"!==n.subscription.type)return void Mp.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat(null===(t=n.subscription)||void 0===t?void 0:t.type));this.closeStreamControllers(n.subscription.streamControllers,e);const i=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(i.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const r of e){var n=tt(r,2);const e=n[0];(0,n[1])();try{e.close()}catch(i){Mp.warn("Failed to close readable stream for track ".concat(t,": ").concat(i))}}}receiveSfuPublicationUpdates(e){return Ao(this,void 0,void 0,(function*(){if(0===e.size)return;const t=new Map;for(const r of e.entries()){var n=tt(r,2);const e=n[0],i=n[1],o=new Set;for(const t of i)o.add(t.sid),this.descriptors.has(t.sid)||this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t));t.set(e,o)}for(const e of t.entries()){var i=tt(e,2);const t=i[0],n=i[1];let r=Array.from(this.descriptors.entries()).filter((e=>{let n=tt(e,2);return n[0],n[1].publisherIdentity===t})).map((e=>tt(e,1)[0])).filter((e=>!n.has(e)));for(const e of r)this.handleTrackUnpublished(e)}}))}queryPublications(){return Ao(this,void 0,void 0,(function*(){return Array.from(this.descriptors.values()).map((e=>e.info))}))}handleTrackPublished(e,t){return Ao(this,void 0,void 0,(function*(){if(this.descriptors.has(t.sid))return void Mp.error("Existing descriptor for track ".concat(t.sid));let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);const i=new Su(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:i})}))}handleSidReassigned(e,t){const n=Array.from(this.descriptors.entries()).find((n=>{let i=tt(n,2);i[0];let r=i[1];return r.publisherIdentity===e&&r.info.pubHandle===t.pubHandle}));if(!n)return!1;const i=tt(n,2),r=i[0],o=i[1],s=o.info,a=s.name,c=s.usesE2ee;if(a!==t.name||c!==t.usesE2ee)return Mp.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;const d=t.sid;if(Mp.debug("SID reassigned: ".concat(r," -> ").concat(d)),!this.descriptors.delete(r))return!1;switch(o.info.sid=d,o.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:d,subscribe:!0})}return"active"===o.subscription.type&&this.subscriptionHandles.set(o.subscription.subcriptionHandle,d),this.descriptors.set(d,o),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);t?(this.descriptors.delete(e),"active"===t.subscription.type&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})):Mp.error("Unknown track ".concat(e))}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=tt(n,2);const e=t[0],i=t[1];this.registerSubscriberHandle(e,i)}}registerSubscriberHandle(e,t){var n,i;const r=this.descriptors.get(t);if(r)switch(r.subscription.type){case"none":return void Mp.warn("No subscription for ".concat(t));case"active":return this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,void this.subscriptionHandles.set(e,t);case"pending":{Mp.debug("data track subscription activated",{sid:t,handle:e});const o=new Dp({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),s=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:o,streamControllers:new Map},this.subscriptionHandles.set(e,t),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}}else Mp.error("Unknown track ".concat(t))}packetReceived(e){return Ao(this,void 0,void 0,(function*(){let t;try{t=tt(hu.fromBinary(e),1)[0]}catch(o){return void Mp.error("Failed to deserialize packet: ".concat(o))}const n=this.subscriptionHandles.get(t.header.trackHandle);if(!n)return void Mp.warn("Unknown subscriber handle ".concat(t.header.trackHandle));const i=this.descriptors.get(n);if(!i)return void Mp.error("Missing descriptor for track ".concat(n));if("active"!==i.subscription.type)return void Mp.warn("Received packet for track ".concat(n," without active subscription"));const r=yield i.subscription.pipeline.processPacket(t);if(r)for(const e of i.subscription.streamControllers.keys()){if(null!==e.desiredSize&&e.desiredSize<=0){Mp.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(e.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const t=tu.lossyIntoFrame(r);e.enqueue(t)}}))}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=tt(t,2);const n=e[0];"none"!==e[1].subscription.type&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(const i of this.descriptors.values())if(i.publisherIdentity===e)switch(i.subscription.type){case"none":break;case"pending":null===(n=(t=i.subscription.completionFuture).reject)||void 0===n||n.call(t,_p.disconnected());break;case"active":this.unSubscribeRequest(i.info.sid)}}reset(){var e,t;for(const n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),"pending"===n.subscription.type&&(null===(t=(e=n.subscription.completionFuture).reject)||void 0===t||t.call(e,_p.disconnected())),"active"===n.subscription.type&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Lp{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new mu(e.info.pubHandle,Lp.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return xo(this,arguments,(function*(){const t=yield No(this.encryptIfNeeded(e));try{yield No(yield*function(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,r){t[i]=e[i]?function(t){return(n=!n)?{value:No(e[i](t)),done:!1}:r?r(t):t}:r}}(Uo(this.packetizer.packetize(t))))}catch(n){if(n instanceof pu)throw vu.packetizer(n);throw n}}))}encryptIfNeeded(e){return Ao(this,void 0,void 0,(function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw vu.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new $l(t.keyIndex,t.iv),e}))}}Lp.TRANSPORT_MTU_BYTES=16e3;const Np=Po(e.LoggerNames.DataTracks),xp={pending:()=>({type:"pending",completionFuture:new Da}),active:(e,t)=>({type:"active",info:e,publishState:"published",pipeline:new Lp({info:e,e2eeManager:t}),unpublishingFuture:new Da})};class Up extends Vo.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new ou,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=null!==(t=null==e?void 0:e.e2eeManager)&&void 0!==t?t:null}static withDescriptors(e){const t=new Up;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())"active"===t.type&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return null!==(t=this.descriptors.get(e))&&void 0!==t?t:null}tryProcessAndSend(e,t){return Ao(this,void 0,void 0,(function*(){var n,i,r,o,s;const a=this.getDescriptor(e);if("active"!==(null==a?void 0:a.type))throw fu.trackUnpublished();if("unpublished"===a.publishState)throw fu.trackUnpublished();if("republishing"===a.publishState)throw fu.dropped("Data track republishing");try{try{for(var c,d=!0,l=Uo(a.pipeline.processFrame(t));!(n=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const t=o,n=null!==(s=this.inFlightPacketCounter.get(e))&&void 0!==s?s:0;this.inFlightPacketCounter.set(e,n+1),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:t.toBinary()})}}catch(u){i={error:u}}finally{try{d||n||!(r=l.return)||(yield r.call(l))}finally{if(i)throw i.error}}}catch(h){throw fu.dropped(h)}}))}handlePacketSendComplete(e){var t;let n=(null!==(t=this.inFlightPacketCounter.get(e))&&void 0!==t?t:0)-1;n<0&&(Np.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),n=0),this.inFlightPacketCounter.set(e,n),0===n&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return Ao(this,void 0,void 0,(function*(){const n=this.handleAllocator.get();if(!n)throw gu.limitReached();const i=wc(1e4),r=t?Cc([t,i]):i;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const o=xp.pending();this.descriptors.set(n,o);const s=()=>{var e,t;const r=this.descriptors.get(n);r?(this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),"pending"===r.type&&(null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,i.aborted?gu.timeout():gu.cancelled()))):Np.warn("No descriptor for ".concat(n))};return r.aborted?(s(),o.completionFuture.promise.then((()=>n))):(r.addEventListener("abort",s),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:null!==this.e2eeManager}),yield o.completionFuture.promise,r.removeEventListener("abort",s),this.emit("trackPublished",{track:bu.withExplicitHandle(e,this,n)}),n)}))}queryPublished(){return Array.from(this.descriptors.values()).filter((e=>"active"===e.type)).map((e=>e.info))}unpublishRequest(e){return Ao(this,void 0,void 0,(function*(){const t=this.descriptors.get(e);t?"active"===t.type?(this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})):Np.warn("Track ".concat(e," not active")):Np.warn("No descriptor for ".concat(e))}))}receivedSfuPublishResponse(e,t){var n,i,r,o;const s=this.descriptors.get(e);if(s)switch(this.descriptors.delete(e),s.type){case"pending":if("ok"===t.type){const r=t.data;Np.debug("SFU accepted publish request for handle ".concat(e),{sid:r.sid});const o=r.usesE2ee?this.e2eeManager:null;this.descriptors.set(r.pubHandle,xp.active(r,o)),null===(i=(n=s.completionFuture).resolve)||void 0===i||i.call(n)}else Np.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),null===(o=(r=s.completionFuture).reject)||void 0===o||o.call(r,t.error);return;case"active":if("republishing"!==s.publishState)return void Np.warn("Track ".concat(e," already active"));if("error"===t.type)return Np.warn("Republish failed for track ".concat(e,": ").concat(t.error)),void(s.publishState="unpublished");Np.debug("Track ".concat(e," republished")),s.info.sid=t.data.sid,s.publishState="published",this.descriptors.set(s.info.pubHandle,s)}else Np.warn("No descriptor for ".concat(e))}receivedSfuUnpublishResponse(e){var t,n;const i=this.descriptors.get(e);i?(this.descriptors.delete(e),"active"===i.type?(i.publishState="unpublished",null===(n=(t=i.unpublishingFuture).resolve)||void 0===n||n.call(t)):Np.warn("Track ".concat(e," not active"))):Np.warn("No descriptor for ".concat(e))}sfuWillRepublishTracks(){var e,t;for(const i of this.descriptors.entries()){var n=tt(i,2);const r=n[0],o=n[1];switch(o.type){case"pending":this.descriptors.delete(r),null===(t=(e=o.completionFuture).reject)||void 0===t||t.call(e,gu.disconnected());break;case"active":o.publishState="republishing",this.emit("sfuPublishRequest",{handle:o.info.pubHandle,name:o.info.name,usesE2ee:o.info.usesE2ee})}}}reset(){return Ao(this,void 0,void 0,(function*(){var e,t,n,i;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":null===(t=(e=r.completionFuture).reject)||void 0===t||t.call(e,gu.disconnected());break;case"active":null===(i=(n=r.unpublishingFuture).resolve)||void 0===i||i.call(n),yield this.unpublishRequest(r.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")}))}}const Fp=e=>e.map((e=>Tu.from(e))),jp={key:Symbol("lk.extension.dataTracks"),install(t,n){const i=new Ap,r=new Up;i.on("sfuUpdateSubscription",(e=>{t.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)})).on("trackPublished",(n=>{var i;n.track.publisherIdentity!==t.localParticipant.identity&&(t.emit(e.RoomEvent.DataTrackPublished,n.track),null===(i=t.remoteParticipants.get(n.track.publisherIdentity))||void 0===i||i.addRemoteDataTrack(n.track))})).on("trackUnpublished",(n=>{var i;n.publisherIdentity!==t.localParticipant.identity&&(t.emit(e.RoomEvent.DataTrackUnpublished,n.sid),null===(i=t.remoteParticipants.get(n.publisherIdentity))||void 0===i||i.removeRemoteDataTrack(n.sid))})),r.on("sfuPublishRequest",(e=>{t.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)})).on("sfuUnpublishRequest",(e=>{t.engine.client.sendUnPublishDataTrackRequest(e.handle)})).on("trackPublished",(n=>{t.emit(e.RoomEvent.LocalDataTrackPublished,n.track)})).on("trackUnpublished",(n=>{t.emit(e.RoomEvent.LocalDataTrackUnpublished,n.sid)})).on("packetAvailable",(e=>{let n=e.handle,i=e.bytes;t.engine.sendDataTrackFrame(i).finally((()=>r.handlePacketSendComplete(n)))}));return t.on(e.RoomEvent.ParticipantDisconnected,(e=>i.handleRemoteParticipantDisconnected(e.identity))),{incoming:i,outgoing:r,onEngineCreated:t=>{var o;const s=null!==(o=n.slot("e2eeManager"))&&void 0!==o?o:null;i.updateE2eeManager(s),r.updateE2eeManager(s),t.on(e.EngineEvent.PublishDataTrackResponse,(e=>{e.info?r.receivedSfuPublishResponse(e.info.pubHandle,{type:"ok",data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==xn.NONE}}):n.log.warn("received PublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.UnPublishDataTrackResponse,(e=>{e.info?r.receivedSfuUnpublishResponse(e.info.pubHandle):n.log.warn("received UnPublishDataTrackResponse, but event.info was ".concat(e.info,", so skipping."))})).on(e.EngineEvent.DataTrackSubscriberHandles,(e=>{const t=new Map(Object.entries(e.subHandles).map((e=>{let t=tt(e,2),n=t[0],i=t[1];return[parseInt(n,10),i.trackSid]})));i.receivedSfuSubscriberHandles(t)})).on(e.EngineEvent.DataTrackPacketReceived,(e=>{try{i.packetReceived(e)}catch(t){throw t}})).on(e.EngineEvent.Joined,(e=>{i.receiveSfuPublicationUpdates(new Map(e.otherParticipants.map((e=>[e.identity,Fp(e.dataTracks)]))))})).on(e.EngineEvent.Restarted,(()=>{r.sfuWillRepublishTracks(),i.resendSubscriptionUpdates()})).on(e.EngineEvent.SignalRequestResponse,(e=>{if("publishDataTrack"!==e.request.case)return;let t;switch(e.reason){case co.NOT_ALLOWED:t=gu.notAllowed(e.message);break;case co.DUPLICATE_NAME:t=gu.duplicateName(e.message);break;case co.INVALID_NAME:t=gu.invalidName(e.message);break;case co.LIMIT_EXCEEDED:t=gu.limitReached(e.message);break;default:t=gu.unknown(e.reason,e.message)}r.receivedSfuPublishResponse(e.request.value.pubHandle,{type:"error",error:t})}))},onDisconnect:()=>{i.reset(),r.reset()},onParticipantCreated:(e,t)=>{for(const n of t.dataTracks)e.addRemoteDataTrack(new Su(Tu.from(n),i,{publisherIdentity:t.identity}))},onParticipantUpdates:e=>{i.receiveSfuPublicationUpdates(new Map(e.filter((e=>e.identity!==t.localParticipant.identity)).map((e=>[e.identity,Fp(e.dataTracks)]))))},syncState:()=>r.queryPublished().map((e=>new lr({info:Tu.toProtobuf(e)}))),localParticipant:{publishDataTrack:e=>Ao(this,void 0,void 0,(function*(){const t=new bu(e,r);return yield t.publish(),t}))}}}},Bp={key:Symbol("lk.extension.rpc"),requires:[Th],install(t,n){const i=n.get(Th),r=i.incoming,o=i.outgoing,s=e=>{var n,i;return null!==(i=null===(n=t.remoteParticipants.get(e))||void 0===n?void 0:n.clientProtocol)&&void 0!==i?i:0},a=new Ju(n.log,o,s,(()=>{var e;return null===(e=t.engine)||void 0===e?void 0:e.serverVersion}));a.on("sendDataPacket",(e=>{let n=e.packet;var i;null===(i=t.engine)||void 0===i||i.sendDataPacket(n,Ud.RELIABLE)}));const c=new Qu(n.log,o,s);c.on("sendDataPacket",(e=>{let n=e.packet;var i;null===(i=t.engine)||void 0===i||i.sendDataPacket(n,Ud.RELIABLE)})),r.registerTextStreamHandler(Wu,((e,t)=>Ao(this,[e,t],void 0,(function(e,t){let n=t.identity;return function*(){var t;yield c.handleIncomingDataStream(e,n,null!==(t=e.info.attributes)&&void 0!==t?t:{})}()})))),r.registerTextStreamHandler(Hu,((e,t)=>Ao(this,[e,t],void 0,(function(e,t){let n=t.identity;return function*(){var t;yield a.handleIncomingDataStream(e,n,null!==(t=e.info.attributes)&&void 0!==t?t:{})}()})))),t.on(e.RoomEvent.ParticipantDisconnected,(e=>a.handleParticipantDisconnected(e.identity)));return{dataPackets:{rpcRequest:(e,t)=>{c.handleIncomingRpcRequest(t.participantIdentity,e)},rpcResponse:e=>{switch(e.value.case){case"payload":a.handleIncomingRpcResponseSuccess(e.requestId,e.value.value);break;case"error":a.handleIncomingRpcResponseFailure(e.requestId,Vu.fromProto(e.value.value));break;default:n.log.warn("Unknown rpcResponse.value.case: ".concat(e.value.case))}},rpcAck:e=>a.handleIncomingRpcAck(e.requestId)},onDisconnect:()=>a.handleRoomDisconnected(),room:{registerRpcMethod:(e,t)=>c.registerRpcMethod(e,t),unregisterRpcMethod:e=>c.unregisterRpcMethod(e)},localParticipant:{performRpc:e=>a.performRpc(e).then((e=>{let t=tt(e,2);return t[0],t[1]}))}}}},qp={key:Symbol("lk.extension.rpcLegacy"),requires:[Bp],install(e,t){const n=t.get(Bp).room;return{localParticipant:{registerRpcMethod:n.registerRpcMethod,unregisterRpcMethod:n.unregisterRpcMethod}}}},Vp={key:Symbol("lk.extension.simulatedParticipants"),install:(t,n)=>({room:{simulateParticipants:i=>function(t,n,i){return Ao(this,void 0,void 0,(function*(){var r,o,s,a;const c=Object.assign({audio:!0,video:!0,useRealTracks:!1},i.publish),d=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},i.participants),l=t.localParticipant,u=l.trackLoggerOptions;if(n.simulateConnected(new _n({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ve.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),new Mn({identity:"simulated-local",name:"local-name"})),c.video){const t=new fl(Bs.Kind.Video,new Fn({source:bn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO,name:"video-dummy"}),yl().createTrack(c.useRealTracks&&(null===(r=window.navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Pa(160*(null!==(o=d.aspectRatios[0])&&void 0!==o?o:1),160,!0,!0),void 0,!1,u),u);l.addTrackPublication(t),l.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(c.audio){const t=new fl(Bs.Kind.Audio,new Fn({source:bn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO}),new hl(c.useRealTracks&&(null===(s=navigator.mediaDevices)||void 0===s?void 0:s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:n.acquireEmptyAudioStreamTrack(),void 0,!1,l.audioContext,u),u);l.addTrackPublication(t),l.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e<d.count-1;e+=1){let t=new Mn({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:An.ACTIVE,tracks:[],joinedAt:Ve.parse(Date.now())});const i=n.getOrCreateParticipant(t.identity,t);if(d.video){const n=Pa(160*(null!==(a=d.aspectRatios[e%d.aspectRatios.length])&&void 0!==a?a:1),160,!1,!0),r=new Fn({source:bn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO});i.addSubscribedMediaTrack(n,r.sid,new MediaStream([n]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}if(d.audio){const e=n.acquireEmptyAudioStreamTrack(),r=new Fn({source:bn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO});i.addSubscribedMediaTrack(e,r.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,r]}i.updateInfo(t)}}))}(t,n,i)}})};const Wp=[Th,Bp,qp,jp,Sp,Tp,Oh,Vp,Ep];wh();const Hp=pe;e.BaseKeyProvider=Gh,e.CLIENT_PROTOCOL_DATA_STREAM_RPC=1,e.CLIENT_PROTOCOL_DATA_STREAM_V2=2,e.CLIENT_PROTOCOL_DEFAULT=0,e.Checker=Ah,e.ConnectionCheck=Wh,e.ConnectionError=ss,e.CriticalTimers=ks,e.CryptorError=Jh,e.DataPacket_Kind=Xn,e.DataStreamError=fs,e.DataTrackPacket=hu,e.DefaultReconnectPolicy=Od,e.DeviceUnsupportedError=cs,e.DisconnectReason=Cn,e.Encryption_Type=xn,e.ExternalE2EEKeyProvider=class extends Gh{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 Ao(this,void 0,void 0,(function*(){const t="string"==typeof e?yield lc(e):yield uc(e);this.onSetEncryptionKey(t)}))}},e.FrameMetadataManager=Xu,e.LivekitError=Xo,e.LivekitReasonedError=Zo,e.LocalAudioTrack=hl,e.LocalDataTrack=bu,e.LocalParticipant=Cl,e.LocalTrack=ul,e.LocalTrackPublication=fl,e.LocalTrackRecorder=ll,e.LocalVideoTrack=Nu,e.Mutex=be,e.NegotiationError=hs,e.PROTOCOL_NEGOTIATED_DATA_CHANNELS=18,e.PacketTrailerManager=Zu,e.Participant=El,e.ParticipantKind=Ln,e.PublishDataError=ps,e.PublishTrackError=ms,e.RemoteAudioTrack=ml,e.RemoteDataTrack=Su,e.RemoteParticipant=Ml,e.RemoteTrack=pl,e.RemoteTrackPublication=Pl,e.RemoteVideoTrack=Il,e.Room=class extends Nl{constructor(e){super(e),ol(this,Wp)}},e.RpcError=Vu,e.ScreenSharePresets=ve,e.SignalReconnectError=vs,e.SignalRequestError=gs,e.SimulatedError=class extends Xo{constructor(){super(-1,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Simulated failure"),this.name="simulated"}},e.SubscriptionError=Rn,e.TokenSource=pp,e.TokenSourceConfigurable=Yh,e.TokenSourceFixed=Qh,e.Track=Bs,e.TrackInvalidError=ds,e.TrackPublication=gl,e.TrackType=yn,e.UnexpectedConnectionState=us,e.UnsupportedServer=ls,e.VideoPreset=de,e.VideoPresets=ge,e.VideoPresets43=fe,e.areTokenSourceFetchOptionsEqual=op,e.asEncryptablePacket=pc,e.attachToElement=qs,e.attributes=Fl,e.audioCodecs=le,e.canFailOverToAnotherRegion=as,e.clientProtocol=2,e.compareVersions=va,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=_s();if(!i)throw new Error("Audio Context not supported on this browser");const r=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,o=i.createMediaStreamSource(new MediaStream([r])),s=i.createAnalyser();s.minDecibels=n.minDecibels,s.maxDecibels=n.maxDecibels,s.fftSize=n.fftSize,s.smoothingTimeConstant=n.smoothingTimeConstant,o.connect(s);const a=new Uint8Array(s.frequencyBinCount);let c=!1;return{calculateVolume:()=>{s.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:s,cleanup:()=>Ao(this,void 0,void 0,(function*(){c||(c=!0,o.disconnect(),s.disconnect(),n.cloneTrack&&r.stop(),yield i.close())}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=uc,e.createKeyMaterialFromString=lc,e.createLocalAudioTrack=Tl,e.createLocalScreenTracks=function(e){return Ao(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||ca()||(e.resolution=ve.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new cs("getDisplayMedia not supported");const t=Ms(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new ds("no video track found");const r=new Nu(i[0],void 0,!1);r.source=Bs.Source.ScreenShare;const o=[r];if(n.getAudioTracks().length>0){const e=new hl(n.getAudioTracks()[0],void 0,!1);e.source=Bs.Source.ScreenShareAudio,o.push(e)}return o}))},e.createLocalTracks=bl,e.createLocalVideoTrack=Rh,e.decodeTokenPayload=rp,e.deriveKeys=function(e,t){return Ao(this,void 0,void 0,(function*(){const n=hc(e.algorithm.name,t.ratchetSalt),i=yield crypto.subtle.deriveKey(n,e,{name:ic,length:t.keySize},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Vs,e.facingModeFromDeviceLabel=fp,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=ja(e)?e.mediaStreamTrack:e,r=i.getSettings();let o={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in r){const e=r.facingMode;wo.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)){wo.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=fp(i.label);void 0!==e&&(o=e)}return o},e.getBrowser=zo,e.getEmptyAudioStreamTrack=_a,e.getEmptyVideoStreamTrack=function(){return Ca||(Ca=Pa()),Ca.clone()},e.getLogger=Po,e.getVideoCapture=yl,e.importKey=function(e){return Ao(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:ic},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 le.includes(e)},e.isAudioTrack=Ba,e.isBackupCodec=Hp,e.isBackupVideoCodec=pe,e.isBrowserSupported=ta,e.isE2EESupported=ac,e.isInsertableStreamSupported=dc,e.isLocalParticipant=Ga,e.isLocalTrack=ja,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=Ha,e.isSVCCodec=Ys,e.isScriptTransformSupported=cc,e.isSerializer=function(e){return"object"==typeof e&&null!==e&&"symbol"in e&&e.symbol===vp},e.isVideoCodec=Ma,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=qa,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=18,e.ratchet=function(e,t){return Ao(this,void 0,void 0,(function*(){const n=hc(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.releaseEmptyAudioStreamTrack=Oa,e.serializers=yp,e.setLogExtension=function(t,n){(n?[n]:Ro).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,r,o)=>{const s=i(n,r,o),a=e.LogLevel[n],c=a>=r&&a<e.LogLevel.silent;return(e,n)=>{n?s(e,n):s(e),c&&t(a,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){if(t)Co.getLogger(t).setLevel(e);else for(const n of Ro)n.setLevel(e)},e.setVideoCapture=kl,e.supportsAV1=Js,e.supportsAdaptiveStream=function(){return"undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return ea()},e.supportsDynacast=function(){return zs()},e.supportsH265=function(){if(!("getCapabilities"in RTCRtpSender))return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/h265"===n.mimeType.toLowerCase()){t=!0;break}return t},e.supportsVP9=Qs,e.version=Yo,e.videoCodecs=he,e.writeRbsp=function(e){const t=[];let n=0;for(let o=0;o<e.length;++o){const i=e[o];i<=3&&n>=2&&(t.push(o),n=0),n=0===i?n+1:0}if(0===t.length)return e;const i=new Uint8Array(e.length+t.length);let r=0;for(let o=0;o<t.length;++o)i.set(e.subarray(r,t[o]),r+o),i[t[o]+o]=3,r=t[o];return i.set(e.subarray(r),r+t.length),i}}));
|
|
2
2
|
//# sourceMappingURL=livekit-client.umd.js.map
|