@unith-ai/core-client 2.0.4-beta.2 → 2.0.4-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib.js +1 -1
- package/dist/lib.js.map +1 -1
- package/dist/lib.module.js +1 -1
- package/dist/lib.module.js.map +1 -1
- package/dist/lib.web.js +11 -15
- package/dist/lib.web.js.map +1 -1
- package/dist/modules/microphone.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/lib.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,t}function t(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 n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},n.apply(null,arguments)}function i(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var r,s,o=new Map,a=(r="audio-concat-processor",s='\nconst decodeTable = [0,132,396,924,1980,4092,8316,16764];\n\nexport function decodeSample(muLawSample) {\n let sign;\n let exponent;\n let mantissa;\n let sample;\n muLawSample = ~muLawSample;\n sign = (muLawSample & 0x80);\n exponent = (muLawSample >> 4) & 0x07;\n mantissa = muLawSample & 0x0F;\n sample = decodeTable[exponent] + (mantissa << (exponent+3));\n if (sign !== 0) sample = -sample;\n\n return sample;\n}\n\nclass AudioConcatProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffers = [];\n this.cursor = 0;\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n this.currentBufferStartSample = 0;\n this.wasInterrupted = false;\n this.playing = false;\n this.finished = false;\n\n this.playbackRate = 1.0;\n this.adjustUntilSample = null;\n this.sampleCounter = 0;\n this.format = { sampleRate: 48000 };\n\n // Time synchronization properties\n this.playbackStartTime = null;\n this.totalSamplesPlayed = 0;\n \n // Drift correction parameters\n this.maxCorrectionRate = 0.1; // Maximum 10% speed adjustment\n this.correctionSmoothness = 0.95; // How smoothly to apply corrections (0-1)\n this.targetPlaybackRate = 1.0;\n\n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.format = data.format;\n break;\n\n case "buffer":\n this.wasInterrupted = false;\n \n const bufferData = this.format.encoding === "ulaw"\n ? new Uint8Array(data.buffer)\n : new Int16Array(data.buffer);\n \n // Store buffer with its timestamp\n this.buffers.push({\n buffer: bufferData,\n timestamp: data.timestamp_ms\n });\n break;\n \n case "startPlayback":\n this.playing = true;\n this.playbackStartTime = currentTime;\n this.totalSamplesPlayed = 0;\n this.sampleCounter = 0;\n break;\n \n case "stopPlayback":\n this.playing = false;\n this.finished = true;\n \n // Discard all queued buffers\n this.buffers = [];\n \n // Clear current buffer and reset cursor\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n this.cursor = 0;\n \n // Reset playback rate adjustments\n this.playbackRate = 1.0;\n this.adjustUntilSample = null;\n this.targetPlaybackRate = 1.0;\n \n // Notify that playback has stopped\n this.port.postMessage({ \n type: "process", \n finished: true,\n stopped: true\n });\n break;\n\n case "adjustPlaybackRate":\n this.playbackRate = data.rate;\n this.adjustUntilSample = this.sampleCounter + Math.floor(this.format.sampleRate * data.duration);\n break;\n \n case "reset":\n this.playing = false;\n this.finished = false;\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n this.currentBufferStartSample = 0;\n this.cursor = 0;\n this.buffers = [];\n this.playbackStartTime = null;\n this.totalSamplesPlayed = 0;\n this.targetPlaybackRate = 1.0;\n break;\n\n case "interrupt":\n this.wasInterrupted = true;\n break;\n\n case "clearInterrupted":\n if (this.wasInterrupted) {\n this.wasInterrupted = false;\n this.buffers = [];\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n }\n break;\n }\n };\n }\n\n // Calculate the expected timestamp based on samples played\n getExpectedTimestamp() {\n if (!this.playbackStartTime) return 0;\n \n // Convert samples to milliseconds\n const samplesPlayedMs = (this.totalSamplesPlayed / this.format.sampleRate) * 1000;\n return samplesPlayedMs;\n }\n\n // Calculate the actual timestamp of current playback position\n getCurrentActualTimestamp() {\n if (!this.currentBufferTimestamp) return 0;\n \n // Current position within the buffer in samples\n const samplesIntoBuffer = Math.floor(this.cursor);\n \n // Convert buffer position to milliseconds (assuming buffer covers specific time duration)\n // Each buffer typically represents a fixed time duration\n const bufferDurationMs = (this.currentBuffer.length / this.format.sampleRate) * 1000;\n const progressThroughBuffer = samplesIntoBuffer / this.currentBuffer.length;\n \n return this.currentBufferTimestamp + (progressThroughBuffer * bufferDurationMs);\n }\n\n // Calculate timing drift and adjust playback rate accordingly\n calculateDriftCorrection() {\n if (!this.currentBufferTimestamp || !this.playbackStartTime) {\n return 1.0;\n }\n\n const expectedTimestamp = this.getExpectedTimestamp();\n const actualTimestamp = this.getCurrentActualTimestamp();\n \n // Calculate drift in milliseconds\n const drift = actualTimestamp - expectedTimestamp;\n \n // Convert drift to a playback rate adjustment\n // Positive drift means we\'re ahead - slow down\n // Negative drift means we\'re behind - speed up\n let correctionFactor = 1.0;\n \n if (Math.abs(drift) > 10) { // Only correct if drift > 10ms\n // Calculate correction rate based on drift\n // More drift = more correction, but capped at maxCorrectionRate\n const driftRatio = Math.min(Math.abs(drift) / 1000, this.maxCorrectionRate);\n \n if (drift > 0) {\n // We\'re ahead, slow down\n correctionFactor = 1.0 - driftRatio;\n } else {\n // We\'re behind, speed up\n correctionFactor = 1.0 + driftRatio;\n }\n \n // Apply smoothing to avoid jarring rate changes\n this.targetPlaybackRate = this.targetPlaybackRate * this.correctionSmoothness + \n correctionFactor * (1 - this.correctionSmoothness);\n } else {\n // Gradually return to normal speed when drift is small\n this.targetPlaybackRate = this.targetPlaybackRate * this.correctionSmoothness + \n 1.0 * (1 - this.correctionSmoothness);\n }\n\n return this.targetPlaybackRate;\n }\n\n process(_, outputs, parameters) {\n const output = outputs[0][0];\n\n if (!this.playing) {\n output.fill(0);\n return true;\n }\n\n let finished = false;\n\n for (let i = 0; i < output.length; i++) {\n // If no buffer is ready, get the next one\n if (!this.currentBuffer) {\n if (this.buffers.length === 0) {\n finished = true;\n break;\n }\n \n const bufferData = this.buffers.shift();\n this.currentBuffer = bufferData.buffer;\n this.currentBufferTimestamp = bufferData.timestamp;\n this.currentBufferStartSample = this.totalSamplesPlayed;\n this.cursor = 0;\n }\n\n // Calculate drift correction for timing synchronization\n const driftCorrectedRate = this.calculateDriftCorrection();\n \n // Apply manual playback rate adjustments if active\n let finalPlaybackRate = driftCorrectedRate;\n if (this.adjustUntilSample !== null && this.sampleCounter < this.adjustUntilSample) {\n finalPlaybackRate *= this.playbackRate;\n } else if (this.adjustUntilSample !== null) {\n this.playbackRate = 1.0;\n this.adjustUntilSample = null;\n }\n\n const idx = Math.floor(this.cursor);\n const nextIdx = Math.min(idx + 1, this.currentBuffer.length - 1);\n\n let s1 = this.currentBuffer[idx];\n let s2 = this.currentBuffer[nextIdx];\n if (this.format.encoding === "ulaw") {\n s1 = decodeSample(s1);\n s2 = decodeSample(s2);\n }\n\n const frac = this.cursor - idx;\n const interpolated = s1 * (1 - frac) + s2 * frac;\n output[i] = interpolated / 32768;\n\n this.cursor += finalPlaybackRate;\n this.sampleCounter++;\n this.totalSamplesPlayed++;\n\n if (this.cursor >= this.currentBuffer.length) {\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n }\n }\n\n if (this.finished !== finished) {\n this.finished = finished;\n this.port.postMessage({ \n type: "process", \n finished,\n // Optional: send timing info for debugging\n timing: {\n expectedTimestamp: this.getExpectedTimestamp(),\n actualTimestamp: this.getCurrentActualTimestamp(),\n playbackRate: this.targetPlaybackRate\n }\n });\n }\n\n return true;\n }\n}\nregisterProcessor("audio-concat-processor", AudioConcatProcessor);\n',function(e){try{var t,n=function(n){return t?n:i(function(){var t="data:application/javascript;base64,"+btoa(s);return Promise.resolve(e.addModule(t)).then(function(){o.set(r,t)})},function(){throw new Error("Failed to load the "+r+" worklet module. Make sure the browser supports AudioWorklets.")})},a=o.get(r);if(a)return Promise.resolve(e.addModule(a));var c=new Blob([s],{type:"application/javascript"}),d=URL.createObjectURL(c),l=i(function(){return Promise.resolve(e.addModule(d)).then(function(){o.set(r,d),t=1})},function(){URL.revokeObjectURL(d)});return Promise.resolve(l&&l.then?l.then(n):n(l))}catch(e){return Promise.reject(e)}});function c(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var d,l,u=/*#__PURE__*/function(){function e(e,t,n,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this._isMuted=!1,this.context=e,this.analyser=t,this.gain=n,this.worklet=i}e.createAudioOutput=function(t){var n=t.sampleRate,i=t.format;try{var r=null;return Promise.resolve(c(function(){var t=(r=new AudioContext({sampleRate:n})).createAnalyser(),s=r.createGain();return s.connect(t),t.connect(r.destination),Promise.resolve(a(r.audioWorklet)).then(function(){var n=new AudioWorkletNode(r,"audio-concat-processor");n.port.postMessage({type:"setFormat",format:i}),n.connect(s);var o=new e(r,t,s,n);return Promise.resolve(o.ensureIOSCompatibility()).then(function(){return o})})},function(e){var t;throw null==(t=r)||t.close(),e}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.ensureIOSCompatibility=function(){try{var e=this;if(/iPad|iPhone|iPod/.test(navigator.userAgent)){var t=e.context.createBuffer(1,1,e.context.sampleRate),n=e.context.createBufferSource();n.buffer=t,n.connect(e.context.destination),n.start()}return Promise.resolve()}catch(e){return Promise.reject(e)}},t.getOutputDevice=function(){try{var e=this;return Promise.resolve(c(function(){var t=e.context.sinkId||"";return Promise.resolve(navigator.mediaDevices.enumerateDevices()).then(function(e){var n=e.filter(function(e){return"audiooutput"===e.kind});return""===t?n.find(function(e){return"default"===e.deviceId})||n[0]||null:n.find(function(e){return e.deviceId===t})||null})},function(e){return console.error("Error getting output device:",e),null}))}catch(e){return Promise.reject(e)}},t.getAvailableOutputDevices=function(){try{return Promise.resolve(c(function(){return Promise.resolve(navigator.mediaDevices.enumerateDevices()).then(function(e){return e.filter(function(e){return"audiooutput"===e.kind})})},function(e){return console.error("Error enumerating devices:",e),[]}))}catch(e){return Promise.reject(e)}},t.mute=function(){this.gain.gain.value=0,this._isMuted=!0},t.unmute=function(){this.gain.gain.value=1,this._isMuted=!1},t.toggleMute=function(){return this._isMuted?this.unmute():this.mute(),this._isMuted},t.close=function(){try{return Promise.resolve(this.context.close()).then(function(){})}catch(e){return Promise.reject(e)}},e}(),h=/*#__PURE__*/function(){function e(e,t,n){var i=this;this.syncController=void 0,this.audioOutput=void 0,this.videoOutput=void 0,this.initialized=!1,this.isPlaying=!1,this.isPlayingAudio=!1,this.isPlayingVideo=!1,this.isStoppingAV=!1,this.handleAudioWorkletMessage=function(e){"process"===e.type&&(i.isPlayingAudio=!1,i.isPlayingVideo||(i.isPlaying=!1),i.audioOutput.worklet.port.postMessage({type:"reset"}))},this.syncController=e,this.audioOutput=t,this.videoOutput=n,this.videoOutput.setEventCallbacks({onIdleVideoShown:function(){},onIdleVideoHidden:function(){i.isPlayingVideo=!1,i.isPlayingAudio||(i.isPlaying=!1),i.videoOutput.stopBufferMonitoring()}})}var t=e.prototype;return t.updatePlayingState=function(e){this.isPlaying=e,this.isPlayingAudio=e,this.isPlayingVideo=e},t.toggleStoppingVideo=function(e){this.isStoppingAV=e},t.startPlayback=function(e){void 0===e&&(e=!1);try{var t=this;return t.isPlaying?Promise.resolve():(e&&(t.initialized=e),Promise.resolve(t.audioOutput.context.resume()).then(function(){t.updatePlayingState(!0),t.videoOutput.startStreaming(e),t.audioOutput.worklet.port.postMessage({type:"startPlayback"})}))}catch(e){return Promise.reject(e)}},t.playAudioVideo=function(){try{var e=this;if(!e.initialized)return Promise.resolve();if(e.isPlaying||e.isStoppingAV)return Promise.resolve();var t=e.videoOutput.getBufferLength();return e.startPlayback(!0),t>=6&&e.startPlayback(),Promise.resolve()}catch(e){return Promise.reject(e)}},e}();function p(e){return e.event===exports.EventType.JOIN}function m(e){return e.event===exports.EventType.TEXT}function g(e){return e.event===exports.EventType.RESPONSE}function f(e){return e.event===exports.EventType.STREAMING}function v(e){return e.event===exports.EventType.STREAMING&&e.type===exports.StreamingEventType.ERROR}function y(e){return e.event===exports.EventType.BINARY}function b(e){return e.type===exports.EventType.PONG}function k(e){return e.event===exports.EventType.TIMEOUT_WARNING}function T(e){return e.event===exports.EventType.TIME_OUT}function S(e){return e.event===exports.EventType.KEEP_SESSION}function C(e){switch(e){case"production":default:return"https://chat-api.unith.ai";case"staging":return"https://chat-api.stg.unith.live";case"development":return"https://chat-api.dev.unith.live"}}function E(e){return!!e.event}exports.EventType=void 0,(d=exports.EventType||(exports.EventType={})).TEXT="text",d.CONVERSATION_END="conversation_end",d.JOIN="join",d.ERROR="error",d.TIME_OUT="timeout",d.UNITH_NLP_EXCEPTION="unith_nlp_exception",d.ANALYTICS="analytics-userFeedback",d.CHOICE="choice",d.TIMEOUT_WARNING="timeout_warning",d.KEEP_SESSION="keep_session",d.RESPONSE="response",d.STREAMING="streaming",d.PING="ping",d.PONG="pong",d.BINARY="binary",exports.StreamingEventType=void 0,(l=exports.StreamingEventType||(exports.StreamingEventType={})).VIDEO_FRAME="video_frame",l.AUDIO_FRAME="audio_frame",l.METADATA="metadata",l.ERROR="error",l.CACHE="cache";var w=/*#__PURE__*/function(){function e(e,t){var n=this;this.socket=void 0,this.userId=void 0,this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onPingPongCallback=null,this.socket=e,this.userId=t,this.socket.addEventListener("error",function(e){n.disconnect({reason:"error",message:"The connection was closed due to a websocket error.",context:e})}),this.socket.addEventListener("close",function(e){n.disconnect({reason:"error",message:e.reason||"The connection was closed by the server.",context:e})}),this.socket.addEventListener("message",function(e){try{var t;if(b(t=e.data instanceof Blob||e.data instanceof ArrayBuffer?{event:exports.EventType.BINARY,user_id:"",username:"",data:e.data}:JSON.parse(e.data))){if(!n.onPingPongCallback)return;return void n.onPingPongCallback(t)}if(!E(t))return;n.onMessageCallback?n.onMessageCallback(t):n.queue.push(t)}catch(e){}})}e.create=function(t){try{var n=null,i=function(e){switch(e){case"production":default:return"wss://stream-api.unith.ai/stream-hub";case"staging":return"wss://stream-api.stg.unith.live/stream-hub";case"development":return"wss://stream-api.dev.unith.live/stream-hub"}}(t.environment);return Promise.resolve(function(r,s){try{var o=(n=new WebSocket(i+"/"+t.orgId+"/"+t.headId),Promise.resolve(new Promise(function(e,i){n.addEventListener("open",function(){n.send(JSON.stringify({token:t.token,api_key:t.apiKey,text_only:!0,format:"vp8",quality:"standard",crop:!1}))},{once:!0}),n.addEventListener("close",function(e){i()}),n.addEventListener("error",i),n.addEventListener("message",function(n){var r=JSON.parse(n.data);E(r)&&(p(r)?r.granted&&(null==t.onJoin||t.onJoin(),e(r.user_id)):v(r)&&i({type:"connection",message:"We are currently at full capacity. Please try again later."}))},{once:!0})})).then(function(t){return new e(n,t)}))}catch(e){return s(e)}return o&&o.then?o.then(void 0,s):o}(0,function(e){var t;throw null==(t=n)||t.close(),e}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.disconnect=function(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,null==(t=this.onDisconnectCallback)||t.call(this,e))},t.close=function(){this.socket.close()},t.sendMessage=function(e){this.socket.send(JSON.stringify(e))},t.sendPingEvent=function(e){this.onPingPongCallback?this.socket.send(JSON.stringify(e)):console.warn("Ping event sent without a callback set.")},t.onPingPong=function(e){this.onPingPongCallback=e},t.onMessage=function(e){this.onMessageCallback=e;var t=this.queue;this.queue=[],t.length>0&&queueMicrotask(function(){t.forEach(e)})},t.onDisconnect=function(e){this.onDisconnectCallback=e;var t=this.disconnectionDetails;t&&queueMicrotask(function(){e(t)})},e}(),P=/*#__PURE__*/function(){function e(e,t){this.idleVideoSource=void 0,this.videoId=void 0,this.idleVideoSource=e,this.videoId=t}return e.getIdleVideo=function(t,n,i){try{return Promise.resolve(e.getIdleVideoId(t,n,i)).then(function(r){return Promise.resolve(fetch(t+"/api/v1/idle/"+n+"/"+i+"/"+r)).then(function(t){return t.status>=200&&t.status<=299?Promise.resolve(t.json()).then(function(t){if(t)return new e(t,r);throw new Error("No idle video found for the specified orgId and headId.")}):Promise.resolve(t.text()).then(function(e){var n=new Error("An error occurred retrieving idle video: "+t.status+" "+t.statusText+". Response: "+e);throw n.name="IdleVideoError",n})})})}catch(e){return Promise.reject(e)}},e.prototype.getAvatarSrc=function(e,t,n){try{return Promise.resolve(fetch(e+"/api/v1/avatar/"+t+"/"+n+"/"+this.videoId)).then(function(e){return e.status>=200&&e.status<=299?Promise.resolve(e.json()).then(function(e){if(e)return e;throw new Error("No avatar image found for the specified orgId and headId.")}):Promise.resolve(e.text()).then(function(t){var n=new Error("An error occurred retrieving avatar: "+e.status+" "+e.statusText+". Response: "+t);throw n.name="AvatarError",n})})}catch(e){return Promise.reject(e)}},e.getIdleVideoId=function(e,t,n){try{return Promise.resolve(fetch(e+"/api/v1/videos/"+t+"/"+n)).then(function(e){return e.status>=200&&e.status<=299?Promise.resolve(e.json()).then(function(e){if(e.length>0)return e[0].id;throw new Error("No idle video found for the specified orgId and headId.")}):Promise.resolve(e.text()).then(function(t){var n=new Error("An error occurred retrieving idle video: "+e.status+" "+e.statusText+". Response: "+t);throw n.name="IdleVideoError",n})})}catch(e){return Promise.reject(e)}},e}();function R(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var I=Object.defineProperty,O=(e,t,n)=>((e,t,n)=>t in e?I(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class _{constructor(){O(this,"_locking"),O(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 D(e,t){if(!e)throw new Error(t)}function M(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 A(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 x(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 N=Symbol("@bufbuild/protobuf/enum-type");function L(e,t,n,i){e[N]=U(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function U(e,t,n){const i=Object.create(null),r=Object.create(null),s=[];for(const e of t){const t=j(e);s.push(t),i[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>i[e],findNumber:e=>r[e]}}function j(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class F{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(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function V(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function B(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,s=!(r>>>7==0&&0==t);if(n.push(255&(s?128|r:r)),!s)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);if(n.push(255&(r?128|i:i)),!r)return}n.push(t>>>31&1)}}const q=4294967296;function W(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function s(t,s){const o=Number(e.slice(t,s));r*=n,i=i*n+o,i>=q&&(r+=i/q|0,i%=q)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?G(i,r):z(i,r)}function H(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(q*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let r=(16777215&e)+6777216*n+6710656*i,s=n+8147497*i,o=2*i;const a=1e7;return r>=a&&(s+=Math.floor(r/a),r%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+K(s)+K(r)}function z(e,t){return{lo:0|e,hi:0|t}}function G(e,t){return t=~t,e?e=1+~e:t+=1,z(e,t)}const K=e=>{const t=String(e);return"0000000".slice(t.length)+t};function J(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 Q(){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 t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Y=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=>D(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>D(/^[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),W(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),W(e)),dec:(e,t)=>function(e,t){let n=z(e,t);const i=2147483648&n.hi;i&&(n=G(n.lo,n.hi));const r=H(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>H(e,t)}}();var X,$,Z;function ee(e,t,n){if(t===n)return!0;if(e==X.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 X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return t==n}return!1}function te(e,t){switch(e){case X.BOOL:return!1;case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return 0==t?Y.zero:"0";case X.DOUBLE:case X.FLOAT:return 0;case X.BYTES:return new Uint8Array(0);case X.STRING:return"";default:return 0}}function ne(e,t){switch(e){case X.BOOL:return!1===t;case X.STRING:return""===t;case X.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(X||(X={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}($||($={})),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"}(Z||(Z={}));class ie{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(A(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return M(e),J(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){x(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){A(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){M(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return M(e),J(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=Y.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=Y.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=Y.enc(e);return B(t.lo,t.hi,this.buf),this}sint64(e){let t=Y.enc(e),n=t.hi>>31;return B(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Y.uEnc(e);return B(t.lo,t.hi,this.buf),this}}class re{constructor(e,t){this.varint64=V,this.uint32=Q,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 Z.Varint:for(;128&this.buf[this.pos++];);break;case Z.Bit64:this.pos+=4;case Z.Bit32:this.pos+=4;break;case Z.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Z.StartGroup:for(;;){const[e,n]=this.tag();if(n===Z.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return Y.dec(...this.varint64())}uint64(){return Y.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,Y.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Y.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Y.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 se(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 te(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 oe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ae=[];for(let e=0;e<oe.length;e++)ae[oe[e].charCodeAt(0)]=e;ae["-".charCodeAt(0)]=oe.indexOf("+"),ae["_".charCodeAt(0)]=oe.indexOf("/");const ce={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,s=0,o=0;for(let t=0;t<e.length;t++){if(n=ae[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=n,s=1;break;case 1:i[r++]=o<<2|(48&n)>>4,o=n,s=2;break;case 2:i[r++]=(15&o)<<4|(60&n)>>2,o=n,s=3;break;case 3:i[r++]=(3&o)<<6|n,s=0}}if(1==s)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],i){case 0:n+=oe[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=oe[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=oe[r|t>>6],n+=oe[63&t],i=0}return i&&(n+=oe[r],n+="=",1==i&&(n+="=")),n}};function de(e,t,n){he(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),[s,o]=se(t);for(const e of r)t.runtime.bin.readField(s,i.readerFactory(e.data),t.field,e.wireType,i);return o()}function le(e,t,n,i){he(t,e);const r=t.runtime.bin.makeReadOptions(i),s=t.runtime.bin.makeWriteOptions(i);if(ue(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 o=s.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,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),i=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function ue(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 he(e,t){D(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function pe(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:!ne(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function me(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?te(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function ge(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(F.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 fe(e,t){return ge(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}const ve={ignoreUnknownFields:!1},ye={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},be=Symbol(),ke=Symbol();function Te(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 Se(e,t,n,i,r){let s=n.localName;if(n.repeated){if(D("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(Te(t)));const o=e[s];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,i));break;case"enum":const t=we(n.T,e,i.ignoreUnknownFields,!0);t!==ke&&o.push(t);break;case"scalar":try{o.push(Ee(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t)));const o=e[s];for(const[e,s]of Object.entries(t)){if(null===s)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let a;try{a=Ce(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":o[a]=n.V.T.fromJson(s,i);break;case"enum":const e=we(n.V.T,s,i.ignoreUnknownFields,!0);e!==ke&&(o[a]=e);break;case"scalar":try{o[a]=Ee(n.V.T,s,$.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[s];ge(a)?a.fromJson(t,i):(e[s]=a=o.fromJson(t,i),o.fieldWrapper&&!n.oneof&&(e[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=we(n.T,t,i.ignoreUnknownFields,!1);switch(c){case be:me(n,e);break;case ke:break;default:e[s]=c}break;case"scalar":try{const i=Ee(n.T,t,n.L,!1);i===be?me(n,e):e[s]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function Ce(e,t){if(e===X.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Ee(e,t,$.BIGINT,!0).toString()}function Ee(e,t,n,i){if(null===t)return i?te(e,n):be;switch(e){case X.DOUBLE:case X.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==X.FLOAT&&x(i),i;case X.INT32:case X.FIXED32:case X.SFIXED32:case X.SINT32:case X.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==X.UINT32||e==X.FIXED32?A(r):M(r),r;case X.INT64:case X.SFIXED64:case X.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=Y.parse(t);return n?s.toString():s;case X.FIXED64:case X.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=Y.uParse(t);return n?o.toString():o;case X.BOOL:if("boolean"!=typeof t)break;return t;case X.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case X.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ce.dec(t)}throw new Error}function we(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:be;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 ke}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Te(t)))}function Pe(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function Re(e,t,n){if("map"==e.kind){D("object"==typeof t&&null!=t);const i={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of r)i[t.toString()]=Oe(e.V.T,n);break;case"message":for(const[e,t]of r)i[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,s]of r)i[e.toString()]=Ie(t,s,n.enumAsInteger)}return n.emitDefaultValues||r.length>0?i:void 0}if(e.repeated){D(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(Oe(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(Ie(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 Oe(e.T,t);case"enum":return Ie(e.T,t,n.enumAsInteger);case"message":return fe(e.T,t).toJson(n)}}function Ie(e,t,n){var i;if(D("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 Oe(e,t){switch(e){case X.INT32:case X.SFIXED32:case X.SINT32:case X.FIXED32:case X.UINT32:return D("number"==typeof t),t;case X.FLOAT:case X.DOUBLE:return D("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case X.STRING:return D("string"==typeof t),t;case X.BOOL:return D("boolean"==typeof t),t;case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return D("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case X.BYTES:return D(t instanceof Uint8Array),ce.enc(t)}}const _e=Symbol("@bufbuild/protobuf/unknown-fields"),De={readUnknownFields:!0,readerFactory:e=>new re(e)},Me={writeUnknownFields:!0,writerFactory:()=>new ie};function Ae(e,t,n,i,r){let{repeated:s,localName:o}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const a="enum"==n.kind?X.INT32:n.T;let c=Le;if("scalar"==n.kind&&n.L>0&&(c=Ne),s){let n=e[o];if(i==Z.LengthDelimited&&a!=X.STRING&&a!=X.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,a))}else n.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=n.T;s?e[o].push(xe(t,new d,r,n)):ge(e[o])?xe(t,e[o],r,n):(e[o]=xe(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,n){const i=t.uint32(),r=t.pos+i;let s,o;for(;t.pos<r;){const[i]=t.tag();switch(i){case 1:s=Le(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Le(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=xe(t,new e.V.T,n,void 0)}}}if(void 0===s&&(s=te(e.K,$.BIGINT)),"string"!=typeof s&&"number"!=typeof s&&(s=s.toString()),void 0===o)switch(e.V.kind){case"scalar":o=te(e.V.T,$.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[s,o]}(n,t,r);e[o][l]=u}}function xe(e,t,n,i){const r=t.getType().runtime.bin,s=null==i?void 0:i.delimited;return r.readMessage(t,e,s?i.no:e.uint32(),n,s),t}function Ne(e,t){const n=Le(e,t);return"bigint"==typeof n?n.toString():n}function Le(e,t){switch(t){case X.STRING:return e.string();case X.BOOL:return e.bool();case X.DOUBLE:return e.double();case X.FLOAT:return e.float();case X.INT32:return e.int32();case X.INT64:return e.int64();case X.UINT64:return e.uint64();case X.FIXED64:return e.fixed64();case X.BYTES:return e.bytes();case X.FIXED32:return e.fixed32();case X.SFIXED32:return e.sfixed32();case X.SFIXED64:return e.sfixed64();case X.SINT64:return e.sint64();case X.UINT32:return e.uint32();case X.SINT32:return e.sint32()}}function Ue(e,t,n,i){D(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?X.INT32:e.T;if(r)if(D(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,Z.LengthDelimited).fork();let[,r]=Be(t);for(let t=0;t<i.length;t++)e[r](i[t]);e.join()}(n,s,e.no,t);else for(const i of t)Ve(n,s,e.no,i);else Ve(n,s,e.no,t);break;case"message":if(r){D(Array.isArray(t));for(const r of t)Fe(n,i,e,r)}else Fe(n,i,e,t);break;case"map":D("object"==typeof t&&null!=t);for(const[r,s]of Object.entries(t))je(n,i,e,r,s)}}function je(e,t,n,i,r){e.tag(n.no,Z.LengthDelimited),e.fork();let s=i;switch(n.K){case X.INT32:case X.FIXED32:case X.UINT32:case X.SFIXED32:case X.SINT32:s=Number.parseInt(i);break;case X.BOOL:D("true"==i||"false"==i),s="true"==i}switch(Ve(e,n.K,1,s),n.V.kind){case"scalar":Ve(e,n.V.T,2,r);break;case"enum":Ve(e,X.INT32,2,r);break;case"message":D(void 0!==r),e.tag(2,Z.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Fe(e,t,n,i){const r=fe(n.T,i);n.delimited?e.tag(n.no,Z.StartGroup).raw(r.toBinary(t)).tag(n.no,Z.EndGroup):e.tag(n.no,Z.LengthDelimited).bytes(r.toBinary(t))}function Ve(e,t,n,i){D(void 0!==i);let[r,s]=Be(t);e.tag(n,r)[s](i)}function Be(e){let t=Z.Varint;switch(e){case X.BYTES:case X.STRING:t=Z.LengthDelimited;break;case X.DOUBLE:case X.FIXED64:case X.SFIXED64:t=Z.Bit64;break;case X.FIXED32:case X.SFIXED32:case X.FLOAT:t=Z.Bit32}return[t,X[e].toLowerCase()]}function qe(e){if(void 0===e)return e;if(ge(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function We(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class He{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 ze(e,t){const n=Ke(e);return t?n:$e(Xe(n))}const Ge=Ke;function Ke(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 Je=new Set(["constructor","toString","toJSON","valueOf"]),Qe=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ye=e=>"".concat(e,"$"),Xe=e=>Qe.has(e)?Ye(e):e,$e=e=>Je.has(e)?Ye(e):e;class Ze{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=ze(e,!1)}addField(e){D(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 et=(tt=e=>new He(e,e=>function(e){var t,n,i,r,s,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=ze(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:Ge(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:$.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(s=d.req)&&void 0!==s&&s,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=X.BYTES&&d.T!=X.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ze(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e)),nt=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]=te(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},ve),e):ve},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},ye),e):ye},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(Te(t)));i=null!=i?i:new e;const r=new Map,s=n.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const n=r.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(o,'"'));r.set(t.oneof,o)}Se(i,a,t,n,e)}else{let t=!1;if((null==s?void 0:s.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const r=s.findExtension(o.substring(1,o.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;const[e,s]=se(r);Se(e,a,r.field,n,r),le(i,r,s(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!pe(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Pe(r))continue}const n=Re(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const o=s.findExtensionFor(n.typeName,r.no);if(o&&ue(e,o)){const n=de(e,o,t),r=Re(o.field,n,t);void 0!==r&&(i[o.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>Ee(e,t,null!=n?n:$.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||ne(e,t)?Oe(e,t):void 0},debug:Te},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},De),e):De},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Me),e):Me},listUnknownFields(e){var t;return null!==(t=e[_e])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[_e]},writeUnknownFields(e,t){const n=e[_e];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[_e])||(r[_e]=[]),r[_e].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const s=e.getType(),o=r?t.len:t.pos+n;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==r||c!=Z.EndGroup);){const n=s.fields.find(a);if(!n){const n=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,n);continue}Ae(e,t,n,c,i)}if(r&&(c!=Z.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:Ae,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(pe(r,e))Ue(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&&Ue(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:L,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,r=t,s=e;if(null!=s[n])switch(i.kind){case"oneof":const e=s[n].case;if(void 0===e)continue;const t=i.findField(e);let o=s[n].value;t&&"message"==t.kind&&!ge(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===X.BYTES&&(o=We(o)),r[n]={case:e,value:o};break;case"scalar":case"enum":let a=s[n];i.T===X.BYTES&&(a=i.repeated?a.map(We):We(a)),r[n]=a;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===X.BYTES)for(const[e,t]of Object.entries(s[n]))r[n][e]=We(t);else Object.assign(r[n],s[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(s[n])){let i=s[n][t];e.fieldWrapper||(i=new e(i)),r[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)r[n]=s[n].map(e=>ge(e,c)?e:new c(e));else{const e=s[n];r[n]=c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?We(e):e:ge(e,c)?e:new c(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)=>ee(e.T,t,r[n]));case"enum":return i.every((e,t)=>ee(X.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||ge(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||ge(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return ee(X.INT32,i,r);case"scalar":return ee(e.T,i,r);case"oneof":if(i.case!==r.case)return!1;const s=e.findField(i.case);if(void 0===s)return!0;switch(s.kind){case"message":return s.T.equals(i.value,r.value);case"enum":return ee(X.INT32,i.value,r.value);case"scalar":return ee(s.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const o=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return o.every(e=>t.equals(i[e],r[e]));case"enum":return o.every(e=>ee(X.INT32,i[e],r[e]));case"scalar":const n=e.V.T;return o.every(e=>ee(n,i[e],r[e]))}}}),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let r;if(n.repeated)r=t.map(qe);else if("map"==n.kind){r=i[n.localName];for(const[e,n]of Object.entries(t))r[e]=qe(n)}else r="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:qe(t.value)}:{case:void 0}:qe(t);i[n.localName]=r}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:tt,initFields:nt}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const s=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(o.prototype,new F),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,n)=>e.util.equals(o,t,n)}),o}(this,e,t,n)},makeEnum:function(e,t,n){const i={};for(const e of t){const t=j(e);i[t.localName]=t.no,i[t.no]=t.localName}return L(i,e,t),i},makeEnumType:U,getEnumType:function(e){const t=e[N];return D(t,"missing enum type on enum object"),t},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 tt,nt;class it extends F{constructor(e){super(),this.seconds=Y.zero,this.nanos=0,et.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(et.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=Y.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 it.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new it({seconds:Y.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new it).fromBinary(e,t)}static fromJson(e,t){return(new it).fromJson(e,t)}static fromJsonString(e,t){return(new it).fromJsonString(e,t)}static equals(e,t){return et.util.equals(it,e,t)}}it.runtime=et,it.typeName="google.protobuf.Timestamp",it.fields=et.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const rt=/* @__PURE__ */et.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:it},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:st,repeated:!0},{no:5,name:"events",kind:"message",T:at,repeated:!0}]),st=/* @__PURE__ */et.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:ot,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ot=/* @__PURE__ */et.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:it},{no:3,name:"value",kind:"scalar",T:2}]),at=/* @__PURE__ */et.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:it},{no:7,name:"normalized_end_timestamp",kind:"message",T:it,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ct=/* @__PURE__ */et.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),dt=/* @__PURE__ */et.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),lt=/* @__PURE__ */et.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"}]),ut=/* @__PURE__ */et.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ht=/* @__PURE__ */et.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),pt=/* @__PURE__ */et.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),mt=/* @__PURE__ */et.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"}]),gt=/* @__PURE__ */et.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"}]),ft=/* @__PURE__ */et.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),vt=/* @__PURE__ */et.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"}]),yt=/* @__PURE__ */et.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:bt,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:Zt}]),bt=/* @__PURE__ */et.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),kt=/* @__PURE__ */et.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:et.getEnumType(lt),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Tt=/* @__PURE__ */et.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:et.getEnumType(St)},{no:4,name:"tracks",kind:"message",T:Rt,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:kt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:et.getEnumType(Ct)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:et.getEnumType(mt)},{no:18,name:"kind_details",kind:"enum",T:et.getEnumType(Et),repeated:!0}]),St=/* @__PURE__ */et.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ct=/* @__PURE__ */et.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"}]),Et=/* @__PURE__ */et.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),wt=/* @__PURE__ */et.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Pt=/* @__PURE__ */et.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:It,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:et.getEnumType(Ot)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Rt=/* @__PURE__ */et.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:et.getEnumType(dt)},{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:et.getEnumType(lt)},{no:10,name:"layers",kind:"message",T:It,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:Pt,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:et.getEnumType(wt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Zt},{no:19,name:"audio_features",kind:"enum",T:et.getEnumType(vt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:et.getEnumType(ct)}]),It=/* @__PURE__ */et.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:et.getEnumType(ut)},{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}]),Ot=/* @__PURE__ */et.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"}]),_t=/* @__PURE__ */et.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:et.getEnumType(Dt)},{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:Lt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:xt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ut,oneof:"value"},{no:7,name:"transcription",kind:"message",T:jt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:rt,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Vt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Bt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:qt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Wt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:rn,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:sn,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:on,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Mt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Dt=/* @__PURE__ */et.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Mt=/* @__PURE__ */et.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:et.getEnumType(wt)},{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}]),At=/* @__PURE__ */et.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Lt,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Vt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Bt,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:qt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Wt,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:rn,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:sn,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:on,oneof:"value"}]),xt=/* @__PURE__ */et.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Nt,repeated:!0}]),Nt=/* @__PURE__ */et.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}]),Lt=/* @__PURE__ */et.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}]),Ut=/* @__PURE__ */et.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),jt=/* @__PURE__ */et.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:Ft,repeated:!0}]),Ft=/* @__PURE__ */et.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}]),Vt=/* @__PURE__ */et.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}]),Bt=/* @__PURE__ */et.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}]),qt=/* @__PURE__ */et.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Wt=/* @__PURE__ */et.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:Ht,oneof:"value"}]),Ht=/* @__PURE__ */et.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}]),zt=/* @__PURE__ */et.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Gt=/* @__PURE__ */et.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:et.getEnumType(Kt)},{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}]),Kt=/* @__PURE__ */et.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Jt=/* @__PURE__ */et.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:et.getEnumType(Qt)},{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}]),Qt=/* @__PURE__ */et.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"}]),Yt=/* @__PURE__ */et.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Xt},{no:2,name:"screen",kind:"message",T:Xt},{no:3,name:"resume_connection",kind:"enum",T:et.getEnumType(pt)},{no:4,name:"disabled_codecs",kind:"message",T:$t},{no:5,name:"force_relay",kind:"enum",T:et.getEnumType(pt)}]),Xt=/* @__PURE__ */et.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:et.getEnumType(pt)}]),$t=/* @__PURE__ */et.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:bt,repeated:!0},{no:2,name:"publish",kind:"message",T:bt,repeated:!0}]),Zt=/* @__PURE__ */et.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),en=/* @__PURE__ */et.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),tn=/* @__PURE__ */et.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:et.getEnumType(en)},{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"}),nn=/* @__PURE__ */et.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),rn=/* @__PURE__ */et.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:et.getEnumType(wt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:tn,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:nn,oneof:"content_header"}],{localName:"DataStream_Header"}),sn=/* @__PURE__ */et.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"}),on=/* @__PURE__ */et.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"}),an=/* @__PURE__ */et.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),cn=/* @__PURE__ */et.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),dn=/* @__PURE__ */et.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ln=/* @__PURE__ */et.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),un=/* @__PURE__ */et.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Tn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:gn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:mn,oneof:"message"},{no:5,name:"mute",kind:"message",T:fn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Cn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:En,oneof:"message"},{no:8,name:"leave",kind:"message",T:Rn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:On,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Wn,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Gn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Qn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:_n,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Yn,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:wn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Pn,oneof:"message"}]),hn=/* @__PURE__ */et.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:vn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Tn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:gn,oneof:"message"},{no:5,name:"update",kind:"message",T:Sn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:bn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Rn,oneof:"message"},{no:9,name:"mute",kind:"message",T:fn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Mn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:An,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Nn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Un,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Vn,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Hn,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:kn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:yn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Xn,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ei,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ti,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ii,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:zn,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:ci,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Bn,oneof:"message"}]),pn=/* @__PURE__ */et.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:It,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:et.getEnumType(Ot)}]),mn=/* @__PURE__ */et.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:et.getEnumType(dt)},{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:et.getEnumType(lt)},{no:9,name:"layers",kind:"message",T:It,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:pn,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:et.getEnumType(wt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:et.getEnumType(ct)},{no:17,name:"audio_features",kind:"enum",T:et.getEnumType(vt),repeated:!0}]),gn=/* @__PURE__ */et.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:et.getEnumType(cn)},{no:3,name:"final",kind:"scalar",T:8}]),fn=/* @__PURE__ */et.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),vn=/* @__PURE__ */et.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:yt},{no:2,name:"participant",kind:"message",T:Tt},{no:3,name:"other_participants",kind:"message",T:Tt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Dn,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:Yt},{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:Gt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:bt,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),yn=/* @__PURE__ */et.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Dn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Yt},{no:3,name:"server_info",kind:"message",T:Gt},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),bn=/* @__PURE__ */et.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Rt}]),kn=/* @__PURE__ */et.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Tn=/* @__PURE__ */et.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}}]),Sn=/* @__PURE__ */et.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Tt,repeated:!0}]),Cn=/* @__PURE__ */et.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:zt,repeated:!0}]),En=/* @__PURE__ */et.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:et.getEnumType(ut)},{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}]),wn=/* @__PURE__ */et.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:et.getEnumType(vt),repeated:!0}]),Pn=/* @__PURE__ */et.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}]),Rn=/* @__PURE__ */et.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:et.getEnumType(mt)},{no:3,name:"action",kind:"enum",T:et.getEnumType(In)},{no:4,name:"regions",kind:"message",T:$n}]),In=/* @__PURE__ */et.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),On=/* @__PURE__ */et.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:It,repeated:!0}]),_n=/* @__PURE__ */et.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}]),Dn=/* @__PURE__ */et.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}]),Mn=/* @__PURE__ */et.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Nt,repeated:!0}]),An=/* @__PURE__ */et.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:yt}]),xn=/* @__PURE__ */et.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:et.getEnumType(ht)},{no:3,name:"score",kind:"scalar",T:2}]),Nn=/* @__PURE__ */et.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:xn,repeated:!0}]),Ln=/* @__PURE__ */et.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:et.getEnumType(dn)}]),Un=/* @__PURE__ */et.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Ln,repeated:!0}]),jn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:et.getEnumType(ut)},{no:2,name:"enabled",kind:"scalar",T:8}]),Fn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:jn,repeated:!0}]),Vn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:jn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Fn,repeated:!0}]),Bn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:an,repeated:!0}]),qn=/* @__PURE__ */et.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}]),Wn=/* @__PURE__ */et.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:qn,repeated:!0}]),Hn=/* @__PURE__ */et.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}]),zn=/* @__PURE__ */et.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:yt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Tt},{no:4,name:"other_participants",kind:"message",T:Tt,repeated:!0}]),Gn=/* @__PURE__ */et.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Tn},{no:2,name:"subscription",kind:"message",T:Cn},{no:3,name:"publish_tracks",kind:"message",T:bn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Jn,repeated:!0},{no:5,name:"offer",kind:"message",T:Tn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Kn,repeated:!0}]),Kn=/* @__PURE__ */et.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Jn=/* @__PURE__ */et.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:et.getEnumType(cn)}]),Qn=/* @__PURE__ */et.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:et.getEnumType(ln),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"}]),Yn=/* @__PURE__ */et.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Xn=/* @__PURE__ */et.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),$n=/* @__PURE__ */et.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Zn,repeated:!0}]),Zn=/* @__PURE__ */et.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}]),ei=/* @__PURE__ */et.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:et.getEnumType(ft)}]),ti=/* @__PURE__ */et.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:et.getEnumType(ni)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:gn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:mn,oneof:"request"},{no:6,name:"mute",kind:"message",T:fn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:_n,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:wn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Pn,oneof:"request"}]),ni=/* @__PURE__ */et.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"}]),ii=/* @__PURE__ */et.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ri=/* @__PURE__ */et.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}]),si=/* @__PURE__ */et.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Jt},{no:2,name:"connection_settings",kind:"message",T:ri},{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:mn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Tn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:et.getEnumType(gt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Gn}]),oi=/* @__PURE__ */et.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:et.getEnumType(ai)},{no:2,name:"join_request",kind:"scalar",T:12}]),ai=/* @__PURE__ */et.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),ci=/* @__PURE__ */et.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function di(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var li,ui,hi,pi,mi,gi={exports:{}},fi=(li||(li=1,ui=gi.exports,hi=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={},s=null;function o(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),r=0;r<i.length;r++){var s=i[r];this[s]=r<n?e:this.methodFactory(s,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,s){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?a:void 0!==console[i]?o(console,i):void 0!==console.log?o(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=n||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,n){return d=m(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(o=m(s.getLevel())),c.call(u),s===u)for(var e in r)r[e].rebuild()},o=m(s?s.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(s=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,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},gi.exports?gi.exports=hi():ui.log=hi()),gi.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(pi||(pi={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(mi||(mi={}));let vi=fi.getLogger("livekit");function yi(e){const t=fi.getLogger(e);return t.setDefaultLevel(vi.getLevel()),t}Object.values(mi).map(e=>fi.getLogger(e)),vi.setDefaultLevel(pi.info);const bi=fi.getLogger("lk-e2ee"),ki=7e3,Ti=[0,300,1200,2700,4800,ki,ki,ki,ki,ki];function Si(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})}function Ci(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=function(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.")}(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)})}}}"function"==typeof SuppressedError&&SuppressedError;var Ei,wi={exports:{}},Pi=function(){if(Ei)return wi.exports;Ei=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)}wi.exports=r,wi.exports.once=function(e,t){return new Promise(function(n,i){function r(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,r)})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,s,c;if(o(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),c=s[t]),void 0===c)c=s[t]=n,++e._eventsCount;else if("function"==typeof c?c=s[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 d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,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(s){i.once&&e.removeEventListener(t,r),n(s)})}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},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+".");s=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,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[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.on=r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,s,a;if(o(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,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,r=s;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,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(r=s[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):[]},wi.exports}();let Ri=!0,Ii=!0;function Oi(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function _i(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const s=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,s),r.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(n))return s.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,s.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 Di(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ri=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Mi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ii=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Ai(){if("object"==typeof window){if(Ri)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function xi(e,t){Ii&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ni(e){return"[object Object]"===Object.prototype.toString.call(e)}function Li(e){return Ni(e)?Object.keys(e).reduce(function(t,n){const i=Ni(e[n]),r=i?Li(e[n]):e[n],s=i&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[n]:r})},{}):e}function Ui(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?Ui(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(t=>{Ui(e,e.get(t),n)})}))}function ji(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(n=>{n.type===i&&n.trackId===t.id&&Ui(e,n,r)})}),r}const Fi=Ai;function Vi(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const 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 s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then(n=>{let o=(n=n.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes("back")&&(o=n[n.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),Fi("chrome: "+JSON.stringify(e)),r(e)})}e.video=i(e.video)}return Fi("chrome: "+JSON.stringify(e)),r(e)},s=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(s(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(s(e))))}}}function Bi(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function qi(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};const 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 _i(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Wi(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&&(this._dtmf="audio"===t.kind?e.createDTMFSender(t):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&&(this._dtmf="audio"===this.track.kind?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function Hi(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>ji(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}),_i(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>ji(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach(n=>{n.track===e&&(t?i=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?i=!0:n=t),t.track===e)),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function zi(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 Gi(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return zi(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 s(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t];n=n.replace(new RegExp(e._streams[i.id].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=s(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>s(this,e))}};e.RTCPeerConnection.prototype[t]=i[t]});const o=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]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(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 Ki(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 Ji(e,t){_i(e,"negotiationneeded",e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e})}var Qi=/*#__PURE__*/Object.freeze({__proto__:null,fixNegotiationNeeded:Ji,shimAddTrackRemoveTrack:Gi,shimAddTrackRemoveTrackWithNative:zi,shimGetSendersWithDtmf:Wi,shimGetUserMedia:Vi,shimMediaStream:Bi,shimOnTrack:qi,shimPeerConnection:Ki,shimSenderReceiverGetStats:Hi});function Yi(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){xi("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 Xi(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 $i(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return i.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(r,s)}}function Zi(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 er(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}),_i(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function tr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){xi("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function nr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return i})}function rr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function sr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function or(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var ar=/*#__PURE__*/Object.freeze({__proto__:null,shimAddTransceiver:ir,shimCreateAnswer:or,shimCreateOffer:sr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:rr,shimGetUserMedia:Yi,shimOnTrack:Xi,shimPeerConnection:$i,shimRTCDataChannel:nr,shimReceiverGetStats:er,shimRemoveStream:tr,shimSenderGetStats:Zi});function cr(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 dr(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 lr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=n.apply(this,[arguments.length>=2?arguments[2]:arguments[0]]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const n=i.apply(this,[arguments.length>=2?arguments[2]:arguments[0]]);return t?(n.then(e,t),Promise.resolve()):n};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=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function ur(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(hr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function hr(e){return e&&void 0!==e.video?Object.assign({},e,{video:Li(e.video)}):e}function pr(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?(xi("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 mr(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 gr(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 fr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var vr,yr=/*#__PURE__*/Object.freeze({__proto__:null,shimAudioContext:fr,shimCallbacksAPI:lr,shimConstraints:hr,shimCreateOfferLegacy:gr,shimGetUserMedia:ur,shimLocalStreamsAPI:cr,shimRTCIceServerUrls:pr,shimRemoteStreamsAPI:dr,shimTrackEventTransceiver:mr}),br={exports:{}},kr=(vr||(vr=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>0===e.indexOf(n))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;t.push("rtp"===n?1:"rtcp"===n?2:n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach(t=>{i.push(void 0!==e.parameters[t]?t+"="+e.parameters[t]: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 r=3;r<i.length;r++){const s=i[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const i=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").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"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),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:s?"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 s=t.matchPrefix(e,"a=rtcp-mux");return n.mux=s.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 s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize: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 s=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(br)),br.exports),Tr=/*@__PURE__*/di(kr),Sr=/*#__PURE__*/R({__proto__:null,default:Tr},[kr]);function Cr(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=Tr.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,_i(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Er(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||_i(e,"icecandidate",e=>{if(e.candidate){const t=Tr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function wr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Tr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Tr.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=Tr.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 s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return n.apply(this,arguments)}}function Pr(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0];if("open"===e.readyState&&t.sctp&&(i.length||i.size||i.byteLength)>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},_i(e,"datachannel",e=>(t(e.channel,e.target),e))}function Rr(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 Ir(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 Or(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 _r(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"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?n.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var Dr=/*#__PURE__*/Object.freeze({__proto__:null,removeExtmapAllowMixed:Ir,shimAddIceCandidateNullOrEmpty:Or,shimConnectionState:Rr,shimMaxMessageSize:wr,shimParameterlessSetLocalDescription:_r,shimRTCIceCandidate:Cr,shimRTCIceCandidateRelayProtocol:Er,shimSendThrowTypeError:Pr});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Ai,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Oi(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Oi(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Oi(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Oi(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:Dr,extractVersion:Oi,disableLog:Di,disableWarnings:Mi,sdp:Sr};switch(i.browser){case"chrome":if(!Qi||!Ki||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Qi,Or(e,i),_r(e),Vi(e,i),Bi(e),Ki(e,i),qi(e),Gi(e,i),Wi(e),Hi(e),Ji(e,i),Cr(e),Er(e),Rr(e),wr(e,i),Pr(e),Ir(e,i);break;case"firefox":if(!ar||!$i||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=ar,Or(e,i),_r(e),Yi(e,i),$i(e,i),Xi(e),tr(e),Zi(e),er(e),nr(e),ir(e),rr(e),sr(e),or(e),Cr(e),Rr(e),wr(e,i),Pr(e);break;case"safari":if(!yr||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=yr,Or(e,i),_r(e),pr(e),gr(e),lr(e),cr(e),dr(e),mr(e),ur(e),fr(e),Cr(e),Er(e),wr(e,i),Pr(e),Ir(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Mr="lk_e2ee";var Ar,xr,Nr,Lr,Ur,jr,Fr,Vr,Br,qr,Wr,Hr;function zr(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(Ar||(Ar={})),function(e){e.KeyRatcheted="keyRatcheted"}(xr||(xr={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(Nr||(Nr={})),function(e){e.Error="cryptorError"}(Lr||(Lr={}));class Gr extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(Ur||(Ur={}));class Kr extends Gr{constructor(e,t,n,i){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=i,this.reasonName=Ur[t]}}class Jr extends Gr{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Qr extends Gr{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Yr extends Gr{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Xr extends Gr{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class $r extends Gr{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Zr extends Gr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class es extends Gr{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:ni[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(jr||(jr={}));class ts extends Gr{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=jr[t]}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Fr||(Fr={})),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}}(Fr||(Fr={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(Vr||(Vr={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(Br||(Br={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(qr||(qr={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(Wr||(Wr={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(Hr||(Hr={}));const ns=/version\/(\d+(\.?_?\d+)+)/i;let is;function rs(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===is||t){const e=ss.find(e=>{let{test:t}=e;return t.test(n)});is=null==e?void 0:e.describe(n)}return is}const ss=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:os(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:as(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:os(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:as(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:os(ns,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:as(e)})}];function os(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 as(e){return e.includes("mac os")?os(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class cs{}cs.setTimeout=function(){return setTimeout(...arguments)},cs.setInterval=function(){return setInterval(...arguments)},cs.clearTimeout=function(){return clearTimeout(...arguments)},cs.clearInterval=function(){return clearInterval(...arguments)};const ds=[];var ls;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(ls||(ls={}));class us extends Pi.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=us.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=vi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:mi.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=us.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ko(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===us.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===us.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ds.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&ds.splice(ds.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),hs(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),i=n.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(i?Hr.AudioPlaybackStarted:Hr.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(i?Hr.AudioPlaybackFailed:Hr.VideoPlaybackFailed,t):"AbortError"===t.name?vi.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):vi.warn("could not playback ".concat(i?"audio":"video"),t),i&&e&&n.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(Hr.ElementAttached,e),e}detach(e){try{if(e){ps(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Hr.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(e=>{ps(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Hr.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=yi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ds.forEach(e=>{e.parentElement||(t=!1)}),t&&ds.push(e)}}handleAppVisibilityChanged(){return Si(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==us.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){xs()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){xs()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function hs(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)),Ds()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(Ds()||Os())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function ps(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),t.srcObject=n.getTracks().length>0?n: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 dt.AUDIO;case t.Video:return dt.VIDEO;default:return dt.DATA}},e.kindFromProto=function(e){switch(e){case dt.AUDIO:return t.Audio;case dt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return lt.CAMERA;case n.Microphone:return lt.MICROPHONE;case n.ScreenShare:return lt.SCREEN_SHARE;case n.ScreenShareAudio:return lt.SCREEN_SHARE_AUDIO;default:return lt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case lt.CAMERA:return n.Camera;case lt.MICROPHONE:return n.Microphone;case lt.SCREEN_SHARE:return n.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case dn.ACTIVE:return i.Active;case dn.PAUSED:return i.Paused;default:return i.Unknown}}}(us||(us={}));class ms{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 gs=["vp8","h264"],fs=["vp8","h264","vp9","av1","h265"],vs=function(e){return!!gs.find(t=>t===e)};var ys,bs;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(ys||(ys={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(bs||(bs={}));const ks={h90:new ms(160,90,9e4,20),h180:new ms(320,180,16e4,20),h216:new ms(384,216,18e4,20),h360:new ms(640,360,45e4,20),h540:new ms(960,540,8e5,25),h720:new ms(1280,720,17e5,30),h1080:new ms(1920,1080,3e6,30),h1440:new ms(2560,1440,5e6,30),h2160:new ms(3840,2160,8e6,30)},Ts={h120:new ms(160,120,7e4,20),h180:new ms(240,180,125e3,20),h240:new ms(320,240,14e4,20),h360:new ms(480,360,33e4,20),h480:new ms(640,480,5e5,20),h540:new ms(720,540,6e5,25),h720:new ms(960,720,13e5,30),h1080:new ms(1440,1080,23e5,30),h1440:new ms(1920,1440,38e5,30)},Ss={h360fps3:new ms(640,360,2e5,3,"medium"),h360fps15:new ms(640,360,4e5,15,"medium"),h720fps5:new ms(1280,720,8e5,5,"medium"),h720fps15:new ms(1280,720,15e5,15,"medium"),h720fps30:new ms(1280,720,2e6,30,"medium"),h1080fps15:new ms(1920,1080,25e5,15,"medium"),h1080fps30:new ms(1920,1080,5e6,30,"medium"),original:new ms(0,0,7e6,30,"medium")},Cs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Es(e){return Si(this,void 0,void 0,function*(){return new Promise(t=>cs.setTimeout(t,e))})}function ws(){return"addTransceiver"in RTCPeerConnection.prototype}function Ps(){return"addTrack"in RTCPeerConnection.prototype}function Rs(e){return"av1"===e||"vp9"===e}function Is(e){return!(!document||Ms())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Os(){var e;return"Firefox"===(null===(e=rs())||void 0===e?void 0:e.name)}function _s(){const e=rs();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function Ds(){var e;return"Safari"===(null===(e=rs())||void 0===e?void 0:e.name)}function Ms(){const e=rs();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function As(){var e,t;return!!xs()&&(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 xs(){return"undefined"!=typeof document}function Ns(){return"ReactNative"==navigator.product}function Ls(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Us(e){return Ls(e)?e.hostname.split(".")[0]:null}function js(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Fs(){if(!Ns())return;let e=js();return e?e.platform:void 0}function Vs(){if(xs())return window.devicePixelRatio;if(Ns()){let e=js();if(e)return e.devicePixelRatio}return 1}function Bs(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let e=0;e<r;++e){const t=parseInt(n[e],10),s=parseInt(i[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function qs(e){for(const t of e)t.target.handleResize(t)}function Ws(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Hs=null;const zs=()=>(Hs||(Hs=new ResizeObserver(qs)),Hs);let Gs=null;const Ks=()=>(Gs||(Gs=new IntersectionObserver(Ws,{root:null,rootMargin:"0px"})),Gs);function Js(){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 s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Qs;function Ys(){if(!Qs){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[Qs]=i.stream.getAudioTracks(),!Qs)throw Error("Could not get empty media stream audio track");Qs.enabled=!1}return Qs.clone()}class Xs{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>Si(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 $s(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Zs(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function eo(e){switch(e.reason){case Ur.LeaveRequest:return e.context;case Ur.Cancelled:return mt.CLIENT_INITIATED;case Ur.NotAllowed:return mt.USER_REJECTED;case Ur.ServerUnreachable:return mt.JOIN_FAILURE;default:return mt.UNKNOWN_REASON}}function to(e){return void 0!==e?Number(e):void 0}function no(e){return void 0!==e?BigInt(e):void 0}function io(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function ro(e){return!!e&&e.kind==us.Kind.Audio}function so(e){return!!e&&e.kind==us.Kind.Video}function oo(e){return io(e)&&so(e)}function ao(e){return io(e)&&ro(e)}function co(e){return!!e&&!e.isLocal}function lo(e){return!!e&&!e.isLocal}function uo(e){return co(e)&&so(e)}function ho(e,t,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=To(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==n?void 0:n.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(po(h.audio,t),null!==(i=(s=h.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(po(h.video,n),null!==(r=(o=h.video).deviceId)&&void 0!==r||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function po(e,t){return Object.keys(t).forEach(n=>{void 0===e[n]&&(e[n]=t[n])}),e}function mo(e){var t,n,i,r;const s={};if(e.video)if("object"==typeof e.video){const n={},r=n,o=e.video;Object.keys(o).forEach(e=>{"resolution"===e?po(r,o.resolution):r[e]=o[e]}),s.video=n,null!==(t=(i=s.video).deviceId)&&void 0!==t||(i.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}};else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(n=(r=s.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function go(){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=()=>Si(this,void 0,void 0,function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}});n.addEventListener("statechange",()=>{var t;"closed"===n.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return n}}function fo(e){return"audioinput"===e?us.Source.Microphone:"videoinput"===e?us.Source.Camera:us.Source.Unknown}function vo(e){return e===us.Source.Microphone?"audioinput":e===us.Source.Camera?"videoinput":void 0}function yo(e){return e.split("/")[1].toLowerCase()}function bo(e){const t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new bn({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function ko(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?ko(e.track):{})}}function To(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 So(e,t){return e.width*e.height<t.width*t.height}class Co extends Pi.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,n;const{kind:i,data:r}=e.data;switch(i){case"error":if(vi.error(r.error.message),r.uuid){const e=this.decryptDataRequests.get(r.uuid);if(null==e?void 0:e.reject){e.reject(r.error);break}const t=this.encryptDataRequests.get(r.uuid);if(null==t?void 0:t.reject){t.reject(r.error);break}}this.emit(Nr.EncryptionError,r.error,r.participantIdentity);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Nr.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){const e=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(Nr.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Ar.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(r.uuid);(null==e?void 0:e.resolve)&&e.resolve(r);break;case"encryptDataResponse":const i=this.encryptDataRequests.get(r.uuid);(null==i?void 0:i.resolve)&&i.resolve(r)}},this.onWorkerError=e=>{vi.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Nr.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||zr()))throw new Jr("tried to setup end-to-end encryption on an unsupported browser");if(vi.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:bi.getLevel()}};this.worker&&(vi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){vi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):vi.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Wr.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Br.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==wt.NONE,t.identity)),e.on(Br.ConnectionStateChanged,t=>{t===Ha.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==wt.NONE,e.identity)})})}).on(Br.TrackUnsubscribed,(e,t,n)=>{var i;null===(i=this.worker)||void 0===i||i.postMessage({kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}})}).on(Br.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(Br.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(qr.LocalSenderCreated,(e,t)=>Si(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(qr.LocalTrackPublished,e=>{if(!so(e.track)||!Ms())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:yo(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(Ar.SetKey,e=>this.postKey(e)).on(Ar.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return Si(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 Xs;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(),s={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:i}},o=new Xs;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(s),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}})}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");this.worker.postMessage({kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}})}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?yo(n.mimeType):void 0)}}setupE2EESender(e,t){io(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||vi.warn("early return because sender is not ready")}handleReceiver(e,t,n,i){return Si(this,void 0,void 0,function*(){if(this.worker){if(zr()&&!_s())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:n,trackId:t,codec:i});else{if(Mr in e&&i)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}});let r=e.writableStream,s=e.readableStream;if(!r||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}this.worker.postMessage({kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:i,participantIdentity:n,isReuse:Mr in e}},[s,r])}e[Mr]=!0}})}handleSender(e,t,n){var i;if(!(Mr in e)&&this.worker){if(!(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(zr()&&!_s())vi.info("initialize script transform"),e.transform=new RTCRtpScriptTransform(this.worker,{kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n});else{vi.info("initialize encoded streams");const i=e.createEncodedStreams();this.worker.postMessage({kind:"encode",data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}},[i.readable,i.writable])}e[Mr]=!0}}}class Eo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Eo),this._instance}addFailedConnectionAttempt(e){var t;const n=Us(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,Es(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&Us(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&Us(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Eo._instance=null;const wo="default";class Po{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Po),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Si(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=Po.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){vi.debug("awaiting getUserMedia promise");try{e?yield Po.userMediaPromiseMap.get(e):yield Promise.all(Po.userMediaPromiseMap.values())}catch(e){vi.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(n&&(!Ds()||!t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>""===t.label&&(!e||t.kind===e)))){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 Si(this,void 0,void 0,function*(){if(t!==wo)return t;const i=yield this.getDevices(e),r=i.find(e=>e.deviceId===wo);if(!r)return void vi.warn("could not reliably determine default device");const s=i.find(e=>e.deviceId!==wo&&e.groupId===(null!=n?n:r.groupId));if(s)return null==s?void 0:s.deviceId;vi.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?Po.userMediaPromiseMap.has(e):Po.userMediaPromiseMap.size>0}}var Ro;Po.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Po.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Ro||(Ro={}));class Io{constructor(){this.pendingTasks=new Map,this.taskMutex=new _,this.nextTaskIndex=0}run(e){return Si(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ro.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ro.RUNNING,yield e()}finally{t.status=Ro.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return Si(this,void 0,void 0,function*(){return this.run(()=>Si(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Oo{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:[]);r.binaryType="arraybuffer",this.ws=r;const s=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r.close(e,t)};this.opened=new Promise((e,t)=>{r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},r.onerror=t=>e.error(t)},cancel:s}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:s}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",t)},r.addEventListener("error",t)}),this.closed=new Promise((e,t)=>{const n=()=>Si(this,void 0,void 0,function*(){const n=new Promise(e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",t=>{e(t)},{once:!0})}),i=yield Promise.race([Es(250),n]);i?e(i):t(new Error("Encountered unspecified websocket error without a timely close event"))});r.onclose=t=>{let{code:i,reason:s}=t;e({closeCode:i,reason:s}),r.removeEventListener("error",n)},r.addEventListener("error",n)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=s}}function _o(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}function Do(e){if("string"==typeof e)return hn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return hn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const Mo=["syncState","trickle","offer","answer","simulate","leave"];var Ao;!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"}(Ao||(Ao={}));class xo{get currentState(){return this.state}get isDisconnected(){return this.state===Ao.DISCONNECTING||this.state===Ao.DISCONNECTED}get isEstablishingConnection(){return this.state===Ao.CONNECTING||this.state===Ao.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;this.rtt=0,this.state=Ao.DISCONNECTED,this.log=vi,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=yi(null!==(n=t.loggerName)&&void 0!==n?n:mi.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Io,this.queuedRequests=[],this.closingLock=new _,this.connectionLock=new _,this.state=Ao.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return Si(this,void 0,void 0,function*(){return this.state=Ao.CONNECTING,this.options=n,yield this.connect(e,t,n,i)})}reconnect(e,t,n,i){return Si(this,void 0,void 0,function*(){if(this.options)return this.state=Ao.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)})}connect(e,t,n,i){return Si(this,void 0,void 0,function*(){const r=yield this.connectionLock.lock();this.connectOptions=n;const s=function(){var e;const t=new Jt({sdk:Qt.JS,protocol:16,version:"2.16.0"});return Ns()&&(t.os=null!==(e=Fs())&&void 0!==e?e:""),t}(),o=n.singlePeerConnection?function(e,t,n){const i=new URLSearchParams;i.set("access_token",e);const r=new si({clientInfo:t,connectionSettings:new ri({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0});n.reconnectReason&&(r.reconnectReason=n.reconnectReason);const s=new oi({joinRequest:r.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(s.toBinary()))),i}(t,s,n):function(e,t,n){var i;const r=new URLSearchParams;return r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",Ns()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type),r}(t,s,n),a=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)}),_o(n,"rtc")}(e,o),c=_o(new URL(Zs(a)),"validate");return new Promise((e,t)=>Si(this,void 0,void 0,function*(){var s,o;try{let r=!1;const d=e=>Si(this,void 0,void 0,function*(){if(r)return;r=!0;const n=e instanceof Event?e.currentTarget:e,i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";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}}(n,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(i)).catch(e=>{this.log.error(e),this.close()}):this.close(),l(),t(n instanceof AbortSignal?n.reason:n)});null==i||i.addEventListener("abort",d);const l=()=>{clearTimeout(u),null==i||i.removeEventListener("abort",d)},u=setTimeout(()=>{d(new Kr("room connection has timed out (signal)",Ur.ServerUnreachable))},n.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,u,t)},p=new URL(a);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(p),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Oo(a);try{this.ws.closed.then(e=>{var n;this.isEstablishingConnection&&t(new Kr("Websocket got closed during a (re)connection attempt: ".concat(e.reason),Ur.InternalError)),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===Ao.CONNECTED&&this.handleOnClose(null!==(n=e.reason)&&void 0!==n?n:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(new Kr("Websocket error during a (re)connection attempt: ".concat(e),Ur.InternalError))});const i=yield this.ws.opened.catch(e=>Si(this,void 0,void 0,function*(){if(this.state!==Ao.CONNECTED){this.state=Ao.DISCONNECTED,clearTimeout(u);const n=yield this.handleConnectionError(e,c);return void t(n)}this.handleWSError(e),t(e)}));if(clearTimeout(u),!i)return;const r=i.readable.getReader();this.streamWriter=i.writable.getWriter();const a=yield r.read();if(r.releaseLock(),!a.value)throw new Kr("no message received as first message",Ur.InternalError);const d=Do(a.value),l=this.validateFirstMessage(d,null!==(s=n.reconnect)&&void 0!==s&&s);if(!l.isValid)return void t(l.error);"join"===(null===(o=d.message)||void 0===o?void 0:o.case)&&(this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}))),h(i,l.shouldProcessFirstMessage?d:void 0),e(l.response)}catch(e){t(e)}finally{l()}}finally{r()}}))})}startReadingLoop(e,t){return Si(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Es(this.signalLatency));const{done:t,value:n}=yield e.read();if(t)break;const i=Do(n);this.handleSignalResponse(i)}})}close(){return Si(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*(){if([Ao.DISCONNECTING||Ao.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Ao.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,Es(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=Ao.DISCONNECTED),i()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Lo(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Lo(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new gn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new fn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Si(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 _n({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 On({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Wn({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Y.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Yn({timestamp:Y.parse(Date.now()),rtt:Y.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new wn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Rn({reason:mt.CLIENT_INITIATED,action:In.DISCONNECT})})}sendRequest(e){return Si(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=Mo.indexOf(e.case)>=0;return vi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&t.state===Ao.RECONNECTING)return void t.queuedRequests.push(()=>Si(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Es(t.signalLatency)),t.isDisconnected)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),t.logContext);const r=new un({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message",this.logContext);let r=!1;if("answer"===i.case){const e=No(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=No(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):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{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 Si(this,void 0,void 0,function*(){if(this.state===Ao.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=cs.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&cs.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=cs.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&cs.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=Ao.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,i,r,s,o;return"join"===(null===(n=e.message)||void 0===n?void 0:n.case)?{isValid:!0,response:e.message.value}:this.state===Ao.RECONNECTING&&"leave"!==(null===(i=e.message)||void 0===i?void 0:i.case)?"reconnect"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!1,error:new Kr("Received leave request while trying to (re)connect",Ur.LeaveRequest,void 0,e.message.value.reason)}:t?{isValid:!1,error:new Kr("Unexpected first message",Ur.InternalError)}:{isValid:!1,error:new Kr("did not receive join response, got ".concat(null===(o=e.message)||void 0===o?void 0:o.case," instead"),Ur.InternalError)}}handleConnectionError(e,t){return Si(this,void 0,void 0,function*(){try{const n=yield fetch(t);if(n.status.toFixed(0).startsWith("4")){const e=yield n.text();return new Kr(e,Ur.NotAllowed,n.status)}return e instanceof Kr?e:new Kr("Encountered unknown websocket error during connection: ".concat(e),Ur.InternalError,n.status)}catch(e){return e instanceof Kr?e:new Kr(e instanceof Error?e.message:"server was not reachable",Ur.ServerUnreachable)}})}}function No(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 Lo(e,t){return new Tn({sdp:e.sdp,type:e.type,id:t})}class Uo{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0&&!(this._totalSize-this.buffer[0].data.byteLength<=e);)this.pop()}get length(){return this.buffer.length}}class jo{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();return n-this._lastCleanup>this.ttl/2&&this.cleanup(),this._map.set(e,{value:t,expiresAt:n+this.ttl}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!(!t||t.expiresAt<Date.now()&&(this._map.delete(e),1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[i,r]of n.entries())t.push(e(r,i,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Fo,Vo,Bo,qo,Wo,Ho={},zo={},Go={exports:{}};function Ko(){if(Fo)return Go.exports;Fo=1;var e=Go.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),Go.exports}function Jo(){return Vo||(Vo=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 s=e.push?{}:r?n[e.name]:n;!function(e,n,i,r){if(r&&!i)n[r]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(n[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&n[e.push].push(s)},i=Ko(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.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,o,r)}}),t.media=s,t};var s=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(s,{})},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(s,{})})},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}})})}}(zo)),zo}function Qo(){if(qo)return Bo;qo=1;var e=Ko(),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 s=0;s<t.names.length;s+=1)r.push(t.name?i[t.name][t.names[s]]:i[t.names[s]]);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"],s=["i","c","b","a"];return Bo=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 o=n.innerOrder||s,a=[];return(n.outerOrder||r).forEach(function(n){e[n].forEach(function(e){e.name in t&&null!=t[e.name]?a.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){a.push(i(n,e,t))})})}),t.media.forEach(function(t){a.push(i("m",e.m[0],t)),o.forEach(function(n){e[n].forEach(function(e){e.name in t&&null!=t[e.name]?a.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){a.push(i(n,e,t))})})})}),a.join("\r\n")+"\r\n"},Bo}var Yo=function(){if(Wo)return Ho;Wo=1;var e=Jo(),t=Qo(),n=Ko();return Ho.grammar=n,Ho.write=t,Ho.parse=e.parse,Ho.parseParams=e.parseParams,Ho.parseFmtpConfig=e.parseFmtpConfig,Ho.parsePayloads=e.parsePayloads,Ho.parseRemoteCandidates=e.parseRemoteCandidates,Ho.parseImageAttributes=e.parseImageAttributes,Ho.parseSimulcastStreamList=e.parseSimulcastStreamList,Ho}();function Xo(e,t,n){var i,r,s;void 0===t&&(t=50),void 0===n&&(n={});var o=null!=(i=n.isImmediate)&&i,a=null!=(r=n.callback)&&r,c=n.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),n=this;return new Promise(function(i,r){var c=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,d=Date.now(),!o){var i=e.apply(n,t);a&&a(i),l.forEach(function(e){return(0,e.resolve)(i)}),l=[]}},u()),c){var h=e.apply(n,t);return a&&a(h),i(h)}l.push({resolve:i,reject:r})})};return h.cancel=function(e){void 0!==s&&clearTimeout(s),l.forEach(function(t){return(0,t.reject)(e)}),l=[]},h}const $o="negotiationStarted",Zo="negotiationComplete",ea="rtpVideoPayloadTypes";class ta extends Pi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;super(),this.log=vi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xo(e=>Si(this,void 0,void 0,function*(){this.emit($o);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=yi(null!==(n=t.loggerName)&&void 0!==n?n:mi.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new _}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Si(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return Si(this,void 0,void 0,function*(){var n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let i;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],r=Yo.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach(e=>{var t;const r=ra(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===s&&"nack"===e.type))&&i.push(r),e.fmtp.some(e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&n.push(r),!0)))}),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){const t=Yo.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach(e=>{const t=ra(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})}),i=Yo.write(t)}return yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(Zo),e.sdp)&&Yo.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(ea,e.rtp)}),!0})}createAndSendOffer(e){return Si(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Yo.parse(null!==(t=i.sdp)&&void 0!==t?t:"");if(r.media.forEach(e=>{ia(e),"audio"===e.type?na(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;if(Rs(t.codec)&&!Ds()&&this.ensureVideoDDExtensionForSVC(e,r),!Rs(t.codec))return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0})}),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));yield this.setMungedSDP(i,Yo.write(r)),this.onOffer(i,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return Si(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Yo.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach(e=>{ia(e),"audio"===e.type&&na(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Yo.write(n)),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 Xr("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Xr("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Si(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 Si(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let i="unknown error";t instanceof Error?i=t.message:"string"==typeof t&&(i=t);const r={error:i,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(r.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:r})),new $r(i)}})}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!(null===(n=e.ext)||void 0===n?void 0:n.some(e=>e.uri===Cs))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var n;"video"===t.type&&(null===(n=t.ext)||void 0===n||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(i=e.ext)||void 0===i||i.push({value:this.ddExtID,uri:Cs})}}}function na(e,t,n){const i=ra(e.mid);let r=0;e.rtp.some(e=>"opus"===e.codec&&(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&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function ia(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function ra(e){return"number"==typeof e?e.toFixed(0):e}const sa="vp8",oa={audioPreset:bs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ss.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:sa,backupCodec:!0,preConnectBuffer:!1},aa={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ca={deviceId:{ideal:"default"},resolution:ks.h720.resolution},da={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Ti}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},la={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ua;!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"}(ua||(ua={}));class ha{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var i;this.peerConnectionTimeout=la.peerConnectionTimeout,this.log=vi,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map(e=>e.getConnectionState());i.every(e=>"connected"===e)?this.state=ua.CONNECTED:i.some(e=>"failed"===e)?this.state=ua.FAILED:i.some(e=>"connecting"===e)?this.state=ua.CONNECTING:i.every(e=>"closed"===e)?this.state=ua.CLOSED:i.some(e=>"closed"===e)?this.state=ua.CLOSING:i.every(e=>"new"===e)&&(this.state=ua.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(ua[n]," to ").concat(ua[this.state]),this.logContext),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.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:mi.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new ta(e,n),"publisher-only"!==t&&(this.subscriber=new ta(e,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,cn.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,cn.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=ua.NEW,this.connectionLock=new _,this.remoteOfferLock=new _}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){this.isPublisherConnectionRequired=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],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 Si(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(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return Si(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return Si(this,void 0,void 0,function*(){var n;t===cn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return Si(this,void 0,void 0,function*(){var n,i,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()}));const s=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{s()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Si(this,void 0,void 0,function*(){var n;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map(n=>this.ensureTransportConnected(n,e,t)))}finally{i()}})}negotiate(e){return Si(this,void 0,void 0,function*(){return new Promise((t,n)=>Si(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(i),n("negotiation aborted")}),this.publisher.once($o,()=>{e.signal.aborted||this.publisher.once(Zo,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(i),n(e)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===cn.PUBLISHER||e===cn.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 Si(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)=>Si(n,void 0,void 0,function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),cs.clearTimeout(s),r(new Kr("room connection has been cancelled",Ur.Cancelled))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const s=cs.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",n),r(new Kr("could not establish pc connection",Ur.InternalError))},i);for(;this.state!==ua.CONNECTED;)if(yield Es(50),null==t?void 0:t.signal.aborted)return void r(new Kr("room connection has been cancelled",Ur.Cancelled));cs.clearTimeout(s),null==t||t.signal.removeEventListener("abort",n),e()}))}()})}}class pa{static fetchRegionSettings(e,t,n){return Si(this,void 0,void 0,function*(){const i=yield pa.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:5e3;return{regionSettings:yield i.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw new Kr("Could not fetch region settings: ".concat(i.statusText),401===i.status?Ur.NotAllowed:Ur.InternalError,i.status)}catch(e){throw e instanceof Kr?e:(null==n?void 0:n.aborted)?new Kr("Region fetching was aborted",Ur.Cancelled):new Kr("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e),Ur.ServerUnreachable,500)}finally{i()}})}static scheduleRefetch(e,t,n){return Si(this,void 0,void 0,function*(){const i=pa.settingsTimeouts.get(e.hostname);clearTimeout(i),pa.settingsTimeouts.set(e.hostname,setTimeout(()=>Si(this,void 0,void 0,function*(){try{const n=yield pa.fetchRegionSettings(e,t);pa.updateCachedRegionSettings(e,t,n)}catch(i){if(i instanceof Kr&&i.reason===Ur.NotAllowed)return void vi.debug("token is not valid, cancelling auto region refresh");vi.debug("auto refetching of region settings failed",{error:i}),pa.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){pa.cache.set(e.hostname,n),pa.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=pa.settingsTimeouts.get(e);t&&(clearTimeout(t),pa.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=pa.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const t=pa.connectionTrackers.get(e);t&&0===t.connectionCount&&(vi.debug("stopping region refetch after disconnect delay",{hostname:e}),pa.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){const t=pa.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=pa.connectionTrackers.get(e);t||(t={connectionCount:0},pa.connectionTrackers.set(e,t)),t.connectionCount++,pa.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=pa.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&pa.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ls(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Si(this,void 0,void 0,function*(){return pa.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return Si(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=pa.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),pa.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),vi.debug("next region: ".concat(e.region)),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){pa.updateCachedRegionSettings(this.serverUrl,this.token,e)}}pa.cache=new Map,pa.settingsTimeouts=new Map,pa.connectionTrackers=new Map,pa.fetchLock=new _;class ma extends Error{constructor(e,t,n){super(t),this.code=e,this.message=fa(t,ma.MAX_MESSAGE_BYTES),this.data=n?fa(n,ma.MAX_DATA_BYTES):void 0}static fromProto(e){return new ma(e.code,e.message,e.data)}toProto(){return new Ht({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ma(ma.ErrorCode[e],ma.ErrorMessage[e],t)}}function ga(e){return(new TextEncoder).encode(e).length}function fa(e,t){if(ga(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(e.slice(0,s)).length<=t?n=s:i=s-1}return e.slice(0,n)}ma.MAX_MESSAGE_BYTES=256,ma.MAX_DATA_BYTES=15360,ma.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},ma.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 va=2e3;function ya(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 ba="undefined"!=typeof MediaRecorder,ka=ba?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Ta extends ka{constructor(e,t){if(!ba)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",s),null==i||i.close(),i=void 0},s=e=>{null==i||i.error(e),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),this.removeEventListener("error",s),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>Si(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",s)}}class Sa extends us{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Xo(()=>Si(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>Si(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(Hr.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new _,this.pauseUpstreamLock=new _,this.trackChangeLock=new _,this.trackChangeLock.lock().then(t=>Si(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==us.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Si(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{ps(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&&(hs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&"closed"!==(null===(n=this.sender.transport)||void 0===n?void 0:n.state)&&(yield this.sender.replaceTrack(null!=i?i:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{hs(null!=i?i:e,t)}))})}waitForDimensions(){return Si(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var n;if(e.kind===us.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=rs())||void 0===n?void 0:n.os)&&(yield Es(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield Es(50)}throw new Qr("unable to get track dimensions after timeout")}()})}setDeviceId(e){return Si(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===$s(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),$s(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return Si(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===us.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===us.Kind.Audio?"audioinput":"videoinput";return t?Po.getInstance().normalizeDeviceId(r,n,i):n}()})}mute(){return Si(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return Si(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return Si(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Qr("unable to replace an unpublished track");let n,i;return"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e){return Si(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:n}=e,i=function(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}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const r={audio:!1,video:!1};this.kind===us.Kind.Video?r.video=!t&&!n||{deviceId:t,facingMode:n}:r.audio=!t||Object.assign({deviceId:t},i),this.attachedElements.forEach(e=>{ps(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const s=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return this.kind===us.Kind.Video&&(yield s.applyConstraints(i)),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(Hr.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Hr.Muted:Hr.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 Si(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),As()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Si(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Hr.UpstreamPaused,this);const t=rs();if("Safari"===(null==t?void 0:t.name)&&Bs(t.version,"12.0")<0)throw new Jr("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return Si(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Hr.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return Si(this,void 0,void 0,function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return Si(this,arguments,void 0,function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var i;const r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(hs(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&n&&(ps(t._mediaStreamTrack,e),hs(t.processor.processedTrack,e));yield null===(i=t.sender)||void 0===i?void 0:i.replaceTrack(t.processor.processedTrack)}t.emit(Hr.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return Si(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return Si(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(n=e.processor.processedTrack)||void 0===n||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(i=e.processorElement)||void 0===i||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Hr.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(ba)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 Ta(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 Ca extends Sa{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>3?arguments[3]:void 0;super(e,us.Kind.Audio,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>4?arguments[4]:void 0),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Si(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=ya(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Hr.AudioTrackFeatureUpdate,this,vt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Hr.AudioTrackFeatureUpdate,this,vt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Si(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===us.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 Si(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==$s(this._constraints.deviceId);return this.source!==us.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return Si(this,void 0,void 0,function*(){let t;if(e){const n=mo({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Si(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){xs()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},va)))}setProcessor(e){return Si(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!Ns()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const n={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(n),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Hr.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return Si(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return Si(this,void 0,void 0,function*(){const e=yield function(e){return Si(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=go();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Es(t),i.getByteTimeDomainData(r);const s=r.some(e=>128!==e&&0!==e);return n.close(),!s}return!1}()})}(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Hr.AudioSilenceDetected)),e})}}const Ea=Object.values(ks),wa=Object.values(Ts),Pa=Object.values(Ss),Ra=[ks.h180,ks.h360],Ia=[Ts.h180,Ts.h360],Oa=["q","h","f"];function _a(e,t,n,i){var r,s;let o=null==i?void 0:i.videoEncoding;e&&(o=null==i?void 0:i.screenShareEncoding);const a=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!o&&!a&&!c||!t||!n)return[{}];o||(o=function(e,t,n,i){const r=function(e,t,n){if(e)return Pa;const i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?Ea:wa}(e,t,n);let{encoding:s}=r[0];const o=Math.max(t,n);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=o)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,n,d),vi.debug("using video encoding",o));const l=o.maxFramerate,u=new ms(t,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Rs(d)){const e=new xa(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=rs();if(Ms()||Ns()||"Chrome"===(null==n?void 0:n.name)&&Bs(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,r=function(e){return e||(e=rs()),"Safari"===(null==e?void 0:e.name)&&Bs(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Bs(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:Oa[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),vi.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(r=Aa(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:Da(e,u):null!==(s=Aa(null==i?void 0:i.videoSimulcastLayers))&&void 0!==s?s:Da(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const i=Math.max(t,n);if(i>=960&&h)return Ma(t,n,[e,h,u],l);if(i>=480)return Ma(t,n,[e,u],l)}return Ma(t,n,[u])}function Da(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(n=t).encoding.maxFramerate}].map(e=>{var t,i;return new ms(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{width:i,height:r}=t,s=i>r?i/r:r/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?Ra:Ia}function Ma(e,t,n,i){const r=[];if(n.forEach((n,s)=>{if(s>=Oa.length)return;const o=Math.min(e,t),a={rid:Oa[s],scaleResolutionDownBy:Math.max(1,o/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=Os()||0===s;n.encoding.priority&&d&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),r.push(a)}),Ns()&&"ios"===Fs()){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,vi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),vi.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)})}return r}function Aa(e){if(e)return e.sort((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class xa{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 Na extends Sa{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){super(e,us.Kind.Video,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>3?arguments[3]:void 0),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Si(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>"cpu"===e.qualityLimitationReason);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(Hr.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{var i;const r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=ya(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new _}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!xs())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},va))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Si(this,void 0,void 0,function*(){var t,n,i,r;yield e.pauseUpstream.call(this);try{for(var s,o=!0,a=Ci(this.simulcastCodecs.values());!(t=(s=yield a.next()).done);o=!0){o=!1;const e=s.value;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(e){n={error:e}}finally{try{o||t||!(i=a.return)||(yield i.call(a))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Si(this,void 0,void 0,function*(){var t,n,i,r;yield e.resumeUpstream.call(this);try{for(var s,o=!0,a=Ci(this.simulcastCodecs.values());!(t=(s=yield a.next()).done);o=!0){o=!1;const e=s.value;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{o||t||!(i=a.return)||(yield i.call(a))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Si(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!==us.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 Si(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==us.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Si(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},s=n.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.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})}setPublishingQuality(e){const t=[];for(let n=ls.LOW;n<=ls.HIGH;n+=1)t.push(new jn({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Rs(this.codec),t)}restartTrack(e){return Si(this,void 0,void 0,function*(){var t,n,i,r;let s;if(e){const t=mo({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var o,a=!0,c=Ci(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){a=!1;const e=o.value;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{a||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Si(this,arguments,void 0,function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,s,o,a,c;if(yield t.setProcessor.call(n,e,i),null===(a=n.processor)||void 0===a?void 0:a.processedTrack)try{for(var d,l=!0,u=Ci(n.simulcastCodecs.values());!(r=(d=yield u.next()).done);l=!0){l=!1;const e=d.value;yield null===(c=e.sender)||void 0===c?void 0:c.replaceTrack(n.processor.processedTrack)}}catch(e){s={error:e}}finally{try{l||r||!(o=u.return)||(yield o.call(u))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return Si(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return Si(this,void 0,void 0,function*(){var t,n,i,r,s,o;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(Rs(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const a=[];try{for(t=!0,n=Ci(e);!(r=(i=yield n.next()).done);t=!0){t=!1;const e=i.value;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 La(t.sender,t.encodings,e.qualities,this.senderLock,Rs(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){a.push(e.codec);break}}else yield this.setPublishingLayers(Rs(e.codec),e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(o=n.return)||(yield o.call(n))}finally{if(s)throw s.error}}return a})}setPublishingLayers(e,t){return Si(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 La(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return Si(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&&Rs(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Si(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),As()&&this.isInBackground&&this.source===us.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function La(e,t,n,i,r,s,o){return Si(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),{encodings:a}=i;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let c=!1;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=Ua(a),l=n.find(e=>e.quality===d);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),Os()&&(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,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}})}function Ua(e){switch(e){case"f":default:return ls.HIGH;case"h":return ls.MEDIUM;case"q":return ls.LOW}}function ja(e,t,n,i){if(!n)return[new It({quality:ls.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(i){const i=new xa(n[0].scalabilityMode),r=[],s="h"==i.suffix?1.5:2,o="h"==i.suffix?2:3;for(let a=0;a<i.spatial;a+=1)r.push(new It({quality:Math.min(ls.HIGH,i.spatial-1)-a,width:Math.ceil(e/Math.pow(s,a)),height:Math.ceil(t/Math.pow(s,a)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(o,a)):0,ssrc:0}));return r}return n.map(n=>{var i,r,s;const o=null!==(i=n.scaleResolutionDownBy)&&void 0!==i?i:1;let a=Ua(null!==(r=n.rid)&&void 0!==r?r:"");return new It({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(s=n.maxBitrate)&&void 0!==s?s:0,ssrc:0})})}const Fa="_lossy",Va="_reliable",Ba="leave-reconnect";var qa,Wa,Ha,za;!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"}(qa||(qa={}));class Ga extends Pi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=la.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=qa.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=vi,this.reliableDataSequence=1,this.reliableMessageBuffer=new Uo,this.reliableReceivedState=new jo(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>Si(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(n){if(n.label===Va)t.reliableDCSub=n;else{if(n.label!==Fa)return;t.lossyDCSub=n}t.log.debug("on data channel ".concat(n.id,", ").concat(n.label),t.logContext),n.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>Si(this,void 0,void 0,function*(){var t,n,i,r,s;const o=yield this.dataProcessLock.lock();try{let o;if(e.data instanceof ArrayBuffer)o=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));o=yield e.data.arrayBuffer()}const a=_t.fromBinary(new Uint8Array(o));if(a.sequence>0&&""!==a.participantSid){const e=this.reliableReceivedState.get(a.participantSid);if(e&&a.sequence<=e)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(t=a.value)||void 0===t?void 0:t.case))this.emit(Wr.ActiveSpeakersUpdate,a.value.value.speakers);else if("encryptedPacket"===(null===(n=a.value)||void 0===n?void 0:n.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const e=yield null===(i=this.e2eeManager)||void 0===i?void 0:i.handleEncryptedData(a.value.value.encryptedValue,a.value.value.iv,a.participantIdentity,a.value.value.keyIndex),t=At.fromBinary(e.payload),n=new _t({value:t.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(r=n.value)||void 0===r?void 0:r.case)&&Ja(n,n.value.value),this.emit(Wr.DataPacketReceived,n,a.value.value.encryptionType)}else"user"===(null===(s=a.value)||void 0===s?void 0:s.case)&&Ja(a,a.value.value),this.emit(Wr.DataPacketReceived,a,wt.NONE)}finally{o()}}),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(0===e.currentTarget.maxRetransmits?Dt.LOSSY:Dt.RELIABLE)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=Date.now()-this.reconnectStart;let i=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==i?(e===Ba&&(i=0),this.log.debug("reconnecting in ".concat(i,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=cs.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Wr.Disconnected),this.close()})(n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===qa.Connected&&e();const n=()=>{this.off(Wr.Disconnected,i),e()},i=()=>{this.off(Wr.Restarted,n),t()};this.once(Wr.Restarted,n),this.once(Wr.Disconnected,i)}),this.updateAndEmitDCBufferStatus=e=>{if(e===Dt.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Wr.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Si(this,void 0,void 0,function*(){this.url&&(yield fetch(Zs(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===Ao.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Ao.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(gt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>Si(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Zs(this.url),{method:"HEAD"}),Es(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=yi(null!==(t=e.loggerName)&&void 0!==t?t:mi.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new xo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new _,this.dataProcessLock=new _,this.dcBufferStatus=new Map([[Dt.LOSSY,!0],[Dt.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Wr.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Wr.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Wr.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Wr.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Wr.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Wr.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Wr.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Wr.SignalRequestResponse,e)}get logContext(){var e,t,n,i,r,s;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===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,pID:this.participantSid}}join(e,t,n,i){return Si(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),this.subscriberPrimary&&!r.fastPublish||this.negotiate().catch(e=>{vi.error(e,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=r.clientConfiguration,this.emit(Wr.SignalConnected,r),r}catch(r){if(r instanceof Kr&&r.reason===Ur.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw r}})}close(){return Si(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Wr.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return Si(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Uo,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return Si(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Qr("a track with the same ID has already been published");return new Promise((t,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new Kr("publication of local track timed out, no response from server",Ur.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(i),t(e)},reject:()=>{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{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Si(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Si(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==ua.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const i=this.makeRTCConfiguration(e);var r;this.pcManager=new ha(i,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Wr.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)=>Si(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===ua.CONNECTED){const t=this.pcState===qa.New;this.pcState=qa.Connected,t&&this.emit(Wr.Connected,e)}else t===ua.FAILED&&(this.pcState!==qa.Connected&&this.pcState!==qa.Reconnecting||(this.pcState=qa.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?gt.RR_SUBSCRIBER_FAILED:gt.RR_PUBLISHER_FAILED)));const r=this.client.isDisconnected||this.client.currentState===Ao.RECONNECTING,s=[ua.FAILED,ua.CLOSING,ua.CLOSED].includes(t);r&&s&&!this._isClosed&&this.emit(Wr.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(Wr.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(r=null===(n=e.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>Si(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>Si(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",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Wr.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Wr.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Wr.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Wr.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Wr.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,n;const i={direction:"recvonly"};for(let n=0;n<e.numAudios;n++)null===(t=this.pcManager)||void 0===t||t.addPublisherTransceiverOfKind("audio",i);for(let t=0;t<e.numVideos;t++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("video",i);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",gt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case In.DISCONNECT:this.emit(Wr.Disconnected,null==e?void 0:e.reason),this.close();break;case In.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ba);break;case In.RESUME:this.handleDisconnect(Ba)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach(e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)}),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===pt.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Fa,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Va,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return Si(this,void 0,void 0,function*(){if(ws())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Ps())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Xr("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,i){return Si(this,void 0,void 0,function*(){if(ws())return this.createSimulcastTransceiverSender(e,t,n,i);if(Ps())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Xr("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),so(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,i){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return Si(this,void 0,void 0,function*(){var t,n,i;if(!this._isClosed)if(this.attemptingReconnect)vi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==pt.DISABLED&&(null!==(i=null===(n=this.pcManager)||void 0===n?void 0:n.currentState)&&void 0!==i?i:ua.NEW)!==ua.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Xr?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Ka||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",gt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Wr.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return Si(this,void 0,void 0,function*(){var t,n,i;try{if(!this.url||!this.token)throw new Xr("could not reconnect, url or token not saved");let n;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Wr.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ka;n=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof Kr&&e.reason===Ur.NotAllowed)throw new Xr("could not reconnect, token might be expired");throw new Ka}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Wr.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==Ao.CONNECTED)throw new Ka("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Wr.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),e}})}resumeConnection(e){return Si(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Xr("could not reconnect, url or token not saved");if(!this.pcManager)throw new Xr("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Wr.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof Kr&&e.reason===Ur.NotAllowed)throw new Xr("could not reconnect, token might be expired");if(e instanceof Kr&&e.reason===Ur.LeaveRequest)throw e;throw new Ka(t)}if(this.emit(Wr.SignalResumed),n){const e=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Ao.CONNECTED)throw new Ka("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(Wr.Resumed)})}waitForPCInitialConnection(e,t){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return Si(this,void 0,void 0,function*(){this.pcState=qa.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Es(2e3),!this.pcManager)throw new Xr("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=qa.Connected}catch(e){throw this.pcState=qa.Disconnected,new Kr("could not establish PC connection, ".concat(e.message),Ur.InternalError)}})}publishRpcResponse(e,t,n,i){return Si(this,void 0,void 0,function*(){const r=new _t({destinationIdentities:[e],kind:Dt.RELIABLE,value:{case:"rpcResponse",value:new Wt({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}});yield this.sendDataPacket(r,Dt.RELIABLE)})}publishRpcAck(e,t){return Si(this,void 0,void 0,function*(){const n=new _t({destinationIdentities:[e],kind:Dt.RELIABLE,value:{case:"rpcAck",value:new qt({requestId:t})}});yield this.sendDataPacket(n,Dt.RELIABLE)})}sendDataPacket(e,t){return Si(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,n,i,r,s;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===(s=e.value)||void 0===s?void 0:s.case))return new At({value:e.value})}(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Mt({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===Dt.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary();yield this.waitForBufferStatusLow(t);const i=this.dataChannelForKind(t);if(i){if(t===Dt.RELIABLE&&this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;i.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return Si(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Dt.RELIABLE);const t=this.dataChannelForKind(Dt.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(Dt.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,n)=>Si(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>n("Engine closed");for(this.once(Wr.Closing,i);!this.dcBufferStatus.get(e);)yield Es(10);this.off(Wr.Closing,i),t()}}))}ensureDataTransportConnected(e){return Si(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 Xr("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,s=n?"Subscriber":"Publisher";if(!r)throw new Kr("".concat(s," connection not set"),Ur.InternalError);let o=!1;n||t.dataChannelForKind(e,n)||(t.createDataChannels(),o=!0),o||n||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate().catch(e=>{vi.error(e,t.logContext)});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 Es(50)}throw new Kr("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()),Ur.InternalError)}()})}ensurePublisherConnected(e){return Si(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===ua.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Si(this,void 0,void 0,function*(){return new Promise((e,t)=>Si(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new $r("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(Wr.Closing,i),this.pcManager.publisher.once(ea,e=>{const t=new Map;e.forEach(e=>{const n=e.codec.toLowerCase();fs.includes(n)&&t.set(e.payload,n)}),this.emit(Wr.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(e){e instanceof $r&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",gt.RR_UNKNOWN),t(e)}finally{this.off(Wr.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===Dt.LOSSY)return this.lossyDCSub;if(e===Dt.RELIABLE)return this.reliableDCSub}else{if(e===Dt.LOSSY)return this.lossyDC;if(e===Dt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i,r,s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const o=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getLocalDescription(),l=null===(s=null===(r=this.signalOpts)||void 0===r?void 0:r.autoSubscribe)||void 0===s||s,u=new Array,h=new Array;e.forEach(e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)}),this.client.sendSyncState(new Gn({answer:this.options.singlePeerConnection?a?Lo({sdp:a.sdp,type:a.type}):void 0:d?Lo({sdp:d.sdp,type:d.type}):void 0,offer:this.options.singlePeerConnection?o?Lo({sdp:o.sdp,type:o.type}):void 0:c?Lo({sdp:c.sdp,type:c.type}):void 0,subscription:new Cn({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:bo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new Kn({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Jn({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(Dt.LOSSY),cn.PUBLISHER),t(this.dataChannelForKind(Dt.RELIABLE),cn.PUBLISHER),t(this.dataChannelForKind(Dt.LOSSY,!0),cn.SUBSCRIBER),t(this.dataChannelForKind(Dt.RELIABLE,!0),cn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&cs.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){xs()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){xs()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(n){const e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===n});if(e)return e[1]}}}class Ka extends Error{}function Ja(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}class Qa{get info(){return this._info}validateBytesReceived(){if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.bytesReceived<this.totalByteSize)throw new ts("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),jr.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ts("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),jr.LengthExceeded)}}constructor(e,t,n,i){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=i}}class Ya extends Qa{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived(),null===(t=this.onProgress)||void 0===t||t.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Xs,n=null,i=null;if(this.signal){const e=this.signal;i=()=>{var n;null===(n=t.reject)||void 0===n||n.call(t,e.reason)},e.addEventListener("abort",i),n=e}const r=()=>{e.releaseLock(),n&&i&&n.removeEventListener("abort",i),this.signal=void 0};return{next:()=>Si(this,void 0,void 0,function*(){var n,i;try{const{done:r,value:s}=yield Promise.race([e.read(),t.promise,null!==(i=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==i?i:new Promise(()=>{})]);return r?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(s),{done:!1,value:s.content})}catch(e){throw r(),e}}),return(){return Si(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Si(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;let s=new Set;const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var a,c=!0,d=Ci(o);!(n=(a=yield d.next()).done);c=!0)c=!1,s.add(a.value)}catch(e){i={error:e}}finally{try{c||n||!(r=d.return)||(yield r.call(d))}finally{if(i)throw i.error}}return Array.from(s)}()})}}class Xa extends Qa{constructor(e,t,n,i){super(e,t,n,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=to(e.chunkIndex),i=this.receivedChunks.get(n);i&&i.version>e.version||(this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived(),null===(t=this.onProgress)||void 0===t||t.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0))}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Xs,i=null,r=null;if(this.signal){const e=this.signal;r=()=>{var t;null===(t=n.reject)||void 0===t||t.call(n,e.reason)},e.addEventListener("abort",r),i=e}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>Si(this,void 0,void 0,function*(){var i,r;try{const{done:s,value:o}=yield Promise.race([e.read(),n.promise,null!==(r=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==r?r:new Promise(()=>{})]);if(s)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(o);try{e=t.decode(o.content)}catch(e){throw new ts("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(e),jr.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw s(),e}}),return(){return Si(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Si(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;let s="";const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var a,c=!0,d=Ci(o);!(n=(a=yield d.next()).done);c=!0)c=!1,s+=a.value}catch(e){i={error:e}}finally{try{c||n||!(r=d.return)||(yield r.call(d))}finally{if(i)throw i.error}}return s}()})}}class $a{constructor(){this.log=vi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new ts('A text stream handler for topic "'.concat(e,'" has already been set.'),jr.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new ts('A byte stream handler for topic "'.concat(e,'" has already been set.'),jr.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,i,r;const s=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(s.length>0||o.length>0){const a=new ts("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),jr.AbnormalEnd);for(const[e,i]of o)null===(n=(t=i.outOfBandFailureRejectingFuture).reject)||void 0===n||n.call(t,a),this.byteStreamControllers.delete(e);for(const[e,t]of s)null===(r=(i=t.outOfBandFailureRejectingFuture).reject)||void 0===r||r.call(i,a),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return Si(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,n){return Si(this,void 0,void 0,function*(){var i;if("byteHeader"===e.contentHeader.case){const r=this.byteStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const o=new Xs;o.promise.catch(e=>{this.log.error(e)});const a={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:to(e.timestamp),attributes:e.attributes,encryptionType:n},c=new ReadableStream({start:n=>{if(s=n,this.textStreamControllers.has(e.streamId))throw new ts("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),jr.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new Ya(a,c,to(e.totalLength),o),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let r;const s=new Xs;s.promise.catch(e=>{this.log.error(e)});const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n},a=new ReadableStream({start:n=>{if(r=n,this.textStreamControllers.has(e.streamId))throw new ts("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),jr.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});i(new Xa(o,a,to(e.totalLength),s),{identity:t})}})}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),jr.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),jr.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),jr.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),jr.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Za{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 Si(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 ec extends Za{}class tc extends Za{}class nc{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Si(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),r=(new TextEncoder).encode(e).byteLength,s=null===(n=null==t?void 0:t.attachments)||void 0===n?void 0:n.map(()=>crypto.randomUUID()),o=new Array(s?s.length+1:1).fill(0),a=(e,n)=>{var i;o[n]=e;const r=o.reduce((e,t)=>e+t,0);null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,r)},c=yield this.streamText({streamId:i,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map((e,n)=>Si(this,void 0,void 0,function*(){return this._sendFile(s[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,n+1)}})})))),c.info})}streamText(e){return Si(this,void 0,void 0,function*(){var t,n,i;const r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(i=this.engine.e2eeManager)||void 0===i?void 0:i.isDataChannelEncryptionEnabled)?wt.GCM:wt.NONE},o=new rn({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:no(s.timestamp),totalLength:no(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new tn({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?en.UPDATE:en.CREATE})}}),a=null==e?void 0:e.destinationIdentities,c=new _t({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Dt.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Si(this,void 0,void 0,function*(){for(const t of function(e){const t=[];let n=(new TextEncoder).encode(e);for(;n.length>15e3;){let e=15e3;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&t.push(n),t}(e)){const e=new sn({content:t,streamId:r,chunkIndex:no(d)}),n=new _t({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(n,Dt.RELIABLE),d+=1}})},close(){return Si(this,void 0,void 0,function*(){const e=new on({streamId:r}),t=new _t({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,Dt.RELIABLE)})},abort(e){console.log("Sink error:",e)}});let h=()=>Si(this,void 0,void 0,function*(){yield p.close()});l.once(Wr.Closing,h);const p=new ec(u,s,()=>this.engine.off(Wr.Closing,h));return p})}sendFile(e,t){return Si(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return Si(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(i=null==n?void 0:n.mimeType)&&void 0!==i?i:t.type,topic:null==n?void 0:n.topic,destinationIdentities:null==n?void 0:n.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:e,value:t}=yield s.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return Si(this,void 0,void 0,function*(){var t,n,i,r,s,o;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:a,mimeType:null!==(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===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?wt.GCM:wt.NONE},l=new rn({totalLength:no(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:no(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new nn({name:d.name})}}),u=new _t({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Dt.RELIABLE);let h=0;const p=new _,m=this.engine,g=this.log,f=new WritableStream({write(e){return Si(this,void 0,void 0,function*(){const t=yield p.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+15e3),i=new _t({destinationIdentities:c,value:{case:"streamChunk",value:new sn({content:t,streamId:a,chunkIndex:no(h)})}});yield m.sendDataPacket(i,Dt.RELIABLE),h+=1,n+=t.byteLength}}finally{t()}})},close(){return Si(this,void 0,void 0,function*(){const e=new on({streamId:a}),t=new _t({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Dt.RELIABLE)})},abort(e){g.error("Sink error:",e)}});return new tc(f,d)})}}class ic extends us{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Hr.Muted:Hr.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Hr.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Si(this,void 0,void 0,function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),va)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:e,rtpTimestamp:t}=n;t&&this.rtpTimestamp!==t&&(this.emit(Hr.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class rc extends ic{constructor(e,t,n,i,r,s){super(e,t,us.Kind.Audio,n,s),this.monitorReceiver=()=>Si(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=ya(e,this.prevStats)),this.prevStats=e}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ns()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ns())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return Si(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Is(t))return t.setSinkId(e)}))})}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Is(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(Hr.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(Hr.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Si(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 sc extends ic{constructor(e,t,n,i,r){super(e,t,us.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>Si(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=ya(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=Xo(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===us.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?ps(this._mediaStreamTrack,t):hs(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){const t=new oc(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter(t=>t===e);for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Si(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach(e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)}),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(t=>t.element===e);for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Si(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const i=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),r=!(null!==(n=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==n&&!n)&&this.isInBackground,s=this.elementInfos.some(e=>e.pictureInPicture),o=this.elementInfos.some(e=>e.visible)&&!r||s;(this.lastVisible!==o||e)&&(!o&&Date.now()-i<100?cs.setTimeout(()=>{this.updateVisibility()},100):(this.lastVisible=o,this.emit(Hr.VisibilityChanged,o,this)))}updateDimensions(){var e,t;let n=0,i=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,s=e.height()*r;t+s>n+i&&(n=t,i=s)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===n&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===i||(this.lastDimensions={width:n,height:i},this.emit(Hr.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?Vs():t||(Vs()>2?2:1)}}class oc{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,this.isPiP=ac(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,n;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ac(this.element),null===(n=this.handleVisibilityChanged)||void 0===n||n.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=ac(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:cc(e),this.isPiP=xs()&&ac(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=cc(this.element),this.isPiP=ac(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ks().observe(this.element),zs().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=Ks())||void 0===e||e.unobserve(this.element),null===(t=zs())||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 ac(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&cc(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function cc(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&"none"!==c}class dc extends Pi.EventEmitter{constructor(e,t,n,i){var r;super(),this.metadataMuted=!1,this.encryption=wt.NONE,this.log=vi,this.handleMuted=()=>{this.emit(Hr.Muted)},this.handleUnmuted=()=>{this.emit(Hr.Unmuted)},this.log=yi(null!==(r=null==i?void 0:i.loggerName)&&void 0!==r?r:mi.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=us.Source.Unknown}setTrack(e){this.track&&(this.track.off(Hr.Muted,this.handleMuted),this.track.off(Hr.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Hr.Muted,this.handleMuted),e.on(Hr.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ko(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==wt.NONE}get audioTrack(){if(ro(this.track))return this.track}get videoTrack(){if(so(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=us.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===us.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"}(dc||(dc={}));class lc extends dc{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Hr.Ended)},this.handleCpuConstrained=()=>{this.track&&so(this.track)&&this.emit(Hr.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(Hr.Ended,this.handleTrackEnded),this.track.off(Hr.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Hr.Ended,this.handleTrackEnded),e.on(Hr.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 Si(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return Si(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return Si(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return Si(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ro(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(vt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(vt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(vt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(vt.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(vt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(vt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function uc(e,t){return Si(this,void 0,void 0,function*(){null!=e||(e={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=To(e);let o=s.audio,a=s.video;if(i&&"object"==typeof s.audio&&(s.audio.processor=i),r&&"object"==typeof s.video&&(s.video.processor=r),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){const e=s.audio.deviceId;s.audio.deviceId={exact:e},n=!0,o=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,a=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 c=ho(s,aa,ca),d=mo(c),l=navigator.mediaDevices.getUserMedia(d);s.audio&&(Po.userMediaPromiseMap.set("audioinput",l),l.catch(()=>Po.userMediaPromiseMap.delete("audioinput"))),s.video&&(Po.userMediaPromiseMap.set("videoinput",l),l.catch(()=>Po.userMediaPromiseMap.delete("videoinput")));try{const e=yield l;return yield Promise.all(e.getTracks().map(n=>Si(this,void 0,void 0,function*(){const s="audio"===n.kind;let o,a=s?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=s?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=n.getSettings().deviceId;(null==o?void 0:o.deviceId)&&$s(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,n){switch(e.kind){case"audio":return new Ca(e,t,!1,void 0,n);case"video":return new Na(e,t,!1,n);default:throw new Qr("unsupported track type: ".concat(e.kind))}}(n,o,t);return h.kind===us.Kind.Video?h.source=us.Source.Camera:h.kind===us.Kind.Audio&&(h.source=us.Source.Microphone),h.mediaStream=e,ro(h)&&i?yield h.setProcessor(i):so(h)&&r&&(yield h.setProcessor(r)),h})))}catch(i){if(!n)throw i;return uc(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}})}!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Wa||(Wa={}));class hc extends Pi.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===Ct.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===St.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,i,r,s){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Ct.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Wa.Unknown,this.log=vi,this.log=yi(null!==(a=null==s?void 0:s.loggerName)&&void 0!==a?a:mi.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Xs,this.once(qr.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(us.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(us.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(us.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version||(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===St.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==St.ACTIVE&&this.emit(qr.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,0))}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(qr.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(qr.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var n;void 0===e&&(e={}),void 0===t&&(t={});const i=[...Object.keys(t),...Object.keys(e)],r={};for(const s of i)e[s]!==t[s]&&(r[s]=null!==(n=t[s])&&void 0!==n?n:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(qr.AttributesChanged,t)}setPermissions(e){var t,n,i,r,s,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||e.canPublishData!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(qr.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(qr.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ht.EXCELLENT:return Wa.Excellent;case ht.GOOD:return Wa.Good;case ht.POOR:return Wa.Poor;case ht.LOST:return Wa.Lost;default:return Wa.Unknown}}(e),t!==this._connectionQuality&&this.emit(qr.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ro(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(Hr.Muted,()=>{this.emit(qr.TrackMuted,e)}),e.on(Hr.Unmuted,()=>{this.emit(qr.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case us.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case us.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class pc extends hc{constructor(e,t,n,i,r,s){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=wt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Xs)},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,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,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===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.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 Xs),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:n,message:i}=e,r=this.pendingSignalRequests.get(t);r&&(n!==ni.OK&&r.reject(new es(i,n)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,n=null,i=null;"payload"===t.value.case?n=t.value.value:"error"===t.value.case&&(i=ma.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,i);break;case"rpcAck":this.handleIncomingRpcAck(e.value.value.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new qn({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,trackSids:e.allowedTrackSids||[]})}(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ko(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ko(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ko(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ko(t))),this.emit(qr.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>Si(this,void 0,void 0,function*(){var t,n,i,r;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const s=this.videoTrackPublications.get(e.trackSid);if(!s)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!s.videoTrack)return;const o=yield s.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var a,c=!0,d=Ci(o);!(t=(a=yield d.next()).done);c=!0){c=!1;const e=a.value;vs(e)&&(this.log.debug("publish ".concat(e," for ").concat(s.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ko(s))),yield this.publishAdditionalCodecForTrack(s.videoTrack,e,s.options))}}catch(e){n={error:e}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Si(this,void 0,void 0,function*(){if(e.source===us.Source.ScreenShare||e.source===us.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ko(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(ao(e)||oo(e))try{if(xs())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===us.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),ko(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ko(e))),ao(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ko(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==wt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(Wr.RemoteMute,(e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(Wr.Connected,this.handleReconnected).on(Wr.SignalConnected,this.handleSignalConnected).on(Wr.SignalRestarted,this.handleReconnected).on(Wr.SignalResumed,this.handleReconnected).on(Wr.Restarting,this.handleReconnecting).on(Wr.Resuming,this.handleReconnecting).on(Wr.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Wr.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Wr.Closing,this.handleClosing).on(Wr.SignalRequestResponse,this.handleSignalRequestResponse).on(Wr.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Si(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return Si(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return Si(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return Si(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:i,attributes:r}=e;return function*(){return new Promise((e,s)=>Si(t,void 0,void 0,function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(o=null!=i?i:this.name)&&void 0!==o?o:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(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,n]=e;return this.attributes[t]===n||""===n&&!this.attributes[t]})))return this.pendingSignalRequests.delete(c),void e();yield Es(50)}s(new es("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&s(e)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(us.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(us.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(us.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return Si(this,void 0,void 0,function*(){this.encryptionType=e?wt.GCM:wt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,i){return Si(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case us.Source.Camera:t=yield this.createTracks({video:null===(r=n)||void 0===r||r});break;case us.Source.Microphone:t=yield this.createTracks({audio:null===(s=n)||void 0===s||s});break;case us.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Qr(e)}}catch(n){throw null==t||t.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(qr.MediaDevicesError,n,vo(e)),this.pendingPublishing.delete(e),n}for(const i of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===us.Source.Microphone&&ro(i)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),i.startPreConnectBuffer())}try{const e=[];for(const n of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ko(n))),e.push(this.publishTrack(n,i));const n=yield Promise.all(e);[o]=n}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===us.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication(us.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return Si(this,void 0,void 0,function*(){if(!this.pendingPublishing.has(us.Source.Camera)&&!this.pendingPublishing.has(us.Source.Microphone)){this.pendingPublishing.add(us.Source.Camera),this.pendingPublishing.add(us.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(us.Source.Camera),this.pendingPublishing.delete(us.Source.Microphone)}}})}createTracks(e){return Si(this,void 0,void 0,function*(){var t,n;null!=e||(e={});const i=ho(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(n=this.roomOptions)||void 0===n?void 0:n.videoCaptureDefaults);try{return(yield uc(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(ro(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=us.Source.Microphone,this.emit(qr.AudioStreamAcquired)),so(e)&&(this.cameraError=void 0,e.source=us.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return Si(this,void 0,void 0,function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Jr("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=rs();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)&&Bs(e.osVersion,"17")>=0}()||(e.resolution=Ss.h1080fps30.resolution);const t=function(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=Ds()?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}}(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Qr("no video track found");const r=new Na(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=us.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(qr.AudioStreamAcquired);const e=new Ca(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=us.Source.ScreenShareAudio,s.push(e)}return s})}publishTrack(e,t){return Si(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return Si(this,arguments,void 0,function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,s,o,a;let c,d;if(ao(e)&&e.setAudioContext(n.audioContext),yield null===(r=n.reconnectFuture)||void 0===r?void 0:r.promise,n.republishPromise&&!i&&(yield n.republishPromise),io(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case us.Source.Microphone:t="audioinput";break;case us.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Ca(e,c,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=new Na(e,c,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Qr("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return n.log.warn("track has already been published, skipping",Object.assign(Object.assign({},n.logContext),ko(d))),d;const l=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(s=l.forceStereo)&&void 0!==s?s:u;h&&(void 0===l.dtx&&n.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},n.logContext),ko(e))),void 0===l.red&&n.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=l.dtx)&&void 0!==o||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=rs(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Bs(e.osVersion,t)>=0)||"Safari"===e.name&&Bs(e.version,t)>=0}()&&n.roomOptions.e2ee&&(n.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},n.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise((t,i)=>Si(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Ao.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ko(e)}));let n=!1;const r=setTimeout(()=>{n=!0,e.stop(),i(new Zr("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),n)return;const s=yield this.publish(e,l,h);t(s)}else try{const n=yield this.publish(e,l,h);t(n)}catch(e){i(e)}}catch(e){i(e)}}));n.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Xs),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ko(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return!(!t||0!==n.length&&!n.map(e=>function(e){switch(e){case lt.CAMERA:return us.Source.Camera;case lt.MICROPHONE:return us.Source.Microphone;case lt.SCREEN_SHARE:return us.Source.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return us.Source.ScreenShareAudio;default:return us.Source.Unknown}}(e)).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ko(e))),!1)}publish(e,t,n){return Si(this,void 0,void 0,function*(){var i,r,s,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Zr("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>io(e)&&t.source===e.source)&&e.source!==us.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ko(e))),t.stopMicTrackOnMute&&ro(e)&&(e.stopOnMute=!0),e.source===us.Source.ScreenShare&&Os()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ds()||Os())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}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Os())return!1;if(Ds()){const e=rs();if((null==e?void 0:e.version)&&Bs(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&Bs(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}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=sa),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===yo(e.mime))||(t.videoCodec=yo(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Hr.Muted,this.onTrackMuted),e.on(Hr.Unmuted,this.onTrackUnmuted),e.on(Hr.Ended,this.handleTrackEnded),e.on(Hr.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Hr.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Hr.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(i=t.dtx)||void 0===i||i),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(vt.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(vt.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(vt.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(vt.TF_STEREO),g&&m.push(vt.TF_NO_DTX),ao(e)&&e.hasPreConnectBuffer&&m.push(vt.TF_PRECONNECT_BUFFER);const v=new mn({cid:e.mediaStreamTrack.id,name:t.name,type:us.kindToProto(e.kind),muted:e.isMuted,source:us.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let y;if(e.kind===us.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch(t){const i=null!==(o=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==o?o:ks.h720.resolution;n={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{dims:n}))}v.width=n.width,v.height=n.height,oo(e)&&(Rs(p)&&(e.source===us.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),ko(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new pn({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:sa}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===wt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new pn({codec:t.backupCodec.codec,cid:""})))),y=_a(e.source===us.Source.ScreenShare,v.width,v.height,t),v.layers=ja(v.width,v.height,y,Rs(t.videoCodec))}else e.kind===us.Kind.Audio&&(y=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Xr("cannot publish track when not connected");const b=()=>Si(this,void 0,void 0,function*(){var n,i,r;if(!this.engine.pcManager)throw new Xr("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(qr.LocalSenderCreated,e.sender,e),oo(e)&&(null!==(n=t.degradationPreference)&&void 0!==n||(t.degradationPreference=function(e){return e.source===us.Source.ScreenShare||e.constraints.height&&$s(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),y)if(Os()&&e.kind===us.Kind.Audio){let t;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(i=y[0])||void 0===i?void 0:i.maxBitrate)?y[0].maxBitrate/1e3:0})}else e.codec&&Rs(e.codec)&&(null===(r=y[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const T=new Promise((t,n)=>Si(this,void 0,void 0,function*(){var i;try{k=yield this.engine.addTrack(v),t(k)}catch(t){e.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([T,b()]);k=e[0]}else{let n;if(k=yield T,k.codecs.forEach(e=>{void 0===n&&(n=e.mimeType)}),n&&e.kind===us.Kind.Video){const i=yo(n);i!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{codec:i})),t.videoCodec=i,y=_a(e.source===us.Source.ScreenShare,v.width,v.height,t))}yield b()}const S=new lc(e.kind,k,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(Hr.CpuConstrained,e=>this.onTrackCpuConstrained(e,S)),S.options=t,e.sid=k.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:k})),oo(e)?e.startMonitor(this.engine.client):ao(e)&&e.startMonitor(),this.addTrackPublication(S),this.emit(qr.LocalTrackPublished,S),ao(e)&&k.audioFeatures.includes(vt.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();if(this.on(qr.LocalTrackSubscribed,t=>{if(t.trackSid===k.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ko(e))),e.stopPreConnectBuffer()}}),t){const i=new Promise((i,r)=>Si(this,void 0,void 0,function*(){var s,o,a,c,d;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ko(e)));const p=setTimeout(()=>{r(new Error("agent not active within 10 seconds"))},1e4),m=yield this.waitUntilActiveAgentPresent();clearTimeout(p),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ko(e)));const g=yield this.streamBytes({name:"preconnect-buffer",mimeType:n,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[m.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(c=f.sampleRate)&&void 0!==c?c:"48000"),channels:String(null!==(d=f.channelCount)&&void 0!==d?d:"1")}});try{for(var l,u=!0,h=Ci(t);!(s=(l=yield h.next()).done);u=!0){u=!1;const e=l.value;yield g.write(e)}}catch(e){o={error:e}}finally{try{u||s||!(a=h.return)||(yield a.call(h))}finally{if(o)throw o.error}}yield g.close(),i()}catch(e){r(e)}}));i.then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ko(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{error:t}))})}}return S})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return Si(this,void 0,void 0,function*(){var i;if(this.encryptionType!==wt.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new Qr("track is not published");if(!oo(e))throw new Qr("track is not a video track");const s=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),o=function(e,t,n){var i,r,s,o;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&vi.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!==(s=a.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===us.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),_a(e.source===us.Source.ScreenShare,c,d,n)}(e,t,s);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ko(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new mn({cid:a.mediaStreamTrack.id,type:us.kindToProto(e.kind),muted:e.isMuted,source:us.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=ja(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Xr("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Si(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return Si(this,void 0,void 0,function*(){var n,i;if(io(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ko(e))),yield t)}const r=this.getPublicationForTrack(e),s=r?ko(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));(e=r.track).off(Hr.Muted,this.onTrackMuted),e.off(Hr.Unmuted,this.onTrackUnmuted),e.off(Hr.Ended,this.handleTrackEnded),e.off(Hr.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Hr.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Hr.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(i=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===i||i),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ua.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),oo(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case us.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case us.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(qr.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return Si(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return Si(this,arguments,void 0,function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((i,r)=>Si(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=>Si(this,void 0,void 0,function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===us.Source.ScreenShare||t.source===us.Source.ScreenShareAudio||!ao(t)&&!oo(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),i()}catch(e){r(e)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return Si(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?Dt.RELIABLE:Dt.LOSSY;let r=new Lt({participantIdentity:t.identity,payload:e,destinationIdentities:n.destinationIdentities,topic:n.topic});const s=new _t({kind:i,value:{case:"user",value:r}});yield t.engine.sendDataPacket(s,i)}()})}publishDtmf(e,t){return Si(this,void 0,void 0,function*(){const n=new _t({kind:Dt.RELIABLE,value:{case:"sipDtmf",value:new Ut({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Dt.RELIABLE)})}sendChatMessage(e,t){return Si(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},i=new _t({value:{case:"chatMessage",value:new Vt(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,Dt.RELIABLE),this.emit(qr.ChatMessage,n),n})}editChatMessage(e,t){return Si(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new _t({value:{case:"chatMessage",value:new Vt(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp),editTimestamp:Y.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,Dt.RELIABLE),this.emit(qr.ChatMessage,n),n})}sendText(e,t){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return Si(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:n,method:i,payload:r,responseTimeout:s=15e3}=e;return function*(){return new Promise((e,o)=>Si(t,void 0,void 0,function*(){var t,a,c,d;if(ga(r)>15360)return void o(ma.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&Bs(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(ma.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(s,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(n,u,i,r,l);const h=setTimeout(()=>{this.pendingAcks.delete(u),o(ma.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:n});const p=setTimeout(()=>{this.pendingResponses.delete(u),o(ma.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(u,{resolve:(t,n)=>{clearTimeout(p),this.pendingAcks.has(u)&&(console.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),n?o(n):e(null!=t?t:"")},participantIdentity:n})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,r){return Si(this,void 0,void 0,function*(){const s=new _t({destinationIdentities:[e],kind:Dt.RELIABLE,value:{case:"rpcRequest",value:new Bt({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,Dt.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,ma.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,n;const i=this.trackPublications.get(e.sid);if(i){const 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(Object.assign({},this.logContext),ko(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 Xs),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(ao(i)||oo(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))}),t}waitForPendingPublicationOfSource(e){return Si(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[n]=t;return n.source===e});if(t)return t[1];yield Es(20)}})}}class mc extends dc{constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Hr.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Cn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new zt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Hr.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?dc.SubscriptionStatus.Unsubscribed:super.isSubscribed?dc.SubscriptionStatus.Subscribed:dc.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?dc.PermissionStatus.Allowed:dc.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||(uo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&uo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:ls.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(Hr.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(Hr.VisibilityChanged,this.handleVisibilityChange),i.off(Hr.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(Hr.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Hr.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Hr.VisibilityChanged,this.handleVisibilityChange),e.on(Hr.Ended,this.handleEnded),this.emit(Hr.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Hr.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Hr.Muted:Hr.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Hr.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Hr.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return uo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new En({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===us.Kind.Video){let i=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(i)So(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),i=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.requestedMaxQuality,null===(n=this.trackInfo.layers)||void 0===n?void 0:n.find(e=>e.quality===t));e&&So(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),i=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),i=this.videoDimensionsAdaptiveStream;i?(e.width=Math.ceil(i.width),e.height=Math.ceil(i.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ls.HIGH})),e.quality=ls.HIGH)}var t,n;this.emit(Hr.UpdateSettings,e)}}class gc extends hc{static fromParticipantInfo(e,t,n){return new gc(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,o){super(t,n||"",i,r,s,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:Ct.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Hr.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Hr.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Hr.SubscriptionPermissionChanged,t=>{this.emit(qr.TrackSubscriptionPermissionChanged,e,t)}),e.on(Hr.SubscriptionStatusChanged,t=>{this.emit(qr.TrackSubscriptionStatusChanged,e,t)}),e.on(Hr.Subscribed,t=>{this.emit(qr.TrackSubscribed,t,e)}),e.on(Hr.Unsubscribed,t=>{this.emit(qr.TrackUnsubscribed,t,e)}),e.on(Hr.SubscriptionFailed,t=>{this.emit(qr.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:us.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]:us.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,i,r,s){let o,a=this.getTrackPublicationBySid(t);return a||t.startsWith("TR")||this.trackPublications.forEach(t=>{a||e.kind!==t.kind.toString()||(a=t)}),a?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ko(a))),void this.emit(qr.TrackSubscriptionFailed,t)):(o="video"===e.kind?new sc(e,t,i,r):new rc(e,t,i,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(n),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&co(o)&&ro(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===s?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(qr.TrackSubscriptionFailed,t)):(void 0===s&&(s=20),void setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,i,r,s-1)},150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(e=>{var i,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{const t=us.kindFromProto(e.type);if(!t)return;s=new mc(t,e,null===(i=this.signalClient.connectOptions)||void 0===i?void 0:i.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),s.updateInfo(e),n.set(e.sid,s);const o=Array.from(this.trackPublications.values()).find(e=>e.source===(null==s?void 0:s.source));o&&s.source!==us.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ko(o),newTrack:ko(s)})),this.addTrackPublication(s)}t.set(e.sid,s)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ko(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(qr.TrackPublished,e)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case us.Kind.Audio:this.audioTrackPublications.delete(e);break;case us.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(qr.TrackUnpublished,n)}setAudioOutput(e){return Si(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var i;ro(n.track)&&co(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(Ha||(Ha={}));class fc extends Pi.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,n,i,r;if(super(),t=this,this.state=Ha.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=vi,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>Si(this,void 0,void 0,function*(){var i;if("undefined"==typeof RTCPeerConnection||!ws()&&!Ps())throw Ns()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const r=yield this.disconnectLock.lock();if(this.state===Ha.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Ha.Connecting),(null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ls(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new pa(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));const s=(i,o,a)=>Si(this,void 0,void 0,function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==r||r();try{if(yield Eo.getInstance().getBackOffPromise(e),l.signal.aborted)throw new Kr("Connection attempt aborted",Ur.Cancelled);yield this.attemptConnection(null!=a?a:e,t,n,l),this.abortController=void 0,i()}catch(t){if(this.regionUrlProvider&&t instanceof Kr&&t.reason!==Ur.Cancelled&&t.reason!==Ur.NotAllowed){let n=null;try{this.log.debug("Fetching next region"),n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof Kr&&(401===e.status||e.reason===Ur.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(e)}[Ur.InternalError,Ur.ServerUnreachable,Ur.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Eo.getInstance().addFailedConnectionAttempt(e)),n&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(n),this.logContext),this.recreateEngine(),yield s(i,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,eo(t)),o(t))}else{let e=mt.UNKNOWN_REASON;t instanceof Kr&&(e=eo(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Xs((e,t)=>{s(e,t,o)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,i,r,s)=>Si(this,void 0,void 0,function*(){var o,a,c;const d=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout,singlePeerConnection:r.singlePeerConnection},s.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map(e=>{let[t,n]=e;return"".concat(t,": ").concat(n)}).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Yr("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),d}),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,i)=>Si(this,void 0,void 0,function*(){var r,s;this.state===Ha.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},la),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,i);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(Br.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new Kr("could not establish signal connection",i.signal.aborted?Ur.Cancelled:Ur.ServerUnreachable);throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Kr&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(i.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Kr("Connection attempt aborted",Ur.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,i)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}xs()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),xs()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Ha.Connected),this.emit(Br.Connected),Eo.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return Si(t,[...n],void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,i,r;const s=yield e.disconnectLock.lock();try{if(e.state===Ha.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===Ha.Connecting||e.state===Ha.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null===(n=e.abortController)||void 0===n||n.abort(t),null===(r=null===(i=e.connectFuture)||void 0===i?void 0:i.reject)||void 0===r||r.call(i,new Kr("Client initiated disconnect",Ur.Cancelled)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,mt.CLIENT_INITIATED),e.engine=void 0}finally{s()}}()})},this.onPageLeave=()=>Si(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>Si(this,void 0,void 0,function*(){const e=[],t=rs();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let n=document.getElementById(t);if(!n){n=document.createElement("audio"),n.id=t,n.autoplay=!0,n.hidden=!0;const e=Ys();e.enabled=!0;const i=new MediaStream([e]);n.srcObject=i,document.addEventListener("visibilitychange",()=>{n&&(n.srcObject=document.hidden?null:i,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(n),this.once(Br.Disconnected,()=>{null==n||n.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>Si(this,void 0,void 0,function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;null===(n=t.track)||void 0===n||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Ha.Reconnecting)&&this.emit(Br.Reconnecting)},this.handleSignalRestarted=e=>Si(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(Ha.Connected),this.emit(Br.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let n=this.remoteParticipants.get(e.identity);e.state===St.DISCONNECTED?this.handleParticipantDisconnected(e.identity,n):n=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{const t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Br.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach(e=>{const n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});const n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(Br.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;const i=us.streamStateFromProto(e.state);n.track.setStreamState(i),i!==n.track.streamState&&(t.emit(qr.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(Br.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const n=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(n,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(n,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(n,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(n,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,n);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,i)=>{this.emit(Br.DataReceived,t.payload,e,n,t.topic,i),null==e||e.emit(qr.DataReceived,t.payload,n,i)},this.handleSipDtmf=(e,t)=>{this.emit(Br.SipDTMFReceived,t,e),null==e||e.emit(qr.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{const n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),i=null==n?void 0:n.trackPublications.get(t.trackId),r=function(e,t){return e.segments.map(e=>{let{id:n,text:i,language:r,startTime:s,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(n))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(n):t.set(n,d),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:r,firstReceivedTime:d,lastReceivedTime:l}})}(t,this.transcriptionReceivedTimes);null==i||i.emit(Hr.TranscriptionReceived,r),null==n||n.emit(qr.TranscriptionReceived,r,i),this.emit(Br.TranscriptionReceived,r,n,i)},this.handleChatMessage=(e,t)=>{const n=function(e){const{id:t,timestamp:n,message:i,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}(t);this.emit(Br.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(Br.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Br.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Br.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Br.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Br.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Si(this,void 0,void 0,function*(){var e;"iOS"!==(null===(e=rs())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(Br.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Br.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Br.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(Br.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Br.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Br.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Br.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Br.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Si(this,void 0,void 0,function*(){var t,n,i,r,s,o;null===(t=e.track)||void 0===t||t.on(Hr.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=e.track)||void 0===n||n.on(Hr.Restarted,this.onLocalTrackRestarted),null===(s=null===(r=null===(i=e.track)||void 0===i?void 0:i.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===s||s.call(r,this),this.emit(Br.LocalTrackPublished,e,this.localParticipant),ao(e.track)&&(yield e.track.checkForSilence())&&this.emit(Br.LocalAudioSilenceDetected,e);const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=vo(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Br.ActiveDeviceChanged,c,a))}),this.onLocalTrackUnpublished=e=>{var t,n;null===(t=e.track)||void 0===t||t.off(Hr.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=e.track)||void 0===n||n.off(Hr.Restarted,this.onLocalTrackRestarted),this.emit(Br.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Si(this,void 0,void 0,function*(){const t=yield e.getDeviceId(!1),n=vo(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug("local track restarted, setting ".concat(n," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(Br.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Br.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Br.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Br.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Br.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},da),e),this.log=yi(null!==(n=this.options.loggerName)&&void 0!==n?n:mi.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},aa),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ca),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},oa),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new $a,this.outgoingDataStreamManager=new nc(this.engine,this.log),this.disconnectLock=new _,this.localParticipant=new pc("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",$s(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",$s(this.options.audioCaptureDefaults.deviceId)),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&this.switchActiveDevice("audiooutput",$s(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),xs()){const e=new AbortController;null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),fc.cleanupRegistry&&fc.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return Si(this,void 0,void 0,function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)})}setupE2EE(){var e;const t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Co(n,t),this.e2eeManager.on(Nr.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Br.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(Nr.EncryptionError,(e,t)=>{const n=t?this.getParticipantByIdentity(t):void 0;this.emit(Br.EncryptionError,e,n)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Si(this,void 0,void 0,function*(){return this.state===Ha.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{const n=t=>{""!==t.sid&&(this.engine.off(Wr.RoomUpdate,n),e(t.sid))};this.engine.on(Wr.RoomUpdate,n),this.once(Br.Disconnected,()=>{this.engine.off(Wr.RoomUpdate,n),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Ga(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Wr.ParticipantUpdate,this.handleParticipantUpdates).on(Wr.RoomUpdate,this.handleRoomUpdate).on(Wr.SpeakersChanged,this.handleSpeakersChanged).on(Wr.StreamStateChanged,this.handleStreamStateUpdate).on(Wr.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Wr.SubscriptionError,this.handleSubscriptionError).on(Wr.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Wr.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(Wr.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Wr.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Wr.DataPacketReceived,this.handleDataPacket).on(Wr.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Ha.SignalReconnecting)&&this.emit(Br.SignalReconnecting)}).on(Wr.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Ha.Connected)&&this.emit(Br.Reconnected)}).on(Wr.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Ha.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(Wr.Restarting,this.handleRestarting).on(Wr.SignalRestarted,this.handleSignalRestarted).on(Wr.Offline,()=>{this.setAndEmitConnectionState(Ha.Reconnecting)&&this.emit(Br.Reconnecting)}).on(Wr.DCBufferStatusChanged,(e,t)=>{this.emit(Br.DCBufferStatusChanged,e,t)}).on(Wr.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});t?(this.localParticipant.emit(qr.LocalTrackSubscribed,t),this.emitWhenConnected(Br.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(Wr.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Br.Moved,e.room.name),this.handleParticipantUpdates(e.participant?[e.participant,...e.otherParticipants]:e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Po.getInstance().getDevices(e,t)}prepareConnection(e,t){return Si(this,void 0,void 0,function*(){if(this.state===Ha.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ls(new URL(e))&&t){this.regionUrlProvider=new pa(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Ha.Disconnected&&(this.regionUrl=n,yield fetch(Zs(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Zs(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Si(this,void 0,void 0,function*(){let n,i=()=>Si(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new Qn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Qn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Qn({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Qn({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=()=>Si(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),n=new Qn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Si(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),n=new Qn({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 Qn({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Si(this,void 0,void 0,function*(){const e=this.engine.client.onLeave;e&&e(new Rn({reason:mt.CLIENT_INITIATED,action:In.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new Qn({scenario:{case:"subscriberBandwidth",value:no(t)}});break;case"leave-full-reconnect":n=new Qn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Si(this,arguments,void 0,function(e,t){var n=this;let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var r,s,o,a,c,d,l;let u=!0,h=!1;const p=i?{exact:t}:t;if("audioinput"===e){h=0===n.localParticipant.audioTrackPublications.size;const t=null!==(r=n.getActiveDevice(e))&&void 0!==r?r:n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=p;const i=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===us.Source.Microphone);try{u=(yield Promise.all(i.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}const s=i.some(e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n});u&&s&&(h=!0)}else if("videoinput"===e){h=0===n.localParticipant.videoTrackPublications.size;const t=null!==(s=n.getActiveDevice(e))&&void 0!==s?s:n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=p;const i=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===us.Source.Camera);try{u=(yield Promise.all(i.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}const r=i.some(e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n});u&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!Is()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!("setSinkId"in n.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");n.options.webAudioMix&&(t=null!==(o=yield Po.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(l=n.options).audioOutput)&&void 0!==a||(l.audioOutput={});const i=null!==(c=n.getActiveDevice(e))&&void 0!==c?c:n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&(null===(d=n.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=i,e}}return h&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(Br.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(qr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(qr.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(qr.AttributesChanged,this.onLocalAttributesChanged).on(qr.TrackMuted,this.onLocalTrackMuted).on(qr.TrackUnmuted,this.onLocalTrackUnmuted).on(qr.LocalTrackPublished,this.onLocalTrackPublished).on(qr.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(qr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(qr.MediaDevicesError,this.onMediaDevicesError).on(qr.AudioStreamAcquired,this.startAudio).on(qr.ChatMessage,this.onLocalChatMessageSent).on(qr.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Ha.Connecting||this.state===Ha.Reconnecting){const i=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),r()},r=()=>{this.off(Br.Reconnected,i),this.off(Br.Connected,i),this.off(Br.Disconnected,r)};return this.once(Br.Reconnected,i),this.once(Br.Connected,i),void this.once(Br.Disconnected,r)}if(this.state===Ha.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const i=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find(e=>e.sid===r);if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);if(!o.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(n);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(r),this.logContext);o=e}let c;o.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(r,", streamId: ").concat(s,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:s,trackId:o})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(e,o,t,n,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(Br.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Ha.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,i,r;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(n=t.track)||void 0===n||n.detach(),null===(i=t.track)||void 0===i||i.stop()):null===(r=t.track)||void 0===r||r.stopMonitor()}),this.localParticipant.off(qr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(qr.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(qr.AttributesChanged,this.onLocalAttributesChanged).off(qr.TrackMuted,this.onLocalTrackMuted).off(qr.TrackUnmuted,this.onLocalTrackUnmuted).off(qr.LocalTrackPublished,this.onLocalTrackPublished).off(qr.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(qr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(qr.MediaDevicesError,this.onMediaDevicesError).off(qr.AudioStreamAcquired,this.startAudio).off(qr.ChatMessage,this.onLocalChatMessageSent).off(qr.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),xs()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Ha.Disconnected),this.emit(Br.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Br.ParticipantDisconnected,t),t.setDisconnected(),null===(n=this.localParticipant)||void 0===n||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,i,r,s){return Si(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==s)return void(yield this.engine.publishRpcResponse(e,t,null,ma.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(n);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,ma.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const s=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:r});ga(s)>15360?(a=ma.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=s}catch(e){e instanceof ma?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),e),a=ma.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}selectDefaultDevices(){return Si(this,void 0,void 0,function*(){var e,t,n;const i=Po.getInstance().previousDevices,r=yield Po.getInstance().getDevices(void 0,!1),s=rs();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let e of r){const t=i.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(Br.ActiveDeviceChanged,e.kind,e.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let s of o){const o=fo(s),a=this.localParticipant.getTrackPublication(o);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=r.filter(e=>e.kind===s),d=this.getActiveDevice(s);d===(null===(t=i.filter(e=>e.kind===s)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(n=c[0])||void 0===n?void 0:n.deviceId)!==d?yield this.switchActiveDevice(s,c[0].deviceId):"audioinput"===s&&!Ms()||"videoinput"===s||!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(s))||"audiooutput"===s&&Ms()||(yield this.switchActiveDevice(s,c[0].deviceId))}})}acquireAudioContext(){return Si(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=go())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Es(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const n="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(Br.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let i;return i=t?gc.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new gc(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Br.ParticipantConnected,n),n.on(qr.TrackPublished,e=>{this.emitWhenConnected(Br.TrackPublished,e,n)}).on(qr.TrackSubscribed,(e,t)=>{e.kind===us.Kind.Audio?(e.on(Hr.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Hr.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===us.Kind.Video&&(e.on(Hr.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Hr.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Br.TrackSubscribed,e,t,n)}).on(qr.TrackUnpublished,e=>{this.emit(Br.TrackUnpublished,e,n)}).on(qr.TrackUnsubscribed,(e,t)=>{this.emit(Br.TrackUnsubscribed,e,t,n)}).on(qr.TrackMuted,e=>{this.emitWhenConnected(Br.TrackMuted,e,n)}).on(qr.TrackUnmuted,e=>{this.emitWhenConnected(Br.TrackUnmuted,e,n)}).on(qr.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Br.ParticipantMetadataChanged,e,n)}).on(qr.ParticipantNameChanged,e=>{this.emitWhenConnected(Br.ParticipantNameChanged,e,n)}).on(qr.AttributesChanged,e=>{this.emitWhenConnected(Br.ParticipantAttributesChanged,e,n)}).on(qr.ConnectionQualityChanged,e=>{this.emitWhenConnected(Br.ConnectionQualityChanged,e,n)}).on(qr.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Br.ParticipantPermissionsChanged,e,n)}).on(qr.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Br.TrackSubscriptionStatusChanged,e,t,n)}).on(qr.TrackSubscriptionFailed,(e,t)=>{this.emit(Br.TrackSubscriptionFailed,e,n,t)}).on(qr.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Br.TrackSubscriptionPermissionChanged,e,t,n)}).on(qr.Active,()=>{this.emitWhenConnected(Br.ParticipantActive,n),n.kind===Ct.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&lo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=cs.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,mt.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&cs.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Br.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(this.state===Ha.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===Ha.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return Si(this,void 0,void 0,function*(){var t,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new yt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Y.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Tt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Br.SignalConnected),this.emit(Br.Connected),this.setAndEmitConnectionState(Ha.Connected),i.video){const e=new lc(us.Kind.Video,new Rt({source:lt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO,name:"video-dummy"}),new Na(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Js(160*(null!==(t=r.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(qr.LocalTrackPublished,e)}if(i.audio){const e=new lc(us.Kind.Audio,new Rt({source:lt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO}),new Ca(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ys(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(qr.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new Tt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:St.ACTIVE,tracks:[],joinedAt:Y.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const s=Js(160*(null!==(n=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==n?n:1),160,!1,!0),o=new Rt({source:lt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO});i.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Ys(),n=new Rt({source:lt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(e!==Br.ActiveSpeakersChanged&&e!==Br.TranscriptionReceived){const t=vc(n).filter(e=>void 0!==e);e!==Br.TrackSubscribed&&e!==Br.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...n)}}function vc(e){return e.map(e=>{if(e)return Array.isArray(e)?vc(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e})}function yc(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);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}fc.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(za||(za={})),new TextEncoder,new TextDecoder;class bc extends Error{constructor(e,t){var n;super(e,t),yc(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}yc(bc,"code","ERR_JOSE_GENERIC"),yc(class extends bc{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}}),yc(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),yc(this,"claim",void 0),yc(this,"reason",void 0),yc(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),yc(class extends bc{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}}),yc(this,"code","ERR_JWT_EXPIRED"),yc(this,"claim",void 0),yc(this,"reason",void 0),yc(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),yc(class extends bc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),yc(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),yc(class extends bc{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),yc(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),yc(class extends bc{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),yc(this,Symbol.asyncIterator,void 0),yc(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),yc(class extends bc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),yc(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),yc(class extends bc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),yc(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const kc=new Map;class Tc{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);n&&n.add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}}var Sc;!function(e){e.SESSION_STARTED="session_started",e.PARTIAL_TRANSCRIPT="partial_transcript",e.COMMITTED_TRANSCRIPT="committed_transcript",e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",e.AUTH_ERROR="auth_error",e.ERROR="error",e.OPEN="open",e.CLOSE="close",e.QUOTA_EXCEEDED="quota_exceeded",e.COMMIT_THROTTLED="commit_throttled",e.TRANSCRIBER_ERROR="transcriber_error",e.UNACCEPTED_TERMS="unaccepted_terms",e.RATE_LIMITED="rate_limited",e.INPUT_ERROR="input_error",e.QUEUE_OVERFLOW="queue_overflow",e.RESOURCE_EXHAUSTED="resource_exhausted",e.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",e.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",e.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"}(Sc||(Sc={}));class Cc{constructor(e){this.websocket=null,this.eventEmitter=new Tc,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Sc.OPEN):this.websocket.addEventListener("open",()=>{this.eventEmitter.emit(Sc.OPEN)}),this.websocket.addEventListener("message",e=>{try{const t=JSON.parse(e.data);switch(t.message_type){case"session_started":this.eventEmitter.emit(Sc.SESSION_STARTED,t);break;case"partial_transcript":this.eventEmitter.emit(Sc.PARTIAL_TRANSCRIPT,t);break;case"committed_transcript":this.eventEmitter.emit(Sc.COMMITTED_TRANSCRIPT,t);break;case"committed_transcript_with_timestamps":this.eventEmitter.emit(Sc.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case"auth_error":this.eventEmitter.emit(Sc.AUTH_ERROR,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"quota_exceeded":this.eventEmitter.emit(Sc.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"commit_throttled":this.eventEmitter.emit(Sc.COMMIT_THROTTLED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"transcriber_error":this.eventEmitter.emit(Sc.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"unaccepted_terms":this.eventEmitter.emit(Sc.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"rate_limited":this.eventEmitter.emit(Sc.RATE_LIMITED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"input_error":this.eventEmitter.emit(Sc.INPUT_ERROR,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"queue_overflow":this.eventEmitter.emit(Sc.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"resource_exhausted":this.eventEmitter.emit(Sc.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"session_time_limit_exceeded":this.eventEmitter.emit(Sc.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"chunk_size_exceeded":this.eventEmitter.emit(Sc.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"insufficient_audio_activity":this.eventEmitter.emit(Sc.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"error":this.eventEmitter.emit(Sc.ERROR,t);break;default:console.warn("Unknown message type:",t)}}catch(t){console.error("Failed to parse WebSocket message:",t,e.data),this.eventEmitter.emit(Sc.ERROR,new Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener("error",e=>{console.error("WebSocket error:",e),this.eventEmitter.emit(Sc.ERROR,e)}),this.websocket.addEventListener("close",e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||1e3!==e.code&&1005!==e.code){const t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||"No reason provided"}`;console.error(t),this.eventEmitter.emit(Sc.ERROR,new Error(t))}this.eventEmitter.emit(Sc.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t,n;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");const i={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:null!=(t=e.commit)&&t,sample_rate:null!=(n=e.sampleRate)?n:this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(i))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");this.websocket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,"User ended session")}}const Ec=function(e,t){return async(n,i)=>{const r=kc.get(e);if(r)return n.addModule(r);if(i)try{return await n.addModule(i),void kc.set(e,i)}catch(t){throw new Error(`Failed to load the ${e} worklet module from path: ${i}. Error: ${t}`)}const s=new Blob([t],{type:"application/javascript"}),o=URL.createObjectURL(s);try{return await n.addModule(o),void kc.set(e,o)}catch(e){URL.revokeObjectURL(o)}try{const i=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(i),kc.set(e,i)}catch(t){throw new Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}("scribeAudioProcessor",'/*\n * Scribe Audio Processor for converting microphone audio to PCM16 format\n * Supports resampling for browsers like Firefox that don\'t support\n * AudioContext sample rate constraints.\n * USED BY @elevenlabs/client\n */\n\nclass ScribeAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = [];\n this.bufferSize = 4096; // Buffer size for optimal chunk transmission\n\n // Resampling state\n this.inputSampleRate = null;\n this.outputSampleRate = null;\n this.resampleRatio = 1;\n this.lastSample = 0;\n this.resampleAccumulator = 0;\n\n this.port.onmessage = ({ data }) => {\n if (data.type === "configure") {\n this.inputSampleRate = data.inputSampleRate;\n this.outputSampleRate = data.outputSampleRate;\n if (this.inputSampleRate && this.outputSampleRate) {\n this.resampleRatio = this.inputSampleRate / this.outputSampleRate;\n }\n }\n };\n }\n\n // Linear interpolation resampling\n resample(inputData) {\n if (this.resampleRatio === 1 || !this.inputSampleRate) {\n return inputData;\n }\n\n const outputSamples = [];\n\n for (let i = 0; i < inputData.length; i++) {\n const currentSample = inputData[i];\n\n // Generate output samples using linear interpolation\n while (this.resampleAccumulator < 1) {\n const interpolated =\n this.lastSample +\n (currentSample - this.lastSample) * this.resampleAccumulator;\n outputSamples.push(interpolated);\n this.resampleAccumulator += this.resampleRatio;\n }\n\n this.resampleAccumulator -= 1;\n this.lastSample = currentSample;\n }\n\n return new Float32Array(outputSamples);\n }\n\n process(inputs) {\n const input = inputs[0];\n if (input.length > 0) {\n let channelData = input[0]; // Get first channel (mono)\n\n // Resample if needed (for Firefox and other browsers that don\'t\n // support AudioContext sample rate constraints)\n if (this.resampleRatio !== 1) {\n channelData = this.resample(channelData);\n }\n\n // Add incoming audio to buffer\n for (let i = 0; i < channelData.length; i++) {\n this.buffer.push(channelData[i]);\n }\n\n // When buffer reaches threshold, convert and send\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = new Float32Array(this.buffer);\n const int16Array = new Int16Array(float32Array.length);\n\n // Convert Float32 [-1, 1] to Int16 [-32768, 32767]\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to prevent overflow\n const sample = Math.max(-1, Math.min(1, float32Array[i]));\n // Scale to PCM16 range\n int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767;\n }\n\n // Send to main thread as transferable ArrayBuffer\n this.port.postMessage(\n {\n audioData: int16Array.buffer\n },\n [int16Array.buffer]\n );\n\n // Clear buffer\n this.buffer = [];\n }\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("scribeAudioProcessor", ScribeAudioProcessor);\n\n');var wc,Pc;!function(e){e.PCM_8000="pcm_8000",e.PCM_16000="pcm_16000",e.PCM_22050="pcm_22050",e.PCM_24000="pcm_24000",e.PCM_44100="pcm_44100",e.PCM_48000="pcm_48000",e.ULAW_8000="ulaw_8000"}(wc||(wc={})),function(e){e.MANUAL="manual",e.VAD="vad"}(Pc||(Pc={}));class Rc{static getWebSocketUri(e=Rc.DEFAULT_BASE_URI){return`${e}/v1/speech-to-text/realtime`}static buildWebSocketUri(e){const t=Rc.getWebSocketUri(e.baseUri),n=new URLSearchParams;if(n.append("model_id",e.modelId),n.append("token",e.token),void 0!==e.commitStrategy&&n.append("commit_strategy",e.commitStrategy),void 0!==e.audioFormat&&n.append("audio_format",e.audioFormat),void 0!==e.vadSilenceThresholdSecs){if(e.vadSilenceThresholdSecs<=.3||e.vadSilenceThresholdSecs>3)throw new Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");n.append("vad_silence_threshold_secs",e.vadSilenceThresholdSecs.toString())}if(void 0!==e.vadThreshold){if(e.vadThreshold<.1||e.vadThreshold>.9)throw new Error("vadThreshold must be between 0.1 and 0.9");n.append("vad_threshold",e.vadThreshold.toString())}if(void 0!==e.minSpeechDurationMs){if(e.minSpeechDurationMs<=50||e.minSpeechDurationMs>2e3)throw new Error("minSpeechDurationMs must be between 50 and 2000");n.append("min_speech_duration_ms",e.minSpeechDurationMs.toString())}if(void 0!==e.minSilenceDurationMs){if(e.minSilenceDurationMs<=50||e.minSilenceDurationMs>2e3)throw new Error("minSilenceDurationMs must be between 50 and 2000");n.append("min_silence_duration_ms",e.minSilenceDurationMs.toString())}void 0!==e.languageCode&&n.append("language_code",e.languageCode),void 0!==e.includeTimestamps&&n.append("include_timestamps",e.includeTimestamps?"true":"false");const i=n.toString();return i?`${t}?${i}`:t}static connect(e){if(!e.modelId)throw new Error("modelId is required");const t=new Cc("microphone"in e&&e.microphone?16e3:e.sampleRate),n=Rc.buildWebSocketUri(e),i=new WebSocket(n);return"microphone"in e&&e.microphone&&i.addEventListener("open",()=>{Rc.streamFromMicrophone(e,t)}),t.setWebSocket(i),t}static async streamFromMicrophone(e,t){const n=16e3;try{var i,r,s,o,a,c,d,l,u,h;const p=await navigator.mediaDevices.getUserMedia({audio:{deviceId:null==(i=e.microphone)?void 0:i.deviceId,echoCancellation:null==(r=null==(s=e.microphone)?void 0:s.echoCancellation)||r,noiseSuppression:null==(o=null==(a=e.microphone)?void 0:a.noiseSuppression)||o,autoGainControl:null==(c=null==(d=e.microphone)?void 0:d.autoGainControl)||c,channelCount:null!=(l=null==(u=e.microphone)?void 0:u.channelCount)?l:1,sampleRate:{ideal:n}}}),m=null==(h=p.getAudioTracks()[0])?void 0:h.getSettings(),g=null==m?void 0:m.sampleRate,f=new AudioContext(g?{sampleRate:g}:{});await Ec(f.audioWorklet);const v=f.createMediaStreamSource(p),y=new AudioWorkletNode(f,"scribeAudioProcessor");f.sampleRate!==n&&y.port.postMessage({type:"configure",inputSampleRate:f.sampleRate,outputSampleRate:n}),y.port.onmessage=e=>{const{audioData:n}=e.data,i=new Uint8Array(n);let r="";for(let e=0;e<i.length;e++)r+=String.fromCharCode(i[e]);const s=btoa(r);t.send({audioBase64:s})},v.connect(y),"suspended"===f.state&&await f.resume(),t._audioCleanup=()=>{p.getTracks().forEach(e=>{e.stop()}),v.disconnect(),y.disconnect(),f.close()}}catch(e){throw console.error("Failed to start microphone streaming:",e),e}}}function Ic(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}Rc.DEFAULT_BASE_URI="wss://api.elevenlabs.io";var Oc=/*#__PURE__*/function(){function t(e,t,n,i,r,s,o,a){this.provider=void 0,this.options=void 0,this.elevenLabsOptions=void 0,this.user=void 0,this.headInfo=void 0,this.sendMessage=void 0,this.microphoneStatus="OFF",this.microphoneAccess=!1,this.recognizer=null,this.connection=null,this.tokenObj={token:"",generatedAt:null,region:""},this.micBeep=new Audio("https://embedded.unith.ai/assets/beep_up.wav"),this.provider=e,this.options=t,this.elevenLabsOptions=n,this.user=i,this.headInfo=r,this.sendMessage=a,this.microphoneAccess=s,this.tokenObj=o,this.microphoneAccess||this.options.onMicrophoneError({message:"Microphone access not granted."})}t.initializeMicrophone=function(e,n,i,r,s,o,a){try{var c={token:"",generatedAt:null,region:""};return Promise.resolve(r.getAsrToken("eleven_labs"===n?"elevenlabs":"azure")).then(function(d){return c={token:d.token,generatedAt:Date.now(),region:d.region},new t(n,e,i,r,s,o,c,a)})}catch(e){return Promise.reject(e)}};var n=t.prototype;return n.updateMicrophoneStatus=function(e){this.microphoneStatus=e,this.options.onMicrophoneStatusChange({status:e})},n.handleRecognitionResult=function(e){e.length<2||this.options.onMicrophoneSpeechRecognitionResult({transcript:e})},n.startAzureMicrophone=function(){try{var t=function(t){return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return e(require("microsoft-cognitiveservices-speech-sdk"))}).catch(function(e){throw new Error("Azure Speech SDK not available: "+e)})).then(function(e){var t=e.SpeechSDK||e.default||e,i=t.SpeechConfig,r=t.AudioConfig,s=t.SpeechRecognizer,o=t.ResultReason,a=t.PhraseListGrammar;if(console.log({SpeechConfig:i,AudioConfig:r,SpeechRecognizer:s}),!i||!r||!s)throw new Error("Azure Speech SDK does not expose expected symbols.");var c=i.fromAuthorizationToken(n.tokenObj.token,n.tokenObj.region);c.speechRecognitionLanguage=n.headInfo.lang_speech_recognition||"en-US";var d=r.fromDefaultMicrophoneInput();n.recognizer=new s(c,d),n.headInfo.phrases.length>0&&a.fromRecognizer(n.recognizer).addPhrases(n.headInfo.phrases),n.recognizer.recognized=function(e,t){t.result.reason===o.RecognizedSpeech?n.handleRecognitionResult(t.result.text):t.result.reason===o.NoMatch&&n.options.onMicrophoneError({message:"Speech could not be recognized - No clear speech detected"})},n.recognizer.startContinuousRecognitionAsync(function(){n.micBeep.play(),n.updateMicrophoneStatus("ON")},function(){console.error("Error starting recognizer")}),n.tokenObj.token=""})},n=this,i=function(){if(0===n.tokenObj.token.length)return Promise.resolve(n.user.getAsrToken("azure")).then(function(e){if(!e.region||!e.token)throw new Error("Failed to initialize Azure microphone.");n.tokenObj={token:e.token,region:e.region,generatedAt:Date.now()}})}();return Promise.resolve(i&&i.then?i.then(t):t())}catch(e){return Promise.reject(e)}},n.stopAzureMicrophone=function(){try{var e=this;return e.recognizer&&e.recognizer.stopContinuousRecognitionAsync(function(){e.updateMicrophoneStatus("OFF")},function(t){e.options.onMicrophoneError({message:"Error stopping microphone : "+t})}),Promise.resolve()}catch(e){return Promise.reject(e)}},n.startElevenLabsMicrophone=function(){try{var e=function(e){t.connection=Rc.connect({token:t.tokenObj.token,modelId:"scribe_v2_realtime",includeTimestamps:!1,microphone:{echoCancellation:!0,noiseSuppression:t.elevenLabsOptions.noiseSuppression},commitStrategy:Pc.VAD,vadSilenceThresholdSecs:t.elevenLabsOptions.vadSilenceThresholdSecs,vadThreshold:t.elevenLabsOptions.vadThreshold,minSpeechDurationMs:t.elevenLabsOptions.minSpeechDurationMs,minSilenceDurationMs:t.elevenLabsOptions.minSilenceDurationMs}),t.connection.on(Sc.SESSION_STARTED,function(){t.micBeep.play(),t.updateMicrophoneStatus("ON")}),t.connection.on(Sc.COMMITTED_TRANSCRIPT,function(e){e.text.length<2||"("===e.text[0]||t.handleRecognitionResult(e.text)}),t.connection.on(Sc.ERROR,function(e){console.error("Error:",e),t.options.onMicrophoneError({message:"Error recognizing speech"})}),t.tokenObj.token=""},t=this,n=function(){if(0===t.tokenObj.token.length)return Promise.resolve(t.user.getAsrToken("elevenlabs")).then(function(e){if(!e.token)throw new Error("Failed to initialize Eleven Labs microphone.");t.tokenObj={token:e.token,region:"",generatedAt:Date.now()}})}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},n.stopElevenLabsMicrophone=function(){try{var e,t=this;return Promise.resolve(Ic(function(){function n(n){if(e)return n;t.connection=null}var i=function(){if(t.connection)return Promise.resolve(t.connection.close()).then(function(){t.updateMicrophoneStatus("OFF"),e=1})}();return i&&i.then?i.then(n):n(i)},function(){t.updateMicrophoneStatus("OFF")}))}catch(e){return Promise.reject(e)}},n.toggleMicrophone=function(){try{var e=this;return Promise.resolve(Ic(function(){var t=function(){if("ON"===e.microphoneStatus){e.updateMicrophoneStatus("PROCESSING");var t=function(){if("azure"===e.provider)return Promise.resolve(e.stopAzureMicrophone()).then(function(){});var t=function(){if("eleven_labs"===e.provider)return Promise.resolve(e.stopElevenLabsMicrophone()).then(function(){})}();return t&&t.then?t.then(function(){}):void 0}();if(t&&t.then)return t.then(function(){})}else{var n=function(){if("OFF"===e.microphoneStatus){e.updateMicrophoneStatus("PROCESSING");var t=function(){if("azure"===e.provider)return Promise.resolve(e.startAzureMicrophone()).then(function(){});var t=function(){if("eleven_labs"===e.provider)return Promise.resolve(e.startElevenLabsMicrophone()).then(function(){})}();return t&&t.then?t.then(function(){}):void 0}();if(t&&t.then)return t.then(function(){})}else console.error("Microphone is currently processing. Please wait.")}();if(n&&n.then)return n.then(function(){})}}();if(t&&t.then)return t.then(function(){})},function(t){e.updateMicrophoneStatus("OFF"),e.options.onMicrophoneError({message:t.message||"An unknown error occurred."})}))}catch(e){return Promise.reject(e)}},n.status=function(){return this.microphoneStatus},t}(),_c=/*#__PURE__*/function(){function e(e,t){this.connection=void 0,this.intervalId=null,this.pingInterval=void 0,this.timeout=void 0,this.lastPingTimestamp="0",this.history=[],this.maxHistory=void 0,this.onUpdate=void 0,this.connection=e,this.pingInterval=(null==t?void 0:t.pingInterval)||4e3,this.timeout=(null==t?void 0:t.timeout)||2e3,this.maxHistory=(null==t?void 0:t.maxHistory)||3,this.onUpdate=null==t?void 0:t.onUpdate,this.handleMessage=this.handleMessage.bind(this),this.connection.onPingPong(this.handleMessage)}var t=e.prototype;return t.start=function(){var e=this;this.intervalId||(this.intervalId=setInterval(function(){e.sendPing()},this.pingInterval))},t.stop=function(){clearInterval(this.intervalId),this.intervalId=null},t.destroy=function(){this.stop()},t.sendPing=function(){var e=performance.now().toString();this.lastPingTimestamp=e;var t={event:exports.EventType.PING,timestamp:this.lastPingTimestamp,id:"0"};this.connection.sendPingEvent(t)},t.handleMessage=function(e){try{if(e.timestamp===this.lastPingTimestamp){var t=performance.now()-parseFloat(e.timestamp);this.recordLatency(t)}}catch(e){}},t.recordLatency=function(e){this.history.push(e),this.history.length>this.maxHistory&&this.history.shift();var t=this.history.reduce(function(e,t){return e+t},0)/this.history.length,n=this.classifyLatency(t);this.onUpdate&&this.onUpdate({rtt:e,average:t,status:n})},t.classifyLatency=function(e){return e<100?"good":e<250?"moderate":"poor"},e}(),Dc=/*#__PURE__*/function(){function e(e){this.config=void 0,this.driftHistory=[],this.correctionInProgress=!1,this.lastAudioTiming=null,this.lastVideoTiming=null,this.config=e}var t=e.prototype;return t.updateAudioTime=function(e){this.lastAudioTiming={timestamp:performance.now(),relativeTime:e}},t.updateVideoTime=function(e){this.lastVideoTiming={timestamp:performance.now(),relativeTime:e}},t.resetTiming=function(){this.lastAudioTiming=null,this.lastVideoTiming=null},t.checkSync=function(){try{var e=this;if(e.correctionInProgress)return console.warn("Sync correction already in progress"),Promise.resolve();if(!e.lastAudioTiming||!e.lastVideoTiming)return console.warn("Insufficient timing data for sync check"),Promise.resolve();var t=Math.abs(e.lastAudioTiming.relativeTime-e.lastVideoTiming.relativeTime);return e.recordDrift(t),t>e.config.tolerance?console.log("Drift detected: "+t+"ms"):console.log("No significant drift detected"),Promise.resolve()}catch(e){return Promise.reject(e)}},t.recordDrift=function(e){this.driftHistory.push({timestamp:Date.now(),drift:e,audioTime:this.lastAudioTiming.relativeTime,videoTime:this.lastVideoTiming.relativeTime}),this.driftHistory.length>this.config.historyLength&&this.driftHistory.shift()},e}(),Mc=window.localStorage,Ac=window.location.origin+window.location.pathname,xc=function(e,t,n){if(void 0!==Mc)return Mc.getItem("chat:"+Ac+":"+t+":"+n+":"+e)},Nc=function(e,t,n,i){void 0===Mc||Mc.setItem("chat:"+Ac+":"+n+":"+i+":"+e,t)};function Lc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Uc,jc,Fc=/*#__PURE__*/function(){function e(e,t,n,i,r,s,o,a){this.id=void 0,this.username=void 0,this.password=void 0,this.orgId=void 0,this.headId=void 0,this.apiBase=void 0,this.EXPIRATION_OFFSET=9e5,this.accessToken="",this.tokenType="",this.sessionId=0,this.id=n,this.username=i,this.password=r,this.orgId=s,this.headId=o,this.apiBase=a,this.accessToken=e,this.tokenType=t;var c=xc("session_id",s,o);c&&(this.sessionId=parseInt(c),this.sessionId+=1),Nc("session_id",this.sessionId.toString(),s,o)}e.loginUser=function(t,n,i,r,s){try{var o=new FormData;return o.append("username",t),o.append("password",n),Promise.resolve(Lc(function(){return Promise.resolve(fetch(i+"/token",{method:"POST",body:o})).then(function(o){return o.status>=200&&o.status<=299?Promise.resolve(o.json()).then(function(o){return new e(o.access_token,o.token_type,o.user_id,t,n,r,s,i)}):Promise.resolve(o.text()).then(function(e){var t=new Error("An error occurred: "+o.status+" "+o.statusText+". Response: "+e);throw t.response={status:o.status,status_code:o.status,data:JSON.parse(e)},t})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.getHeadDetails=function(e){try{var t=this,n=t.apiBase+"/api/v1/head/"+t.orgId+"/"+t.headId+"/"+e;return Promise.resolve(Lc(function(){return Promise.resolve(fetch(n)).then(function(e){return e.status>=200&&e.status<=299?Promise.resolve(e.json()):Promise.resolve(e.text()).then(function(t){var n=new Error("An error occurred: "+e.status+" "+e.statusText+". Response: "+t);throw n.response={status:e.status,status_code:e.status,data:JSON.parse(t)},n})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))}))}catch(e){return Promise.reject(e)}},t.getAuthToken=function(e,t){try{var n,i=this.apiBase+"/token",r=new FormData;r.append("username",e),r.append("password",t);var s=Lc(function(){return Promise.resolve(fetch(i,{method:"POST",body:r})).then(function(e){return Promise.resolve(e.json()).then(function(e){n=e})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))});return Promise.resolve(s&&s.then?s.then(function(e){return n}):n)}catch(e){return Promise.reject(e)}},t.getProviderToken=function(e,t){try{var n,i,r=function(e){return{token:n,region:i}},s=this.apiBase+"/api/v1/asr_token?provider="+t,o=Lc(function(){return Promise.resolve(fetch(s,{method:"GET",headers:{Authorization:"Bearer "+e}})).then(function(e){return Promise.resolve(e.json()).then(function(e){n=e.token,i=e.region})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))});return Promise.resolve(o&&o.then?o.then(r):r())}catch(e){return Promise.reject(e)}},t.getAccessToken=function(){try{var e=function(e){var s=JSON.parse(window.atob(n.split(".")[1]));return t.username=s.username,{access_token:n,user_id:i,session_id:r}},t=this,n=xc("access_token",t.orgId,t.headId),i=xc("user_id",t.orgId,t.headId),r=parseInt(xc("session_id",t.orgId,t.headId)||"")||0,s=!0;if("undefined"!==n&&n&&i&&"number"==typeof r){var o=1e3*JSON.parse(window.atob(n.split(".")[1])).exp,a=(new Date).getTime()+t.EXPIRATION_OFFSET;s=a>o}var c=function(){if(s)return Promise.resolve(t.getAuthToken(t.username,t.password)).then(function(e){if(!e)throw new Error("Could not renew authentication token");i=e.user_id,r++,Nc("access_token",n=e.access_token,t.orgId,t.headId),Nc("user_id",i,t.orgId,t.headId),Nc("session_id",r.toString(),t.orgId,t.headId)})}();return Promise.resolve(c&&c.then?c.then(e):e())}catch(e){return Promise.reject(e)}},t.getAsrToken=function(e){try{var t=this,n=xc("asr_token",t.orgId,t.headId),i=xc("region",t.orgId,t.headId);return Promise.resolve(t.getAccessToken()).then(function(r){var s,o=r.access_token;function a(e){return s?e:{token:n,region:i}}var c=!0;if(n&&i){var d=1e3*JSON.parse(window.atob(n.split(".")[1])).exp,l=(new Date).getTime()+t.EXPIRATION_OFFSET;c=l>d}var u=function(){if(c)return Promise.resolve(t.getProviderToken(o,e)).then(function(e){if(!e)return s=1,{token:"",region:""};i=e.region,Nc("asr_token",n=e.token,t.orgId,t.headId),Nc("asr_region",i,t.orgId,t.headId)})}();return u&&u.then?u.then(a):a(u)})}catch(e){return Promise.reject(e)}},e}();function Vc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}!function(e){e.INITIALIZING="initializing",e.READY="ready",e.PLAYING="playing",e.PAUSED="paused",e.INTERRUPTED="interrupted",e.DESTROYED="destroyed"}(Uc||(Uc={})),exports.VideoTransitionType=void 0,(jc=exports.VideoTransitionType||(exports.VideoTransitionType={})).NONE="none",jc.CROSSFADE="crossfade",jc.FADEIN="fadein",jc.FADEOUT="fadeout";var Bc=/*#__PURE__*/function(){function e(e,t,i,r){var s=this;this.canvas=void 0,this.ctx=void 0,this.container=void 0,this.config=void 0,this.resizeObserver=null,this.decoder=null,this.state=Uc.INITIALIZING,this.isProcessingFrame=!1,this.isStreaming=!1,this.startTime=0,this.frameBuffer=[],this.currentSequenceId=0,this.animationFrameId=null,this.renderLoop=!1,this.fpsCounter={count:0,lastTime:0},this.handleContextLoss=function(){},this.handleContextRestore=function(){},this.handleResize=function(){var e=s.container.getBoundingClientRect(),t=e.width,n=e.height;s.canvas.width=t,s.canvas.height=n,s.canvas.style.width=t+"px",s.canvas.style.height=n+"px",s.ctx.imageSmoothingEnabled=!0},this.canvas=e,this.ctx=t,this.container=i,this.config=n({maxBufferSize:1e3,enableAdaptiveQuality:!1},r),this.setupContextLossHandling(),this.setupResizeHandling(),this.initializeDecoder()}e.create=function(t,n){try{var i;if(!("VideoDecoder"in window))throw new Error("WebCodecs VideoDecoder API is not supported in this browser");var r=document.createElement("canvas");r.width=n.width,r.height=n.height,r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.backgroundColor=(null==(i=n.backgroundColor)?void 0:i.toString())||"#000000",r.style.maxWidth="100%",r.style.height="100%",r.style.zIndex="0",r.style.pointerEvents="none",r.style.objectFit="cover",r.style.imageRendering="pixelated";var s=r.getContext("2d",{alpha:!1,desynchronized:!0});if(!s)throw new Error("Failed to get 2D canvas context");return s.imageSmoothingEnabled=!0,t.appendChild(r),Promise.resolve(new e(r,s,t,n))}catch(e){return Promise.reject(e)}};var i=e.prototype;return i.initializeDecoder=function(){try{var e=this;return Promise.resolve(Vc(function(){return new VideoDecoder({output:function(){},error:function(){}}).close(),e.decoder=new VideoDecoder({output:function(t){e.renderVideoFrame(t)},error:function(e){console.error("VP8 Decoder error:",e.message)}}),Promise.resolve(e.decoder.configure({codec:"vp8",codedWidth:e.config.width,codedHeight:e.config.height})).then(function(){})},function(e){throw new Error("Failed to initialize VP8 decoder: "+e.message)}))}catch(e){return Promise.reject(e)}},i.setupResizeHandling=function(){var e=this;this.resizeObserver=new ResizeObserver(function(n){for(var i,r=function(e){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,n){if(e){if("string"==typeof e)return t(e,n);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,n):void 0}}(e))){n&&(e=n);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(i=r()).done;)i.value.target===e.container&&e.handleResize()}),this.resizeObserver.observe(this.container),window.addEventListener("resize",this.handleResize)},i.getBufferLength=function(){return this.frameBuffer.length},i.getStreamingStatus=function(){return this.isStreaming},i.addFrame=function(e,t,n){void 0===n&&(n=!1);try{var i=this;if(i.state===Uc.DESTROYED)throw new Error("Cannot add frame to destroyed video output");var r={data:e,timestamp:t,isKeyframe:n,sequenceId:i.currentSequenceId++,size:e.byteLength};if(i.frameBuffer.length>=(i.config.maxBufferSize||1e3))if(i.config.enableAdaptiveQuality){if(!n)return Promise.resolve();var s=i.frameBuffer.findIndex(function(e){return!e.isKeyframe});-1!==s?i.frameBuffer.splice(s,1):i.frameBuffer.shift()}else i.frameBuffer.shift();return i.frameBuffer.push(r),Promise.resolve()}catch(e){return Promise.reject(e)}},i.toggleStream=function(e){try{return this.isStreaming=e,Promise.resolve()}catch(e){return Promise.reject(e)}},i.clearFrame=function(){if(this.state===Uc.DESTROYED)throw new Error("Cannot clear frame from destroyed video output");if(this.renderLoop=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.frameBuffer=[],this.isProcessingFrame=!1,this.currentSequenceId=0,this.startTime=0,this.fpsCounter={count:0,lastTime:0},this.decoder&&"configured"===this.decoder.state)try{this.decoder.flush()}catch(e){console.warn("Error flushing decoder:",e)}this.clearCanvas(),this.state=Uc.READY},i.interrupt=function(e){var t=this;if(void 0===e&&(e=!1),this.state!==Uc.DESTROYED){if(this.state=Uc.INTERRUPTED,this.frameBuffer=[],this.isProcessingFrame=!1,this.decoder&&"configured"===this.decoder.state)try{this.decoder.flush()}catch(e){console.warn("Error flushing decoder:",e)}e?this.fadeOutCanvas().then(function(){t.clearCanvas()}):this.clearCanvas()}},i.destroy=function(){this.state!==Uc.DESTROYED&&(this.state=Uc.DESTROYED,this.renderLoop=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.decoder&&(this.decoder.close(),this.decoder=null),this.frameBuffer=[],this.canvas.removeEventListener("webglcontextlost",this.handleContextLoss),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestore),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.isProcessingFrame=!1)},i.getState=function(){return this.state},i.startRenderingStreamingVideo=function(e){e&&(this.state=Uc.READY,this.renderLoop=!0,this.startTime=performance.now(),this.render())},i.render=function(){var e,t=this;if(this.renderLoop&&this.state!==Uc.DESTROYED){var n=(null==(e=this.frameBuffer[0])?void 0:e.timestamp)||0;this.frameBuffer.length>0&&0===this.frameBuffer[0].sequenceId&&(this.startTime=performance.now());var i=performance.now()-this.startTime;i>=n&&this.frameBuffer.length>0&&!this.isProcessingFrame&&this.processNextFrame(i,i-n),this.animationFrameId=requestAnimationFrame(function(){return t.render()})}},i.processNextFrame=function(e,t){try{var n=this;if(n.isProcessingFrame||0===n.frameBuffer.length||!n.decoder)return Promise.resolve();if("configured"!==n.decoder.state)return Promise.resolve();n.isProcessingFrame=!0;var i=n.frameBuffer.shift(),r=function(e,t){try{var r=Vc(function(){return Promise.resolve(n.decodeVP8Frame(i)).then(function(){})},function(e){console.error("Frame processing failed:",e)})}catch(e){return t(!0,e)}return r&&r.then?r.then(t.bind(null,!1),t.bind(null,!0)):t(!1,r)}(0,function(e,t){if(n.isProcessingFrame=!1,e)throw t;return t});return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},i.decodeVP8Frame=function(e){try{try{var t=new EncodedVideoChunk({type:e.isKeyframe?"key":"delta",timestamp:1e3*e.timestamp,data:e.data});this.decoder.decode(t)}catch(e){throw new Error("VP8 decode failed: "+e.message)}return Promise.resolve()}catch(e){return Promise.reject(e)}},i.renderVideoFrame=function(e){try{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);var t,n,i,r,s=e.displayWidth/e.displayHeight;s>this.canvas.width/this.canvas.height?(i=(this.canvas.width-(t=(n=this.canvas.height)*s))/2,r=0):(i=0,r=(this.canvas.height-(n=(t=this.canvas.width)/s))/2),this.ctx.drawImage(e,i,r,t,n),e.close()}catch(e){console.error("Error rendering video frame:",e)}},i.clearCanvas=function(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)},i.fadeOutCanvas=function(){try{var e=this;return Promise.resolve(new Promise(function(t){var n=1,i=function(){e.canvas.style.opacity=(n-=.05).toString(),n<=0?(e.canvas.style.opacity="1",t()):requestAnimationFrame(i)};i()}))}catch(e){return Promise.reject(e)}},i.setupContextLossHandling=function(){var e=this;this.handleContextLoss=function(t){t.preventDefault(),console.warn("Canvas context lost"),e.state=Uc.PAUSED},this.handleContextRestore=function(){e.state===Uc.PAUSED&&(e.state=Uc.PLAYING)},this.canvas.addEventListener("webglcontextlost",this.handleContextLoss),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestore)},e}();function qc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Wc=/*#__PURE__*/function(){function e(e,t,n,i){this.videoOutput=void 0,this.container=void 0,this.idleVideo=null,this.cachedVideo=null,this.idleVideoConfig=null,this.videoTransitionConfig=null,this.CROSSFADE_DURATION=500,this.isTransitioning=!1,this.isShowingIdleVideo=!0,this.bufferCheckAnimationId=null,this.lastBufferCheckTime=0,this.sessionStarted=!1,this.isShowingCachedVideo=!1,this.onIdleVideoShown=void 0,this.onIdleVideoHidden=void 0,this.onSpeakingStartCallback=null,this.onSpeakingEndCallback=null,this.videoOutput=e,this.container=t,this.videoTransitionConfig=n}e.createVideoOutput=function(t,n){try{return Promise.resolve(Bc.create(t,n)).then(function(i){var r=new e(i,t,n.transition,n.effects);return Promise.resolve(r.setupIdleVideo(n.idleVideo,n)).then(function(){return Promise.resolve(r.setupCachedVideo(n)).then(function(){return r})})})}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.setupIdleVideo=function(e,t){try{var n=this;n.idleVideoConfig=e,n.idleVideo=document.createElement("video"),n.idleVideo.src=e.src,n.idleVideo.width=t.width,n.idleVideo.height=t.height,n.idleVideo.style.position="absolute",n.idleVideo.style.top="0",n.idleVideo.style.left="0",n.idleVideo.style.width="100%",n.idleVideo.style.height="100%",n.idleVideo.style.objectFit="cover",n.idleVideo.style.maxWidth="100%",n.idleVideo.style.backgroundColor=t.backgroundColor||"#000000",n.idleVideo.style.zIndex="1",n.idleVideo.style.pointerEvents="none",n.idleVideo.style.opacity="1",n.idleVideo.muted=!0,n.idleVideo.loop=!0,n.idleVideo.controls=!1,n.idleVideo.playsInline=!0,n.idleVideo.preload="auto","static"===getComputedStyle(n.container).position&&(n.container.style.position="relative"),n.container.appendChild(n.idleVideo);var i=qc(function(){return Promise.resolve(n.idleVideo.load()).then(function(){return Promise.resolve(n.idleVideo.play()).then(function(){})})},function(e){console.error("Failed to load idle video:",e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.setupCachedVideo=function(e){try{var t=this;return t.cachedVideo=document.createElement("video"),t.cachedVideo.src="",t.cachedVideo.width=e.width,t.cachedVideo.height=e.height,t.cachedVideo.style.position="absolute",t.cachedVideo.style.top="0",t.cachedVideo.style.left="0",t.cachedVideo.style.width="100%",t.cachedVideo.style.height="100%",t.cachedVideo.style.objectFit="cover",t.cachedVideo.style.maxWidth="100%",t.cachedVideo.style.zIndex="2",t.cachedVideo.style.pointerEvents="none",t.cachedVideo.style.opacity="0",t.cachedVideo.style.transition="opacity "+t.CROSSFADE_DURATION+"ms ease-in-out",t.cachedVideo.controls=!1,t.cachedVideo.playsInline=!0,t.cachedVideo.preload="auto",t.container.appendChild(t.cachedVideo),Promise.resolve()}catch(e){return Promise.reject(e)}},t.onSpeakingStart=function(e){this.onSpeakingStartCallback=e},t.onSpeakingEnd=function(e){this.onSpeakingEndCallback=e},t.startStreaming=function(e){void 0===e&&(e=!1),this.sessionStarted=!0,this.startBufferMonitoring(),this.videoOutput.startRenderingStreamingVideo(e)},t.stopBufferMonitoring=function(){this.bufferCheckAnimationId&&(cancelAnimationFrame(this.bufferCheckAnimationId),this.bufferCheckAnimationId=null),this.lastBufferCheckTime=0,this.sessionStarted=!1},t.getBufferLength=function(){return this.videoOutput.getBufferLength()},t.startBufferMonitoring=function(){var e=this;if(!this.bufferCheckAnimationId){this.lastBufferCheckTime=0;var t=function(n){n-e.lastBufferCheckTime>=100&&(e.sessionStarted&&e.videoOutput.getBufferLength()>0?e.hideIdleVideoBeforeStream():e.videoOutput.getStreamingStatus()||0!==e.videoOutput.getBufferLength()||e.showIdleVideoAfterStream(),e.lastBufferCheckTime=n),e.bufferCheckAnimationId=requestAnimationFrame(t)};this.bufferCheckAnimationId=requestAnimationFrame(t)}},t.toggleCacheVideoMute=function(){this.cachedVideo&&(this.cachedVideo.muted=!this.cachedVideo.muted)},t.playCachedVideo=function(e){try{var t=this;if(t.isShowingCachedVideo||!t.cachedVideo||!e||t.isTransitioning)return Promise.resolve();t.isShowingCachedVideo=!0;var n=qc(function(){return t.cachedVideo.src=e,t.cachedVideo.style.opacity="0",Promise.resolve(new Promise(function(e,n){t.cachedVideo.addEventListener("loadeddata",function(){return e()},{once:!0}),t.cachedVideo.addEventListener("error",function(){return n(new Error("Video failed to load"))},{once:!0}),t.cachedVideo.load()})).then(function(){return t.crossfadeFromIdleToCached(),Promise.resolve(t.cachedVideo.play()).then(function(){t.cachedVideo.addEventListener("ended",function(){try{return Promise.resolve(t.crossfadeFromCachedToIdle()).then(function(){return Promise.resolve(t.cleanupCachedVideo()).then(function(){return Promise.resolve(t.showIdleVideo()).then(function(){})})})}catch(e){return Promise.reject(e)}},{once:!0})})})},function(e){return console.error("Failed to play cached video:",e),t.cachedVideo.style.opacity="0",t.isShowingCachedVideo=!1,Promise.resolve(t.showIdleVideo()).then(function(){})});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.crossfadeFromIdleToCached=function(){try{var e=this;return e.idleVideo&&e.cachedVideo&&!e.isTransitioning?(e.isTransitioning=!0,e.idleVideo.style.opacity="1",e.cachedVideo.style.opacity="1",Promise.resolve(new Promise(function(t){return setTimeout(t,e.CROSSFADE_DURATION)})).then(function(){e.idleVideo&&(e.idleVideo.style.opacity="0"),e.isShowingIdleVideo=!1,null==e.onIdleVideoHidden||e.onIdleVideoHidden(),null==e.onSpeakingStartCallback||e.onSpeakingStartCallback(),e.isTransitioning=!1})):Promise.resolve()}catch(e){return Promise.reject(e)}},t.crossfadeFromCachedToIdle=function(){try{var e=function(){return t.cachedVideo.style.opacity="0",Promise.resolve(new Promise(function(e){return setTimeout(e,t.CROSSFADE_DURATION)})).then(function(){t.isShowingIdleVideo=!0,null==t.onSpeakingEndCallback||t.onSpeakingEndCallback(),null==t.onIdleVideoShown||t.onIdleVideoShown(),t.isTransitioning=!1})},t=this;if(!t.idleVideo||!t.cachedVideo||t.isTransitioning)return Promise.resolve();t.isTransitioning=!0,t.idleVideo.style.opacity="1";var n=function(){if(t.idleVideo.paused){var e=qc(function(){return Promise.resolve(t.idleVideo.play()).then(function(){})},function(e){console.error("Failed to play idle video during crossfade:",e)});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},t.cleanupCachedVideo=function(){try{var e=this;return e.cachedVideo&&(e.cachedVideo.pause(),e.cachedVideo.currentTime=0,e.cachedVideo.src="",e.cachedVideo.style.opacity="0"),e.isShowingCachedVideo=!1,Promise.resolve()}catch(e){return Promise.reject(e)}},t.hideIdleVideo=function(){var e,t;this.idleVideo&&this.isShowingIdleVideo&&(null==(e=this.onSpeakingStartCallback)||e.call(this),this.isShowingIdleVideo=!1,this.idleVideo.style.opacity="0",null==(t=this.onIdleVideoHidden)||t.call(this))},t.hideIdleVideoBeforeStream=function(){var e,t;this.idleVideo&&this.isShowingIdleVideo&&(null==(e=this.onSpeakingStartCallback)||e.call(this),this.idleVideo.style.transition="opacity "+this.CROSSFADE_DURATION+"ms ease-in-out",this.isShowingIdleVideo=!1,this.idleVideo.style.opacity="0",null==(t=this.onIdleVideoHidden)||t.call(this))},t.setEventCallbacks=function(e){this.onIdleVideoShown=e.onIdleVideoShown,this.onIdleVideoHidden=e.onIdleVideoHidden},t.getStreamingStatus=function(){return this.videoOutput.getStreamingStatus()},t.showIdleVideo=function(){try{var e=this;return!e.idleVideo||e.isShowingIdleVideo?Promise.resolve():(null==e.onSpeakingEndCallback||e.onSpeakingEndCallback(),null==e.onIdleVideoShown||e.onIdleVideoShown(),e.isShowingIdleVideo=!0,e.idleVideo.style.opacity="1",Promise.resolve(qc(function(){var t=function(){if(e.idleVideo.paused)return Promise.resolve(e.idleVideo.play()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(e){console.error("failed to play idle video:",e)})))}catch(e){return Promise.reject(e)}},t.showIdleVideoAfterStream=function(){try{var e=this;return!e.idleVideo||e.isShowingIdleVideo?Promise.resolve():(null==e.onSpeakingEndCallback||e.onSpeakingEndCallback(),null==e.onIdleVideoShown||e.onIdleVideoShown(),e.isShowingIdleVideo=!0,e.idleVideo.style.opacity="1",Promise.resolve(qc(function(){var t=function(){if(e.idleVideo.paused)return Promise.resolve(e.idleVideo.play()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(e){console.error("failed to play idle video:",e)})))}catch(e){return Promise.reject(e)}},t.addFrame=function(e,t,n){try{var i=function(e){var i=s?new Uint8Array(e):e;return r.videoOutput.addFrame(i,t,n)},r=this,s=e instanceof Blob;return Promise.resolve(s?Promise.resolve(e.arrayBuffer()).then(i):i(new Uint8Array(e)))}catch(e){return Promise.reject(e)}},t.clearFrame=function(){return this.showIdleVideo(),this.videoOutput.clearFrame()},t.toggleStream=function(e){try{return Promise.resolve(this.videoOutput.toggleStream(e))}catch(e){return Promise.reject(e)}},t.interrupt=function(e){this.videoOutput.interrupt(e)},t.destroy=function(){this.bufferCheckAnimationId&&(cancelAnimationFrame(this.bufferCheckAnimationId),this.bufferCheckAnimationId=null),this.idleVideo&&(this.idleVideo.pause(),this.idleVideo.parentNode&&this.idleVideo.parentNode.removeChild(this.idleVideo),this.idleVideo=null),this.cachedVideo&&(this.cachedVideo.pause(),this.cachedVideo.parentNode&&this.cachedVideo.parentNode.removeChild(this.cachedVideo),this.cachedVideo=null),this.videoOutput.destroy()},e}(),Hc={vadSilenceThresholdSecs:1.5,noiseSuppression:!0,vadThreshold:.4,minSpeechDurationMs:100,minSilenceDurationMs:100},zc={tolerance:40,softCorrectionThreshold:100,hardCorrectionThreshold:200,historyLength:50,maxCorrectionRate:.02,correctionCoolDown:500,correctionFadeTime:1e3,minAudioBuffer:100,maxAudioBuffer:500,minVideoBuffer:3,maxVideoBuffer:10};function Gc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Kc=/*#__PURE__*/function(){function e(e,t,n,i,r,s,o,a,c){var d=this,l=this,u=this,p=this,v=this,b=this,C=this,E=this;this.options=void 0,this.microphoneAccess=void 0,this.connection=void 0,this.idleVideo=void 0,this.wakeLock=void 0,this.user=void 0,this.audioOutput=void 0,this.videoOutput=void 0,this.headInfo=void 0,this.status="connecting",this.volume=1,this.sessionStarted=!1,this.messageCounter=0,this.syncController=void 0,this.avController=void 0,this.monitor=null,this.microphone=null,this.videoFrameQueue=[],this.cachedResponseQueue=[],this.suggestionsQueue=[],this.onOutputWorkletMessage=function(e){E.avController.handleAudioWorkletMessage(e.data)},this.handleMessage=function(e){try{if(d.options.onMessage({timestamp:e.timestamp,sender:e.speaker,text:e.text,visible:e.visible}),"suggestions"in e){var t=e.suggestions||[];t.length>1&&(d.suggestionsQueue=t)}return Promise.resolve()}catch(e){return Promise.reject(e)}},this.handleStreamError=function(e){var t=e.error_type;if(t&&["resource_exhausted","deadline_exceeded","inactivity_timeout"].includes(t)){if("resource_exhausted"===t){if(!E.avController.isPlaying)return void E.options.onError({message:"The system is experiencing heavy traffic. Please try again later.",endConversation:!0,type:"toast"});E.options.onError({message:"We are experiencing heavy traffic and we can't deliver the response, try again",endConversation:!1,type:"toast"})}else if("deadline_exceeded"===t)E.options.onError({message:"We are experiencing heavy traffic and we can't deliver the response, try again",endConversation:!1,type:"toast"});else if("inactivity_timeout"===t)return void E.options.onTimeout()}else E.options.onError({message:"A connection error occurred. Please try again.",endConversation:!0,type:"toast"})},this.handleStreamingEvent=function(e){try{var t,n=function(n){if(t)return n;if("metadata"===e.type&&("start"!==e.metadata_type&&"end"!==e.metadata_type||(l.avController.isStoppingAV=!1,l.videoOutput.toggleStream("start"===e.metadata_type),"start"===e.metadata_type&&(l.videoFrameQueue=[],l.syncController.resetTiming()))),"audio_frame"===e.type){if(l.avController.isStoppingAV)return;l.handleAudioFrame(e)}if("video_frame"===e.type){if(l.avController.isStoppingAV)return;l.handleVideoFrame(e)}l.avController.playAudioVideo()};if("error"===e.type)return l.handleStreamError(e),Promise.resolve();var i=function(){if("cache"===e.type){var n,i,r=function(){t=1},s={id:e.session_id||Math.random().toString(36).substring(2),timestamp:new Date,isSent:!0,visible:!0,event:exports.EventType.TEXT,user_id:e.user_id,username:e.username,text:null!=(n=e.text)?n:"",speaker:"ai",session_id:e.session_id||"",suggestions:null!=(i=e.suggestions)?i:[]},o=function(){if(l.sessionStarted)return Promise.resolve(l.videoOutput.playCachedVideo(e.video_url||"")).then(function(){l.handleMessage(s)});l.cachedResponseQueue.push({video_url:e.video_url||"",textEventData:s})}();return o&&o.then?o.then(r):r()}}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(e){return Promise.reject(e)}},this.handleVideoFrame=function(e){try{var t;return e.frame_data||u.videoFrameQueue.push({timeStamp:e.event_timestamp_ms,isKeyframe:null!=(t=e.is_keyframe)&&t}),Promise.resolve()}catch(e){return Promise.reject(e)}},this.handleBinaryData=function(e){try{if(p.videoFrameQueue.length>0){var t=p.videoFrameQueue.shift();p.updateStatus("connected"),p.videoOutput.addFrame(e.data,t.timeStamp,t.isKeyframe),p.syncController.updateVideoTime(t.timeStamp)}return Promise.resolve()}catch(e){return Promise.reject(e)}},this.handleAudioFrame=function(e){try{if(!e.frame_data)return console.warn("Audio frame data is missing in the event:",e),Promise.resolve();var t,n=function(e){for(var t=window.atob(e),n=t.length,i=new Uint8Array(n),r=0;r<n;r++)i[r]=t.charCodeAt(r);return i.buffer}(e.frame_data);return t=new Int16Array(n),v.audioOutput.gain.gain.value=v.volume,v.audioOutput.worklet.port.postMessage({type:"clearInterrupted"}),v.audioOutput.worklet.port.postMessage({type:"buffer",buffer:t,time_stamp:e.event_timestamp_ms}),v.syncController.updateAudioTime(e.event_timestamp_ms),Promise.resolve()}catch(e){return Promise.reject(e)}},this.onMessage=function(e){try{switch(e.event){case exports.EventType.JOIN:return Promise.resolve();case exports.EventType.TEXT:if(m(e)){var t=e;t.timestamp=new Date,t.isSent=!0,t.visible=!0,b.handleMessage(t)}return Promise.resolve();case exports.EventType.RESPONSE:if(g(e)){var n=e;n.timestamp=new Date,n.speaker="ai",n.isSent=!0,b.handleMessage(n)}return Promise.resolve();case exports.EventType.STREAMING:return f(e)&&b.handleStreamingEvent(e),Promise.resolve();case exports.EventType.BINARY:y(e)&&b.handleBinaryData(e);case exports.EventType.TIMEOUT_WARNING:return k(e)&&b.options.onTimeoutWarning(),Promise.resolve();case exports.EventType.TIME_OUT:return T(e)&&b.options.onTimeout(),Promise.resolve();case exports.EventType.KEEP_SESSION:return S(e)&&b.options.onKeepSession({granted:e.granted}),Promise.resolve();default:return console.warn("Unhandled event type:",e.event),Promise.resolve()}}catch(e){return Promise.reject(e)}},this.handleStopVideoEvents=function(){E.options.onSpeakingEnd(),E.suggestionsQueue.length>0&&(E.options.onSuggestions({suggestions:E.suggestionsQueue}),E.suggestionsQueue=[])},this.endSessionWithDetails=function(e){try{return"connected"!==C.status&&"connecting"!==C.status?Promise.resolve():(C.sessionStarted=!1,C.updateStatus("disconnecting"),Promise.resolve(C.handleEndSession()).then(function(){var t;C.updateStatus("disconnected"),null==(t=C.monitor)||t.stop(),C.options.onDisconnect(e)}))}catch(e){return Promise.reject(e)}},this.options=e,this.microphoneAccess=t,this.connection=n,this.idleVideo=i,this.wakeLock=r,this.user=s,this.audioOutput=o,this.videoOutput=a,this.headInfo=c,this.syncController=new Dc(zc),this.avController=new h(this.syncController,this.audioOutput,this.videoOutput),this.options.onConnect({userId:n.userId,headInfo:{name:this.headInfo.name,phrases:this.headInfo.phrases,language:this.headInfo.language,avatar:this.headInfo.avatarSrc},microphoneAccess:t}),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onMessage(this.onMessage),this.videoOutput.onSpeakingStart(this.options.onSpeakingStart),this.videoOutput.onSpeakingEnd(this.handleStopVideoEvents),this.updateStatus("connected"),this.audioOutput.worklet.port.onmessage=this.onOutputWorkletMessage,this.handleIOSSilentMode(),this.startLatencyMonitoring()}e.getFullOptions=function(e){return n({username:"anonymous",environment:"production",mode:"default",apiKey:"",microphoneProvider:"azure",microphoneOptions:{onMicrophoneError:function(){},onMicrophoneStatusChange:function(){},onMicrophoneSpeechRecognitionResult:function(){}},elevenLabsOptions:Hc,onStatusChange:function(){},onConnect:function(){},onDisconnect:function(){},onMessage:function(){},onMuteStatusChange:function(){},onSuggestions:function(){},onSpeakingStart:function(){},onSpeakingEnd:function(){},onStoppingEnd:function(){},onTimeout:function(){},onTimeoutWarning:function(){},onKeepSession:function(){},onError:function(){}},e)},e.startDigitalHuman=function(t){try{var n=function(){var n=C(s);return Gc(function(){return Promise.resolve(Fc.loginUser(r,"Password1",n,o,a)).then(function(r){return f=r,Promise.resolve(P.getIdleVideo(n,o,a)).then(function(r){return Promise.resolve(f.getHeadDetails(d)).then(function(l){return Promise.resolve(r.getAvatarSrc(n,o,a)).then(function(n){l.avatarSrc=n;var g=h||l.language||navigator.language;return l.language=g,Promise.resolve(w.create({environment:s,orgId:o,headId:a,token:f.accessToken,mode:c,apiKey:d,language:g})).then(function(n){function s(){return Promise.resolve(Promise.all([u.createAudioOutput(k),Wc.createVideoOutput(o,{width:o.getBoundingClientRect().width,height:o.getBoundingClientRect().height,frameRate:30,backgroundColor:"transparent",format:"jpeg",idleVideo:{src:r.idleVideoSource,enabled:!0},transition:null!=p?p:exports.VideoTransitionType.NONE})])).then(function(t){return new e(i,a,v,r,T,f,b=t[0],y=t[1],l)})}v=n;var o=t.element,a=!1,c=function(){if("custom"!==m){var e=Gc(function(){return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:!0})).then(function(e){e.getTracks().forEach(function(e){e.stop()}),a=!0})},function(){a=!1});if(e&&e.then)return e.then(function(){})}else a=!0}();return c&&c.then?c.then(s):s()})})})})})},function(e){var t,n;return g({status:"disconnected"}),null==(t=v)||t.close(),Promise.resolve(null==(n=b)?void 0:n.close()).then(function(){var t;return Promise.resolve(null==(t=y)?void 0:t.destroy()).then(function(){function t(){throw e}var n=Gc(function(){var e;return Promise.resolve(null==(e=T)?void 0:e.release()).then(function(){T=null})},function(){});return n&&n.then?n.then(t):t()})})})},i=e.getFullOptions(t),r=i.username,s=i.environment,o=i.orgId,a=i.headId,c=i.mode,d=i.apiKey,l=i.allowWakeLock,h=i.language,p=i.fadeTransitionsType,m=i.microphoneProvider,g=i.onStatusChange;g({status:"connecting"});var f=null,v=null,y=null,b=null,k={sampleRate:16e3,format:"pcm"},T=null,S=function(){if(null==l||l){var e=Gc(function(){return Promise.resolve(navigator.wakeLock.request("screen")).then(function(e){T=e})},function(){});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(S&&S.then?S.then(n):n())}catch(e){return Promise.reject(e)}},e.getBackgroundVideo=function(e){try{var t=e.environment,n=e.orgId,i=e.headId,r=C(null!=t?t:"production");return Promise.resolve(P.getIdleVideo(null!=r?r:"https://chat-origin.api.unith.live",n,i)).then(function(e){return e.idleVideoSource})}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.startLatencyMonitoring=function(){this.monitor=new _c(this.connection,{onUpdate:function(e){}})},t.handleIOSSilentMode=function(){var e=this;/iPad|iPhone|iPod/.test(navigator.userAgent)&&this.audioOutput.context.addEventListener("statechange",function(){"suspended"===e.audioOutput.context.state&&(console.warn("Audio context suspended - likely due to iOS silent mode"),e.audioOutput.context.resume())})},t.getUserId=function(){return this.connection.userId},t.handleEndSession=function(){try{return this.connection.close(),Promise.resolve()}catch(e){return Promise.reject(e)}},t.updateStatus=function(e){e!==this.status&&(this.status=e,this.options.onStatusChange({status:e}))},t.toggleMute=function(){try{var e=this;return e.volume=0===e.volume?1:0,e.audioOutput.toggleMute(),e.videoOutput.toggleCacheVideoMute(),e.options.onMuteStatusChange({isMuted:0===e.volume}),Promise.resolve(e.volume)}catch(e){return Promise.reject(e)}},t.startSession=function(){try{var e=function(){return Promise.resolve(t.avController.startPlayback(!0)).then(function(){function e(){function e(){return t.connection}var n=function(){var e;if("custom"!==t.options.microphoneProvider)return Promise.resolve(Oc.initializeMicrophone(t.options.microphoneOptions,t.options.microphoneProvider,null!=(e=t.options.elevenLabsOptions)?e:Hc,t.user,t.headInfo,t.microphoneAccess,t.sendMessage)).then(function(e){t.microphone=e})}();return n&&n.then?n.then(e):e()}var n=function(){if(t.cachedResponseQueue.length){var e=t.cachedResponseQueue[t.cachedResponseQueue.length-1];return Promise.resolve(new Promise(function(e){return setTimeout(e,50)})).then(function(){return Promise.resolve(t.videoOutput.playCachedVideo(e.video_url)).then(function(){t.handleMessage(e.textEventData)})})}}();return n&&n.then?n.then(e):e()})},t=this;t.sessionStarted=!0;var n=function(){if("suspended"===t.audioOutput.context.state)return Promise.resolve(t.audioOutput.context.resume()).then(function(){})}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},t.toggleMicrophone=function(){try{var e=function(){if(!t.microphoneAccess&&"OFF"===t.microphone.status())throw new Error("Microphone access not granted.");return Promise.resolve(t.microphone.toggleMicrophone()).then(function(){})},t=this;if("custom"===t.options.microphoneProvider)throw new Error("Cannot toggle microphone for custom provider.");var n=function(){var e;if(!t.microphone)return Promise.resolve(Oc.initializeMicrophone(t.options.microphoneOptions,t.options.microphoneProvider,null!=(e=t.options.elevenLabsOptions)?e:Hc,t.user,t.headInfo,t.microphoneAccess,t.sendMessage)).then(function(e){t.microphone=e})}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},t.getMicrophoneStatus=function(){return this.microphone?this.microphone.status():"OFF"},t.endSession=function(){return this.endSessionWithDetails({reason:"user"})},t.sendMessage=function(e){if(!this.connection)throw new Error("Connection not established");var t=this.user.id+"::"+this.user.orgId+"::"+this.user.headId+"::"+this.user.sessionId.toString().padStart(5,"0"),n={id:this.messageCounter++,timestamp:(new Date).toISOString(),speaker:"user",text:e,isSent:!1,user_id:this.user.id,username:this.user.username,event:exports.EventType.TEXT,visible:!0,session_id:t};return this.connection.sendMessage(n)},t.keepSession=function(){if(!this.connection)throw new Error("Connection not established");var e=this.user.id+"::"+this.user.orgId+"::"+this.user.headId+"::"+this.user.sessionId.toString().padStart(5,"0"),t={id:this.messageCounter,timestamp:(new Date).toISOString(),speaker:"user",text:"",isSent:!1,user_id:this.user.id,username:this.user.username,event:exports.EventType.KEEP_SESSION,visible:!0,session_id:e};return this.connection.sendMessage(t)},e}();exports.Conversation=Kc,exports.isBinaryEvent=y,exports.isConversationEndEvent=function(e){return e.event===exports.EventType.CONVERSATION_END},exports.isJoinEvent=p,exports.isKeepSessionEvent=S,exports.isPongEvent=b,exports.isResponseEvent=g,exports.isStreamingErrorEvent=v,exports.isStreamingEvent=f,exports.isTextEvent=m,exports.isTimeoutEvent=T,exports.isTimeoutWarningEvent=k;
|
|
1
|
+
function e(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,t}function t(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 n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},n.apply(null,arguments)}function i(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var r,s,o=new Map,a=(r="audio-concat-processor",s='\nconst decodeTable = [0,132,396,924,1980,4092,8316,16764];\n\nexport function decodeSample(muLawSample) {\n let sign;\n let exponent;\n let mantissa;\n let sample;\n muLawSample = ~muLawSample;\n sign = (muLawSample & 0x80);\n exponent = (muLawSample >> 4) & 0x07;\n mantissa = muLawSample & 0x0F;\n sample = decodeTable[exponent] + (mantissa << (exponent+3));\n if (sign !== 0) sample = -sample;\n\n return sample;\n}\n\nclass AudioConcatProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffers = [];\n this.cursor = 0;\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n this.currentBufferStartSample = 0;\n this.wasInterrupted = false;\n this.playing = false;\n this.finished = false;\n\n this.playbackRate = 1.0;\n this.adjustUntilSample = null;\n this.sampleCounter = 0;\n this.format = { sampleRate: 48000 };\n\n // Time synchronization properties\n this.playbackStartTime = null;\n this.totalSamplesPlayed = 0;\n \n // Drift correction parameters\n this.maxCorrectionRate = 0.1; // Maximum 10% speed adjustment\n this.correctionSmoothness = 0.95; // How smoothly to apply corrections (0-1)\n this.targetPlaybackRate = 1.0;\n\n this.port.onmessage = ({ data }) => {\n switch (data.type) {\n case "setFormat":\n this.format = data.format;\n break;\n\n case "buffer":\n this.wasInterrupted = false;\n \n const bufferData = this.format.encoding === "ulaw"\n ? new Uint8Array(data.buffer)\n : new Int16Array(data.buffer);\n \n // Store buffer with its timestamp\n this.buffers.push({\n buffer: bufferData,\n timestamp: data.timestamp_ms\n });\n break;\n \n case "startPlayback":\n this.playing = true;\n this.playbackStartTime = currentTime;\n this.totalSamplesPlayed = 0;\n this.sampleCounter = 0;\n break;\n \n case "stopPlayback":\n this.playing = false;\n this.finished = true;\n \n // Discard all queued buffers\n this.buffers = [];\n \n // Clear current buffer and reset cursor\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n this.cursor = 0;\n \n // Reset playback rate adjustments\n this.playbackRate = 1.0;\n this.adjustUntilSample = null;\n this.targetPlaybackRate = 1.0;\n \n // Notify that playback has stopped\n this.port.postMessage({ \n type: "process", \n finished: true,\n stopped: true\n });\n break;\n\n case "adjustPlaybackRate":\n this.playbackRate = data.rate;\n this.adjustUntilSample = this.sampleCounter + Math.floor(this.format.sampleRate * data.duration);\n break;\n \n case "reset":\n this.playing = false;\n this.finished = false;\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n this.currentBufferStartSample = 0;\n this.cursor = 0;\n this.buffers = [];\n this.playbackStartTime = null;\n this.totalSamplesPlayed = 0;\n this.targetPlaybackRate = 1.0;\n break;\n\n case "interrupt":\n this.wasInterrupted = true;\n break;\n\n case "clearInterrupted":\n if (this.wasInterrupted) {\n this.wasInterrupted = false;\n this.buffers = [];\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n }\n break;\n }\n };\n }\n\n // Calculate the expected timestamp based on samples played\n getExpectedTimestamp() {\n if (!this.playbackStartTime) return 0;\n \n // Convert samples to milliseconds\n const samplesPlayedMs = (this.totalSamplesPlayed / this.format.sampleRate) * 1000;\n return samplesPlayedMs;\n }\n\n // Calculate the actual timestamp of current playback position\n getCurrentActualTimestamp() {\n if (!this.currentBufferTimestamp) return 0;\n \n // Current position within the buffer in samples\n const samplesIntoBuffer = Math.floor(this.cursor);\n \n // Convert buffer position to milliseconds (assuming buffer covers specific time duration)\n // Each buffer typically represents a fixed time duration\n const bufferDurationMs = (this.currentBuffer.length / this.format.sampleRate) * 1000;\n const progressThroughBuffer = samplesIntoBuffer / this.currentBuffer.length;\n \n return this.currentBufferTimestamp + (progressThroughBuffer * bufferDurationMs);\n }\n\n // Calculate timing drift and adjust playback rate accordingly\n calculateDriftCorrection() {\n if (!this.currentBufferTimestamp || !this.playbackStartTime) {\n return 1.0;\n }\n\n const expectedTimestamp = this.getExpectedTimestamp();\n const actualTimestamp = this.getCurrentActualTimestamp();\n \n // Calculate drift in milliseconds\n const drift = actualTimestamp - expectedTimestamp;\n \n // Convert drift to a playback rate adjustment\n // Positive drift means we\'re ahead - slow down\n // Negative drift means we\'re behind - speed up\n let correctionFactor = 1.0;\n \n if (Math.abs(drift) > 10) { // Only correct if drift > 10ms\n // Calculate correction rate based on drift\n // More drift = more correction, but capped at maxCorrectionRate\n const driftRatio = Math.min(Math.abs(drift) / 1000, this.maxCorrectionRate);\n \n if (drift > 0) {\n // We\'re ahead, slow down\n correctionFactor = 1.0 - driftRatio;\n } else {\n // We\'re behind, speed up\n correctionFactor = 1.0 + driftRatio;\n }\n \n // Apply smoothing to avoid jarring rate changes\n this.targetPlaybackRate = this.targetPlaybackRate * this.correctionSmoothness + \n correctionFactor * (1 - this.correctionSmoothness);\n } else {\n // Gradually return to normal speed when drift is small\n this.targetPlaybackRate = this.targetPlaybackRate * this.correctionSmoothness + \n 1.0 * (1 - this.correctionSmoothness);\n }\n\n return this.targetPlaybackRate;\n }\n\n process(_, outputs, parameters) {\n const output = outputs[0][0];\n\n if (!this.playing) {\n output.fill(0);\n return true;\n }\n\n let finished = false;\n\n for (let i = 0; i < output.length; i++) {\n // If no buffer is ready, get the next one\n if (!this.currentBuffer) {\n if (this.buffers.length === 0) {\n finished = true;\n break;\n }\n \n const bufferData = this.buffers.shift();\n this.currentBuffer = bufferData.buffer;\n this.currentBufferTimestamp = bufferData.timestamp;\n this.currentBufferStartSample = this.totalSamplesPlayed;\n this.cursor = 0;\n }\n\n // Calculate drift correction for timing synchronization\n const driftCorrectedRate = this.calculateDriftCorrection();\n \n // Apply manual playback rate adjustments if active\n let finalPlaybackRate = driftCorrectedRate;\n if (this.adjustUntilSample !== null && this.sampleCounter < this.adjustUntilSample) {\n finalPlaybackRate *= this.playbackRate;\n } else if (this.adjustUntilSample !== null) {\n this.playbackRate = 1.0;\n this.adjustUntilSample = null;\n }\n\n const idx = Math.floor(this.cursor);\n const nextIdx = Math.min(idx + 1, this.currentBuffer.length - 1);\n\n let s1 = this.currentBuffer[idx];\n let s2 = this.currentBuffer[nextIdx];\n if (this.format.encoding === "ulaw") {\n s1 = decodeSample(s1);\n s2 = decodeSample(s2);\n }\n\n const frac = this.cursor - idx;\n const interpolated = s1 * (1 - frac) + s2 * frac;\n output[i] = interpolated / 32768;\n\n this.cursor += finalPlaybackRate;\n this.sampleCounter++;\n this.totalSamplesPlayed++;\n\n if (this.cursor >= this.currentBuffer.length) {\n this.currentBuffer = null;\n this.currentBufferTimestamp = null;\n }\n }\n\n if (this.finished !== finished) {\n this.finished = finished;\n this.port.postMessage({ \n type: "process", \n finished,\n // Optional: send timing info for debugging\n timing: {\n expectedTimestamp: this.getExpectedTimestamp(),\n actualTimestamp: this.getCurrentActualTimestamp(),\n playbackRate: this.targetPlaybackRate\n }\n });\n }\n\n return true;\n }\n}\nregisterProcessor("audio-concat-processor", AudioConcatProcessor);\n',function(e){try{var t,n=function(n){return t?n:i(function(){var t="data:application/javascript;base64,"+btoa(s);return Promise.resolve(e.addModule(t)).then(function(){o.set(r,t)})},function(){throw new Error("Failed to load the "+r+" worklet module. Make sure the browser supports AudioWorklets.")})},a=o.get(r);if(a)return Promise.resolve(e.addModule(a));var c=new Blob([s],{type:"application/javascript"}),d=URL.createObjectURL(c),l=i(function(){return Promise.resolve(e.addModule(d)).then(function(){o.set(r,d),t=1})},function(){URL.revokeObjectURL(d)});return Promise.resolve(l&&l.then?l.then(n):n(l))}catch(e){return Promise.reject(e)}});function c(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var d,l,u=/*#__PURE__*/function(){function e(e,t,n,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this._isMuted=!1,this.context=e,this.analyser=t,this.gain=n,this.worklet=i}e.createAudioOutput=function(t){var n=t.sampleRate,i=t.format;try{var r=null;return Promise.resolve(c(function(){var t=(r=new AudioContext({sampleRate:n})).createAnalyser(),s=r.createGain();return s.connect(t),t.connect(r.destination),Promise.resolve(a(r.audioWorklet)).then(function(){var n=new AudioWorkletNode(r,"audio-concat-processor");n.port.postMessage({type:"setFormat",format:i}),n.connect(s);var o=new e(r,t,s,n);return Promise.resolve(o.ensureIOSCompatibility()).then(function(){return o})})},function(e){var t;throw null==(t=r)||t.close(),e}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.ensureIOSCompatibility=function(){try{var e=this;if(/iPad|iPhone|iPod/.test(navigator.userAgent)){var t=e.context.createBuffer(1,1,e.context.sampleRate),n=e.context.createBufferSource();n.buffer=t,n.connect(e.context.destination),n.start()}return Promise.resolve()}catch(e){return Promise.reject(e)}},t.getOutputDevice=function(){try{var e=this;return Promise.resolve(c(function(){var t=e.context.sinkId||"";return Promise.resolve(navigator.mediaDevices.enumerateDevices()).then(function(e){var n=e.filter(function(e){return"audiooutput"===e.kind});return""===t?n.find(function(e){return"default"===e.deviceId})||n[0]||null:n.find(function(e){return e.deviceId===t})||null})},function(e){return console.error("Error getting output device:",e),null}))}catch(e){return Promise.reject(e)}},t.getAvailableOutputDevices=function(){try{return Promise.resolve(c(function(){return Promise.resolve(navigator.mediaDevices.enumerateDevices()).then(function(e){return e.filter(function(e){return"audiooutput"===e.kind})})},function(e){return console.error("Error enumerating devices:",e),[]}))}catch(e){return Promise.reject(e)}},t.mute=function(){this.gain.gain.value=0,this._isMuted=!0},t.unmute=function(){this.gain.gain.value=1,this._isMuted=!1},t.toggleMute=function(){return this._isMuted?this.unmute():this.mute(),this._isMuted},t.close=function(){try{return Promise.resolve(this.context.close()).then(function(){})}catch(e){return Promise.reject(e)}},e}(),h=/*#__PURE__*/function(){function e(e,t,n){var i=this;this.syncController=void 0,this.audioOutput=void 0,this.videoOutput=void 0,this.initialized=!1,this.isPlaying=!1,this.isPlayingAudio=!1,this.isPlayingVideo=!1,this.isStoppingAV=!1,this.handleAudioWorkletMessage=function(e){"process"===e.type&&(i.isPlayingAudio=!1,i.isPlayingVideo||(i.isPlaying=!1),i.audioOutput.worklet.port.postMessage({type:"reset"}))},this.syncController=e,this.audioOutput=t,this.videoOutput=n,this.videoOutput.setEventCallbacks({onIdleVideoShown:function(){},onIdleVideoHidden:function(){i.isPlayingVideo=!1,i.isPlayingAudio||(i.isPlaying=!1),i.videoOutput.stopBufferMonitoring()}})}var t=e.prototype;return t.updatePlayingState=function(e){this.isPlaying=e,this.isPlayingAudio=e,this.isPlayingVideo=e},t.toggleStoppingVideo=function(e){this.isStoppingAV=e},t.startPlayback=function(e){void 0===e&&(e=!1);try{var t=this;return t.isPlaying?Promise.resolve():(e&&(t.initialized=e),Promise.resolve(t.audioOutput.context.resume()).then(function(){t.updatePlayingState(!0),t.videoOutput.startStreaming(e),t.audioOutput.worklet.port.postMessage({type:"startPlayback"})}))}catch(e){return Promise.reject(e)}},t.playAudioVideo=function(){try{var e=this;if(!e.initialized)return Promise.resolve();if(e.isPlaying||e.isStoppingAV)return Promise.resolve();var t=e.videoOutput.getBufferLength();return e.startPlayback(!0),t>=6&&e.startPlayback(),Promise.resolve()}catch(e){return Promise.reject(e)}},e}();function p(e){return e.event===exports.EventType.JOIN}function m(e){return e.event===exports.EventType.TEXT}function g(e){return e.event===exports.EventType.RESPONSE}function f(e){return e.event===exports.EventType.STREAMING}function v(e){return e.event===exports.EventType.STREAMING&&e.type===exports.StreamingEventType.ERROR}function y(e){return e.event===exports.EventType.BINARY}function b(e){return e.type===exports.EventType.PONG}function k(e){return e.event===exports.EventType.TIMEOUT_WARNING}function T(e){return e.event===exports.EventType.TIME_OUT}function S(e){return e.event===exports.EventType.KEEP_SESSION}function C(e){switch(e){case"production":default:return"https://chat-api.unith.ai";case"staging":return"https://chat-api.stg.unith.live";case"development":return"https://chat-api.dev.unith.live"}}function E(e){return!!e.event}exports.EventType=void 0,(d=exports.EventType||(exports.EventType={})).TEXT="text",d.CONVERSATION_END="conversation_end",d.JOIN="join",d.ERROR="error",d.TIME_OUT="timeout",d.UNITH_NLP_EXCEPTION="unith_nlp_exception",d.ANALYTICS="analytics-userFeedback",d.CHOICE="choice",d.TIMEOUT_WARNING="timeout_warning",d.KEEP_SESSION="keep_session",d.RESPONSE="response",d.STREAMING="streaming",d.PING="ping",d.PONG="pong",d.BINARY="binary",exports.StreamingEventType=void 0,(l=exports.StreamingEventType||(exports.StreamingEventType={})).VIDEO_FRAME="video_frame",l.AUDIO_FRAME="audio_frame",l.METADATA="metadata",l.ERROR="error",l.CACHE="cache";var w=/*#__PURE__*/function(){function e(e,t){var n=this;this.socket=void 0,this.userId=void 0,this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onPingPongCallback=null,this.socket=e,this.userId=t,this.socket.addEventListener("error",function(e){n.disconnect({reason:"error",message:"The connection was closed due to a websocket error.",context:e})}),this.socket.addEventListener("close",function(e){n.disconnect({reason:"error",message:e.reason||"The connection was closed by the server.",context:e})}),this.socket.addEventListener("message",function(e){try{var t;if(b(t=e.data instanceof Blob||e.data instanceof ArrayBuffer?{event:exports.EventType.BINARY,user_id:"",username:"",data:e.data}:JSON.parse(e.data))){if(!n.onPingPongCallback)return;return void n.onPingPongCallback(t)}if(!E(t))return;n.onMessageCallback?n.onMessageCallback(t):n.queue.push(t)}catch(e){}})}e.create=function(t){try{var n=null,i=function(e){switch(e){case"production":default:return"wss://stream-api.unith.ai/stream-hub";case"staging":return"wss://stream-api.stg.unith.live/stream-hub";case"development":return"wss://stream-api.dev.unith.live/stream-hub"}}(t.environment);return Promise.resolve(function(r,s){try{var o=(n=new WebSocket(i+"/"+t.orgId+"/"+t.headId),Promise.resolve(new Promise(function(e,i){n.addEventListener("open",function(){n.send(JSON.stringify({token:t.token,api_key:t.apiKey,text_only:!0,format:"vp8",quality:"standard",crop:!1}))},{once:!0}),n.addEventListener("close",function(e){i()}),n.addEventListener("error",i),n.addEventListener("message",function(n){var r=JSON.parse(n.data);E(r)&&(p(r)?r.granted&&(null==t.onJoin||t.onJoin(),e(r.user_id)):v(r)&&i({type:"connection",message:"We are currently at full capacity. Please try again later."}))},{once:!0})})).then(function(t){return new e(n,t)}))}catch(e){return s(e)}return o&&o.then?o.then(void 0,s):o}(0,function(e){var t;throw null==(t=n)||t.close(),e}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.disconnect=function(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,null==(t=this.onDisconnectCallback)||t.call(this,e))},t.close=function(){this.socket.close()},t.sendMessage=function(e){this.socket.send(JSON.stringify(e))},t.sendPingEvent=function(e){this.onPingPongCallback?this.socket.send(JSON.stringify(e)):console.warn("Ping event sent without a callback set.")},t.onPingPong=function(e){this.onPingPongCallback=e},t.onMessage=function(e){this.onMessageCallback=e;var t=this.queue;this.queue=[],t.length>0&&queueMicrotask(function(){t.forEach(e)})},t.onDisconnect=function(e){this.onDisconnectCallback=e;var t=this.disconnectionDetails;t&&queueMicrotask(function(){e(t)})},e}(),P=/*#__PURE__*/function(){function e(e,t){this.idleVideoSource=void 0,this.videoId=void 0,this.idleVideoSource=e,this.videoId=t}return e.getIdleVideo=function(t,n,i){try{return Promise.resolve(e.getIdleVideoId(t,n,i)).then(function(r){return Promise.resolve(fetch(t+"/api/v1/idle/"+n+"/"+i+"/"+r)).then(function(t){return t.status>=200&&t.status<=299?Promise.resolve(t.json()).then(function(t){if(t)return new e(t,r);throw new Error("No idle video found for the specified orgId and headId.")}):Promise.resolve(t.text()).then(function(e){var n=new Error("An error occurred retrieving idle video: "+t.status+" "+t.statusText+". Response: "+e);throw n.name="IdleVideoError",n})})})}catch(e){return Promise.reject(e)}},e.prototype.getAvatarSrc=function(e,t,n){try{return Promise.resolve(fetch(e+"/api/v1/avatar/"+t+"/"+n+"/"+this.videoId)).then(function(e){return e.status>=200&&e.status<=299?Promise.resolve(e.json()).then(function(e){if(e)return e;throw new Error("No avatar image found for the specified orgId and headId.")}):Promise.resolve(e.text()).then(function(t){var n=new Error("An error occurred retrieving avatar: "+e.status+" "+e.statusText+". Response: "+t);throw n.name="AvatarError",n})})}catch(e){return Promise.reject(e)}},e.getIdleVideoId=function(e,t,n){try{return Promise.resolve(fetch(e+"/api/v1/videos/"+t+"/"+n)).then(function(e){return e.status>=200&&e.status<=299?Promise.resolve(e.json()).then(function(e){if(e.length>0)return e[0].id;throw new Error("No idle video found for the specified orgId and headId.")}):Promise.resolve(e.text()).then(function(t){var n=new Error("An error occurred retrieving idle video: "+e.status+" "+e.statusText+". Response: "+t);throw n.name="IdleVideoError",n})})}catch(e){return Promise.reject(e)}},e}();function R(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var I=Object.defineProperty,O=(e,t,n)=>((e,t,n)=>t in e?I(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class _{constructor(){O(this,"_locking"),O(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 D(e,t){if(!e)throw new Error(t)}function M(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 A(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 x(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 N=Symbol("@bufbuild/protobuf/enum-type");function L(e,t,n,i){e[N]=U(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function U(e,t,n){const i=Object.create(null),r=Object.create(null),s=[];for(const e of t){const t=j(e);s.push(t),i[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>i[e],findNumber:e=>r[e]}}function j(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class F{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(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function V(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function B(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,s=!(r>>>7==0&&0==t);if(n.push(255&(s?128|r:r)),!s)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);if(n.push(255&(r?128|i:i)),!r)return}n.push(t>>>31&1)}}const q=4294967296;function W(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function s(t,s){const o=Number(e.slice(t,s));r*=n,i=i*n+o,i>=q&&(r+=i/q|0,i%=q)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?z(i,r):G(i,r)}function H(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(q*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let r=(16777215&e)+6777216*n+6710656*i,s=n+8147497*i,o=2*i;const a=1e7;return r>=a&&(s+=Math.floor(r/a),r%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+K(s)+K(r)}function G(e,t){return{lo:0|e,hi:0|t}}function z(e,t){return t=~t,e?e=1+~e:t+=1,G(e,t)}const K=e=>{const t=String(e);return"0000000".slice(t.length)+t};function J(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 Q(){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 t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const Y=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=>D(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>D(/^[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),W(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),W(e)),dec:(e,t)=>function(e,t){let n=G(e,t);const i=2147483648&n.hi;i&&(n=z(n.lo,n.hi));const r=H(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>H(e,t)}}();var X,$,Z;function ee(e,t,n){if(t===n)return!0;if(e==X.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 X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return t==n}return!1}function te(e,t){switch(e){case X.BOOL:return!1;case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return 0==t?Y.zero:"0";case X.DOUBLE:case X.FLOAT:return 0;case X.BYTES:return new Uint8Array(0);case X.STRING:return"";default:return 0}}function ne(e,t){switch(e){case X.BOOL:return!1===t;case X.STRING:return""===t;case X.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(X||(X={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}($||($={})),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"}(Z||(Z={}));class ie{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(A(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return M(e),J(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){x(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){A(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){M(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return M(e),J(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=Y.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=Y.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=Y.enc(e);return B(t.lo,t.hi,this.buf),this}sint64(e){let t=Y.enc(e),n=t.hi>>31;return B(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Y.uEnc(e);return B(t.lo,t.hi,this.buf),this}}class re{constructor(e,t){this.varint64=V,this.uint32=Q,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 Z.Varint:for(;128&this.buf[this.pos++];);break;case Z.Bit64:this.pos+=4;case Z.Bit32:this.pos+=4;break;case Z.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Z.StartGroup:for(;;){const[e,n]=this.tag();if(n===Z.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return Y.dec(...this.varint64())}uint64(){return Y.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,Y.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Y.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Y.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 se(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 te(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 oe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ae=[];for(let e=0;e<oe.length;e++)ae[oe[e].charCodeAt(0)]=e;ae["-".charCodeAt(0)]=oe.indexOf("+"),ae["_".charCodeAt(0)]=oe.indexOf("/");const ce={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,s=0,o=0;for(let t=0;t<e.length;t++){if(n=ae[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:o=n,s=1;break;case 1:i[r++]=o<<2|(48&n)>>4,o=n,s=2;break;case 2:i[r++]=(15&o)<<4|(60&n)>>2,o=n,s=3;break;case 3:i[r++]=(3&o)<<6|n,s=0}}if(1==s)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let s=0;s<e.length;s++)switch(t=e[s],i){case 0:n+=oe[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=oe[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=oe[r|t>>6],n+=oe[63&t],i=0}return i&&(n+=oe[r],n+="=",1==i&&(n+="=")),n}};function de(e,t,n){he(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),[s,o]=se(t);for(const e of r)t.runtime.bin.readField(s,i.readerFactory(e.data),t.field,e.wireType,i);return o()}function le(e,t,n,i){he(t,e);const r=t.runtime.bin.makeReadOptions(i),s=t.runtime.bin.makeWriteOptions(i);if(ue(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 o=s.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,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),i=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function ue(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 he(e,t){D(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function pe(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:!ne(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function me(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?te(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function ge(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(F.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 fe(e,t){return ge(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}const ve={ignoreUnknownFields:!1},ye={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},be=Symbol(),ke=Symbol();function Te(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 Se(e,t,n,i,r){let s=n.localName;if(n.repeated){if(D("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(Te(t)));const o=e[s];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,i));break;case"enum":const t=we(n.T,e,i.ignoreUnknownFields,!0);t!==ke&&o.push(t);break;case"scalar":try{o.push(Ee(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t)));const o=e[s];for(const[e,s]of Object.entries(t)){if(null===s)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let a;try{a=Ce(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":o[a]=n.V.T.fromJson(s,i);break;case"enum":const e=we(n.V.T,s,i.ignoreUnknownFields,!0);e!==ke&&(o[a]=e);break;case"scalar":try{o[a]=Ee(n.V.T,s,$.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:s},s="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[s];ge(a)?a.fromJson(t,i):(e[s]=a=o.fromJson(t,i),o.fieldWrapper&&!n.oneof&&(e[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=we(n.T,t,i.ignoreUnknownFields,!1);switch(c){case be:me(n,e);break;case ke:break;default:e[s]=c}break;case"scalar":try{const i=Ee(n.T,t,n.L,!1);i===be?me(n,e):e[s]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(Te(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function Ce(e,t){if(e===X.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Ee(e,t,$.BIGINT,!0).toString()}function Ee(e,t,n,i){if(null===t)return i?te(e,n):be;switch(e){case X.DOUBLE:case X.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==X.FLOAT&&x(i),i;case X.INT32:case X.FIXED32:case X.SFIXED32:case X.SINT32:case X.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==X.UINT32||e==X.FIXED32?A(r):M(r),r;case X.INT64:case X.SFIXED64:case X.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=Y.parse(t);return n?s.toString():s;case X.FIXED64:case X.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=Y.uParse(t);return n?o.toString():o;case X.BOOL:if("boolean"!=typeof t)break;return t;case X.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case X.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ce.dec(t)}throw new Error}function we(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:be;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 ke}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Te(t)))}function Pe(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function Re(e,t,n){if("map"==e.kind){D("object"==typeof t&&null!=t);const i={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of r)i[t.toString()]=Oe(e.V.T,n);break;case"message":for(const[e,t]of r)i[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,s]of r)i[e.toString()]=Ie(t,s,n.enumAsInteger)}return n.emitDefaultValues||r.length>0?i:void 0}if(e.repeated){D(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(Oe(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(Ie(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 Oe(e.T,t);case"enum":return Ie(e.T,t,n.enumAsInteger);case"message":return fe(e.T,t).toJson(n)}}function Ie(e,t,n){var i;if(D("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 Oe(e,t){switch(e){case X.INT32:case X.SFIXED32:case X.SINT32:case X.FIXED32:case X.UINT32:return D("number"==typeof t),t;case X.FLOAT:case X.DOUBLE:return D("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case X.STRING:return D("string"==typeof t),t;case X.BOOL:return D("boolean"==typeof t),t;case X.UINT64:case X.FIXED64:case X.INT64:case X.SFIXED64:case X.SINT64:return D("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case X.BYTES:return D(t instanceof Uint8Array),ce.enc(t)}}const _e=Symbol("@bufbuild/protobuf/unknown-fields"),De={readUnknownFields:!0,readerFactory:e=>new re(e)},Me={writeUnknownFields:!0,writerFactory:()=>new ie};function Ae(e,t,n,i,r){let{repeated:s,localName:o}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const a="enum"==n.kind?X.INT32:n.T;let c=Le;if("scalar"==n.kind&&n.L>0&&(c=Ne),s){let n=e[o];if(i==Z.LengthDelimited&&a!=X.STRING&&a!=X.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,a))}else n.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=n.T;s?e[o].push(xe(t,new d,r,n)):ge(e[o])?xe(t,e[o],r,n):(e[o]=xe(t,new d,r,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,n){const i=t.uint32(),r=t.pos+i;let s,o;for(;t.pos<r;){const[i]=t.tag();switch(i){case 1:s=Le(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Le(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=xe(t,new e.V.T,n,void 0)}}}if(void 0===s&&(s=te(e.K,$.BIGINT)),"string"!=typeof s&&"number"!=typeof s&&(s=s.toString()),void 0===o)switch(e.V.kind){case"scalar":o=te(e.V.T,$.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[s,o]}(n,t,r);e[o][l]=u}}function xe(e,t,n,i){const r=t.getType().runtime.bin,s=null==i?void 0:i.delimited;return r.readMessage(t,e,s?i.no:e.uint32(),n,s),t}function Ne(e,t){const n=Le(e,t);return"bigint"==typeof n?n.toString():n}function Le(e,t){switch(t){case X.STRING:return e.string();case X.BOOL:return e.bool();case X.DOUBLE:return e.double();case X.FLOAT:return e.float();case X.INT32:return e.int32();case X.INT64:return e.int64();case X.UINT64:return e.uint64();case X.FIXED64:return e.fixed64();case X.BYTES:return e.bytes();case X.FIXED32:return e.fixed32();case X.SFIXED32:return e.sfixed32();case X.SFIXED64:return e.sfixed64();case X.SINT64:return e.sint64();case X.UINT32:return e.uint32();case X.SINT32:return e.sint32()}}function Ue(e,t,n,i){D(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?X.INT32:e.T;if(r)if(D(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,Z.LengthDelimited).fork();let[,r]=Be(t);for(let t=0;t<i.length;t++)e[r](i[t]);e.join()}(n,s,e.no,t);else for(const i of t)Ve(n,s,e.no,i);else Ve(n,s,e.no,t);break;case"message":if(r){D(Array.isArray(t));for(const r of t)Fe(n,i,e,r)}else Fe(n,i,e,t);break;case"map":D("object"==typeof t&&null!=t);for(const[r,s]of Object.entries(t))je(n,i,e,r,s)}}function je(e,t,n,i,r){e.tag(n.no,Z.LengthDelimited),e.fork();let s=i;switch(n.K){case X.INT32:case X.FIXED32:case X.UINT32:case X.SFIXED32:case X.SINT32:s=Number.parseInt(i);break;case X.BOOL:D("true"==i||"false"==i),s="true"==i}switch(Ve(e,n.K,1,s),n.V.kind){case"scalar":Ve(e,n.V.T,2,r);break;case"enum":Ve(e,X.INT32,2,r);break;case"message":D(void 0!==r),e.tag(2,Z.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Fe(e,t,n,i){const r=fe(n.T,i);n.delimited?e.tag(n.no,Z.StartGroup).raw(r.toBinary(t)).tag(n.no,Z.EndGroup):e.tag(n.no,Z.LengthDelimited).bytes(r.toBinary(t))}function Ve(e,t,n,i){D(void 0!==i);let[r,s]=Be(t);e.tag(n,r)[s](i)}function Be(e){let t=Z.Varint;switch(e){case X.BYTES:case X.STRING:t=Z.LengthDelimited;break;case X.DOUBLE:case X.FIXED64:case X.SFIXED64:t=Z.Bit64;break;case X.FIXED32:case X.SFIXED32:case X.FLOAT:t=Z.Bit32}return[t,X[e].toLowerCase()]}function qe(e){if(void 0===e)return e;if(ge(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function We(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class He{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 Ge(e,t){const n=Ke(e);return t?n:$e(Xe(n))}const ze=Ke;function Ke(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 Je=new Set(["constructor","toString","toJSON","valueOf"]),Qe=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ye=e=>"".concat(e,"$"),Xe=e=>Qe.has(e)?Ye(e):e,$e=e=>Je.has(e)?Ye(e):e;class Ze{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=Ge(e,!1)}addField(e){D(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 et=(tt=e=>new He(e,e=>function(e){var t,n,i,r,s,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Ge(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:ze(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:$.BIGINT),e.delimited=null!==(r=d.delimited)&&void 0!==r&&r,e.req=null!==(s=d.req)&&void 0!==s&&s,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=X.BYTES&&d.T!=X.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Ze(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e)),nt=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]=te(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},ve),e):ve},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},ye),e):ye},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(Te(t)));i=null!=i?i:new e;const r=new Map,s=n.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const n=r.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(o,'"'));r.set(t.oneof,o)}Se(i,a,t,n,e)}else{let t=!1;if((null==s?void 0:s.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const r=s.findExtension(o.substring(1,o.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;const[e,s]=se(r);Se(e,a,r.field,n,r),le(i,r,s(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!pe(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Pe(r))continue}const n=Re(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const o=s.findExtensionFor(n.typeName,r.no);if(o&&ue(e,o)){const n=de(e,o,t),r=Re(o.field,n,t);void 0!==r&&(i[o.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>Ee(e,t,null!=n?n:$.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||ne(e,t)?Oe(e,t):void 0},debug:Te},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},De),e):De},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Me),e):Me},listUnknownFields(e){var t;return null!==(t=e[_e])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[_e]},writeUnknownFields(e,t){const n=e[_e];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[_e])||(r[_e]=[]),r[_e].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const s=e.getType(),o=r?t.len:t.pos+n;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==r||c!=Z.EndGroup);){const n=s.fields.find(a);if(!n){const n=t.skip(c,a);i.readUnknownFields&&this.onUnknownField(e,a,c,n);continue}Ae(e,t,n,c,i)}if(r&&(c!=Z.EndGroup||a!==n))throw new Error("invalid end group tag")},readField:Ae,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(pe(r,e))Ue(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&&Ue(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:L,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,r=t,s=e;if(null!=s[n])switch(i.kind){case"oneof":const e=s[n].case;if(void 0===e)continue;const t=i.findField(e);let o=s[n].value;t&&"message"==t.kind&&!ge(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===X.BYTES&&(o=We(o)),r[n]={case:e,value:o};break;case"scalar":case"enum":let a=s[n];i.T===X.BYTES&&(a=i.repeated?a.map(We):We(a)),r[n]=a;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===X.BYTES)for(const[e,t]of Object.entries(s[n]))r[n][e]=We(t);else Object.assign(r[n],s[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(s[n])){let i=s[n][t];e.fieldWrapper||(i=new e(i)),r[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)r[n]=s[n].map(e=>ge(e,c)?e:new c(e));else{const e=s[n];r[n]=c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?We(e):e:ge(e,c)?e:new c(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)=>ee(e.T,t,r[n]));case"enum":return i.every((e,t)=>ee(X.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||ge(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||ge(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return ee(X.INT32,i,r);case"scalar":return ee(e.T,i,r);case"oneof":if(i.case!==r.case)return!1;const s=e.findField(i.case);if(void 0===s)return!0;switch(s.kind){case"message":return s.T.equals(i.value,r.value);case"enum":return ee(X.INT32,i.value,r.value);case"scalar":return ee(s.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const o=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return o.every(e=>t.equals(i[e],r[e]));case"enum":return o.every(e=>ee(X.INT32,i[e],r[e]));case"scalar":const n=e.V.T;return o.every(e=>ee(n,i[e],r[e]))}}}),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let r;if(n.repeated)r=t.map(qe);else if("map"==n.kind){r=i[n.localName];for(const[e,n]of Object.entries(t))r[e]=qe(n)}else r="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:qe(t.value)}:{case:void 0}:qe(t);i[n.localName]=r}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:tt,initFields:nt}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const s=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(o.prototype,new F),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,n)=>e.util.equals(o,t,n)}),o}(this,e,t,n)},makeEnum:function(e,t,n){const i={};for(const e of t){const t=j(e);i[t.localName]=t.no,i[t.no]=t.localName}return L(i,e,t),i},makeEnumType:U,getEnumType:function(e){const t=e[N];return D(t,"missing enum type on enum object"),t},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 tt,nt;class it extends F{constructor(e){super(),this.seconds=Y.zero,this.nanos=0,et.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(et.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=Y.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 it.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new it({seconds:Y.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new it).fromBinary(e,t)}static fromJson(e,t){return(new it).fromJson(e,t)}static fromJsonString(e,t){return(new it).fromJsonString(e,t)}static equals(e,t){return et.util.equals(it,e,t)}}it.runtime=et,it.typeName="google.protobuf.Timestamp",it.fields=et.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const rt=/* @__PURE__ */et.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:it},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:st,repeated:!0},{no:5,name:"events",kind:"message",T:at,repeated:!0}]),st=/* @__PURE__ */et.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:ot,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ot=/* @__PURE__ */et.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:it},{no:3,name:"value",kind:"scalar",T:2}]),at=/* @__PURE__ */et.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:it},{no:7,name:"normalized_end_timestamp",kind:"message",T:it,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ct=/* @__PURE__ */et.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),dt=/* @__PURE__ */et.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),lt=/* @__PURE__ */et.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"}]),ut=/* @__PURE__ */et.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ht=/* @__PURE__ */et.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),pt=/* @__PURE__ */et.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),mt=/* @__PURE__ */et.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"}]),gt=/* @__PURE__ */et.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"}]),ft=/* @__PURE__ */et.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),vt=/* @__PURE__ */et.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"}]),yt=/* @__PURE__ */et.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:bt,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:Zt}]),bt=/* @__PURE__ */et.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),kt=/* @__PURE__ */et.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:et.getEnumType(lt),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Tt=/* @__PURE__ */et.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:et.getEnumType(St)},{no:4,name:"tracks",kind:"message",T:Rt,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:kt},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:et.getEnumType(Ct)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:et.getEnumType(mt)},{no:18,name:"kind_details",kind:"enum",T:et.getEnumType(Et),repeated:!0}]),St=/* @__PURE__ */et.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ct=/* @__PURE__ */et.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"}]),Et=/* @__PURE__ */et.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),wt=/* @__PURE__ */et.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Pt=/* @__PURE__ */et.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:It,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:et.getEnumType(Ot)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Rt=/* @__PURE__ */et.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:et.getEnumType(dt)},{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:et.getEnumType(lt)},{no:10,name:"layers",kind:"message",T:It,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:Pt,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:et.getEnumType(wt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Zt},{no:19,name:"audio_features",kind:"enum",T:et.getEnumType(vt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:et.getEnumType(ct)}]),It=/* @__PURE__ */et.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:et.getEnumType(ut)},{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}]),Ot=/* @__PURE__ */et.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"}]),_t=/* @__PURE__ */et.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:et.getEnumType(Dt)},{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:Lt,oneof:"value"},{no:3,name:"speaker",kind:"message",T:xt,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ut,oneof:"value"},{no:7,name:"transcription",kind:"message",T:jt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:rt,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Vt,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Bt,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:qt,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Wt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:rn,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:sn,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:on,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Mt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Dt=/* @__PURE__ */et.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Mt=/* @__PURE__ */et.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:et.getEnumType(wt)},{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}]),At=/* @__PURE__ */et.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Lt,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Vt,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Bt,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:qt,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Wt,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:rn,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:sn,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:on,oneof:"value"}]),xt=/* @__PURE__ */et.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Nt,repeated:!0}]),Nt=/* @__PURE__ */et.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}]),Lt=/* @__PURE__ */et.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}]),Ut=/* @__PURE__ */et.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),jt=/* @__PURE__ */et.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:Ft,repeated:!0}]),Ft=/* @__PURE__ */et.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}]),Vt=/* @__PURE__ */et.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}]),Bt=/* @__PURE__ */et.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}]),qt=/* @__PURE__ */et.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Wt=/* @__PURE__ */et.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:Ht,oneof:"value"}]),Ht=/* @__PURE__ */et.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}]),Gt=/* @__PURE__ */et.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),zt=/* @__PURE__ */et.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:et.getEnumType(Kt)},{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}]),Kt=/* @__PURE__ */et.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Jt=/* @__PURE__ */et.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:et.getEnumType(Qt)},{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}]),Qt=/* @__PURE__ */et.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"}]),Yt=/* @__PURE__ */et.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Xt},{no:2,name:"screen",kind:"message",T:Xt},{no:3,name:"resume_connection",kind:"enum",T:et.getEnumType(pt)},{no:4,name:"disabled_codecs",kind:"message",T:$t},{no:5,name:"force_relay",kind:"enum",T:et.getEnumType(pt)}]),Xt=/* @__PURE__ */et.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:et.getEnumType(pt)}]),$t=/* @__PURE__ */et.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:bt,repeated:!0},{no:2,name:"publish",kind:"message",T:bt,repeated:!0}]),Zt=/* @__PURE__ */et.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),en=/* @__PURE__ */et.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),tn=/* @__PURE__ */et.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:et.getEnumType(en)},{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"}),nn=/* @__PURE__ */et.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),rn=/* @__PURE__ */et.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:et.getEnumType(wt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:tn,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:nn,oneof:"content_header"}],{localName:"DataStream_Header"}),sn=/* @__PURE__ */et.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"}),on=/* @__PURE__ */et.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"}),an=/* @__PURE__ */et.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),cn=/* @__PURE__ */et.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),dn=/* @__PURE__ */et.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ln=/* @__PURE__ */et.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),un=/* @__PURE__ */et.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Tn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tn,oneof:"message"},{no:3,name:"trickle",kind:"message",T:gn,oneof:"message"},{no:4,name:"add_track",kind:"message",T:mn,oneof:"message"},{no:5,name:"mute",kind:"message",T:fn,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Cn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:En,oneof:"message"},{no:8,name:"leave",kind:"message",T:Rn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:On,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Wn,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:zn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Qn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:_n,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Yn,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:wn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Pn,oneof:"message"}]),hn=/* @__PURE__ */et.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:vn,oneof:"message"},{no:2,name:"answer",kind:"message",T:Tn,oneof:"message"},{no:3,name:"offer",kind:"message",T:Tn,oneof:"message"},{no:4,name:"trickle",kind:"message",T:gn,oneof:"message"},{no:5,name:"update",kind:"message",T:Sn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:bn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Rn,oneof:"message"},{no:9,name:"mute",kind:"message",T:fn,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Mn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:An,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Nn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Un,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Vn,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Hn,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:kn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:yn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Xn,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ei,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ti,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ii,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Gn,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:ci,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Bn,oneof:"message"}]),pn=/* @__PURE__ */et.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:It,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:et.getEnumType(Ot)}]),mn=/* @__PURE__ */et.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:et.getEnumType(dt)},{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:et.getEnumType(lt)},{no:9,name:"layers",kind:"message",T:It,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:pn,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:et.getEnumType(wt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:et.getEnumType(ct)},{no:17,name:"audio_features",kind:"enum",T:et.getEnumType(vt),repeated:!0}]),gn=/* @__PURE__ */et.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:et.getEnumType(cn)},{no:3,name:"final",kind:"scalar",T:8}]),fn=/* @__PURE__ */et.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),vn=/* @__PURE__ */et.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:yt},{no:2,name:"participant",kind:"message",T:Tt},{no:3,name:"other_participants",kind:"message",T:Tt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Dn,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:Yt},{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:zt},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:bt,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),yn=/* @__PURE__ */et.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Dn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Yt},{no:3,name:"server_info",kind:"message",T:zt},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),bn=/* @__PURE__ */et.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Rt}]),kn=/* @__PURE__ */et.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Tn=/* @__PURE__ */et.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}}]),Sn=/* @__PURE__ */et.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Tt,repeated:!0}]),Cn=/* @__PURE__ */et.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:Gt,repeated:!0}]),En=/* @__PURE__ */et.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:et.getEnumType(ut)},{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}]),wn=/* @__PURE__ */et.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:et.getEnumType(vt),repeated:!0}]),Pn=/* @__PURE__ */et.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}]),Rn=/* @__PURE__ */et.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:et.getEnumType(mt)},{no:3,name:"action",kind:"enum",T:et.getEnumType(In)},{no:4,name:"regions",kind:"message",T:$n}]),In=/* @__PURE__ */et.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),On=/* @__PURE__ */et.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:It,repeated:!0}]),_n=/* @__PURE__ */et.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}]),Dn=/* @__PURE__ */et.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}]),Mn=/* @__PURE__ */et.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Nt,repeated:!0}]),An=/* @__PURE__ */et.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:yt}]),xn=/* @__PURE__ */et.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:et.getEnumType(ht)},{no:3,name:"score",kind:"scalar",T:2}]),Nn=/* @__PURE__ */et.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:xn,repeated:!0}]),Ln=/* @__PURE__ */et.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:et.getEnumType(dn)}]),Un=/* @__PURE__ */et.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Ln,repeated:!0}]),jn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:et.getEnumType(ut)},{no:2,name:"enabled",kind:"scalar",T:8}]),Fn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:jn,repeated:!0}]),Vn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:jn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Fn,repeated:!0}]),Bn=/* @__PURE__ */et.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:an,repeated:!0}]),qn=/* @__PURE__ */et.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}]),Wn=/* @__PURE__ */et.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:qn,repeated:!0}]),Hn=/* @__PURE__ */et.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}]),Gn=/* @__PURE__ */et.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:yt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Tt},{no:4,name:"other_participants",kind:"message",T:Tt,repeated:!0}]),zn=/* @__PURE__ */et.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Tn},{no:2,name:"subscription",kind:"message",T:Cn},{no:3,name:"publish_tracks",kind:"message",T:bn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Jn,repeated:!0},{no:5,name:"offer",kind:"message",T:Tn},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Kn,repeated:!0}]),Kn=/* @__PURE__ */et.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Jn=/* @__PURE__ */et.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:et.getEnumType(cn)}]),Qn=/* @__PURE__ */et.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:et.getEnumType(ln),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"}]),Yn=/* @__PURE__ */et.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Xn=/* @__PURE__ */et.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),$n=/* @__PURE__ */et.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Zn,repeated:!0}]),Zn=/* @__PURE__ */et.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}]),ei=/* @__PURE__ */et.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:et.getEnumType(ft)}]),ti=/* @__PURE__ */et.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:et.getEnumType(ni)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:gn,oneof:"request"},{no:5,name:"add_track",kind:"message",T:mn,oneof:"request"},{no:6,name:"mute",kind:"message",T:fn,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:_n,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:wn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Pn,oneof:"request"}]),ni=/* @__PURE__ */et.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"}]),ii=/* @__PURE__ */et.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ri=/* @__PURE__ */et.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}]),si=/* @__PURE__ */et.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Jt},{no:2,name:"connection_settings",kind:"message",T:ri},{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:mn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Tn},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:et.getEnumType(gt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:zn}]),oi=/* @__PURE__ */et.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:et.getEnumType(ai)},{no:2,name:"join_request",kind:"scalar",T:12}]),ai=/* @__PURE__ */et.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),ci=/* @__PURE__ */et.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function di(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var li,ui,hi,pi,mi,gi={exports:{}},fi=(li||(li=1,ui=gi.exports,hi=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={},s=null;function o(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),r=0;r<i.length;r++){var s=i[r];this[s]=r<n?e:this.methodFactory(s,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,s){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?a:void 0!==console[i]?o(console,i):void 0!==console.log?o(console,"log"):e)}(i)||d.apply(this,arguments)}function u(e,n){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=n||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,n){return d=m(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(o=m(s.getLevel())),c.call(u),s===u)for(var e in r)r[e].rebuild()},o=m(s?s.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(s=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,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},gi.exports?gi.exports=hi():ui.log=hi()),gi.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(pi||(pi={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(mi||(mi={}));let vi=fi.getLogger("livekit");function yi(e){const t=fi.getLogger(e);return t.setDefaultLevel(vi.getLevel()),t}Object.values(mi).map(e=>fi.getLogger(e)),vi.setDefaultLevel(pi.info);const bi=fi.getLogger("lk-e2ee"),ki=7e3,Ti=[0,300,1200,2700,4800,ki,ki,ki,ki,ki];function Si(e,t,n,i){return new(n||(n=Promise))(function(r,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((i=i.apply(e,t||[])).next())})}function Ci(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=function(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.")}(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)})}}}"function"==typeof SuppressedError&&SuppressedError;var Ei,wi={exports:{}},Pi=function(){if(Ei)return wi.exports;Ei=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)}wi.exports=r,wi.exports.once=function(e,t){return new Promise(function(n,i){function r(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,r)})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,s,c;if(o(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),c=s[t]),void 0===c)c=s[t]=n,++e._eventsCount;else if("function"==typeof c?c=s[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 d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,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(s){i.once&&e.removeEventListener(t,r),n(s)})}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},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+".");s=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,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[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.on=r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,s,a;if(o(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,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,r=s;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,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(r=s[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):[]},wi.exports}();let Ri=!0,Ii=!0;function Oi(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function _i(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const s=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,s),r.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(n))return s.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,s.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 Di(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ri=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Mi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Ii=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Ai(){if("object"==typeof window){if(Ri)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function xi(e,t){Ii&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Ni(e){return"[object Object]"===Object.prototype.toString.call(e)}function Li(e){return Ni(e)?Object.keys(e).reduce(function(t,n){const i=Ni(e[n]),r=i?Li(e[n]):e[n],s=i&&!Object.keys(r).length;return void 0===r||s?t:Object.assign(t,{[n]:r})},{}):e}function Ui(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?Ui(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(t=>{Ui(e,e.get(t),n)})}))}function ji(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(n=>{n.type===i&&n.trackId===t.id&&Ui(e,n,r)})}),r}const Fi=Ai;function Vi(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const 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 s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then(n=>{let o=(n=n.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes("back")&&(o=n[n.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),Fi("chrome: "+JSON.stringify(e)),r(e)})}e.video=i(e.video)}return Fi("chrome: "+JSON.stringify(e)),r(e)},s=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(s(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(s(e))))}}}function Bi(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function qi(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};const 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 _i(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Wi(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&&(this._dtmf="audio"===t.kind?e.createDTMFSender(t):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&&(this._dtmf="audio"===this.track.kind?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function Hi(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>ji(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}),_i(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>ji(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach(n=>{n.track===e&&(t?i=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?i=!0:n=t),t.track===e)),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Gi(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 zi(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Gi(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 s(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t];n=n.replace(new RegExp(e._streams[i.id].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=s(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>s(this,e))}};e.RTCPeerConnection.prototype[t]=i[t]});const o=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]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(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 Ki(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 Ji(e,t){_i(e,"negotiationneeded",e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e})}var Qi=/*#__PURE__*/Object.freeze({__proto__:null,fixNegotiationNeeded:Ji,shimAddTrackRemoveTrack:zi,shimAddTrackRemoveTrackWithNative:Gi,shimGetSendersWithDtmf:Wi,shimGetUserMedia:Vi,shimMediaStream:Bi,shimOnTrack:qi,shimPeerConnection:Ki,shimSenderReceiverGetStats:Hi});function Yi(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){xi("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 Xi(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 $i(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,s]=arguments;return i.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(r,s)}}function Zi(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 er(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}),_i(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function tr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){xi("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function nr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return i})}function rr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function sr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function or(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var ar=/*#__PURE__*/Object.freeze({__proto__:null,shimAddTransceiver:ir,shimCreateAnswer:or,shimCreateOffer:sr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:rr,shimGetUserMedia:Yi,shimOnTrack:Xi,shimPeerConnection:$i,shimRTCDataChannel:nr,shimReceiverGetStats:er,shimRemoveStream:tr,shimSenderGetStats:Zi});function cr(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 dr(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 lr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=n.apply(this,[arguments.length>=2?arguments[2]:arguments[0]]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const n=i.apply(this,[arguments.length>=2?arguments[2]:arguments[0]]);return t?(n.then(e,t),Promise.resolve()):n};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=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function ur(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(hr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function hr(e){return e&&void 0!==e.video?Object.assign({},e,{video:Li(e.video)}):e}function pr(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?(xi("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 mr(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 gr(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 fr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var vr,yr=/*#__PURE__*/Object.freeze({__proto__:null,shimAudioContext:fr,shimCallbacksAPI:lr,shimConstraints:hr,shimCreateOfferLegacy:gr,shimGetUserMedia:ur,shimLocalStreamsAPI:cr,shimRTCIceServerUrls:pr,shimRemoteStreamsAPI:dr,shimTrackEventTransceiver:mr}),br={exports:{}},kr=(vr||(vr=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>0===e.indexOf(n))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;t.push("rtp"===n?1:"rtcp"===n?2:n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach(t=>{i.push(void 0!==e.parameters[t]?t+"="+e.parameters[t]: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 r=3;r<i.length;r++){const s=i[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const i=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").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"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),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:s?"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 s=t.matchPrefix(e,"a=rtcp-mux");return n.mux=s.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 s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize: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 s=void 0!==n?n:2;return r=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(br)),br.exports),Tr=/*@__PURE__*/di(kr),Sr=/*#__PURE__*/R({__proto__:null,default:Tr},[kr]);function Cr(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=Tr.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,_i(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Er(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||_i(e,"icecandidate",e=>{if(e.candidate){const t=Tr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function wr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Tr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Tr.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=Tr.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 s={};Object.defineProperty(s,"maxMessageSize",{get:()=>r}),this._sctp=s}return n.apply(this,arguments)}}function Pr(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0];if("open"===e.readyState&&t.sctp&&(i.length||i.size||i.byteLength)>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},_i(e,"datachannel",e=>(t(e.channel,e.target),e))}function Rr(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 Ir(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 Or(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 _r(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"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?n.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var Dr=/*#__PURE__*/Object.freeze({__proto__:null,removeExtmapAllowMixed:Ir,shimAddIceCandidateNullOrEmpty:Or,shimConnectionState:Rr,shimMaxMessageSize:wr,shimParameterlessSetLocalDescription:_r,shimRTCIceCandidate:Cr,shimRTCIceCandidateRelayProtocol:Er,shimSendThrowTypeError:Pr});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Ai,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Oi(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Oi(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Oi(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Oi(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),r={browserDetails:i,commonShim:Dr,extractVersion:Oi,disableLog:Di,disableWarnings:Mi,sdp:Sr};switch(i.browser){case"chrome":if(!Qi||!Ki||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=Qi,Or(e,i),_r(e),Vi(e,i),Bi(e),Ki(e,i),qi(e),zi(e,i),Wi(e),Hi(e),Ji(e,i),Cr(e),Er(e),Rr(e),wr(e,i),Pr(e),Ir(e,i);break;case"firefox":if(!ar||!$i||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=ar,Or(e,i),_r(e),Yi(e,i),$i(e,i),Xi(e),tr(e),Zi(e),er(e),nr(e),ir(e),rr(e),sr(e),or(e),Cr(e),Rr(e),wr(e,i),Pr(e);break;case"safari":if(!yr||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=yr,Or(e,i),_r(e),pr(e),gr(e),lr(e),cr(e),dr(e),mr(e),ur(e),fr(e),Cr(e),Er(e),wr(e,i),Pr(e),Ir(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Mr="lk_e2ee";var Ar,xr,Nr,Lr,Ur,jr,Fr,Vr,Br,qr,Wr,Hr;function Gr(){return void 0!==window.RTCRtpScriptTransform}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(Ar||(Ar={})),function(e){e.KeyRatcheted="keyRatcheted"}(xr||(xr={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(Nr||(Nr={})),function(e){e.Error="cryptorError"}(Lr||(Lr={}));class zr extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(Ur||(Ur={}));class Kr extends zr{constructor(e,t,n,i){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=i,this.reasonName=Ur[t]}}class Jr extends zr{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Qr extends zr{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Yr extends zr{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Xr extends zr{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class $r extends zr{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class Zr extends zr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class es extends zr{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:ni[t]}}!function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(jr||(jr={}));class ts extends zr{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=jr[t]}}!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Fr||(Fr={})),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}}(Fr||(Fr={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(Vr||(Vr={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(Br||(Br={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(qr||(qr={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(Wr||(Wr={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(Hr||(Hr={}));const ns=/version\/(\d+(\.?_?\d+)+)/i;let is;function rs(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===is||t){const e=ss.find(e=>{let{test:t}=e;return t.test(n)});is=null==e?void 0:e.describe(n)}return is}const ss=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:os(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:as(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:os(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:as(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:os(ns,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:as(e)})}];function os(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 as(e){return e.includes("mac os")?os(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class cs{}cs.setTimeout=function(){return setTimeout(...arguments)},cs.setInterval=function(){return setInterval(...arguments)},cs.clearTimeout=function(){return clearTimeout(...arguments)},cs.clearInterval=function(){return clearInterval(...arguments)};const ds=[];var ls;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(ls||(ls={}));class us extends Pi.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=us.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=vi,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:mi.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=us.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ko(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===us.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===us.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ds.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&ds.splice(ds.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),hs(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),i=n.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(i?Hr.AudioPlaybackStarted:Hr.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(i?Hr.AudioPlaybackFailed:Hr.VideoPlaybackFailed,t):"AbortError"===t.name?vi.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):vi.warn("could not playback ".concat(i?"audio":"video"),t),i&&e&&n.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(Hr.ElementAttached,e),e}detach(e){try{if(e){ps(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Hr.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(e=>{ps(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Hr.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=yi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ds.forEach(e=>{e.parentElement||(t=!1)}),t&&ds.push(e)}}handleAppVisibilityChanged(){return Si(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==us.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){xs()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){xs()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function hs(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)),Ds()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(Ds()||Os())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function ps(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),t.srcObject=n.getTracks().length>0?n: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 dt.AUDIO;case t.Video:return dt.VIDEO;default:return dt.DATA}},e.kindFromProto=function(e){switch(e){case dt.AUDIO:return t.Audio;case dt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return lt.CAMERA;case n.Microphone:return lt.MICROPHONE;case n.ScreenShare:return lt.SCREEN_SHARE;case n.ScreenShareAudio:return lt.SCREEN_SHARE_AUDIO;default:return lt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case lt.CAMERA:return n.Camera;case lt.MICROPHONE:return n.Microphone;case lt.SCREEN_SHARE:return n.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case dn.ACTIVE:return i.Active;case dn.PAUSED:return i.Paused;default:return i.Unknown}}}(us||(us={}));class ms{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 gs=["vp8","h264"],fs=["vp8","h264","vp9","av1","h265"],vs=function(e){return!!gs.find(t=>t===e)};var ys,bs;!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(ys||(ys={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(bs||(bs={}));const ks={h90:new ms(160,90,9e4,20),h180:new ms(320,180,16e4,20),h216:new ms(384,216,18e4,20),h360:new ms(640,360,45e4,20),h540:new ms(960,540,8e5,25),h720:new ms(1280,720,17e5,30),h1080:new ms(1920,1080,3e6,30),h1440:new ms(2560,1440,5e6,30),h2160:new ms(3840,2160,8e6,30)},Ts={h120:new ms(160,120,7e4,20),h180:new ms(240,180,125e3,20),h240:new ms(320,240,14e4,20),h360:new ms(480,360,33e4,20),h480:new ms(640,480,5e5,20),h540:new ms(720,540,6e5,25),h720:new ms(960,720,13e5,30),h1080:new ms(1440,1080,23e5,30),h1440:new ms(1920,1440,38e5,30)},Ss={h360fps3:new ms(640,360,2e5,3,"medium"),h360fps15:new ms(640,360,4e5,15,"medium"),h720fps5:new ms(1280,720,8e5,5,"medium"),h720fps15:new ms(1280,720,15e5,15,"medium"),h720fps30:new ms(1280,720,2e6,30,"medium"),h1080fps15:new ms(1920,1080,25e5,15,"medium"),h1080fps30:new ms(1920,1080,5e6,30,"medium"),original:new ms(0,0,7e6,30,"medium")},Cs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Es(e){return Si(this,void 0,void 0,function*(){return new Promise(t=>cs.setTimeout(t,e))})}function ws(){return"addTransceiver"in RTCPeerConnection.prototype}function Ps(){return"addTrack"in RTCPeerConnection.prototype}function Rs(e){return"av1"===e||"vp9"===e}function Is(e){return!(!document||Ms())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Os(){var e;return"Firefox"===(null===(e=rs())||void 0===e?void 0:e.name)}function _s(){const e=rs();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function Ds(){var e;return"Safari"===(null===(e=rs())||void 0===e?void 0:e.name)}function Ms(){const e=rs();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function As(){var e,t;return!!xs()&&(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 xs(){return"undefined"!=typeof document}function Ns(){return"ReactNative"==navigator.product}function Ls(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Us(e){return Ls(e)?e.hostname.split(".")[0]:null}function js(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Fs(){if(!Ns())return;let e=js();return e?e.platform:void 0}function Vs(){if(xs())return window.devicePixelRatio;if(Ns()){let e=js();if(e)return e.devicePixelRatio}return 1}function Bs(e,t){const n=e.split("."),i=t.split("."),r=Math.min(n.length,i.length);for(let e=0;e<r;++e){const t=parseInt(n[e],10),s=parseInt(i[e],10);if(t>s)return 1;if(t<s)return-1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:n.length==i.length?0:n.length<i.length?-1:1}function qs(e){for(const t of e)t.target.handleResize(t)}function Ws(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Hs=null;const Gs=()=>(Hs||(Hs=new ResizeObserver(qs)),Hs);let zs=null;const Ks=()=>(zs||(zs=new IntersectionObserver(Ws,{root:null,rootMargin:"0px"})),zs);function Js(){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 s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const o=r.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}let Qs;function Ys(){if(!Qs){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[Qs]=i.stream.getAudioTracks(),!Qs)throw Error("Could not get empty media stream audio track");Qs.enabled=!1}return Qs.clone()}class Xs{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>Si(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 $s(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Zs(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function eo(e){switch(e.reason){case Ur.LeaveRequest:return e.context;case Ur.Cancelled:return mt.CLIENT_INITIATED;case Ur.NotAllowed:return mt.USER_REJECTED;case Ur.ServerUnreachable:return mt.JOIN_FAILURE;default:return mt.UNKNOWN_REASON}}function to(e){return void 0!==e?Number(e):void 0}function no(e){return void 0!==e?BigInt(e):void 0}function io(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function ro(e){return!!e&&e.kind==us.Kind.Audio}function so(e){return!!e&&e.kind==us.Kind.Video}function oo(e){return io(e)&&so(e)}function ao(e){return io(e)&&ro(e)}function co(e){return!!e&&!e.isLocal}function lo(e){return!!e&&!e.isLocal}function uo(e){return co(e)&&so(e)}function ho(e,t,n){var i,r,s,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=To(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==n?void 0:n.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(po(h.audio,t),null!==(i=(s=h.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(po(h.video,n),null!==(r=(o=h.video).deviceId)&&void 0!==r||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function po(e,t){return Object.keys(t).forEach(n=>{void 0===e[n]&&(e[n]=t[n])}),e}function mo(e){var t,n,i,r;const s={};if(e.video)if("object"==typeof e.video){const n={},r=n,o=e.video;Object.keys(o).forEach(e=>{"resolution"===e?po(r,o.resolution):r[e]=o[e]}),s.video=n,null!==(t=(i=s.video).deviceId)&&void 0!==t||(i.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}};else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(n=(r=s.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function go(){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=()=>Si(this,void 0,void 0,function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}});n.addEventListener("statechange",()=>{var t;"closed"===n.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))}),window.document.body.addEventListener("click",e)}return n}}function fo(e){return"audioinput"===e?us.Source.Microphone:"videoinput"===e?us.Source.Camera:us.Source.Unknown}function vo(e){return e===us.Source.Microphone?"audioinput":e===us.Source.Camera?"videoinput":void 0}function yo(e){return e.split("/")[1].toLowerCase()}function bo(e){const t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new bn({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function ko(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?ko(e.track):{})}}function To(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 So(e,t){return e.width*e.height<t.width*t.height}class Co extends Pi.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{var t,n;const{kind:i,data:r}=e.data;switch(i){case"error":if(vi.error(r.error.message),r.uuid){const e=this.decryptDataRequests.get(r.uuid);if(null==e?void 0:e.reject){e.reject(r.error);break}const t=this.encryptDataRequests.get(r.uuid);if(null==t?void 0:t.reject){t.reject(r.error);break}}this.emit(Nr.EncryptionError,r.error,r.participantIdentity);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Nr.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){const e=null===(n=this.room)||void 0===n?void 0:n.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(Nr.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Ar.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case"decryptDataResponse":const e=this.decryptDataRequests.get(r.uuid);(null==e?void 0:e.resolve)&&e.resolve(r);break;case"encryptDataResponse":const i=this.encryptDataRequests.get(r.uuid);(null==i?void 0:i.resolve)&&i.resolve(r)}},this.onWorkerError=e=>{vi.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Nr.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||Gr()))throw new Jr("tried to setup end-to-end encryption on an unsupported browser");if(vi.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:bi.getLevel()}};this.worker&&(vi.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){vi.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):vi.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Wr.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Br.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==wt.NONE,t.identity)),e.on(Br.ConnectionStateChanged,t=>{t===Ha.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==wt.NONE,e.identity)})})}).on(Br.TrackUnsubscribed,(e,t,n)=>{var i;null===(i=this.worker)||void 0===i||i.postMessage({kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}})}).on(Br.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(Br.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(qr.LocalSenderCreated,(e,t)=>Si(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(qr.LocalTrackPublished,e=>{if(!so(e.track)||!Ms())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:yo(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(Ar.SetKey,e=>this.postKey(e)).on(Ar.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return Si(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 Xs;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(),s={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:i}},o=new Xs;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(s),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(r=this.room)||void 0===r?void 0:r.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}})}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");this.worker.postMessage({kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}})}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?yo(n.mimeType):void 0)}}setupE2EESender(e,t){io(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||vi.warn("early return because sender is not ready")}handleReceiver(e,t,n,i){return Si(this,void 0,void 0,function*(){if(this.worker){if(Gr()&&!_s())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:n,trackId:t,codec:i});else{if(Mr in e&&i)return void this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}});let r=e.writableStream,s=e.readableStream;if(!r||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}this.worker.postMessage({kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:i,participantIdentity:n,isReuse:Mr in e}},[s,r])}e[Mr]=!0}})}handleSender(e,t,n){var i;if(!(Mr in e)&&this.worker){if(!(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Gr()&&!_s())vi.info("initialize script transform"),e.transform=new RTCRtpScriptTransform(this.worker,{kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n});else{vi.info("initialize encoded streams");const i=e.createEncodedStreams();this.worker.postMessage({kind:"encode",data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}},[i.readable,i.writable])}e[Mr]=!0}}}class Eo{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Eo),this._instance}addFailedConnectionAttempt(e){var t;const n=Us(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,Es(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&Us(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&Us(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Eo._instance=null;const wo="default";class Po{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Po),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Si(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=Po.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){vi.debug("awaiting getUserMedia promise");try{e?yield Po.userMediaPromiseMap.get(e):yield Promise.all(Po.userMediaPromiseMap.values())}catch(e){vi.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(n&&(!Ds()||!t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>""===t.label&&(!e||t.kind===e)))){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 Si(this,void 0,void 0,function*(){if(t!==wo)return t;const i=yield this.getDevices(e),r=i.find(e=>e.deviceId===wo);if(!r)return void vi.warn("could not reliably determine default device");const s=i.find(e=>e.deviceId!==wo&&e.groupId===(null!=n?n:r.groupId));if(s)return null==s?void 0:s.deviceId;vi.warn("could not reliably determine default device")})}hasDeviceInUse(e){return e?Po.userMediaPromiseMap.has(e):Po.userMediaPromiseMap.size>0}}var Ro;Po.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Po.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(Ro||(Ro={}));class Io{constructor(){this.pendingTasks=new Map,this.taskMutex=new _,this.nextTaskIndex=0}run(e){return Si(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ro.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ro.RUNNING,yield e()}finally{t.status=Ro.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return Si(this,void 0,void 0,function*(){return this.run(()=>Si(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Oo{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:[]);r.binaryType="arraybuffer",this.ws=r;const s=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r.close(e,t)};this.opened=new Promise((e,t)=>{r.onopen=()=>{e({readable:new ReadableStream({start(e){r.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},r.onerror=t=>e.error(t)},cancel:s}),writable:new WritableStream({write(e){r.send(e)},abort(){r.close()},close:s}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",t)},r.addEventListener("error",t)}),this.closed=new Promise((e,t)=>{const n=()=>Si(this,void 0,void 0,function*(){const n=new Promise(e=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",t=>{e(t)},{once:!0})}),i=yield Promise.race([Es(250),n]);i?e(i):t(new Error("Encountered unspecified websocket error without a timely close event"))});r.onclose=t=>{let{code:i,reason:s}=t;e({closeCode:i,reason:s}),r.removeEventListener("error",n)},r.addEventListener("error",n)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=s}}function _o(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}function Do(e){if("string"==typeof e)return hn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return hn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const Mo=["syncState","trickle","offer","answer","simulate","leave"];var Ao;!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"}(Ao||(Ao={}));class xo{get currentState(){return this.state}get isDisconnected(){return this.state===Ao.DISCONNECTING||this.state===Ao.DISCONNECTED}get isEstablishingConnection(){return this.state===Ao.CONNECTING||this.state===Ao.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;this.rtt=0,this.state=Ao.DISCONNECTED,this.log=vi,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=yi(null!==(n=t.loggerName)&&void 0!==n?n:mi.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Io,this.queuedRequests=[],this.closingLock=new _,this.connectionLock=new _,this.state=Ao.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return Si(this,void 0,void 0,function*(){return this.state=Ao.CONNECTING,this.options=n,yield this.connect(e,t,n,i)})}reconnect(e,t,n,i){return Si(this,void 0,void 0,function*(){if(this.options)return this.state=Ao.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)})}connect(e,t,n,i){return Si(this,void 0,void 0,function*(){const r=yield this.connectionLock.lock();this.connectOptions=n;const s=function(){var e;const t=new Jt({sdk:Qt.JS,protocol:16,version:"2.16.0"});return Ns()&&(t.os=null!==(e=Fs())&&void 0!==e?e:""),t}(),o=n.singlePeerConnection?function(e,t,n){const i=new URLSearchParams;i.set("access_token",e);const r=new si({clientInfo:t,connectionSettings:new ri({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0});n.reconnectReason&&(r.reconnectReason=n.reconnectReason);const s=new oi({joinRequest:r.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(s.toBinary()))),i}(t,s,n):function(e,t,n){var i;const r=new URLSearchParams;return r.set("access_token",e),n.reconnect&&(r.set("reconnect","1"),n.sid&&r.set("sid",n.sid)),r.set("auto_subscribe",n.autoSubscribe?"1":"0"),r.set("sdk",Ns()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),n.adaptiveStream&&r.set("adaptive_stream","1"),n.reconnectReason&&r.set("reconnect_reason",n.reconnectReason.toString()),(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&r.set("network",navigator.connection.type),r}(t,s,n),a=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)}),_o(n,"rtc")}(e,o),c=_o(new URL(Zs(a)),"validate");return new Promise((e,t)=>Si(this,void 0,void 0,function*(){var s,o;try{let r=!1;const d=e=>Si(this,void 0,void 0,function*(){if(r)return;r=!0;const n=e instanceof Event?e.currentTarget:e,i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";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}}(n,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(i)).catch(e=>{this.log.error(e),this.close()}):this.close(),l(),t(n instanceof AbortSignal?n.reason:n)});null==i||i.addEventListener("abort",d);const l=()=>{clearTimeout(u),null==i||i.removeEventListener("abort",d)},u=setTimeout(()=>{d(new Kr("room connection has timed out (signal)",Ur.ServerUnreachable))},n.websocketTimeout),h=(e,t)=>{this.handleSignalConnected(e,u,t)},p=new URL(a);p.searchParams.has("access_token")&&p.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(p),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Oo(a);try{this.ws.closed.then(e=>{var n;this.isEstablishingConnection&&t(new Kr("Websocket got closed during a (re)connection attempt: ".concat(e.reason),Ur.InternalError)),1e3!==e.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:1e3===e.closeCode,state:this.state})),this.state===Ao.CONNECTED&&this.handleOnClose(null!==(n=e.reason)&&void 0!==n?n:"Unexpected WS error"))}).catch(e=>{this.isEstablishingConnection&&t(new Kr("Websocket error during a (re)connection attempt: ".concat(e),Ur.InternalError))});const i=yield this.ws.opened.catch(e=>Si(this,void 0,void 0,function*(){if(this.state!==Ao.CONNECTED){this.state=Ao.DISCONNECTED,clearTimeout(u);const n=yield this.handleConnectionError(e,c);return void t(n)}this.handleWSError(e),t(e)}));if(clearTimeout(u),!i)return;const r=i.readable.getReader();this.streamWriter=i.writable.getWriter();const a=yield r.read();if(r.releaseLock(),!a.value)throw new Kr("no message received as first message",Ur.InternalError);const d=Do(a.value),l=this.validateFirstMessage(d,null!==(s=n.reconnect)&&void 0!==s&&s);if(!l.isValid)return void t(l.error);"join"===(null===(o=d.message)||void 0===o?void 0:o.case)&&(this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}))),h(i,l.shouldProcessFirstMessage?d:void 0),e(l.response)}catch(e){t(e)}finally{l()}}finally{r()}}))})}startReadingLoop(e,t){return Si(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Es(this.signalLatency));const{done:t,value:n}=yield e.read();if(t)break;const i=Do(n);this.handleSignalResponse(i)}})}close(){return Si(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*(){if([Ao.DISCONNECTING||Ao.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Ao.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,Es(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=Ao.DISCONNECTED),i()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Lo(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Lo(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new gn({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new fn({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Si(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 _n({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 On({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Wn({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Y.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Yn({timestamp:Y.parse(Date.now()),rtt:Y.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new wn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Rn({reason:mt.CLIENT_INITIATED,action:In.DISCONNECT})})}sendRequest(e){return Si(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=Mo.indexOf(e.case)>=0;return vi.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&t.state===Ao.RECONNECTING)return void t.queuedRequests.push(()=>Si(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield Es(t.signalLatency)),t.isDisconnected)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),t.logContext);const r=new un({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message",this.logContext);let r=!1;if("answer"===i.case){const e=No(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=No(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):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{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 Si(this,void 0,void 0,function*(){if(this.state===Ao.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=cs.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&cs.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=cs.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&cs.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=Ao.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,i,r,s,o;return"join"===(null===(n=e.message)||void 0===n?void 0:n.case)?{isValid:!0,response:e.message.value}:this.state===Ao.RECONNECTING&&"leave"!==(null===(i=e.message)||void 0===i?void 0:i.case)?"reconnect"===(null===(r=e.message)||void 0===r?void 0:r.case)?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(s=e.message)||void 0===s?void 0:s.case)?{isValid:!1,error:new Kr("Received leave request while trying to (re)connect",Ur.LeaveRequest,void 0,e.message.value.reason)}:t?{isValid:!1,error:new Kr("Unexpected first message",Ur.InternalError)}:{isValid:!1,error:new Kr("did not receive join response, got ".concat(null===(o=e.message)||void 0===o?void 0:o.case," instead"),Ur.InternalError)}}handleConnectionError(e,t){return Si(this,void 0,void 0,function*(){try{const n=yield fetch(t);if(n.status.toFixed(0).startsWith("4")){const e=yield n.text();return new Kr(e,Ur.NotAllowed,n.status)}return e instanceof Kr?e:new Kr("Encountered unknown websocket error during connection: ".concat(e),Ur.InternalError,n.status)}catch(e){return e instanceof Kr?e:new Kr(e instanceof Error?e.message:"server was not reachable",Ur.ServerUnreachable)}})}}function No(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 Lo(e,t){return new Tn({sdp:e.sdp,type:e.type,id:t})}class Uo{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0&&!(this._totalSize-this.buffer[0].data.byteLength<=e);)this.pop()}get length(){return this.buffer.length}}class jo{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();return n-this._lastCleanup>this.ttl/2&&this.cleanup(),this._map.set(e,{value:t,expiresAt:n+this.ttl}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt<Date.now()))return t.value;this._map.delete(e)}}has(e){const t=this._map.get(e);return!(!t||t.expiresAt<Date.now()&&(this._map.delete(e),1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[i,r]of n.entries())t.push(e(r,i,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Fo,Vo,Bo,qo,Wo,Ho={},Go={},zo={exports:{}};function Ko(){if(Fo)return zo.exports;Fo=1;var e=zo.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),zo.exports}function Jo(){return Vo||(Vo=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 s=e.push?{}:r?n[e.name]:n;!function(e,n,i,r){if(r&&!i)n[r]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(n[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&n[e.push].push(s)},i=Ko(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.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,o,r)}}),t.media=s,t};var s=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(s,{})},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(s,{})})},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}})})}}(Go)),Go}function Qo(){if(qo)return Bo;qo=1;var e=Ko(),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 s=0;s<t.names.length;s+=1)r.push(t.name?i[t.name][t.names[s]]:i[t.names[s]]);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"],s=["i","c","b","a"];return Bo=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 o=n.innerOrder||s,a=[];return(n.outerOrder||r).forEach(function(n){e[n].forEach(function(e){e.name in t&&null!=t[e.name]?a.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){a.push(i(n,e,t))})})}),t.media.forEach(function(t){a.push(i("m",e.m[0],t)),o.forEach(function(n){e[n].forEach(function(e){e.name in t&&null!=t[e.name]?a.push(i(n,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){a.push(i(n,e,t))})})})}),a.join("\r\n")+"\r\n"},Bo}var Yo=function(){if(Wo)return Ho;Wo=1;var e=Jo(),t=Qo(),n=Ko();return Ho.grammar=n,Ho.write=t,Ho.parse=e.parse,Ho.parseParams=e.parseParams,Ho.parseFmtpConfig=e.parseFmtpConfig,Ho.parsePayloads=e.parsePayloads,Ho.parseRemoteCandidates=e.parseRemoteCandidates,Ho.parseImageAttributes=e.parseImageAttributes,Ho.parseSimulcastStreamList=e.parseSimulcastStreamList,Ho}();function Xo(e,t,n){var i,r,s;void 0===t&&(t=50),void 0===n&&(n={});var o=null!=(i=n.isImmediate)&&i,a=null!=(r=n.callback)&&r,c=n.maxWait,d=Date.now(),l=[];function u(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),n=this;return new Promise(function(i,r){var c=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,d=Date.now(),!o){var i=e.apply(n,t);a&&a(i),l.forEach(function(e){return(0,e.resolve)(i)}),l=[]}},u()),c){var h=e.apply(n,t);return a&&a(h),i(h)}l.push({resolve:i,reject:r})})};return h.cancel=function(e){void 0!==s&&clearTimeout(s),l.forEach(function(t){return(0,t.reject)(e)}),l=[]},h}const $o="negotiationStarted",Zo="negotiationComplete",ea="rtpVideoPayloadTypes";class ta extends Pi.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;super(),this.log=vi,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xo(e=>Si(this,void 0,void 0,function*(){this.emit($o);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=yi(null!==(n=t.loggerName)&&void 0!==n?n:mi.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new _}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Si(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return Si(this,void 0,void 0,function*(){var n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let i;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],r=Yo.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return r.media.forEach(e=>{var t;const r=ra(e.mid);"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===s&&"nack"===e.type))&&i.push(r),e.fmtp.some(e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&n.push(r),!0)))}),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){const t=Yo.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach(e=>{const t=ra(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})}),i=Yo.write(t)}return yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(Zo),e.sdp)&&Yo.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(ea,e.rtp)}),!0})}createAndSendOffer(e){return Si(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Yo.parse(null!==(t=i.sdp)&&void 0!==t?t:"");if(r.media.forEach(e=>{ia(e),"audio"===e.type?na(e,["all"],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0)),0===n)return!0;if(Rs(t.codec)&&!Ds()&&this.ensureVideoDDExtensionForSVC(e,r),!Rs(t.codec))return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0})}),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));yield this.setMungedSDP(i,Yo.write(r)),this.onOffer(i,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return Si(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Yo.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach(e=>{ia(e),"audio"===e.type&&na(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Yo.write(n)),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 Xr("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Xr("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Si(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 Si(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let i="unknown error";t instanceof Error?i=t.message:"string"==typeof t&&(i=t);const r={error:i,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(r.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:r})),new $r(i)}})}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!(null===(n=e.ext)||void 0===n?void 0:n.some(e=>e.uri===Cs))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var n;"video"===t.type&&(null===(n=t.ext)||void 0===n||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(i=e.ext)||void 0===i||i.push({value:this.ddExtID,uri:Cs})}}}function na(e,t,n){const i=ra(e.mid);let r=0;e.rtp.some(e=>"opus"===e.codec&&(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&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function ia(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function ra(e){return"number"==typeof e?e.toFixed(0):e}const sa="vp8",oa={audioPreset:bs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ss.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:sa,backupCodec:!0,preConnectBuffer:!1},aa={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ca={deviceId:{ideal:"default"},resolution:ks.h720.resolution},da={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Ti}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},la={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ua;!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"}(ua||(ua={}));class ha{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var i;this.peerConnectionTimeout=la.peerConnectionTimeout,this.log=vi,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map(e=>e.getConnectionState());i.every(e=>"connected"===e)?this.state=ua.CONNECTED:i.some(e=>"failed"===e)?this.state=ua.FAILED:i.some(e=>"connecting"===e)?this.state=ua.CONNECTING:i.every(e=>"closed"===e)?this.state=ua.CLOSED:i.some(e=>"closed"===e)?this.state=ua.CLOSING:i.every(e=>"new"===e)&&(this.state=ua.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(ua[n]," to ").concat(ua[this.state]),this.logContext),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.log=yi(null!==(i=n.loggerName)&&void 0!==i?i:mi.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired="subscriber-primary"!==t,this.isSubscriberConnectionRequired="subscriber-primary"===t,this.publisher=new ta(e,n),"publisher-only"!==t&&(this.subscriber=new ta(e,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,cn.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,cn.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=ua.NEW,this.connectionLock=new _,this.remoteOfferLock=new _}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){this.isPublisherConnectionRequired=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],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 Si(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(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return Si(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return Si(this,void 0,void 0,function*(){var n;t===cn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return Si(this,void 0,void 0,function*(){var n,i,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()}));const s=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{s()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Si(this,void 0,void 0,function*(){var n;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map(n=>this.ensureTransportConnected(n,e,t)))}finally{i()}})}negotiate(e){return Si(this,void 0,void 0,function*(){return new Promise((t,n)=>Si(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(i),n("negotiation aborted")}),this.publisher.once($o,()=>{e.signal.aborted||this.publisher.once(Zo,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(i),n(e)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e);return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===cn.PUBLISHER||e===cn.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 Si(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)=>Si(n,void 0,void 0,function*(){const n=()=>{this.log.warn("abort transport connection",this.logContext),cs.clearTimeout(s),r(new Kr("room connection has been cancelled",Ur.Cancelled))};(null==t?void 0:t.signal.aborted)&&n(),null==t||t.signal.addEventListener("abort",n);const s=cs.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",n),r(new Kr("could not establish pc connection",Ur.InternalError))},i);for(;this.state!==ua.CONNECTED;)if(yield Es(50),null==t?void 0:t.signal.aborted)return void r(new Kr("room connection has been cancelled",Ur.Cancelled));cs.clearTimeout(s),null==t||t.signal.removeEventListener("abort",n),e()}))}()})}}class pa{static fetchRegionSettings(e,t,n){return Si(this,void 0,void 0,function*(){const i=yield pa.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:5e3;return{regionSettings:yield i.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw new Kr("Could not fetch region settings: ".concat(i.statusText),401===i.status?Ur.NotAllowed:Ur.InternalError,i.status)}catch(e){throw e instanceof Kr?e:(null==n?void 0:n.aborted)?new Kr("Region fetching was aborted",Ur.Cancelled):new Kr("Could not fetch region settings, ".concat(e instanceof Error?"".concat(e.name,": ").concat(e.message):e),Ur.ServerUnreachable,500)}finally{i()}})}static scheduleRefetch(e,t,n){return Si(this,void 0,void 0,function*(){const i=pa.settingsTimeouts.get(e.hostname);clearTimeout(i),pa.settingsTimeouts.set(e.hostname,setTimeout(()=>Si(this,void 0,void 0,function*(){try{const n=yield pa.fetchRegionSettings(e,t);pa.updateCachedRegionSettings(e,t,n)}catch(i){if(i instanceof Kr&&i.reason===Ur.NotAllowed)return void vi.debug("token is not valid, cancelling auto region refresh");vi.debug("auto refetching of region settings failed",{error:i}),pa.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){pa.cache.set(e.hostname,n),pa.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=pa.settingsTimeouts.get(e);t&&(clearTimeout(t),pa.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=pa.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const t=pa.connectionTrackers.get(e);t&&0===t.connectionCount&&(vi.debug("stopping region refetch after disconnect delay",{hostname:e}),pa.stopRefetch(e)),t&&(t.cleanupTimeout=void 0)},3e4))}static cancelCleanup(e){const t=pa.connectionTrackers.get(e);(null==t?void 0:t.cleanupTimeout)&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=pa.connectionTrackers.get(e);t||(t={connectionCount:0},pa.connectionTrackers.set(e,t)),t.connectionCount++,pa.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=pa.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),0===t.connectionCount&&pa.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ls(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Si(this,void 0,void 0,function*(){return pa.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return Si(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=pa.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),pa.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),vi.debug("next region: ".concat(e.region)),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){pa.updateCachedRegionSettings(this.serverUrl,this.token,e)}}pa.cache=new Map,pa.settingsTimeouts=new Map,pa.connectionTrackers=new Map,pa.fetchLock=new _;class ma extends Error{constructor(e,t,n){super(t),this.code=e,this.message=fa(t,ma.MAX_MESSAGE_BYTES),this.data=n?fa(n,ma.MAX_DATA_BYTES):void 0}static fromProto(e){return new ma(e.code,e.message,e.data)}toProto(){return new Ht({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ma(ma.ErrorCode[e],ma.ErrorMessage[e],t)}}function ga(e){return(new TextEncoder).encode(e).length}function fa(e,t){if(ga(e)<=t)return e;let n=0,i=e.length;const r=new TextEncoder;for(;n<i;){const s=Math.floor((n+i+1)/2);r.encode(e.slice(0,s)).length<=t?n=s:i=s-1}return e.slice(0,n)}ma.MAX_MESSAGE_BYTES=256,ma.MAX_DATA_BYTES=15360,ma.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},ma.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 va=2e3;function ya(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 ba="undefined"!=typeof MediaRecorder,ka=ba?MediaRecorder:class{constructor(){throw new Error("MediaRecorder is not available in this environment")}};class Ta extends ka{constructor(e,t){if(!ba)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",s),null==i||i.close(),i=void 0},s=e=>{null==i||i.error(e),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",r),this.removeEventListener("error",s),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>Si(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",s)}}class Sa extends us{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Xo(()=>Si(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>Si(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(Hr.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new _,this.pauseUpstreamLock=new _,this.trackChangeLock=new _,this.trackChangeLock.lock().then(t=>Si(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==us.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Si(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{ps(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&&(hs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&"closed"!==(null===(n=this.sender.transport)||void 0===n?void 0:n.state)&&(yield this.sender.replaceTrack(null!=i?i:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{hs(null!=i?i:e,t)}))})}waitForDimensions(){return Si(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var n;if(e.kind===us.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=rs())||void 0===n?void 0:n.os)&&(yield Es(10));const i=Date.now();for(;Date.now()-i<t;){const t=e.dimensions;if(t)return t;yield Es(50)}throw new Qr("unable to get track dimensions after timeout")}()})}setDeviceId(e){return Si(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===$s(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),$s(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return Si(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===us.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===us.Kind.Audio?"audioinput":"videoinput";return t?Po.getInstance().normalizeDeviceId(r,n,i):n}()})}mute(){return Si(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return Si(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return Si(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Qr("unable to replace an unpublished track");let n,i;return"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e){return Si(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:n}=e,i=function(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}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const r={audio:!1,video:!1};this.kind===us.Kind.Video?r.video=!t&&!n||{deviceId:t,facingMode:n}:r.audio=!t||Object.assign({deviceId:t},i),this.attachedElements.forEach(e=>{ps(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const s=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return this.kind===us.Kind.Video&&(yield s.applyConstraints(i)),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(Hr.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Hr.Muted:Hr.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 Si(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),As()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Si(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Hr.UpstreamPaused,this);const t=rs();if("Safari"===(null==t?void 0:t.name)&&Bs(t.version,"12.0")<0)throw new Jr("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return Si(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Hr.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return Si(this,void 0,void 0,function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return Si(this,arguments,void 0,function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var i;const r=yield t.trackChangeLock.lock();try{t.log.debug("setting up processor",t.logContext);const r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.internalStopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(hs(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&n&&(ps(t._mediaStreamTrack,e),hs(t.processor.processedTrack,e));yield null===(i=t.sender)||void 0===i?void 0:i.replaceTrack(t.processor.processedTrack)}t.emit(Hr.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return Si(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return Si(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(n=e.processor.processedTrack)||void 0===n||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(i=e.processorElement)||void 0===i||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Hr.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(ba)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 Ta(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 Ca extends Sa{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>3?arguments[3]:void 0;super(e,us.Kind.Audio,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>4?arguments[4]:void 0),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Si(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=ya(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Hr.AudioTrackFeatureUpdate,this,vt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Hr.AudioTrackFeatureUpdate,this,vt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Si(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===us.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 Si(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==$s(this._constraints.deviceId);return this.source!==us.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return Si(this,void 0,void 0,function*(){let t;if(e){const n=mo({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Si(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){xs()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},va)))}setProcessor(e){return Si(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!Ns()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const n={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(n),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Hr.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return Si(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return Si(this,void 0,void 0,function*(){const e=yield function(e){return Si(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=go();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Es(t),i.getByteTimeDomainData(r);const s=r.some(e=>128!==e&&0!==e);return n.close(),!s}return!1}()})}(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(Hr.AudioSilenceDetected)),e})}}const Ea=Object.values(ks),wa=Object.values(Ts),Pa=Object.values(Ss),Ra=[ks.h180,ks.h360],Ia=[Ts.h180,Ts.h360],Oa=["q","h","f"];function _a(e,t,n,i){var r,s;let o=null==i?void 0:i.videoEncoding;e&&(o=null==i?void 0:i.screenShareEncoding);const a=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!o&&!a&&!c||!t||!n)return[{}];o||(o=function(e,t,n,i){const r=function(e,t,n){if(e)return Pa;const i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?Ea:wa}(e,t,n);let{encoding:s}=r[0];const o=Math.max(t,n);for(let e=0;e<r.length;e+=1){const t=r[e];if(s=t.encoding,t.width>=o)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,n,d),vi.debug("using video encoding",o));const l=o.maxFramerate,u=new ms(t,n,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Rs(d)){const e=new xa(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=rs();if(Ms()||Ns()||"Chrome"===(null==n?void 0:n.name)&&Bs(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,r=function(e){return e||(e=rs()),"Safari"===(null==e?void 0:e.name)&&Bs(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&Bs(e.osVersion,"18.3")>0}(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:Oa[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,n):void 0});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),vi.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(r=Aa(null==i?void 0:i.screenShareSimulcastLayers))&&void 0!==r?r:Da(e,u):null!==(s=Aa(null==i?void 0:i.videoSimulcastLayers))&&void 0!==s?s:Da(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const i=Math.max(t,n);if(i>=960&&h)return Ma(t,n,[e,h,u],l);if(i>=480)return Ma(t,n,[e,u],l)}return Ma(t,n,[u])}function Da(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(n=t).encoding.maxFramerate}].map(e=>{var t,i;return new ms(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{width:i,height:r}=t,s=i>r?i/r:r/i;return Math.abs(s-16/9)<Math.abs(s-4/3)?Ra:Ia}function Ma(e,t,n,i){const r=[];if(n.forEach((n,s)=>{if(s>=Oa.length)return;const o=Math.min(e,t),a={rid:Oa[s],scaleResolutionDownBy:Math.max(1,o/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=Os()||0===s;n.encoding.priority&&d&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),r.push(a)}),Ns()&&"ios"===Fs()){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,vi.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),vi.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)})}return r}function Aa(e){if(e)return e.sort((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class xa{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 Na extends Sa{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){super(e,us.Kind.Video,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2],arguments.length>3?arguments[3]:void 0),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Si(this,void 0,void 0,function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>"cpu"===e.qualityLimitationReason);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(Hr.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{var i;const r=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=ya(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new _}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!xs())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},va))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Si(this,void 0,void 0,function*(){var t,n,i,r;yield e.pauseUpstream.call(this);try{for(var s,o=!0,a=Ci(this.simulcastCodecs.values());!(t=(s=yield a.next()).done);o=!0){o=!1;const e=s.value;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(e){n={error:e}}finally{try{o||t||!(i=a.return)||(yield i.call(a))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Si(this,void 0,void 0,function*(){var t,n,i,r;yield e.resumeUpstream.call(this);try{for(var s,o=!0,a=Ci(this.simulcastCodecs.values());!(t=(s=yield a.next()).done);o=!0){o=!1;const e=s.value;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{o||t||!(i=a.return)||(yield i.call(a))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Si(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!==us.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 Si(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==us.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Si(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},s=n.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.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})}setPublishingQuality(e){const t=[];for(let n=ls.LOW;n<=ls.HIGH;n+=1)t.push(new jn({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Rs(this.codec),t)}restartTrack(e){return Si(this,void 0,void 0,function*(){var t,n,i,r;let s;if(e){const t=mo({video:e});"boolean"!=typeof t.video&&(s=t.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var o,a=!0,c=Ci(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){a=!1;const e=o.value;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{a||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Si(this,arguments,void 0,function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var r,s,o,a,c;if(yield t.setProcessor.call(n,e,i),null===(a=n.processor)||void 0===a?void 0:a.processedTrack)try{for(var d,l=!0,u=Ci(n.simulcastCodecs.values());!(r=(d=yield u.next()).done);l=!0){l=!1;const e=d.value;yield null===(c=e.sender)||void 0===c?void 0:c.replaceTrack(n.processor.processedTrack)}}catch(e){s={error:e}}finally{try{l||r||!(o=u.return)||(yield o.call(u))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return Si(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return Si(this,void 0,void 0,function*(){var t,n,i,r,s,o;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(Rs(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const a=[];try{for(t=!0,n=Ci(e);!(r=(i=yield n.next()).done);t=!0){t=!1;const e=i.value;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 La(t.sender,t.encodings,e.qualities,this.senderLock,Rs(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){a.push(e.codec);break}}else yield this.setPublishingLayers(Rs(e.codec),e.qualities)}}catch(e){s={error:e}}finally{try{t||r||!(o=n.return)||(yield o.call(n))}finally{if(s)throw s.error}}return a})}setPublishingLayers(e,t){return Si(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 La(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))})}prioritizePerformance(){return Si(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&&Rs(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Si(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),As()&&this.isInBackground&&this.source===us.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function La(e,t,n,i,r,s,o){return Si(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),{encodings:a}=i;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));let c=!1;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=Ua(a),l=n.find(e=>e.quality===d);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),o),Os()&&(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,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}})}function Ua(e){switch(e){case"f":default:return ls.HIGH;case"h":return ls.MEDIUM;case"q":return ls.LOW}}function ja(e,t,n,i){if(!n)return[new It({quality:ls.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(i){const i=new xa(n[0].scalabilityMode),r=[],s="h"==i.suffix?1.5:2,o="h"==i.suffix?2:3;for(let a=0;a<i.spatial;a+=1)r.push(new It({quality:Math.min(ls.HIGH,i.spatial-1)-a,width:Math.ceil(e/Math.pow(s,a)),height:Math.ceil(t/Math.pow(s,a)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(o,a)):0,ssrc:0}));return r}return n.map(n=>{var i,r,s;const o=null!==(i=n.scaleResolutionDownBy)&&void 0!==i?i:1;let a=Ua(null!==(r=n.rid)&&void 0!==r?r:"");return new It({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(s=n.maxBitrate)&&void 0!==s?s:0,ssrc:0})})}const Fa="_lossy",Va="_reliable",Ba="leave-reconnect";var qa,Wa,Ha,Ga;!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"}(qa||(qa={}));class za extends Pi.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=la.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=qa.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=vi,this.reliableDataSequence=1,this.reliableMessageBuffer=new Uo,this.reliableReceivedState=new jo(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>Si(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(n){if(n.label===Va)t.reliableDCSub=n;else{if(n.label!==Fa)return;t.lossyDCSub=n}t.log.debug("on data channel ".concat(n.id,", ").concat(n.label),t.logContext),n.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>Si(this,void 0,void 0,function*(){var t,n,i,r,s;const o=yield this.dataProcessLock.lock();try{let o;if(e.data instanceof ArrayBuffer)o=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));o=yield e.data.arrayBuffer()}const a=_t.fromBinary(new Uint8Array(o));if(a.sequence>0&&""!==a.participantSid){const e=this.reliableReceivedState.get(a.participantSid);if(e&&a.sequence<=e)return;this.reliableReceivedState.set(a.participantSid,a.sequence)}if("speaker"===(null===(t=a.value)||void 0===t?void 0:t.case))this.emit(Wr.ActiveSpeakersUpdate,a.value.value.speakers);else if("encryptedPacket"===(null===(n=a.value)||void 0===n?void 0:n.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const e=yield null===(i=this.e2eeManager)||void 0===i?void 0:i.handleEncryptedData(a.value.value.encryptedValue,a.value.value.iv,a.participantIdentity,a.value.value.keyIndex),t=At.fromBinary(e.payload),n=new _t({value:t.value,participantIdentity:a.participantIdentity,participantSid:a.participantSid});"user"===(null===(r=n.value)||void 0===r?void 0:r.case)&&Ja(n,n.value.value),this.emit(Wr.DataPacketReceived,n,a.value.value.encryptionType)}else"user"===(null===(s=a.value)||void 0===s?void 0:s.case)&&Ja(a,a.value.value),this.emit(Wr.DataPacketReceived,a,wt.NONE)}finally{o()}}),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(0===e.currentTarget.maxRetransmits?Dt.LOSSY:Dt.RELIABLE)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const n=Date.now()-this.reconnectStart;let i=this.getNextRetryDelay({elapsedMs:n,retryCount:this.reconnectAttempts});null!==i?(e===Ba&&(i=0),this.log.debug("reconnecting in ".concat(i,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=cs.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Wr.Disconnected),this.close()})(n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===qa.Connected&&e();const n=()=>{this.off(Wr.Disconnected,i),e()},i=()=>{this.off(Wr.Restarted,n),t()};this.once(Wr.Restarted,n),this.once(Wr.Disconnected,i)}),this.updateAndEmitDCBufferStatus=e=>{if(e===Dt.RELIABLE){const t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Wr.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Si(this,void 0,void 0,function*(){this.url&&(yield fetch(Zs(this.url),{method:"HEAD"}).then(e=>e.ok).catch(()=>!1))&&(this.log.info("detected network reconnected"),(this.client.currentState===Ao.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Ao.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(gt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>Si(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Zs(this.url),{method:"HEAD"}),Es(4e3).then(()=>Promise.reject())])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=yi(null!==(t=e.loggerName)&&void 0!==t?t:mi.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new xo(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new _,this.dataProcessLock=new _,this.dcBufferStatus=new Map([[Dt.LOSSY,!0],[Dt.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Wr.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Wr.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Wr.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Wr.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Wr.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Wr.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Wr.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Wr.SignalRequestResponse,e)}get logContext(){var e,t,n,i,r,s;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===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,pID:this.participantSid}}join(e,t,n,i){return Si(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),this.subscriberPrimary&&!r.fastPublish||this.negotiate().catch(e=>{vi.error(e,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=r.clientConfiguration,this.emit(Wr.SignalConnected,r),r}catch(r){if(r instanceof Kr&&r.reason===Ur.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw r}})}close(){return Si(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Wr.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return Si(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Uo,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return Si(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Qr("a track with the same ID has already been published");return new Promise((t,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new Kr("publication of local track timed out, no response from server",Ur.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(i),t(e)},reject:()=>{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{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Si(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Si(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==ua.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const i=this.makeRTCConfiguration(e);var r;this.pcManager=new ha(i,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(Wr.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)=>Si(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(n)&&(this.publisherConnectionPromise=void 0),t===ua.CONNECTED){const t=this.pcState===qa.New;this.pcState=qa.Connected,t&&this.emit(Wr.Connected,e)}else t===ua.FAILED&&(this.pcState!==qa.Connected&&this.pcState!==qa.Reconnecting||(this.pcState=qa.Disconnected,this.handleDisconnect("peerconnection failed","failed"===i?gt.RR_SUBSCRIBER_FAILED:gt.RR_PUBLISHER_FAILED)));const r=this.client.isDisconnected||this.client.currentState===Ao.RECONNECTING,s=[ua.FAILED,ua.CLOSING,ua.CLOSED].includes(t);r&&s&&!this._isClosed&&this.emit(Wr.Offline)}),this.pcManager.onTrack=e=>{0!==e.streams.length&&this.emit(Wr.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(r=null===(n=e.serverInfo)||void 0===n?void 0:n.protocol)&&r>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>Si(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>Si(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",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Wr.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Wr.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,null===(t=this.regionUrlProvider)||void 0===t||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Wr.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Wr.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Wr.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,n;const i={direction:"recvonly"};for(let n=0;n<e.numAudios;n++)null===(t=this.pcManager)||void 0===t||t.addPublisherTransceiverOfKind("audio",i);for(let t=0;t<e.numVideos;t++)null===(n=this.pcManager)||void 0===n||n.addPublisherTransceiverOfKind("video",i);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",gt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:e.regions})),e.action){case In.DISCONNECT:this.emit(Wr.Disconnected,null==e?void 0:e.reason),this.close();break;case In.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Ba);break;case In.RESUME:this.handleDisconnect(Ba)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach(e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)}),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===pt.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Fa,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Va,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return Si(this,void 0,void 0,function*(){if(ws())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Ps())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Xr("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,i){return Si(this,void 0,void 0,function*(){if(ws())return this.createSimulcastTransceiverSender(e,t,n,i);if(Ps())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Xr("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),so(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,i){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return Si(this,void 0,void 0,function*(){var t,n,i;if(!this._isClosed)if(this.attemptingReconnect)vi.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==pt.DISABLED&&(null!==(i=null===(n=this.pcManager)||void 0===n?void 0:n.currentState)&&void 0!==i?i:ua.NEW)!==ua.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof Xr?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Ka||(this.fullReconnectOnNext=!0),t?this.handleDisconnect("reconnect",gt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Wr.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return Si(this,void 0,void 0,function*(){var t,n,i;try{if(!this.url||!this.token)throw new Xr("could not reconnect, url or token not saved");let n;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Wr.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ka;n=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof Kr&&e.reason===Ur.NotAllowed)throw new Xr("could not reconnect, token might be expired");throw new Ka}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Wr.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==Ao.CONNECTED)throw new Ka("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Wr.Restarted)}catch(e){const t=yield null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(i=this.regionUrlProvider)||void 0===i||i.resetAttempts(),e}})}resumeConnection(e){return Si(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Xr("could not reconnect, url or token not saved");if(!this.pcManager)throw new Xr("publisher and subscriber connections unset");let n;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Wr.Resuming);try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t="";if(e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof Kr&&e.reason===Ur.NotAllowed)throw new Xr("could not reconnect, token might be expired");if(e instanceof Kr&&e.reason===Ur.LeaveRequest)throw e;throw new Ka(t)}if(this.emit(Wr.SignalResumed),n){const e=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Ao.CONNECTED)throw new Ka("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==n?void 0:n.lastMessageSeq)&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(Wr.Resumed)})}waitForPCInitialConnection(e,t){return Si(this,void 0,void 0,function*(){if(!this.pcManager)throw new Xr("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return Si(this,void 0,void 0,function*(){this.pcState=qa.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Es(2e3),!this.pcManager)throw new Xr("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=qa.Connected}catch(e){throw this.pcState=qa.Disconnected,new Kr("could not establish PC connection, ".concat(e.message),Ur.InternalError)}})}publishRpcResponse(e,t,n,i){return Si(this,void 0,void 0,function*(){const r=new _t({destinationIdentities:[e],kind:Dt.RELIABLE,value:{case:"rpcResponse",value:new Wt({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}});yield this.sendDataPacket(r,Dt.RELIABLE)})}publishRpcAck(e,t){return Si(this,void 0,void 0,function*(){const n=new _t({destinationIdentities:[e],kind:Dt.RELIABLE,value:{case:"rpcAck",value:new qt({requestId:t})}});yield this.sendDataPacket(n,Dt.RELIABLE)})}sendDataPacket(e,t){return Si(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=function(e){var t,n,i,r,s;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===(s=e.value)||void 0===s?void 0:s.case))return new At({value:e.value})}(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new Mt({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===Dt.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary();yield this.waitForBufferStatusLow(t);const i=this.dataChannelForKind(t);if(i){if(t===Dt.RELIABLE&&this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;i.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return Si(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Dt.RELIABLE);const t=this.dataChannelForKind(Dt.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(Dt.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,n)=>Si(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>n("Engine closed");for(this.once(Wr.Closing,i);!this.dcBufferStatus.get(e);)yield Es(10);this.off(Wr.Closing,i),t()}}))}ensureDataTransportConnected(e){return Si(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 Xr("PC manager is closed");const r=n?t.pcManager.subscriber:t.pcManager.publisher,s=n?"Subscriber":"Publisher";if(!r)throw new Kr("".concat(s," connection not set"),Ur.InternalError);let o=!1;n||t.dataChannelForKind(e,n)||(t.createDataChannels(),o=!0),o||n||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate().catch(e=>{vi.error(e,t.logContext)});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 Es(50)}throw new Kr("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()),Ur.InternalError)}()})}ensurePublisherConnected(e){return Si(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===ua.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Si(this,void 0,void 0,function*(){return new Promise((e,t)=>Si(this,void 0,void 0,function*(){if(!this.pcManager)return void t(new $r("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(Wr.Closing,i),this.pcManager.publisher.once(ea,e=>{const t=new Map;e.forEach(e=>{const n=e.codec.toLowerCase();fs.includes(n)&&t.set(e.payload,n)}),this.emit(Wr.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(e){e instanceof $r&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",gt.RR_UNKNOWN),t(e)}finally{this.off(Wr.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===Dt.LOSSY)return this.lossyDCSub;if(e===Dt.RELIABLE)return this.reliableDCSub}else{if(e===Dt.LOSSY)return this.lossyDC;if(e===Dt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i,r,s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const o=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getLocalDescription(),l=null===(s=null===(r=this.signalOpts)||void 0===r?void 0:r.autoSubscribe)||void 0===s||s,u=new Array,h=new Array;e.forEach(e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)}),this.client.sendSyncState(new zn({answer:this.options.singlePeerConnection?a?Lo({sdp:a.sdp,type:a.type}):void 0:d?Lo({sdp:d.sdp,type:d.type}):void 0,offer:this.options.singlePeerConnection?o?Lo({sdp:o.sdp,type:o.type}):void 0:c?Lo({sdp:c.sdp,type:c.type}):void 0,subscription:new Cn({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:bo(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new Kn({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Jn({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(Dt.LOSSY),cn.PUBLISHER),t(this.dataChannelForKind(Dt.RELIABLE),cn.PUBLISHER),t(this.dataChannelForKind(Dt.LOSSY,!0),cn.SUBSCRIBER),t(this.dataChannelForKind(Dt.RELIABLE,!0),cn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&cs.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){xs()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){xs()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(n){const e=Object.entries(this.midToTrackId).find(e=>{let[t]=e;return t===n});if(e)return e[1]}}}class Ka extends Error{}function Ja(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}class Qa{get info(){return this._info}validateBytesReceived(){if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.bytesReceived<this.totalByteSize)throw new ts("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),jr.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ts("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),jr.LengthExceeded)}}constructor(e,t,n,i){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=i}}class Ya extends Qa{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived(),null===(t=this.onProgress)||void 0===t||t.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Xs,n=null,i=null;if(this.signal){const e=this.signal;i=()=>{var n;null===(n=t.reject)||void 0===n||n.call(t,e.reason)},e.addEventListener("abort",i),n=e}const r=()=>{e.releaseLock(),n&&i&&n.removeEventListener("abort",i),this.signal=void 0};return{next:()=>Si(this,void 0,void 0,function*(){var n,i;try{const{done:r,value:s}=yield Promise.race([e.read(),t.promise,null!==(i=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==i?i:new Promise(()=>{})]);return r?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(s),{done:!1,value:s.content})}catch(e){throw r(),e}}),return(){return Si(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Si(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;let s=new Set;const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var a,c=!0,d=Ci(o);!(n=(a=yield d.next()).done);c=!0)c=!1,s.add(a.value)}catch(e){i={error:e}}finally{try{c||n||!(r=d.return)||(yield r.call(d))}finally{if(i)throw i.error}}return Array.from(s)}()})}}class Xa extends Qa{constructor(e,t,n,i){super(e,t,n,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=to(e.chunkIndex),i=this.receivedChunks.get(n);i&&i.version>e.version||(this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived(),null===(t=this.onProgress)||void 0===t||t.call(this,this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0))}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Xs,i=null,r=null;if(this.signal){const e=this.signal;r=()=>{var t;null===(t=n.reject)||void 0===t||t.call(n,e.reason)},e.addEventListener("abort",r),i=e}const s=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>Si(this,void 0,void 0,function*(){var i,r;try{const{done:s,value:o}=yield Promise.race([e.read(),n.promise,null!==(r=null===(i=this.outOfBandFailureRejectingFuture)||void 0===i?void 0:i.promise)&&void 0!==r?r:new Promise(()=>{})]);if(s)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let e;this.handleChunkReceived(o);try{e=t.decode(o.content)}catch(e){throw new ts("Cannot decode datastream chunk ".concat(o.chunkIndex," as text: ").concat(e),jr.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw s(),e}}),return(){return Si(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Si(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;let s="";const o=t.signal?e.withAbortSignal(t.signal):e;try{for(var a,c=!0,d=Ci(o);!(n=(a=yield d.next()).done);c=!0)c=!1,s+=a.value}catch(e){i={error:e}}finally{try{c||n||!(r=d.return)||(yield r.call(d))}finally{if(i)throw i.error}}return s}()})}}class $a{constructor(){this.log=vi,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new ts('A text stream handler for topic "'.concat(e,'" has already been set.'),jr.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new ts('A byte stream handler for topic "'.concat(e,'" has already been set.'),jr.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,i,r;const s=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(s.length>0||o.length>0){const a=new ts("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),jr.AbnormalEnd);for(const[e,i]of o)null===(n=(t=i.outOfBandFailureRejectingFuture).reject)||void 0===n||n.call(t,a),this.byteStreamControllers.delete(e);for(const[e,t]of s)null===(r=(i=t.outOfBandFailureRejectingFuture).reject)||void 0===r||r.call(i,a),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return Si(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,n){return Si(this,void 0,void 0,function*(){var i;if("byteHeader"===e.contentHeader.case){const r=this.byteStreamHandlers.get(e.topic);if(!r)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const o=new Xs;o.promise.catch(e=>{this.log.error(e)});const a={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:to(e.timestamp),attributes:e.attributes,encryptionType:n},c=new ReadableStream({start:n=>{if(s=n,this.textStreamControllers.has(e.streamId))throw new ts("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),jr.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new Ya(a,c,to(e.totalLength),o),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let r;const s=new Xs;s.promise.catch(e=>{this.log.error(e)});const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n},a=new ReadableStream({start:n=>{if(r=n,this.textStreamControllers.has(e.streamId))throw new ts("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),jr.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:s})}});i(new Xa(o,a,to(e.totalLength),s),{identity:t})}})}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),jr.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),jr.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),jr.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new ts("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),jr.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Za{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 Si(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 ec extends Za{}class tc extends Za{}class nc{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Si(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),r=(new TextEncoder).encode(e).byteLength,s=null===(n=null==t?void 0:t.attachments)||void 0===n?void 0:n.map(()=>crypto.randomUUID()),o=new Array(s?s.length+1:1).fill(0),a=(e,n)=>{var i;o[n]=e;const r=o.reduce((e,t)=>e+t,0);null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,r)},c=yield this.streamText({streamId:i,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map((e,n)=>Si(this,void 0,void 0,function*(){return this._sendFile(s[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,n+1)}})})))),c.info})}streamText(e){return Si(this,void 0,void 0,function*(){var t,n,i;const r=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes,encryptionType:(null===(i=this.engine.e2eeManager)||void 0===i?void 0:i.isDataChannelEncryptionEnabled)?wt.GCM:wt.NONE},o=new rn({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:no(s.timestamp),totalLength:no(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new tn({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?en.UPDATE:en.CREATE})}}),a=null==e?void 0:e.destinationIdentities,c=new _t({destinationIdentities:a,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,Dt.RELIABLE);let d=0;const l=this.engine,u=new WritableStream({write(e){return Si(this,void 0,void 0,function*(){for(const t of function(e){const t=[];let n=(new TextEncoder).encode(e);for(;n.length>15e3;){let e=15e3;for(;e>0;){const t=n[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&t.push(n),t}(e)){const e=new sn({content:t,streamId:r,chunkIndex:no(d)}),n=new _t({destinationIdentities:a,value:{case:"streamChunk",value:e}});yield l.sendDataPacket(n,Dt.RELIABLE),d+=1}})},close(){return Si(this,void 0,void 0,function*(){const e=new on({streamId:r}),t=new _t({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield l.sendDataPacket(t,Dt.RELIABLE)})},abort(e){console.log("Sink error:",e)}});let h=()=>Si(this,void 0,void 0,function*(){yield p.close()});l.once(Wr.Closing,h);const p=new ec(u,s,()=>this.engine.off(Wr.Closing,h));return p})}sendFile(e,t){return Si(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return Si(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(i=null==n?void 0:n.mimeType)&&void 0!==i?i:t.type,topic:null==n?void 0:n.topic,destinationIdentities:null==n?void 0:n.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:e,value:t}=yield s.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return Si(this,void 0,void 0,function*(){var t,n,i,r,s,o;const a=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),c=null==e?void 0:e.destinationIdentities,d={id:a,mimeType:null!==(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===(s=this.engine.e2eeManager)||void 0===s?void 0:s.isDataChannelEncryptionEnabled)?wt.GCM:wt.NONE},l=new rn({totalLength:no(null!==(o=d.size)&&void 0!==o?o:0),mimeType:d.mimeType,streamId:a,topic:d.topic,timestamp:no(Date.now()),attributes:d.attributes,contentHeader:{case:"byteHeader",value:new nn({name:d.name})}}),u=new _t({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,Dt.RELIABLE);let h=0;const p=new _,m=this.engine,g=this.log,f=new WritableStream({write(e){return Si(this,void 0,void 0,function*(){const t=yield p.lock();let n=0;try{for(;n<e.byteLength;){const t=e.slice(n,n+15e3),i=new _t({destinationIdentities:c,value:{case:"streamChunk",value:new sn({content:t,streamId:a,chunkIndex:no(h)})}});yield m.sendDataPacket(i,Dt.RELIABLE),h+=1,n+=t.byteLength}}finally{t()}})},close(){return Si(this,void 0,void 0,function*(){const e=new on({streamId:a}),t=new _t({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield m.sendDataPacket(t,Dt.RELIABLE)})},abort(e){g.error("Sink error:",e)}});return new tc(f,d)})}}class ic extends us{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Hr.Muted:Hr.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Hr.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Si(this,void 0,void 0,function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),va)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:e,rtpTimestamp:t}=n;t&&this.rtpTimestamp!==t&&(this.emit(Hr.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class rc extends ic{constructor(e,t,n,i,r,s){super(e,t,us.Kind.Audio,n,s),this.monitorReceiver=()=>Si(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=ya(e,this.prevStats)),this.prevStats=e}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ns()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ns())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return Si(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Is(t))return t.setSinkId(e)}))})}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Is(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(Hr.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(Hr.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Si(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 sc extends ic{constructor(e,t,n,i,r){super(e,t,us.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>Si(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=ya(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=Xo(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===us.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?ps(this._mediaStreamTrack,t):hs(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){const t=new oc(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter(t=>t===e);for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Si(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach(e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)}),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(t=>t.element===e);for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Si(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const i=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),r=!(null!==(n=null===(t=this.adaptiveStreamSettings)||void 0===t?void 0:t.pauseVideoInBackground)&&void 0!==n&&!n)&&this.isInBackground,s=this.elementInfos.some(e=>e.pictureInPicture),o=this.elementInfos.some(e=>e.visible)&&!r||s;(this.lastVisible!==o||e)&&(!o&&Date.now()-i<100?cs.setTimeout(()=>{this.updateVisibility()},100):(this.lastVisible=o,this.emit(Hr.VisibilityChanged,o,this)))}updateDimensions(){var e,t;let n=0,i=0;const r=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*r,s=e.height()*r;t+s>n+i&&(n=t,i=s)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===n&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===i||(this.lastDimensions={width:n,height:i},this.emit(Hr.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?Vs():t||(Vs()>2?2:1)}}class oc{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,this.isPiP=ac(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,n;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ac(this.element),null===(n=this.handleVisibilityChanged)||void 0===n||n.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=ac(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:cc(e),this.isPiP=xs()&&ac(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=cc(this.element),this.isPiP=ac(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ks().observe(this.element),Gs().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=Ks())||void 0===e||e.unobserve(this.element),null===(t=Gs())||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 ac(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&cc(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function cc(e,t){const n=t||window;let i=e.offsetTop,r=e.offsetLeft;const s=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+s>n.pageXOffset&&!a&&"none"!==c}class dc extends Pi.EventEmitter{constructor(e,t,n,i){var r;super(),this.metadataMuted=!1,this.encryption=wt.NONE,this.log=vi,this.handleMuted=()=>{this.emit(Hr.Muted)},this.handleUnmuted=()=>{this.emit(Hr.Unmuted)},this.log=yi(null!==(r=null==i?void 0:i.loggerName)&&void 0!==r?r:mi.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=us.Source.Unknown}setTrack(e){this.track&&(this.track.off(Hr.Muted,this.handleMuted),this.track.off(Hr.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Hr.Muted,this.handleMuted),e.on(Hr.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ko(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==wt.NONE}get audioTrack(){if(ro(this.track))return this.track}get videoTrack(){if(so(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=us.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===us.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"}(dc||(dc={}));class lc extends dc{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Hr.Ended)},this.handleCpuConstrained=()=>{this.track&&so(this.track)&&this.emit(Hr.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(Hr.Ended,this.handleTrackEnded),this.track.off(Hr.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Hr.Ended,this.handleTrackEnded),e.on(Hr.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 Si(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return Si(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return Si(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return Si(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(ro(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(vt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(vt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(vt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(vt.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(vt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(vt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function uc(e,t){return Si(this,void 0,void 0,function*(){null!=e||(e={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=To(e);let o=s.audio,a=s.video;if(i&&"object"==typeof s.audio&&(s.audio.processor=i),r&&"object"==typeof s.video&&(s.video.processor=r),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){const e=s.audio.deviceId;s.audio.deviceId={exact:e},n=!0,o=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,a=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 c=ho(s,aa,ca),d=mo(c),l=navigator.mediaDevices.getUserMedia(d);s.audio&&(Po.userMediaPromiseMap.set("audioinput",l),l.catch(()=>Po.userMediaPromiseMap.delete("audioinput"))),s.video&&(Po.userMediaPromiseMap.set("videoinput",l),l.catch(()=>Po.userMediaPromiseMap.delete("videoinput")));try{const e=yield l;return yield Promise.all(e.getTracks().map(n=>Si(this,void 0,void 0,function*(){const s="audio"===n.kind;let o,a=s?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=s?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=n.getSettings().deviceId;(null==o?void 0:o.deviceId)&&$s(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,n){switch(e.kind){case"audio":return new Ca(e,t,!1,void 0,n);case"video":return new Na(e,t,!1,n);default:throw new Qr("unsupported track type: ".concat(e.kind))}}(n,o,t);return h.kind===us.Kind.Video?h.source=us.Source.Camera:h.kind===us.Kind.Audio&&(h.source=us.Source.Microphone),h.mediaStream=e,ro(h)&&i?yield h.setProcessor(i):so(h)&&r&&(yield h.setProcessor(r)),h})))}catch(i){if(!n)throw i;return uc(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}})}!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(Wa||(Wa={}));class hc extends Pi.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===Ct.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===St.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,i,r,s){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Ct.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Wa.Unknown,this.log=vi,this.log=yi(null!==(a=null==s?void 0:s.loggerName)&&void 0!==a?a:mi.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Xs,this.once(qr.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(us.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(us.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(us.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version||(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===St.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==St.ACTIVE&&this.emit(qr.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,0))}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(qr.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(qr.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var n;void 0===e&&(e={}),void 0===t&&(t={});const i=[...Object.keys(t),...Object.keys(e)],r={};for(const s of i)e[s]!==t[s]&&(r[s]=null!==(n=t[s])&&void 0!==n?n:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(qr.AttributesChanged,t)}setPermissions(e){var t,n,i,r,s,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(n=this.permissions)||void 0===n?void 0:n.canSubscribe)||e.canPublishData!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(qr.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(qr.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ht.EXCELLENT:return Wa.Excellent;case ht.GOOD:return Wa.Good;case ht.POOR:return Wa.Poor;case ht.LOST:return Wa.Lost;default:return Wa.Unknown}}(e),t!==this._connectionQuality&&this.emit(qr.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>ro(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(Hr.Muted,()=>{this.emit(qr.TrackMuted,e)}),e.on(Hr.Unmuted,()=>{this.emit(qr.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case us.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case us.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class pc extends hc{constructor(e,t,n,i,r,s){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=wt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Xs)},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,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,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===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.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 Xs),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:n,message:i}=e,r=this.pendingSignalRequests.get(t);r&&(n!==ni.OK&&r.reject(new es(i,n)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,n=null,i=null;"payload"===t.value.case?n=t.value.value:"error"===t.value.case&&(i=ma.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,i);break;case"rpcAck":this.handleIncomingRpcAck(e.value.value.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new qn({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,trackSids:e.allowedTrackSids||[]})}(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ko(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ko(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ko(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ko(t))),this.emit(qr.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>Si(this,void 0,void 0,function*(){var t,n,i,r;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const s=this.videoTrackPublications.get(e.trackSid);if(!s)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!s.videoTrack)return;const o=yield s.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var a,c=!0,d=Ci(o);!(t=(a=yield d.next()).done);c=!0){c=!1;const e=a.value;vs(e)&&(this.log.debug("publish ".concat(e," for ").concat(s.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ko(s))),yield this.publishAdditionalCodecForTrack(s.videoTrack,e,s.options))}}catch(e){n={error:e}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Si(this,void 0,void 0,function*(){if(e.source===us.Source.ScreenShare||e.source===us.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ko(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(ao(e)||oo(e))try{if(xs())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===us.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),ko(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ko(e))),ao(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ko(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==wt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(Wr.RemoteMute,(e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(Wr.Connected,this.handleReconnected).on(Wr.SignalConnected,this.handleSignalConnected).on(Wr.SignalRestarted,this.handleReconnected).on(Wr.SignalResumed,this.handleReconnected).on(Wr.Restarting,this.handleReconnecting).on(Wr.Resuming,this.handleReconnecting).on(Wr.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Wr.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Wr.Closing,this.handleClosing).on(Wr.SignalRequestResponse,this.handleSignalRequestResponse).on(Wr.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Si(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return Si(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return Si(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return Si(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:i,attributes:r}=e;return function*(){return new Promise((e,s)=>Si(t,void 0,void 0,function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(o=null!=i?i:this.name)&&void 0!==o?o:"",r),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(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,n]=e;return this.attributes[t]===n||""===n&&!this.attributes[t]})))return this.pendingSignalRequests.delete(c),void e();yield Es(50)}s(new es("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&s(e)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(us.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(us.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(us.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return Si(this,void 0,void 0,function*(){this.encryptionType=e?wt.GCM:wt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,i){return Si(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case us.Source.Camera:t=yield this.createTracks({video:null===(r=n)||void 0===r||r});break;case us.Source.Microphone:t=yield this.createTracks({audio:null===(s=n)||void 0===s||s});break;case us.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new Qr(e)}}catch(n){throw null==t||t.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(qr.MediaDevicesError,n,vo(e)),this.pendingPublishing.delete(e),n}for(const i of t){const t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===us.Source.Microphone&&ro(i)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),i.startPreConnectBuffer())}try{const e=[];for(const n of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ko(n))),e.push(this.publishTrack(n,i));const n=yield Promise.all(e);[o]=n}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===us.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication(us.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return Si(this,void 0,void 0,function*(){if(!this.pendingPublishing.has(us.Source.Camera)&&!this.pendingPublishing.has(us.Source.Microphone)){this.pendingPublishing.add(us.Source.Camera),this.pendingPublishing.add(us.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(us.Source.Camera),this.pendingPublishing.delete(us.Source.Microphone)}}})}createTracks(e){return Si(this,void 0,void 0,function*(){var t,n;null!=e||(e={});const i=ho(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(n=this.roomOptions)||void 0===n?void 0:n.videoCaptureDefaults);try{return(yield uc(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(ro(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=us.Source.Microphone,this.emit(qr.AudioStreamAcquired)),so(e)&&(this.cameraError=void 0,e.source=us.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return Si(this,void 0,void 0,function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new Jr("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=rs();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)&&Bs(e.osVersion,"17")>=0}()||(e.resolution=Ss.h1080fps30.resolution);const t=function(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=Ds()?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}}(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Qr("no video track found");const r=new Na(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=us.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(qr.AudioStreamAcquired);const e=new Ca(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=us.Source.ScreenShareAudio,s.push(e)}return s})}publishTrack(e,t){return Si(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return Si(this,arguments,void 0,function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,s,o,a;let c,d;if(ao(e)&&e.setAudioContext(n.audioContext),yield null===(r=n.reconnectFuture)||void 0===r?void 0:r.promise,n.republishPromise&&!i&&(yield n.republishPromise),io(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case us.Source.Microphone:t="audioinput";break;case us.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Ca(e,c,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=new Na(e,c,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Qr("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(d=t)}),d)return n.log.warn("track has already been published, skipping",Object.assign(Object.assign({},n.logContext),ko(d))),d;const l=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(s=l.forceStereo)&&void 0!==s?s:u;h&&(void 0===l.dtx&&n.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},n.logContext),ko(e))),void 0===l.red&&n.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=l.dtx)&&void 0!==o||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=rs(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Bs(e.osVersion,t)>=0)||"Safari"===e.name&&Bs(e.version,t)>=0}()&&n.roomOptions.e2ee&&(n.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},n.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise((t,i)=>Si(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Ao.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ko(e)}));let n=!1;const r=setTimeout(()=>{n=!0,e.stop(),i(new Zr("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(r),n)return;const s=yield this.publish(e,l,h);t(s)}else try{const n=yield this.publish(e,l,h);t(n)}catch(e){i(e)}}catch(e){i(e)}}));n.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Xs),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ko(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return!(!t||0!==n.length&&!n.map(e=>function(e){switch(e){case lt.CAMERA:return us.Source.Camera;case lt.MICROPHONE:return us.Source.Microphone;case lt.SCREEN_SHARE:return us.Source.ScreenShare;case lt.SCREEN_SHARE_AUDIO:return us.Source.ScreenShareAudio;default:return us.Source.Unknown}}(e)).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ko(e))),!1)}publish(e,t,n){return Si(this,void 0,void 0,function*(){var i,r,s,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new Zr("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>io(e)&&t.source===e.source)&&e.source!==us.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ko(e))),t.stopMicTrackOnMute&&ro(e)&&(e.stopOnMute=!0),e.source===us.Source.ScreenShare&&Os()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ds()||Os())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}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Os())return!1;if(Ds()){const e=rs();if((null==e?void 0:e.version)&&Bs(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&Bs(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}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=sa),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===yo(e.mime))||(t.videoCodec=yo(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Hr.Muted,this.onTrackMuted),e.on(Hr.Unmuted,this.onTrackUnmuted),e.on(Hr.Ended,this.handleTrackEnded),e.on(Hr.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Hr.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Hr.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],g=!(null===(i=t.dtx)||void 0===i||i),f=e.getSourceTrackSettings();f.autoGainControl&&m.push(vt.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&m.push(vt.TF_ECHO_CANCELLATION),f.noiseSuppression&&m.push(vt.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&m.push(vt.TF_STEREO),g&&m.push(vt.TF_NO_DTX),ao(e)&&e.hasPreConnectBuffer&&m.push(vt.TF_PRECONNECT_BUFFER);const v=new mn({cid:e.mediaStreamTrack.id,name:t.name,type:us.kindToProto(e.kind),muted:e.isMuted,source:us.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:m});let y;if(e.kind===us.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch(t){const i=null!==(o=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==o?o:ks.h720.resolution;n={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{dims:n}))}v.width=n.width,v.height=n.height,oo(e)&&(Rs(p)&&(e.source===us.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),ko(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),v.simulcastCodecs=[new pn({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:sa}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===wt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new pn({codec:t.backupCodec.codec,cid:""})))),y=_a(e.source===us.Source.ScreenShare,v.width,v.height,t),v.layers=ja(v.width,v.height,y,Rs(t.videoCodec))}else e.kind===us.Kind.Audio&&(y=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Xr("cannot publish track when not connected");const b=()=>Si(this,void 0,void 0,function*(){var n,i,r;if(!this.engine.pcManager)throw new Xr("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(qr.LocalSenderCreated,e.sender,e),oo(e)&&(null!==(n=t.degradationPreference)&&void 0!==n||(t.degradationPreference=function(e){return e.source===us.Source.ScreenShare||e.constraints.height&&$s(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),y)if(Os()&&e.kind===us.Kind.Audio){let t;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(i=y[0])||void 0===i?void 0:i.maxBitrate)?y[0].maxBitrate/1e3:0})}else e.codec&&Rs(e.codec)&&(null===(r=y[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let k;const T=new Promise((t,n)=>Si(this,void 0,void 0,function*(){var i;try{k=yield this.engine.addTrack(v),t(k)}catch(t){e.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([T,b()]);k=e[0]}else{let n;if(k=yield T,k.codecs.forEach(e=>{void 0===n&&(n=e.mimeType)}),n&&e.kind===us.Kind.Video){const i=yo(n);i!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{codec:i})),t.videoCodec=i,y=_a(e.source===us.Source.ScreenShare,v.width,v.height,t))}yield b()}const S=new lc(e.kind,k,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(Hr.CpuConstrained,e=>this.onTrackCpuConstrained(e,S)),S.options=t,e.sid=k.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:k})),oo(e)?e.startMonitor(this.engine.client):ao(e)&&e.startMonitor(),this.addTrackPublication(S),this.emit(qr.LocalTrackPublished,S),ao(e)&&k.audioFeatures.includes(vt.TF_PRECONNECT_BUFFER)){const t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();if(this.on(qr.LocalTrackSubscribed,t=>{if(t.trackSid===k.sid){if(!e.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ko(e))),e.stopPreConnectBuffer()}}),t){const i=new Promise((i,r)=>Si(this,void 0,void 0,function*(){var s,o,a,c,d;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ko(e)));const p=setTimeout(()=>{r(new Error("agent not active within 10 seconds"))},1e4),m=yield this.waitUntilActiveAgentPresent();clearTimeout(p),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ko(e)));const g=yield this.streamBytes({name:"preconnect-buffer",mimeType:n,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[m.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(c=f.sampleRate)&&void 0!==c?c:"48000"),channels:String(null!==(d=f.channelCount)&&void 0!==d?d:"1")}});try{for(var l,u=!0,h=Ci(t);!(s=(l=yield h.next()).done);u=!0){u=!1;const e=l.value;yield g.write(e)}}catch(e){o={error:e}}finally{try{u||s||!(a=h.return)||(yield a.call(h))}finally{if(o)throw o.error}}yield g.close(),i()}catch(e){r(e)}}));i.then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ko(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{error:t}))})}}return S})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return Si(this,void 0,void 0,function*(){var i;if(this.encryptionType!==wt.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new Qr("track is not published");if(!oo(e))throw new Qr("track is not a video track");const s=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),o=function(e,t,n){var i,r,s,o;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&vi.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!==(s=a.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===us.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),_a(e.source===us.Source.ScreenShare,c,d,n)}(e,t,s);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ko(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new mn({cid:a.mediaStreamTrack.id,type:us.kindToProto(e.kind),muted:e.isMuted,source:us.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=ja(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Xr("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Si(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return Si(this,void 0,void 0,function*(){var n,i;if(io(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ko(e))),yield t)}const r=this.getPublicationForTrack(e),s=r?ko(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));(e=r.track).off(Hr.Muted,this.onTrackMuted),e.off(Hr.Unmuted,this.onTrackUnmuted),e.off(Hr.Ended,this.handleTrackEnded),e.off(Hr.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Hr.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Hr.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(i=null===(n=this.roomOptions)||void 0===n?void 0:n.stopLocalTrackOnUnpublish)||void 0===i||i),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ua.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),oo(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case us.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case us.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(qr.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return Si(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return Si(this,arguments,void 0,function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((i,r)=>Si(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=>Si(this,void 0,void 0,function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===us.Source.ScreenShare||t.source===us.Source.ScreenShareAudio||!ao(t)&&!oo(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),i()}catch(e){r(e)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return Si(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?Dt.RELIABLE:Dt.LOSSY;let r=new Lt({participantIdentity:t.identity,payload:e,destinationIdentities:n.destinationIdentities,topic:n.topic});const s=new _t({kind:i,value:{case:"user",value:r}});yield t.engine.sendDataPacket(s,i)}()})}publishDtmf(e,t){return Si(this,void 0,void 0,function*(){const n=new _t({kind:Dt.RELIABLE,value:{case:"sipDtmf",value:new Ut({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Dt.RELIABLE)})}sendChatMessage(e,t){return Si(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},i=new _t({value:{case:"chatMessage",value:new Vt(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,Dt.RELIABLE),this.emit(qr.ChatMessage,n),n})}editChatMessage(e,t){return Si(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new _t({value:{case:"chatMessage",value:new Vt(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp),editTimestamp:Y.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,Dt.RELIABLE),this.emit(qr.ChatMessage,n),n})}sendText(e,t){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return Si(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return Si(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:n,method:i,payload:r,responseTimeout:s=15e3}=e;return function*(){return new Promise((e,o)=>Si(t,void 0,void 0,function*(){var t,a,c,d;if(ga(r)>15360)return void o(ma.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&Bs(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(ma.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(s,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(n,u,i,r,l);const h=setTimeout(()=>{this.pendingAcks.delete(u),o(ma.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)},7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:n});const p=setTimeout(()=>{this.pendingResponses.delete(u),o(ma.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(u,{resolve:(t,n)=>{clearTimeout(p),this.pendingAcks.has(u)&&(console.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),n?o(n):e(null!=t?t:"")},participantIdentity:n})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,r){return Si(this,void 0,void 0,function*(){const s=new _t({destinationIdentities:[e],kind:Dt.RELIABLE,value:{case:"rpcRequest",value:new Bt({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,Dt.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,ma.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,n;const i=this.trackPublications.get(e.sid);if(i){const 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(Object.assign({},this.logContext),ko(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 Xs),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(ao(i)||oo(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))}),t}waitForPendingPublicationOfSource(e){return Si(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[n]=t;return n.source===e});if(t)return t[1];yield Es(20)}})}}class mc extends dc{constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Hr.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Cn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Gt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Hr.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return!1===this.subscribed?dc.SubscriptionStatus.Unsubscribed:super.isSubscribed?dc.SubscriptionStatus.Subscribed:dc.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?dc.PermissionStatus.Allowed:dc.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||(uo(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&uo(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:ls.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(Hr.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(Hr.VisibilityChanged,this.handleVisibilityChange),i.off(Hr.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(Hr.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Hr.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Hr.VisibilityChanged,this.handleVisibilityChange),e.on(Hr.Ended,this.handleEnded),this.emit(Hr.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Hr.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Hr.Muted:Hr.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Hr.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Hr.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return uo(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new En({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===us.Kind.Video){let i=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(i)So(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),i=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(t=this.requestedMaxQuality,null===(n=this.trackInfo.layers)||void 0===n?void 0:n.find(e=>e.quality===t));e&&So(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),i=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),i=this.videoDimensionsAdaptiveStream;i?(e.width=Math.ceil(i.width),e.height=Math.ceil(i.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:ls.HIGH})),e.quality=ls.HIGH)}var t,n;this.emit(Hr.UpdateSettings,e)}}class gc extends hc{static fromParticipantInfo(e,t,n){return new gc(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,o){super(t,n||"",i,r,s,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:Ct.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Hr.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ko(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Hr.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Hr.SubscriptionPermissionChanged,t=>{this.emit(qr.TrackSubscriptionPermissionChanged,e,t)}),e.on(Hr.SubscriptionStatusChanged,t=>{this.emit(qr.TrackSubscriptionStatusChanged,e,t)}),e.on(Hr.Subscribed,t=>{this.emit(qr.TrackSubscribed,t,e)}),e.on(Hr.Unsubscribed,t=>{this.emit(qr.TrackUnsubscribed,t,e)}),e.on(Hr.SubscriptionFailed,t=>{this.emit(qr.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:us.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]:us.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,i,r,s){let o,a=this.getTrackPublicationBySid(t);return a||t.startsWith("TR")||this.trackPublications.forEach(t=>{a||e.kind!==t.kind.toString()||(a=t)}),a?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ko(a))),void this.emit(qr.TrackSubscriptionFailed,t)):(o="video"===e.kind?new sc(e,t,i,r):new rc(e,t,i,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(n),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&co(o)&&ro(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===s?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(qr.TrackSubscriptionFailed,t)):(void 0===s&&(s=20),void setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,i,r,s-1)},150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(e=>{var i,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{const t=us.kindFromProto(e.type);if(!t)return;s=new mc(t,e,null===(i=this.signalClient.connectOptions)||void 0===i?void 0:i.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName}),s.updateInfo(e),n.set(e.sid,s);const o=Array.from(this.trackPublications.values()).find(e=>e.source===(null==s?void 0:s.source));o&&s.source!==us.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ko(o),newTrack:ko(s)})),this.addTrackPublication(s)}t.set(e.sid,s)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ko(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(qr.TrackPublished,e)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case us.Kind.Audio:this.audioTrackPublications.delete(e);break;case us.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(qr.TrackUnpublished,n)}setAudioOutput(e){return Si(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var i;ro(n.track)&&co(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(Ha||(Ha={}));class fc extends Pi.EventEmitter{get hasE2EESetup(){return void 0!==this.e2eeManager}constructor(e){var t,n,i,r;if(super(),t=this,this.state=Ha.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=vi,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>Si(this,void 0,void 0,function*(){var i;if("undefined"==typeof RTCPeerConnection||!ws()&&!Ps())throw Ns()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const r=yield this.disconnectLock.lock();if(this.state===Ha.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Ha.Connecting),(null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ls(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new pa(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));const s=(i,o,a)=>Si(this,void 0,void 0,function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==r||r();try{if(yield Eo.getInstance().getBackOffPromise(e),l.signal.aborted)throw new Kr("Connection attempt aborted",Ur.Cancelled);yield this.attemptConnection(null!=a?a:e,t,n,l),this.abortController=void 0,i()}catch(t){if(this.regionUrlProvider&&t instanceof Kr&&t.reason!==Ur.Cancelled&&t.reason!==Ur.NotAllowed){let n=null;try{this.log.debug("Fetching next region"),n=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(e){if(e instanceof Kr&&(401===e.status||e.reason===Ur.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(e)}[Ur.InternalError,Ur.ServerUnreachable,Ur.Timeout].includes(t.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Eo.getInstance().addFailedConnectionAttempt(e)),n&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(t.message,". Retrying with another region: ").concat(n),this.logContext),this.recreateEngine(),yield s(i,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,eo(t)),o(t))}else{let e=mt.UNKNOWN_REASON;t instanceof Kr&&(e=eo(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Xs((e,t)=>{s(e,t,o)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,i,r,s)=>Si(this,void 0,void 0,function*(){var o,a,c;const d=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout,singlePeerConnection:r.singlePeerConnection},s.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map(e=>{let[t,n]=e;return"".concat(t,": ").concat(n)}).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Yr("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),d}),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,i)=>Si(this,void 0,void 0,function*(){var r,s;this.state===Ha.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},la),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,i);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(Br.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();const t=new Kr("could not establish signal connection",i.signal.aborted?Ur.Cancelled:Ur.ServerUnreachable);throw e instanceof Error&&(t.message="".concat(t.message,": ").concat(e.message)),e instanceof Kr&&(t.reason=e.reason,t.status=e.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:e})),t}if(i.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Kr("Connection attempt aborted",Ur.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,i)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}xs()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),xs()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Ha.Connected),this.emit(Br.Connected),Eo.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return Si(t,[...n],void 0,function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var n,i,r;const s=yield e.disconnectLock.lock();try{if(e.state===Ha.Disconnected)return void e.log.debug("already disconnected",e.logContext);if(e.log.info("disconnect from room",Object.assign({},e.logContext)),e.state===Ha.Connecting||e.state===Ha.Reconnecting||e.isResuming){const t="Abort connection attempt due to user initiated disconnect";e.log.warn(t,e.logContext),null===(n=e.abortController)||void 0===n||n.abort(t),null===(r=null===(i=e.connectFuture)||void 0===i?void 0:i.reject)||void 0===r||r.call(i,new Kr("Client initiated disconnect",Ur.Cancelled)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,mt.CLIENT_INITIATED),e.engine=void 0}finally{s()}}()})},this.onPageLeave=()=>Si(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>Si(this,void 0,void 0,function*(){const e=[],t=rs();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let n=document.getElementById(t);if(!n){n=document.createElement("audio"),n.id=t,n.autoplay=!0,n.hidden=!0;const e=Ys();e.enabled=!0;const i=new MediaStream([e]);n.srcObject=i,document.addEventListener("visibilitychange",()=>{n&&(n.srcObject=document.hidden?null:i,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(n),this.once(Br.Disconnected,()=>{null==n||n.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>Si(this,void 0,void 0,function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;null===(n=t.track)||void 0===n||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Ha.Reconnecting)&&this.emit(Br.Reconnecting)},this.handleSignalRestarted=e=>Si(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(Ha.Connected),this.emit(Br.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let n=this.remoteParticipants.get(e.identity);e.state===St.DISCONNECTED?this.handleParticipantDisconnected(e.identity,n):n=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{const t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Br.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach(e=>{const n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});const n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(Br.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;const i=us.streamStateFromProto(e.state);n.track.setStreamState(i),i!==n.track.streamState&&(t.emit(qr.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(Br.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const n=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(n,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(n,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(n,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(n,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,n);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,i)=>{this.emit(Br.DataReceived,t.payload,e,n,t.topic,i),null==e||e.emit(qr.DataReceived,t.payload,n,i)},this.handleSipDtmf=(e,t)=>{this.emit(Br.SipDTMFReceived,t,e),null==e||e.emit(qr.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{const n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),i=null==n?void 0:n.trackPublications.get(t.trackId),r=function(e,t){return e.segments.map(e=>{let{id:n,text:i,language:r,startTime:s,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(n))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(n):t.set(n,d),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:r,firstReceivedTime:d,lastReceivedTime:l}})}(t,this.transcriptionReceivedTimes);null==i||i.emit(Hr.TranscriptionReceived,r),null==n||n.emit(qr.TranscriptionReceived,r,i),this.emit(Br.TranscriptionReceived,r,n,i)},this.handleChatMessage=(e,t)=>{const n=function(e){const{id:t,timestamp:n,message:i,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}(t);this.emit(Br.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(Br.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Br.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Br.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Br.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Br.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Si(this,void 0,void 0,function*(){var e;"iOS"!==(null===(e=rs())||void 0===e?void 0:e.os)&&(yield this.selectDefaultDevices()),this.emit(Br.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Br.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Br.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(Br.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Br.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Br.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Br.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Br.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Si(this,void 0,void 0,function*(){var t,n,i,r,s,o;null===(t=e.track)||void 0===t||t.on(Hr.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=e.track)||void 0===n||n.on(Hr.Restarted,this.onLocalTrackRestarted),null===(s=null===(r=null===(i=e.track)||void 0===i?void 0:i.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===s||s.call(r,this),this.emit(Br.LocalTrackPublished,e,this.localParticipant),ao(e.track)&&(yield e.track.checkForSilence())&&this.emit(Br.LocalAudioSilenceDetected,e);const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=vo(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Br.ActiveDeviceChanged,c,a))}),this.onLocalTrackUnpublished=e=>{var t,n;null===(t=e.track)||void 0===t||t.off(Hr.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(n=e.track)||void 0===n||n.off(Hr.Restarted,this.onLocalTrackRestarted),this.emit(Br.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Si(this,void 0,void 0,function*(){const t=yield e.getDeviceId(!1),n=vo(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug("local track restarted, setting ".concat(n," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(Br.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Br.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Br.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Br.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Br.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},da),e),this.log=yi(null!==(n=this.options.loggerName)&&void 0!==n?n:mi.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},aa),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ca),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},oa),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new $a,this.outgoingDataStreamManager=new nc(this.engine,this.log),this.disconnectLock=new _,this.localParticipant=new pc("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",$s(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",$s(this.options.audioCaptureDefaults.deviceId)),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&this.switchActiveDevice("audiooutput",$s(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),xs()){const e=new AbortController;null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),fc.cleanupRegistry&&fc.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return Si(this,void 0,void 0,function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)})}setupE2EE(){var e;const t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&("e2eeManager"in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Co(n,t),this.e2eeManager.on(Nr.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Br.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(Nr.EncryptionError,(e,t)=>{const n=t?this.getParticipantByIdentity(t):void 0;this.emit(Br.EncryptionError,e,n)}),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Si(this,void 0,void 0,function*(){return this.state===Ha.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{const n=t=>{""!==t.sid&&(this.engine.off(Wr.RoomUpdate,n),e(t.sid))};this.engine.on(Wr.RoomUpdate,n),this.once(Br.Disconnected,()=>{this.engine.off(Wr.RoomUpdate,n),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new za(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Wr.ParticipantUpdate,this.handleParticipantUpdates).on(Wr.RoomUpdate,this.handleRoomUpdate).on(Wr.SpeakersChanged,this.handleSpeakersChanged).on(Wr.StreamStateChanged,this.handleStreamStateUpdate).on(Wr.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Wr.SubscriptionError,this.handleSubscriptionError).on(Wr.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Wr.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(Wr.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Wr.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Wr.DataPacketReceived,this.handleDataPacket).on(Wr.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Ha.SignalReconnecting)&&this.emit(Br.SignalReconnecting)}).on(Wr.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Ha.Connected)&&this.emit(Br.Reconnected)}).on(Wr.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Ha.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(Wr.Restarting,this.handleRestarting).on(Wr.SignalRestarted,this.handleSignalRestarted).on(Wr.Offline,()=>{this.setAndEmitConnectionState(Ha.Reconnecting)&&this.emit(Br.Reconnecting)}).on(Wr.DCBufferStatusChanged,(e,t)=>{this.emit(Br.DCBufferStatusChanged,e,t)}).on(Wr.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});t?(this.localParticipant.emit(qr.LocalTrackSubscribed,t),this.emitWhenConnected(Br.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)}).on(Wr.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Br.Moved,e.room.name),this.handleParticipantUpdates(e.participant?[e.participant,...e.otherParticipants]:e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Po.getInstance().getDevices(e,t)}prepareConnection(e,t){return Si(this,void 0,void 0,function*(){if(this.state===Ha.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ls(new URL(e))&&t){this.regionUrlProvider=new pa(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Ha.Disconnected&&(this.regionUrl=n,yield fetch(Zs(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Zs(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Si(this,void 0,void 0,function*(){let n,i=()=>Si(this,void 0,void 0,function*(){});switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new Qn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new Qn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new Qn({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new Qn({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=()=>Si(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),n=new Qn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Si(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),n=new Qn({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 Qn({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Si(this,void 0,void 0,function*(){const e=this.engine.client.onLeave;e&&e(new Rn({reason:mt.CLIENT_INITIATED,action:In.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new Qn({scenario:{case:"subscriberBandwidth",value:no(t)}});break;case"leave-full-reconnect":n=new Qn({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Si(this,arguments,void 0,function(e,t){var n=this;let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var r,s,o,a,c,d,l;let u=!0,h=!1;const p=i?{exact:t}:t;if("audioinput"===e){h=0===n.localParticipant.audioTrackPublications.size;const t=null!==(r=n.getActiveDevice(e))&&void 0!==r?r:n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=p;const i=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===us.Source.Microphone);try{u=(yield Promise.all(i.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}const s=i.some(e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n});u&&s&&(h=!0)}else if("videoinput"===e){h=0===n.localParticipant.videoTrackPublications.size;const t=null!==(s=n.getActiveDevice(e))&&void 0!==s?s:n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=p;const i=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===us.Source.Camera);try{u=(yield Promise.all(i.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}const r=i.some(e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n});u&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!Is()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!("setSinkId"in n.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");n.options.webAudioMix&&(t=null!==(o=yield Po.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(l=n.options).audioOutput)&&void 0!==a||(l.audioOutput={});const i=null!==(c=n.getActiveDevice(e))&&void 0!==c?c:n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&(null===(d=n.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=i,e}}return h&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(Br.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(qr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(qr.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(qr.AttributesChanged,this.onLocalAttributesChanged).on(qr.TrackMuted,this.onLocalTrackMuted).on(qr.TrackUnmuted,this.onLocalTrackUnmuted).on(qr.LocalTrackPublished,this.onLocalTrackPublished).on(qr.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(qr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(qr.MediaDevicesError,this.onMediaDevicesError).on(qr.AudioStreamAcquired,this.startAudio).on(qr.ChatMessage,this.onLocalChatMessageSent).on(qr.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Ha.Connecting||this.state===Ha.Reconnecting){const i=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),r()},r=()=>{this.off(Br.Reconnected,i),this.off(Br.Connected,i),this.off(Br.Disconnected,r)};return this.once(Br.Reconnected,i),this.once(Br.Connected,i),void this.once(Br.Disconnected,r)}if(this.state===Ha.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const i=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find(e=>e.sid===r);if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);if(!o.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(n);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(r),this.logContext);o=e}let c;o.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(r,", streamId: ").concat(s,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:s,trackId:o})),this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const d=a.addSubscribedMediaTrack(e,o,t,n,c);(null==d?void 0:d.isEncrypted)&&!this.e2eeManager&&this.emit(Br.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(a.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Ha.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,i,r;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(n=t.track)||void 0===n||n.detach(),null===(i=t.track)||void 0===i||i.stop()):null===(r=t.track)||void 0===r||r.stopMonitor()}),this.localParticipant.off(qr.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(qr.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(qr.AttributesChanged,this.onLocalAttributesChanged).off(qr.TrackMuted,this.onLocalTrackMuted).off(qr.TrackUnmuted,this.onLocalTrackUnmuted).off(qr.LocalTrackPublished,this.onLocalTrackPublished).off(qr.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(qr.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(qr.MediaDevicesError,this.onMediaDevicesError).off(qr.AudioStreamAcquired,this.startAudio).off(qr.ChatMessage,this.onLocalChatMessageSent).off(qr.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),xs()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(n=navigator.mediaDevices)||void 0===n||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Ha.Disconnected),this.emit(Br.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Br.ParticipantDisconnected,t),t.setDisconnected(),null===(n=this.localParticipant)||void 0===n||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,i,r,s){return Si(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==s)return void(yield this.engine.publishRpcResponse(e,t,null,ma.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(n);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,ma.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const s=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:r});ga(s)>15360?(a=ma.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=s}catch(e){e instanceof ma?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),e),a=ma.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}selectDefaultDevices(){return Si(this,void 0,void 0,function*(){var e,t,n;const i=Po.getInstance().previousDevices,r=yield Po.getInstance().getDevices(void 0,!1),s=rs();if("Chrome"===(null==s?void 0:s.name)&&"iOS"!==s.os)for(let e of r){const t=i.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(Br.ActiveDeviceChanged,e.kind,e.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let s of o){const o=fo(s),a=this.localParticipant.getTrackPublication(o);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;const c=r.filter(e=>e.kind===s),d=this.getActiveDevice(s);d===(null===(t=i.filter(e=>e.kind===s)[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(n=c[0])||void 0===n?void 0:n.deviceId)!==d?yield this.switchActiveDevice(s,c[0].deviceId):"audioinput"===s&&!Ms()||"videoinput"===s||!(c.length>0)||c.find(e=>e.deviceId===this.getActiveDevice(s))||"audiooutput"===s&&Ms()||(yield this.switchActiveDevice(s,c[0].deviceId))}})}acquireAudioContext(){return Si(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=go())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Es(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const n="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(Br.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let i;return i=t?gc.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new gc(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Br.ParticipantConnected,n),n.on(qr.TrackPublished,e=>{this.emitWhenConnected(Br.TrackPublished,e,n)}).on(qr.TrackSubscribed,(e,t)=>{e.kind===us.Kind.Audio?(e.on(Hr.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Hr.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===us.Kind.Video&&(e.on(Hr.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Hr.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Br.TrackSubscribed,e,t,n)}).on(qr.TrackUnpublished,e=>{this.emit(Br.TrackUnpublished,e,n)}).on(qr.TrackUnsubscribed,(e,t)=>{this.emit(Br.TrackUnsubscribed,e,t,n)}).on(qr.TrackMuted,e=>{this.emitWhenConnected(Br.TrackMuted,e,n)}).on(qr.TrackUnmuted,e=>{this.emitWhenConnected(Br.TrackUnmuted,e,n)}).on(qr.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Br.ParticipantMetadataChanged,e,n)}).on(qr.ParticipantNameChanged,e=>{this.emitWhenConnected(Br.ParticipantNameChanged,e,n)}).on(qr.AttributesChanged,e=>{this.emitWhenConnected(Br.ParticipantAttributesChanged,e,n)}).on(qr.ConnectionQualityChanged,e=>{this.emitWhenConnected(Br.ConnectionQualityChanged,e,n)}).on(qr.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Br.ParticipantPermissionsChanged,e,n)}).on(qr.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Br.TrackSubscriptionStatusChanged,e,t,n)}).on(qr.TrackSubscriptionFailed,(e,t)=>{this.emit(Br.TrackSubscriptionFailed,e,n,t)}).on(qr.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Br.TrackSubscriptionPermissionChanged,e,t,n)}).on(qr.Active,()=>{this.emitWhenConnected(Br.ParticipantActive,n),n.kind===Ct.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&lo(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=cs.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,mt.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&cs.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Br.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(this.state===Ha.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===Ha.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return Si(this,void 0,void 0,function*(){var t,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new yt({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Y.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Tt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Br.SignalConnected),this.emit(Br.Connected),this.setAndEmitConnectionState(Ha.Connected),i.video){const e=new lc(us.Kind.Video,new Rt({source:lt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO,name:"video-dummy"}),new Na(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Js(160*(null!==(t=r.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(qr.LocalTrackPublished,e)}if(i.audio){const e=new lc(us.Kind.Audio,new Rt({source:lt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO}),new Ca(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ys(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(qr.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new Tt({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:St.ACTIVE,tracks:[],joinedAt:Y.parse(Date.now())});const i=this.getOrCreateParticipant(t.identity,t);if(r.video){const s=Js(160*(null!==(n=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==n?n:1),160,!1,!0),o=new Rt({source:lt.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO});i.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){const e=Ys(),n=new Rt({source:lt.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:dt.AUDIO});i.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}i.updateInfo(t)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(e!==Br.ActiveSpeakersChanged&&e!==Br.TranscriptionReceived){const t=vc(n).filter(e=>void 0!==e);e!==Br.TrackSubscribed&&e!==Br.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...n)}}function vc(e){return e.map(e=>{if(e)return Array.isArray(e)?vc(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e})}function yc(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);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}fc.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(Ga||(Ga={})),new TextEncoder,new TextDecoder;class bc extends Error{constructor(e,t){var n;super(e,t),yc(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,null===(n=Error.captureStackTrace)||void 0===n||n.call(Error,this,this.constructor)}}yc(bc,"code","ERR_JOSE_GENERIC"),yc(class extends bc{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}}),yc(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),yc(this,"claim",void 0),yc(this,"reason",void 0),yc(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),yc(class extends bc{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}}),yc(this,"code","ERR_JWT_EXPIRED"),yc(this,"claim",void 0),yc(this,"reason",void 0),yc(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED"),yc(class extends bc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),yc(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWT_INVALID")}},"code","ERR_JWT_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID"),yc(class extends bc{constructor(){super(...arguments),yc(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID"),yc(class extends bc{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),yc(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY"),yc(class extends bc{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),yc(this,Symbol.asyncIterator,void 0),yc(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS"),yc(class extends bc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),yc(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT"),yc(class extends bc{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),yc(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const kc=new Map;class Tc{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);n&&n.add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}}var Sc;!function(e){e.SESSION_STARTED="session_started",e.PARTIAL_TRANSCRIPT="partial_transcript",e.COMMITTED_TRANSCRIPT="committed_transcript",e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",e.AUTH_ERROR="auth_error",e.ERROR="error",e.OPEN="open",e.CLOSE="close",e.QUOTA_EXCEEDED="quota_exceeded",e.COMMIT_THROTTLED="commit_throttled",e.TRANSCRIBER_ERROR="transcriber_error",e.UNACCEPTED_TERMS="unaccepted_terms",e.RATE_LIMITED="rate_limited",e.INPUT_ERROR="input_error",e.QUEUE_OVERFLOW="queue_overflow",e.RESOURCE_EXHAUSTED="resource_exhausted",e.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",e.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",e.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"}(Sc||(Sc={}));class Cc{constructor(e){this.websocket=null,this.eventEmitter=new Tc,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Sc.OPEN):this.websocket.addEventListener("open",()=>{this.eventEmitter.emit(Sc.OPEN)}),this.websocket.addEventListener("message",e=>{try{const t=JSON.parse(e.data);switch(t.message_type){case"session_started":this.eventEmitter.emit(Sc.SESSION_STARTED,t);break;case"partial_transcript":this.eventEmitter.emit(Sc.PARTIAL_TRANSCRIPT,t);break;case"committed_transcript":this.eventEmitter.emit(Sc.COMMITTED_TRANSCRIPT,t);break;case"committed_transcript_with_timestamps":this.eventEmitter.emit(Sc.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case"auth_error":this.eventEmitter.emit(Sc.AUTH_ERROR,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"quota_exceeded":this.eventEmitter.emit(Sc.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"commit_throttled":this.eventEmitter.emit(Sc.COMMIT_THROTTLED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"transcriber_error":this.eventEmitter.emit(Sc.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"unaccepted_terms":this.eventEmitter.emit(Sc.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"rate_limited":this.eventEmitter.emit(Sc.RATE_LIMITED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"input_error":this.eventEmitter.emit(Sc.INPUT_ERROR,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"queue_overflow":this.eventEmitter.emit(Sc.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"resource_exhausted":this.eventEmitter.emit(Sc.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"session_time_limit_exceeded":this.eventEmitter.emit(Sc.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"chunk_size_exceeded":this.eventEmitter.emit(Sc.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"insufficient_audio_activity":this.eventEmitter.emit(Sc.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Sc.ERROR,t);break;case"error":this.eventEmitter.emit(Sc.ERROR,t);break;default:console.warn("Unknown message type:",t)}}catch(t){console.error("Failed to parse WebSocket message:",t,e.data),this.eventEmitter.emit(Sc.ERROR,new Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener("error",e=>{console.error("WebSocket error:",e),this.eventEmitter.emit(Sc.ERROR,e)}),this.websocket.addEventListener("close",e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||1e3!==e.code&&1005!==e.code){const t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||"No reason provided"}`;console.error(t),this.eventEmitter.emit(Sc.ERROR,new Error(t))}this.eventEmitter.emit(Sc.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t,n;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");const i={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:null!=(t=e.commit)&&t,sample_rate:null!=(n=e.sampleRate)?n:this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(i))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");this.websocket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,"User ended session")}}const Ec=function(e,t){return async(n,i)=>{const r=kc.get(e);if(r)return n.addModule(r);if(i)try{return await n.addModule(i),void kc.set(e,i)}catch(t){throw new Error(`Failed to load the ${e} worklet module from path: ${i}. Error: ${t}`)}const s=new Blob([t],{type:"application/javascript"}),o=URL.createObjectURL(s);try{return await n.addModule(o),void kc.set(e,o)}catch(e){URL.revokeObjectURL(o)}try{const i=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(i),kc.set(e,i)}catch(t){throw new Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}("scribeAudioProcessor",'/*\n * Scribe Audio Processor for converting microphone audio to PCM16 format\n * Supports resampling for browsers like Firefox that don\'t support\n * AudioContext sample rate constraints.\n * USED BY @elevenlabs/client\n */\n\nclass ScribeAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = [];\n this.bufferSize = 4096; // Buffer size for optimal chunk transmission\n\n // Resampling state\n this.inputSampleRate = null;\n this.outputSampleRate = null;\n this.resampleRatio = 1;\n this.lastSample = 0;\n this.resampleAccumulator = 0;\n\n this.port.onmessage = ({ data }) => {\n if (data.type === "configure") {\n this.inputSampleRate = data.inputSampleRate;\n this.outputSampleRate = data.outputSampleRate;\n if (this.inputSampleRate && this.outputSampleRate) {\n this.resampleRatio = this.inputSampleRate / this.outputSampleRate;\n }\n }\n };\n }\n\n // Linear interpolation resampling\n resample(inputData) {\n if (this.resampleRatio === 1 || !this.inputSampleRate) {\n return inputData;\n }\n\n const outputSamples = [];\n\n for (let i = 0; i < inputData.length; i++) {\n const currentSample = inputData[i];\n\n // Generate output samples using linear interpolation\n while (this.resampleAccumulator < 1) {\n const interpolated =\n this.lastSample +\n (currentSample - this.lastSample) * this.resampleAccumulator;\n outputSamples.push(interpolated);\n this.resampleAccumulator += this.resampleRatio;\n }\n\n this.resampleAccumulator -= 1;\n this.lastSample = currentSample;\n }\n\n return new Float32Array(outputSamples);\n }\n\n process(inputs) {\n const input = inputs[0];\n if (input.length > 0) {\n let channelData = input[0]; // Get first channel (mono)\n\n // Resample if needed (for Firefox and other browsers that don\'t\n // support AudioContext sample rate constraints)\n if (this.resampleRatio !== 1) {\n channelData = this.resample(channelData);\n }\n\n // Add incoming audio to buffer\n for (let i = 0; i < channelData.length; i++) {\n this.buffer.push(channelData[i]);\n }\n\n // When buffer reaches threshold, convert and send\n if (this.buffer.length >= this.bufferSize) {\n const float32Array = new Float32Array(this.buffer);\n const int16Array = new Int16Array(float32Array.length);\n\n // Convert Float32 [-1, 1] to Int16 [-32768, 32767]\n for (let i = 0; i < float32Array.length; i++) {\n // Clamp the value to prevent overflow\n const sample = Math.max(-1, Math.min(1, float32Array[i]));\n // Scale to PCM16 range\n int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767;\n }\n\n // Send to main thread as transferable ArrayBuffer\n this.port.postMessage(\n {\n audioData: int16Array.buffer\n },\n [int16Array.buffer]\n );\n\n // Clear buffer\n this.buffer = [];\n }\n }\n\n return true; // Continue processing\n }\n}\n\nregisterProcessor("scribeAudioProcessor", ScribeAudioProcessor);\n\n');var wc,Pc;!function(e){e.PCM_8000="pcm_8000",e.PCM_16000="pcm_16000",e.PCM_22050="pcm_22050",e.PCM_24000="pcm_24000",e.PCM_44100="pcm_44100",e.PCM_48000="pcm_48000",e.ULAW_8000="ulaw_8000"}(wc||(wc={})),function(e){e.MANUAL="manual",e.VAD="vad"}(Pc||(Pc={}));class Rc{static getWebSocketUri(e=Rc.DEFAULT_BASE_URI){return`${e}/v1/speech-to-text/realtime`}static buildWebSocketUri(e){const t=Rc.getWebSocketUri(e.baseUri),n=new URLSearchParams;if(n.append("model_id",e.modelId),n.append("token",e.token),void 0!==e.commitStrategy&&n.append("commit_strategy",e.commitStrategy),void 0!==e.audioFormat&&n.append("audio_format",e.audioFormat),void 0!==e.vadSilenceThresholdSecs){if(e.vadSilenceThresholdSecs<=.3||e.vadSilenceThresholdSecs>3)throw new Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");n.append("vad_silence_threshold_secs",e.vadSilenceThresholdSecs.toString())}if(void 0!==e.vadThreshold){if(e.vadThreshold<.1||e.vadThreshold>.9)throw new Error("vadThreshold must be between 0.1 and 0.9");n.append("vad_threshold",e.vadThreshold.toString())}if(void 0!==e.minSpeechDurationMs){if(e.minSpeechDurationMs<=50||e.minSpeechDurationMs>2e3)throw new Error("minSpeechDurationMs must be between 50 and 2000");n.append("min_speech_duration_ms",e.minSpeechDurationMs.toString())}if(void 0!==e.minSilenceDurationMs){if(e.minSilenceDurationMs<=50||e.minSilenceDurationMs>2e3)throw new Error("minSilenceDurationMs must be between 50 and 2000");n.append("min_silence_duration_ms",e.minSilenceDurationMs.toString())}void 0!==e.languageCode&&n.append("language_code",e.languageCode),void 0!==e.includeTimestamps&&n.append("include_timestamps",e.includeTimestamps?"true":"false");const i=n.toString();return i?`${t}?${i}`:t}static connect(e){if(!e.modelId)throw new Error("modelId is required");const t=new Cc("microphone"in e&&e.microphone?16e3:e.sampleRate),n=Rc.buildWebSocketUri(e),i=new WebSocket(n);return"microphone"in e&&e.microphone&&i.addEventListener("open",()=>{Rc.streamFromMicrophone(e,t)}),t.setWebSocket(i),t}static async streamFromMicrophone(e,t){const n=16e3;try{var i,r,s,o,a,c,d,l,u,h;const p=await navigator.mediaDevices.getUserMedia({audio:{deviceId:null==(i=e.microphone)?void 0:i.deviceId,echoCancellation:null==(r=null==(s=e.microphone)?void 0:s.echoCancellation)||r,noiseSuppression:null==(o=null==(a=e.microphone)?void 0:a.noiseSuppression)||o,autoGainControl:null==(c=null==(d=e.microphone)?void 0:d.autoGainControl)||c,channelCount:null!=(l=null==(u=e.microphone)?void 0:u.channelCount)?l:1,sampleRate:{ideal:n}}}),m=null==(h=p.getAudioTracks()[0])?void 0:h.getSettings(),g=null==m?void 0:m.sampleRate,f=new AudioContext(g?{sampleRate:g}:{});await Ec(f.audioWorklet);const v=f.createMediaStreamSource(p),y=new AudioWorkletNode(f,"scribeAudioProcessor");f.sampleRate!==n&&y.port.postMessage({type:"configure",inputSampleRate:f.sampleRate,outputSampleRate:n}),y.port.onmessage=e=>{const{audioData:n}=e.data,i=new Uint8Array(n);let r="";for(let e=0;e<i.length;e++)r+=String.fromCharCode(i[e]);const s=btoa(r);t.send({audioBase64:s})},v.connect(y),"suspended"===f.state&&await f.resume(),t._audioCleanup=()=>{p.getTracks().forEach(e=>{e.stop()}),v.disconnect(),y.disconnect(),f.close()}}catch(e){throw console.error("Failed to start microphone streaming:",e),e}}}function Ic(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}Rc.DEFAULT_BASE_URI="wss://api.elevenlabs.io";var Oc=/*#__PURE__*/function(){function t(e,t,n,i,r,s,o,a){this.provider=void 0,this.options=void 0,this.elevenLabsOptions=void 0,this.user=void 0,this.headInfo=void 0,this.sendMessage=void 0,this.microphoneStatus="OFF",this.microphoneAccess=!1,this.recognizer=null,this.connection=null,this.tokenObj={token:"",generatedAt:null,region:""},this.micBeep=new Audio("https://embedded.unith.ai/assets/beep_up.wav"),this.provider=e,this.options=t,this.elevenLabsOptions=n,this.user=i,this.headInfo=r,this.sendMessage=a,this.microphoneAccess=s,this.tokenObj=o,this.microphoneAccess||this.options.onMicrophoneError({message:"Microphone access not granted."})}t.initializeMicrophone=function(e,n,i,r,s,o,a){try{var c={token:"",generatedAt:null,region:""};return Promise.resolve(r.getAsrToken("eleven_labs"===n?"elevenlabs":"azure")).then(function(d){return c={token:d.token,generatedAt:Date.now(),region:d.region},new t(n,e,i,r,s,o,c,a)})}catch(e){return Promise.reject(e)}};var n=t.prototype;return n.updateMicrophoneStatus=function(e){this.microphoneStatus=e,this.options.onMicrophoneStatusChange({status:e})},n.handleRecognitionResult=function(e){e.length<2||this.options.onMicrophoneSpeechRecognitionResult({transcript:e})},n.startAzureMicrophone=function(){try{var t=function(t){return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return e(require("microsoft-cognitiveservices-speech-sdk"))}).catch(function(e){throw new Error("Azure Speech SDK not available: "+e)})).then(function(e){var t,i,r,s,o,a,c,d=e;if(d.SpeechConfig)r=d.SpeechConfig,s=d.AudioConfig,o=d.SpeechRecognizer,a=d.ResultReason,c=d.PhraseListGrammar;else if(null!=(t=d.default)&&t.SpeechConfig){var l=d.default;r=l.SpeechConfig,s=l.AudioConfig,o=l.SpeechRecognizer,a=l.ResultReason,c=l.PhraseListGrammar}else{if(null==(i=d.SpeechSDK)||!i.SpeechConfig)throw new Error("Azure Speech SDK does not expose expected symbols. Check that the package is installed correctly.");var u=d.SpeechSDK;r=u.SpeechConfig,s=u.AudioConfig,o=u.SpeechRecognizer,a=u.ResultReason,c=u.PhraseListGrammar}var h=r.fromAuthorizationToken(n.tokenObj.token,n.tokenObj.region);h.speechRecognitionLanguage=n.headInfo.lang_speech_recognition||"en-US";var p=s.fromDefaultMicrophoneInput();n.recognizer=new o(h,p),n.headInfo.phrases.length>0&&c.fromRecognizer(n.recognizer).addPhrases(n.headInfo.phrases),n.recognizer.recognized=function(e,t){t.result.reason===a.RecognizedSpeech?n.handleRecognitionResult(t.result.text):t.result.reason===a.NoMatch&&n.options.onMicrophoneError({message:"Speech could not be recognized - No clear speech detected"})},n.recognizer.startContinuousRecognitionAsync(function(){n.micBeep.play(),n.updateMicrophoneStatus("ON")},function(){console.error("Error starting recognizer")}),n.tokenObj.token=""})},n=this,i=function(){if(0===n.tokenObj.token.length)return Promise.resolve(n.user.getAsrToken("azure")).then(function(e){if(!e.region||!e.token)throw new Error("Failed to initialize Azure microphone.");n.tokenObj={token:e.token,region:e.region,generatedAt:Date.now()}})}();return Promise.resolve(i&&i.then?i.then(t):t())}catch(e){return Promise.reject(e)}},n.stopAzureMicrophone=function(){try{var e=this;return e.recognizer&&e.recognizer.stopContinuousRecognitionAsync(function(){e.updateMicrophoneStatus("OFF")},function(t){e.options.onMicrophoneError({message:"Error stopping microphone : "+t})}),Promise.resolve()}catch(e){return Promise.reject(e)}},n.startElevenLabsMicrophone=function(){try{var e=function(e){t.connection=Rc.connect({token:t.tokenObj.token,modelId:"scribe_v2_realtime",includeTimestamps:!1,microphone:{echoCancellation:!0,noiseSuppression:t.elevenLabsOptions.noiseSuppression},commitStrategy:Pc.VAD,vadSilenceThresholdSecs:t.elevenLabsOptions.vadSilenceThresholdSecs,vadThreshold:t.elevenLabsOptions.vadThreshold,minSpeechDurationMs:t.elevenLabsOptions.minSpeechDurationMs,minSilenceDurationMs:t.elevenLabsOptions.minSilenceDurationMs}),t.connection.on(Sc.SESSION_STARTED,function(){t.micBeep.play(),t.updateMicrophoneStatus("ON")}),t.connection.on(Sc.COMMITTED_TRANSCRIPT,function(e){e.text.length<2||"("===e.text[0]||t.handleRecognitionResult(e.text)}),t.connection.on(Sc.ERROR,function(e){console.error("Error:",e),t.options.onMicrophoneError({message:"Error recognizing speech"})}),t.tokenObj.token=""},t=this,n=function(){if(0===t.tokenObj.token.length)return Promise.resolve(t.user.getAsrToken("elevenlabs")).then(function(e){if(!e.token)throw new Error("Failed to initialize Eleven Labs microphone.");t.tokenObj={token:e.token,region:"",generatedAt:Date.now()}})}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},n.stopElevenLabsMicrophone=function(){try{var e,t=this;return Promise.resolve(Ic(function(){function n(n){if(e)return n;t.connection=null}var i=function(){if(t.connection)return Promise.resolve(t.connection.close()).then(function(){t.updateMicrophoneStatus("OFF"),e=1})}();return i&&i.then?i.then(n):n(i)},function(){t.updateMicrophoneStatus("OFF")}))}catch(e){return Promise.reject(e)}},n.toggleMicrophone=function(){try{var e=this;return Promise.resolve(Ic(function(){var t=function(){if("ON"===e.microphoneStatus){e.updateMicrophoneStatus("PROCESSING");var t=function(){if("azure"===e.provider)return Promise.resolve(e.stopAzureMicrophone()).then(function(){});var t=function(){if("eleven_labs"===e.provider)return Promise.resolve(e.stopElevenLabsMicrophone()).then(function(){})}();return t&&t.then?t.then(function(){}):void 0}();if(t&&t.then)return t.then(function(){})}else{var n=function(){if("OFF"===e.microphoneStatus){e.updateMicrophoneStatus("PROCESSING");var t=function(){if("azure"===e.provider)return Promise.resolve(e.startAzureMicrophone()).then(function(){});var t=function(){if("eleven_labs"===e.provider)return Promise.resolve(e.startElevenLabsMicrophone()).then(function(){})}();return t&&t.then?t.then(function(){}):void 0}();if(t&&t.then)return t.then(function(){})}else console.error("Microphone is currently processing. Please wait.")}();if(n&&n.then)return n.then(function(){})}}();if(t&&t.then)return t.then(function(){})},function(t){e.updateMicrophoneStatus("OFF"),e.options.onMicrophoneError({message:t.message||"An unknown error occurred."})}))}catch(e){return Promise.reject(e)}},n.status=function(){return this.microphoneStatus},t}(),_c=/*#__PURE__*/function(){function e(e,t){this.connection=void 0,this.intervalId=null,this.pingInterval=void 0,this.timeout=void 0,this.lastPingTimestamp="0",this.history=[],this.maxHistory=void 0,this.onUpdate=void 0,this.connection=e,this.pingInterval=(null==t?void 0:t.pingInterval)||4e3,this.timeout=(null==t?void 0:t.timeout)||2e3,this.maxHistory=(null==t?void 0:t.maxHistory)||3,this.onUpdate=null==t?void 0:t.onUpdate,this.handleMessage=this.handleMessage.bind(this),this.connection.onPingPong(this.handleMessage)}var t=e.prototype;return t.start=function(){var e=this;this.intervalId||(this.intervalId=setInterval(function(){e.sendPing()},this.pingInterval))},t.stop=function(){clearInterval(this.intervalId),this.intervalId=null},t.destroy=function(){this.stop()},t.sendPing=function(){var e=performance.now().toString();this.lastPingTimestamp=e;var t={event:exports.EventType.PING,timestamp:this.lastPingTimestamp,id:"0"};this.connection.sendPingEvent(t)},t.handleMessage=function(e){try{if(e.timestamp===this.lastPingTimestamp){var t=performance.now()-parseFloat(e.timestamp);this.recordLatency(t)}}catch(e){}},t.recordLatency=function(e){this.history.push(e),this.history.length>this.maxHistory&&this.history.shift();var t=this.history.reduce(function(e,t){return e+t},0)/this.history.length,n=this.classifyLatency(t);this.onUpdate&&this.onUpdate({rtt:e,average:t,status:n})},t.classifyLatency=function(e){return e<100?"good":e<250?"moderate":"poor"},e}(),Dc=/*#__PURE__*/function(){function e(e){this.config=void 0,this.driftHistory=[],this.correctionInProgress=!1,this.lastAudioTiming=null,this.lastVideoTiming=null,this.config=e}var t=e.prototype;return t.updateAudioTime=function(e){this.lastAudioTiming={timestamp:performance.now(),relativeTime:e}},t.updateVideoTime=function(e){this.lastVideoTiming={timestamp:performance.now(),relativeTime:e}},t.resetTiming=function(){this.lastAudioTiming=null,this.lastVideoTiming=null},t.checkSync=function(){try{var e=this;if(e.correctionInProgress)return console.warn("Sync correction already in progress"),Promise.resolve();if(!e.lastAudioTiming||!e.lastVideoTiming)return console.warn("Insufficient timing data for sync check"),Promise.resolve();var t=Math.abs(e.lastAudioTiming.relativeTime-e.lastVideoTiming.relativeTime);return e.recordDrift(t),t>e.config.tolerance?console.log("Drift detected: "+t+"ms"):console.log("No significant drift detected"),Promise.resolve()}catch(e){return Promise.reject(e)}},t.recordDrift=function(e){this.driftHistory.push({timestamp:Date.now(),drift:e,audioTime:this.lastAudioTiming.relativeTime,videoTime:this.lastVideoTiming.relativeTime}),this.driftHistory.length>this.config.historyLength&&this.driftHistory.shift()},e}(),Mc=window.localStorage,Ac=window.location.origin+window.location.pathname,xc=function(e,t,n){if(void 0!==Mc)return Mc.getItem("chat:"+Ac+":"+t+":"+n+":"+e)},Nc=function(e,t,n,i){void 0===Mc||Mc.setItem("chat:"+Ac+":"+n+":"+i+":"+e,t)};function Lc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Uc,jc,Fc=/*#__PURE__*/function(){function e(e,t,n,i,r,s,o,a){this.id=void 0,this.username=void 0,this.password=void 0,this.orgId=void 0,this.headId=void 0,this.apiBase=void 0,this.EXPIRATION_OFFSET=9e5,this.accessToken="",this.tokenType="",this.sessionId=0,this.id=n,this.username=i,this.password=r,this.orgId=s,this.headId=o,this.apiBase=a,this.accessToken=e,this.tokenType=t;var c=xc("session_id",s,o);c&&(this.sessionId=parseInt(c),this.sessionId+=1),Nc("session_id",this.sessionId.toString(),s,o)}e.loginUser=function(t,n,i,r,s){try{var o=new FormData;return o.append("username",t),o.append("password",n),Promise.resolve(Lc(function(){return Promise.resolve(fetch(i+"/token",{method:"POST",body:o})).then(function(o){return o.status>=200&&o.status<=299?Promise.resolve(o.json()).then(function(o){return new e(o.access_token,o.token_type,o.user_id,t,n,r,s,i)}):Promise.resolve(o.text()).then(function(e){var t=new Error("An error occurred: "+o.status+" "+o.statusText+". Response: "+e);throw t.response={status:o.status,status_code:o.status,data:JSON.parse(e)},t})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))}))}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.getHeadDetails=function(e){try{var t=this,n=t.apiBase+"/api/v1/head/"+t.orgId+"/"+t.headId+"/"+e;return Promise.resolve(Lc(function(){return Promise.resolve(fetch(n)).then(function(e){return e.status>=200&&e.status<=299?Promise.resolve(e.json()):Promise.resolve(e.text()).then(function(t){var n=new Error("An error occurred: "+e.status+" "+e.statusText+". Response: "+t);throw n.response={status:e.status,status_code:e.status,data:JSON.parse(t)},n})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))}))}catch(e){return Promise.reject(e)}},t.getAuthToken=function(e,t){try{var n,i=this.apiBase+"/token",r=new FormData;r.append("username",e),r.append("password",t);var s=Lc(function(){return Promise.resolve(fetch(i,{method:"POST",body:r})).then(function(e){return Promise.resolve(e.json()).then(function(e){n=e})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))});return Promise.resolve(s&&s.then?s.then(function(e){return n}):n)}catch(e){return Promise.reject(e)}},t.getProviderToken=function(e,t){try{var n,i,r=function(e){return{token:n,region:i}},s=this.apiBase+"/api/v1/asr_token?provider="+t,o=Lc(function(){return Promise.resolve(fetch(s,{method:"GET",headers:{Authorization:"Bearer "+e}})).then(function(e){return Promise.resolve(e.json()).then(function(e){n=e.token,i=e.region})})},function(e){var t,n;if(null!=e&&null!=(t=e.response)&&null!=(t=t.data)&&t.detail)throw new Error(null==e||null==(n=e.response)||null==(n=n.data)?void 0:n.detail);throw new Error(JSON.stringify(e))});return Promise.resolve(o&&o.then?o.then(r):r())}catch(e){return Promise.reject(e)}},t.getAccessToken=function(){try{var e=function(e){var s=JSON.parse(window.atob(n.split(".")[1]));return t.username=s.username,{access_token:n,user_id:i,session_id:r}},t=this,n=xc("access_token",t.orgId,t.headId),i=xc("user_id",t.orgId,t.headId),r=parseInt(xc("session_id",t.orgId,t.headId)||"")||0,s=!0;if("undefined"!==n&&n&&i&&"number"==typeof r){var o=1e3*JSON.parse(window.atob(n.split(".")[1])).exp,a=(new Date).getTime()+t.EXPIRATION_OFFSET;s=a>o}var c=function(){if(s)return Promise.resolve(t.getAuthToken(t.username,t.password)).then(function(e){if(!e)throw new Error("Could not renew authentication token");i=e.user_id,r++,Nc("access_token",n=e.access_token,t.orgId,t.headId),Nc("user_id",i,t.orgId,t.headId),Nc("session_id",r.toString(),t.orgId,t.headId)})}();return Promise.resolve(c&&c.then?c.then(e):e())}catch(e){return Promise.reject(e)}},t.getAsrToken=function(e){try{var t=this,n=xc("asr_token",t.orgId,t.headId),i=xc("region",t.orgId,t.headId);return Promise.resolve(t.getAccessToken()).then(function(r){var s,o=r.access_token;function a(e){return s?e:{token:n,region:i}}var c=!0;if(n&&i){var d=1e3*JSON.parse(window.atob(n.split(".")[1])).exp,l=(new Date).getTime()+t.EXPIRATION_OFFSET;c=l>d}var u=function(){if(c)return Promise.resolve(t.getProviderToken(o,e)).then(function(e){if(!e)return s=1,{token:"",region:""};i=e.region,Nc("asr_token",n=e.token,t.orgId,t.headId),Nc("asr_region",i,t.orgId,t.headId)})}();return u&&u.then?u.then(a):a(u)})}catch(e){return Promise.reject(e)}},e}();function Vc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}!function(e){e.INITIALIZING="initializing",e.READY="ready",e.PLAYING="playing",e.PAUSED="paused",e.INTERRUPTED="interrupted",e.DESTROYED="destroyed"}(Uc||(Uc={})),exports.VideoTransitionType=void 0,(jc=exports.VideoTransitionType||(exports.VideoTransitionType={})).NONE="none",jc.CROSSFADE="crossfade",jc.FADEIN="fadein",jc.FADEOUT="fadeout";var Bc=/*#__PURE__*/function(){function e(e,t,i,r){var s=this;this.canvas=void 0,this.ctx=void 0,this.container=void 0,this.config=void 0,this.resizeObserver=null,this.decoder=null,this.state=Uc.INITIALIZING,this.isProcessingFrame=!1,this.isStreaming=!1,this.startTime=0,this.frameBuffer=[],this.currentSequenceId=0,this.animationFrameId=null,this.renderLoop=!1,this.fpsCounter={count:0,lastTime:0},this.handleContextLoss=function(){},this.handleContextRestore=function(){},this.handleResize=function(){var e=s.container.getBoundingClientRect(),t=e.width,n=e.height;s.canvas.width=t,s.canvas.height=n,s.canvas.style.width=t+"px",s.canvas.style.height=n+"px",s.ctx.imageSmoothingEnabled=!0},this.canvas=e,this.ctx=t,this.container=i,this.config=n({maxBufferSize:1e3,enableAdaptiveQuality:!1},r),this.setupContextLossHandling(),this.setupResizeHandling(),this.initializeDecoder()}e.create=function(t,n){try{var i;if(!("VideoDecoder"in window))throw new Error("WebCodecs VideoDecoder API is not supported in this browser");var r=document.createElement("canvas");r.width=n.width,r.height=n.height,r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.backgroundColor=(null==(i=n.backgroundColor)?void 0:i.toString())||"#000000",r.style.maxWidth="100%",r.style.height="100%",r.style.zIndex="0",r.style.pointerEvents="none",r.style.objectFit="cover",r.style.imageRendering="pixelated";var s=r.getContext("2d",{alpha:!1,desynchronized:!0});if(!s)throw new Error("Failed to get 2D canvas context");return s.imageSmoothingEnabled=!0,t.appendChild(r),Promise.resolve(new e(r,s,t,n))}catch(e){return Promise.reject(e)}};var i=e.prototype;return i.initializeDecoder=function(){try{var e=this;return Promise.resolve(Vc(function(){return new VideoDecoder({output:function(){},error:function(){}}).close(),e.decoder=new VideoDecoder({output:function(t){e.renderVideoFrame(t)},error:function(e){console.error("VP8 Decoder error:",e.message)}}),Promise.resolve(e.decoder.configure({codec:"vp8",codedWidth:e.config.width,codedHeight:e.config.height})).then(function(){})},function(e){throw new Error("Failed to initialize VP8 decoder: "+e.message)}))}catch(e){return Promise.reject(e)}},i.setupResizeHandling=function(){var e=this;this.resizeObserver=new ResizeObserver(function(n){for(var i,r=function(e){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,n){if(e){if("string"==typeof e)return t(e,n);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,n):void 0}}(e))){n&&(e=n);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(i=r()).done;)i.value.target===e.container&&e.handleResize()}),this.resizeObserver.observe(this.container),window.addEventListener("resize",this.handleResize)},i.getBufferLength=function(){return this.frameBuffer.length},i.getStreamingStatus=function(){return this.isStreaming},i.addFrame=function(e,t,n){void 0===n&&(n=!1);try{var i=this;if(i.state===Uc.DESTROYED)throw new Error("Cannot add frame to destroyed video output");var r={data:e,timestamp:t,isKeyframe:n,sequenceId:i.currentSequenceId++,size:e.byteLength};if(i.frameBuffer.length>=(i.config.maxBufferSize||1e3))if(i.config.enableAdaptiveQuality){if(!n)return Promise.resolve();var s=i.frameBuffer.findIndex(function(e){return!e.isKeyframe});-1!==s?i.frameBuffer.splice(s,1):i.frameBuffer.shift()}else i.frameBuffer.shift();return i.frameBuffer.push(r),Promise.resolve()}catch(e){return Promise.reject(e)}},i.toggleStream=function(e){try{return this.isStreaming=e,Promise.resolve()}catch(e){return Promise.reject(e)}},i.clearFrame=function(){if(this.state===Uc.DESTROYED)throw new Error("Cannot clear frame from destroyed video output");if(this.renderLoop=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.frameBuffer=[],this.isProcessingFrame=!1,this.currentSequenceId=0,this.startTime=0,this.fpsCounter={count:0,lastTime:0},this.decoder&&"configured"===this.decoder.state)try{this.decoder.flush()}catch(e){console.warn("Error flushing decoder:",e)}this.clearCanvas(),this.state=Uc.READY},i.interrupt=function(e){var t=this;if(void 0===e&&(e=!1),this.state!==Uc.DESTROYED){if(this.state=Uc.INTERRUPTED,this.frameBuffer=[],this.isProcessingFrame=!1,this.decoder&&"configured"===this.decoder.state)try{this.decoder.flush()}catch(e){console.warn("Error flushing decoder:",e)}e?this.fadeOutCanvas().then(function(){t.clearCanvas()}):this.clearCanvas()}},i.destroy=function(){this.state!==Uc.DESTROYED&&(this.state=Uc.DESTROYED,this.renderLoop=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.decoder&&(this.decoder.close(),this.decoder=null),this.frameBuffer=[],this.canvas.removeEventListener("webglcontextlost",this.handleContextLoss),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestore),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.isProcessingFrame=!1)},i.getState=function(){return this.state},i.startRenderingStreamingVideo=function(e){e&&(this.state=Uc.READY,this.renderLoop=!0,this.startTime=performance.now(),this.render())},i.render=function(){var e,t=this;if(this.renderLoop&&this.state!==Uc.DESTROYED){var n=(null==(e=this.frameBuffer[0])?void 0:e.timestamp)||0;this.frameBuffer.length>0&&0===this.frameBuffer[0].sequenceId&&(this.startTime=performance.now());var i=performance.now()-this.startTime;i>=n&&this.frameBuffer.length>0&&!this.isProcessingFrame&&this.processNextFrame(i,i-n),this.animationFrameId=requestAnimationFrame(function(){return t.render()})}},i.processNextFrame=function(e,t){try{var n=this;if(n.isProcessingFrame||0===n.frameBuffer.length||!n.decoder)return Promise.resolve();if("configured"!==n.decoder.state)return Promise.resolve();n.isProcessingFrame=!0;var i=n.frameBuffer.shift(),r=function(e,t){try{var r=Vc(function(){return Promise.resolve(n.decodeVP8Frame(i)).then(function(){})},function(e){console.error("Frame processing failed:",e)})}catch(e){return t(!0,e)}return r&&r.then?r.then(t.bind(null,!1),t.bind(null,!0)):t(!1,r)}(0,function(e,t){if(n.isProcessingFrame=!1,e)throw t;return t});return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},i.decodeVP8Frame=function(e){try{try{var t=new EncodedVideoChunk({type:e.isKeyframe?"key":"delta",timestamp:1e3*e.timestamp,data:e.data});this.decoder.decode(t)}catch(e){throw new Error("VP8 decode failed: "+e.message)}return Promise.resolve()}catch(e){return Promise.reject(e)}},i.renderVideoFrame=function(e){try{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);var t,n,i,r,s=e.displayWidth/e.displayHeight;s>this.canvas.width/this.canvas.height?(i=(this.canvas.width-(t=(n=this.canvas.height)*s))/2,r=0):(i=0,r=(this.canvas.height-(n=(t=this.canvas.width)/s))/2),this.ctx.drawImage(e,i,r,t,n),e.close()}catch(e){console.error("Error rendering video frame:",e)}},i.clearCanvas=function(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)},i.fadeOutCanvas=function(){try{var e=this;return Promise.resolve(new Promise(function(t){var n=1,i=function(){e.canvas.style.opacity=(n-=.05).toString(),n<=0?(e.canvas.style.opacity="1",t()):requestAnimationFrame(i)};i()}))}catch(e){return Promise.reject(e)}},i.setupContextLossHandling=function(){var e=this;this.handleContextLoss=function(t){t.preventDefault(),console.warn("Canvas context lost"),e.state=Uc.PAUSED},this.handleContextRestore=function(){e.state===Uc.PAUSED&&(e.state=Uc.PLAYING)},this.canvas.addEventListener("webglcontextlost",this.handleContextLoss),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestore)},e}();function qc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Wc=/*#__PURE__*/function(){function e(e,t,n,i){this.videoOutput=void 0,this.container=void 0,this.idleVideo=null,this.cachedVideo=null,this.idleVideoConfig=null,this.videoTransitionConfig=null,this.CROSSFADE_DURATION=500,this.isTransitioning=!1,this.isShowingIdleVideo=!0,this.bufferCheckAnimationId=null,this.lastBufferCheckTime=0,this.sessionStarted=!1,this.isShowingCachedVideo=!1,this.onIdleVideoShown=void 0,this.onIdleVideoHidden=void 0,this.onSpeakingStartCallback=null,this.onSpeakingEndCallback=null,this.videoOutput=e,this.container=t,this.videoTransitionConfig=n}e.createVideoOutput=function(t,n){try{return Promise.resolve(Bc.create(t,n)).then(function(i){var r=new e(i,t,n.transition,n.effects);return Promise.resolve(r.setupIdleVideo(n.idleVideo,n)).then(function(){return Promise.resolve(r.setupCachedVideo(n)).then(function(){return r})})})}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.setupIdleVideo=function(e,t){try{var n=this;n.idleVideoConfig=e,n.idleVideo=document.createElement("video"),n.idleVideo.src=e.src,n.idleVideo.width=t.width,n.idleVideo.height=t.height,n.idleVideo.style.position="absolute",n.idleVideo.style.top="0",n.idleVideo.style.left="0",n.idleVideo.style.width="100%",n.idleVideo.style.height="100%",n.idleVideo.style.objectFit="cover",n.idleVideo.style.maxWidth="100%",n.idleVideo.style.backgroundColor=t.backgroundColor||"#000000",n.idleVideo.style.zIndex="1",n.idleVideo.style.pointerEvents="none",n.idleVideo.style.opacity="1",n.idleVideo.muted=!0,n.idleVideo.loop=!0,n.idleVideo.controls=!1,n.idleVideo.playsInline=!0,n.idleVideo.preload="auto","static"===getComputedStyle(n.container).position&&(n.container.style.position="relative"),n.container.appendChild(n.idleVideo);var i=qc(function(){return Promise.resolve(n.idleVideo.load()).then(function(){return Promise.resolve(n.idleVideo.play()).then(function(){})})},function(e){console.error("Failed to load idle video:",e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.setupCachedVideo=function(e){try{var t=this;return t.cachedVideo=document.createElement("video"),t.cachedVideo.src="",t.cachedVideo.width=e.width,t.cachedVideo.height=e.height,t.cachedVideo.style.position="absolute",t.cachedVideo.style.top="0",t.cachedVideo.style.left="0",t.cachedVideo.style.width="100%",t.cachedVideo.style.height="100%",t.cachedVideo.style.objectFit="cover",t.cachedVideo.style.maxWidth="100%",t.cachedVideo.style.zIndex="2",t.cachedVideo.style.pointerEvents="none",t.cachedVideo.style.opacity="0",t.cachedVideo.style.transition="opacity "+t.CROSSFADE_DURATION+"ms ease-in-out",t.cachedVideo.controls=!1,t.cachedVideo.playsInline=!0,t.cachedVideo.preload="auto",t.container.appendChild(t.cachedVideo),Promise.resolve()}catch(e){return Promise.reject(e)}},t.onSpeakingStart=function(e){this.onSpeakingStartCallback=e},t.onSpeakingEnd=function(e){this.onSpeakingEndCallback=e},t.startStreaming=function(e){void 0===e&&(e=!1),this.sessionStarted=!0,this.startBufferMonitoring(),this.videoOutput.startRenderingStreamingVideo(e)},t.stopBufferMonitoring=function(){this.bufferCheckAnimationId&&(cancelAnimationFrame(this.bufferCheckAnimationId),this.bufferCheckAnimationId=null),this.lastBufferCheckTime=0,this.sessionStarted=!1},t.getBufferLength=function(){return this.videoOutput.getBufferLength()},t.startBufferMonitoring=function(){var e=this;if(!this.bufferCheckAnimationId){this.lastBufferCheckTime=0;var t=function(n){n-e.lastBufferCheckTime>=100&&(e.sessionStarted&&e.videoOutput.getBufferLength()>0?e.hideIdleVideoBeforeStream():e.videoOutput.getStreamingStatus()||0!==e.videoOutput.getBufferLength()||e.showIdleVideoAfterStream(),e.lastBufferCheckTime=n),e.bufferCheckAnimationId=requestAnimationFrame(t)};this.bufferCheckAnimationId=requestAnimationFrame(t)}},t.toggleCacheVideoMute=function(){this.cachedVideo&&(this.cachedVideo.muted=!this.cachedVideo.muted)},t.playCachedVideo=function(e){try{var t=this;if(t.isShowingCachedVideo||!t.cachedVideo||!e||t.isTransitioning)return Promise.resolve();t.isShowingCachedVideo=!0;var n=qc(function(){return t.cachedVideo.src=e,t.cachedVideo.style.opacity="0",Promise.resolve(new Promise(function(e,n){t.cachedVideo.addEventListener("loadeddata",function(){return e()},{once:!0}),t.cachedVideo.addEventListener("error",function(){return n(new Error("Video failed to load"))},{once:!0}),t.cachedVideo.load()})).then(function(){return t.crossfadeFromIdleToCached(),Promise.resolve(t.cachedVideo.play()).then(function(){t.cachedVideo.addEventListener("ended",function(){try{return Promise.resolve(t.crossfadeFromCachedToIdle()).then(function(){return Promise.resolve(t.cleanupCachedVideo()).then(function(){return Promise.resolve(t.showIdleVideo()).then(function(){})})})}catch(e){return Promise.reject(e)}},{once:!0})})})},function(e){return console.error("Failed to play cached video:",e),t.cachedVideo.style.opacity="0",t.isShowingCachedVideo=!1,Promise.resolve(t.showIdleVideo()).then(function(){})});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.crossfadeFromIdleToCached=function(){try{var e=this;return e.idleVideo&&e.cachedVideo&&!e.isTransitioning?(e.isTransitioning=!0,e.idleVideo.style.opacity="1",e.cachedVideo.style.opacity="1",Promise.resolve(new Promise(function(t){return setTimeout(t,e.CROSSFADE_DURATION)})).then(function(){e.idleVideo&&(e.idleVideo.style.opacity="0"),e.isShowingIdleVideo=!1,null==e.onIdleVideoHidden||e.onIdleVideoHidden(),null==e.onSpeakingStartCallback||e.onSpeakingStartCallback(),e.isTransitioning=!1})):Promise.resolve()}catch(e){return Promise.reject(e)}},t.crossfadeFromCachedToIdle=function(){try{var e=function(){return t.cachedVideo.style.opacity="0",Promise.resolve(new Promise(function(e){return setTimeout(e,t.CROSSFADE_DURATION)})).then(function(){t.isShowingIdleVideo=!0,null==t.onSpeakingEndCallback||t.onSpeakingEndCallback(),null==t.onIdleVideoShown||t.onIdleVideoShown(),t.isTransitioning=!1})},t=this;if(!t.idleVideo||!t.cachedVideo||t.isTransitioning)return Promise.resolve();t.isTransitioning=!0,t.idleVideo.style.opacity="1";var n=function(){if(t.idleVideo.paused){var e=qc(function(){return Promise.resolve(t.idleVideo.play()).then(function(){})},function(e){console.error("Failed to play idle video during crossfade:",e)});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},t.cleanupCachedVideo=function(){try{var e=this;return e.cachedVideo&&(e.cachedVideo.pause(),e.cachedVideo.currentTime=0,e.cachedVideo.src="",e.cachedVideo.style.opacity="0"),e.isShowingCachedVideo=!1,Promise.resolve()}catch(e){return Promise.reject(e)}},t.hideIdleVideo=function(){var e,t;this.idleVideo&&this.isShowingIdleVideo&&(null==(e=this.onSpeakingStartCallback)||e.call(this),this.isShowingIdleVideo=!1,this.idleVideo.style.opacity="0",null==(t=this.onIdleVideoHidden)||t.call(this))},t.hideIdleVideoBeforeStream=function(){var e,t;this.idleVideo&&this.isShowingIdleVideo&&(null==(e=this.onSpeakingStartCallback)||e.call(this),this.idleVideo.style.transition="opacity "+this.CROSSFADE_DURATION+"ms ease-in-out",this.isShowingIdleVideo=!1,this.idleVideo.style.opacity="0",null==(t=this.onIdleVideoHidden)||t.call(this))},t.setEventCallbacks=function(e){this.onIdleVideoShown=e.onIdleVideoShown,this.onIdleVideoHidden=e.onIdleVideoHidden},t.getStreamingStatus=function(){return this.videoOutput.getStreamingStatus()},t.showIdleVideo=function(){try{var e=this;return!e.idleVideo||e.isShowingIdleVideo?Promise.resolve():(null==e.onSpeakingEndCallback||e.onSpeakingEndCallback(),null==e.onIdleVideoShown||e.onIdleVideoShown(),e.isShowingIdleVideo=!0,e.idleVideo.style.opacity="1",Promise.resolve(qc(function(){var t=function(){if(e.idleVideo.paused)return Promise.resolve(e.idleVideo.play()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(e){console.error("failed to play idle video:",e)})))}catch(e){return Promise.reject(e)}},t.showIdleVideoAfterStream=function(){try{var e=this;return!e.idleVideo||e.isShowingIdleVideo?Promise.resolve():(null==e.onSpeakingEndCallback||e.onSpeakingEndCallback(),null==e.onIdleVideoShown||e.onIdleVideoShown(),e.isShowingIdleVideo=!0,e.idleVideo.style.opacity="1",Promise.resolve(qc(function(){var t=function(){if(e.idleVideo.paused)return Promise.resolve(e.idleVideo.play()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(e){console.error("failed to play idle video:",e)})))}catch(e){return Promise.reject(e)}},t.addFrame=function(e,t,n){try{var i=function(e){var i=s?new Uint8Array(e):e;return r.videoOutput.addFrame(i,t,n)},r=this,s=e instanceof Blob;return Promise.resolve(s?Promise.resolve(e.arrayBuffer()).then(i):i(new Uint8Array(e)))}catch(e){return Promise.reject(e)}},t.clearFrame=function(){return this.showIdleVideo(),this.videoOutput.clearFrame()},t.toggleStream=function(e){try{return Promise.resolve(this.videoOutput.toggleStream(e))}catch(e){return Promise.reject(e)}},t.interrupt=function(e){this.videoOutput.interrupt(e)},t.destroy=function(){this.bufferCheckAnimationId&&(cancelAnimationFrame(this.bufferCheckAnimationId),this.bufferCheckAnimationId=null),this.idleVideo&&(this.idleVideo.pause(),this.idleVideo.parentNode&&this.idleVideo.parentNode.removeChild(this.idleVideo),this.idleVideo=null),this.cachedVideo&&(this.cachedVideo.pause(),this.cachedVideo.parentNode&&this.cachedVideo.parentNode.removeChild(this.cachedVideo),this.cachedVideo=null),this.videoOutput.destroy()},e}(),Hc={vadSilenceThresholdSecs:1.5,noiseSuppression:!0,vadThreshold:.4,minSpeechDurationMs:100,minSilenceDurationMs:100},Gc={tolerance:40,softCorrectionThreshold:100,hardCorrectionThreshold:200,historyLength:50,maxCorrectionRate:.02,correctionCoolDown:500,correctionFadeTime:1e3,minAudioBuffer:100,maxAudioBuffer:500,minVideoBuffer:3,maxVideoBuffer:10};function zc(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Kc=/*#__PURE__*/function(){function e(e,t,n,i,r,s,o,a,c){var d=this,l=this,u=this,p=this,v=this,b=this,C=this,E=this;this.options=void 0,this.microphoneAccess=void 0,this.connection=void 0,this.idleVideo=void 0,this.wakeLock=void 0,this.user=void 0,this.audioOutput=void 0,this.videoOutput=void 0,this.headInfo=void 0,this.status="connecting",this.volume=1,this.sessionStarted=!1,this.messageCounter=0,this.syncController=void 0,this.avController=void 0,this.monitor=null,this.microphone=null,this.videoFrameQueue=[],this.cachedResponseQueue=[],this.suggestionsQueue=[],this.onOutputWorkletMessage=function(e){E.avController.handleAudioWorkletMessage(e.data)},this.handleMessage=function(e){try{if(d.options.onMessage({timestamp:e.timestamp,sender:e.speaker,text:e.text,visible:e.visible}),"suggestions"in e){var t=e.suggestions||[];t.length>1&&(d.suggestionsQueue=t)}return Promise.resolve()}catch(e){return Promise.reject(e)}},this.handleStreamError=function(e){var t=e.error_type;if(t&&["resource_exhausted","deadline_exceeded","inactivity_timeout"].includes(t)){if("resource_exhausted"===t){if(!E.avController.isPlaying)return void E.options.onError({message:"The system is experiencing heavy traffic. Please try again later.",endConversation:!0,type:"toast"});E.options.onError({message:"We are experiencing heavy traffic and we can't deliver the response, try again",endConversation:!1,type:"toast"})}else if("deadline_exceeded"===t)E.options.onError({message:"We are experiencing heavy traffic and we can't deliver the response, try again",endConversation:!1,type:"toast"});else if("inactivity_timeout"===t)return void E.options.onTimeout()}else E.options.onError({message:"A connection error occurred. Please try again.",endConversation:!0,type:"toast"})},this.handleStreamingEvent=function(e){try{var t,n=function(n){if(t)return n;if("metadata"===e.type&&("start"!==e.metadata_type&&"end"!==e.metadata_type||(l.avController.isStoppingAV=!1,l.videoOutput.toggleStream("start"===e.metadata_type),"start"===e.metadata_type&&(l.videoFrameQueue=[],l.syncController.resetTiming()))),"audio_frame"===e.type){if(l.avController.isStoppingAV)return;l.handleAudioFrame(e)}if("video_frame"===e.type){if(l.avController.isStoppingAV)return;l.handleVideoFrame(e)}l.avController.playAudioVideo()};if("error"===e.type)return l.handleStreamError(e),Promise.resolve();var i=function(){if("cache"===e.type){var n,i,r=function(){t=1},s={id:e.session_id||Math.random().toString(36).substring(2),timestamp:new Date,isSent:!0,visible:!0,event:exports.EventType.TEXT,user_id:e.user_id,username:e.username,text:null!=(n=e.text)?n:"",speaker:"ai",session_id:e.session_id||"",suggestions:null!=(i=e.suggestions)?i:[]},o=function(){if(l.sessionStarted)return Promise.resolve(l.videoOutput.playCachedVideo(e.video_url||"")).then(function(){l.handleMessage(s)});l.cachedResponseQueue.push({video_url:e.video_url||"",textEventData:s})}();return o&&o.then?o.then(r):r()}}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(e){return Promise.reject(e)}},this.handleVideoFrame=function(e){try{var t;return e.frame_data||u.videoFrameQueue.push({timeStamp:e.event_timestamp_ms,isKeyframe:null!=(t=e.is_keyframe)&&t}),Promise.resolve()}catch(e){return Promise.reject(e)}},this.handleBinaryData=function(e){try{if(p.videoFrameQueue.length>0){var t=p.videoFrameQueue.shift();p.updateStatus("connected"),p.videoOutput.addFrame(e.data,t.timeStamp,t.isKeyframe),p.syncController.updateVideoTime(t.timeStamp)}return Promise.resolve()}catch(e){return Promise.reject(e)}},this.handleAudioFrame=function(e){try{if(!e.frame_data)return console.warn("Audio frame data is missing in the event:",e),Promise.resolve();var t,n=function(e){for(var t=window.atob(e),n=t.length,i=new Uint8Array(n),r=0;r<n;r++)i[r]=t.charCodeAt(r);return i.buffer}(e.frame_data);return t=new Int16Array(n),v.audioOutput.gain.gain.value=v.volume,v.audioOutput.worklet.port.postMessage({type:"clearInterrupted"}),v.audioOutput.worklet.port.postMessage({type:"buffer",buffer:t,time_stamp:e.event_timestamp_ms}),v.syncController.updateAudioTime(e.event_timestamp_ms),Promise.resolve()}catch(e){return Promise.reject(e)}},this.onMessage=function(e){try{switch(e.event){case exports.EventType.JOIN:return Promise.resolve();case exports.EventType.TEXT:if(m(e)){var t=e;t.timestamp=new Date,t.isSent=!0,t.visible=!0,b.handleMessage(t)}return Promise.resolve();case exports.EventType.RESPONSE:if(g(e)){var n=e;n.timestamp=new Date,n.speaker="ai",n.isSent=!0,b.handleMessage(n)}return Promise.resolve();case exports.EventType.STREAMING:return f(e)&&b.handleStreamingEvent(e),Promise.resolve();case exports.EventType.BINARY:y(e)&&b.handleBinaryData(e);case exports.EventType.TIMEOUT_WARNING:return k(e)&&b.options.onTimeoutWarning(),Promise.resolve();case exports.EventType.TIME_OUT:return T(e)&&b.options.onTimeout(),Promise.resolve();case exports.EventType.KEEP_SESSION:return S(e)&&b.options.onKeepSession({granted:e.granted}),Promise.resolve();default:return console.warn("Unhandled event type:",e.event),Promise.resolve()}}catch(e){return Promise.reject(e)}},this.handleStopVideoEvents=function(){E.options.onSpeakingEnd(),E.suggestionsQueue.length>0&&(E.options.onSuggestions({suggestions:E.suggestionsQueue}),E.suggestionsQueue=[])},this.endSessionWithDetails=function(e){try{return"connected"!==C.status&&"connecting"!==C.status?Promise.resolve():(C.sessionStarted=!1,C.updateStatus("disconnecting"),Promise.resolve(C.handleEndSession()).then(function(){var t;C.updateStatus("disconnected"),null==(t=C.monitor)||t.stop(),C.options.onDisconnect(e)}))}catch(e){return Promise.reject(e)}},this.options=e,this.microphoneAccess=t,this.connection=n,this.idleVideo=i,this.wakeLock=r,this.user=s,this.audioOutput=o,this.videoOutput=a,this.headInfo=c,this.syncController=new Dc(Gc),this.avController=new h(this.syncController,this.audioOutput,this.videoOutput),this.options.onConnect({userId:n.userId,headInfo:{name:this.headInfo.name,phrases:this.headInfo.phrases,language:this.headInfo.language,avatar:this.headInfo.avatarSrc},microphoneAccess:t}),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onMessage(this.onMessage),this.videoOutput.onSpeakingStart(this.options.onSpeakingStart),this.videoOutput.onSpeakingEnd(this.handleStopVideoEvents),this.updateStatus("connected"),this.audioOutput.worklet.port.onmessage=this.onOutputWorkletMessage,this.handleIOSSilentMode(),this.startLatencyMonitoring()}e.getFullOptions=function(e){return n({username:"anonymous",environment:"production",mode:"default",apiKey:"",microphoneProvider:"azure",microphoneOptions:{onMicrophoneError:function(){},onMicrophoneStatusChange:function(){},onMicrophoneSpeechRecognitionResult:function(){}},elevenLabsOptions:Hc,onStatusChange:function(){},onConnect:function(){},onDisconnect:function(){},onMessage:function(){},onMuteStatusChange:function(){},onSuggestions:function(){},onSpeakingStart:function(){},onSpeakingEnd:function(){},onStoppingEnd:function(){},onTimeout:function(){},onTimeoutWarning:function(){},onKeepSession:function(){},onError:function(){}},e)},e.startDigitalHuman=function(t){try{var n=function(){var n=C(s);return zc(function(){return Promise.resolve(Fc.loginUser(r,"Password1",n,o,a)).then(function(r){return f=r,Promise.resolve(P.getIdleVideo(n,o,a)).then(function(r){return Promise.resolve(f.getHeadDetails(d)).then(function(l){return Promise.resolve(r.getAvatarSrc(n,o,a)).then(function(n){l.avatarSrc=n;var g=h||l.language||navigator.language;return l.language=g,Promise.resolve(w.create({environment:s,orgId:o,headId:a,token:f.accessToken,mode:c,apiKey:d,language:g})).then(function(n){function s(){return Promise.resolve(Promise.all([u.createAudioOutput(k),Wc.createVideoOutput(o,{width:o.getBoundingClientRect().width,height:o.getBoundingClientRect().height,frameRate:30,backgroundColor:"transparent",format:"jpeg",idleVideo:{src:r.idleVideoSource,enabled:!0},transition:null!=p?p:exports.VideoTransitionType.NONE})])).then(function(t){return new e(i,a,v,r,T,f,b=t[0],y=t[1],l)})}v=n;var o=t.element,a=!1,c=function(){if("custom"!==m){var e=zc(function(){return Promise.resolve(navigator.mediaDevices.getUserMedia({audio:!0})).then(function(e){e.getTracks().forEach(function(e){e.stop()}),a=!0})},function(){a=!1});if(e&&e.then)return e.then(function(){})}else a=!0}();return c&&c.then?c.then(s):s()})})})})})},function(e){var t,n;return g({status:"disconnected"}),null==(t=v)||t.close(),Promise.resolve(null==(n=b)?void 0:n.close()).then(function(){var t;return Promise.resolve(null==(t=y)?void 0:t.destroy()).then(function(){function t(){throw e}var n=zc(function(){var e;return Promise.resolve(null==(e=T)?void 0:e.release()).then(function(){T=null})},function(){});return n&&n.then?n.then(t):t()})})})},i=e.getFullOptions(t),r=i.username,s=i.environment,o=i.orgId,a=i.headId,c=i.mode,d=i.apiKey,l=i.allowWakeLock,h=i.language,p=i.fadeTransitionsType,m=i.microphoneProvider,g=i.onStatusChange;g({status:"connecting"});var f=null,v=null,y=null,b=null,k={sampleRate:16e3,format:"pcm"},T=null,S=function(){if(null==l||l){var e=zc(function(){return Promise.resolve(navigator.wakeLock.request("screen")).then(function(e){T=e})},function(){});if(e&&e.then)return e.then(function(){})}}();return Promise.resolve(S&&S.then?S.then(n):n())}catch(e){return Promise.reject(e)}},e.getBackgroundVideo=function(e){try{var t=e.environment,n=e.orgId,i=e.headId,r=C(null!=t?t:"production");return Promise.resolve(P.getIdleVideo(null!=r?r:"https://chat-origin.api.unith.live",n,i)).then(function(e){return e.idleVideoSource})}catch(e){return Promise.reject(e)}};var t=e.prototype;return t.startLatencyMonitoring=function(){this.monitor=new _c(this.connection,{onUpdate:function(e){}})},t.handleIOSSilentMode=function(){var e=this;/iPad|iPhone|iPod/.test(navigator.userAgent)&&this.audioOutput.context.addEventListener("statechange",function(){"suspended"===e.audioOutput.context.state&&(console.warn("Audio context suspended - likely due to iOS silent mode"),e.audioOutput.context.resume())})},t.getUserId=function(){return this.connection.userId},t.handleEndSession=function(){try{return this.connection.close(),Promise.resolve()}catch(e){return Promise.reject(e)}},t.updateStatus=function(e){e!==this.status&&(this.status=e,this.options.onStatusChange({status:e}))},t.toggleMute=function(){try{var e=this;return e.volume=0===e.volume?1:0,e.audioOutput.toggleMute(),e.videoOutput.toggleCacheVideoMute(),e.options.onMuteStatusChange({isMuted:0===e.volume}),Promise.resolve(e.volume)}catch(e){return Promise.reject(e)}},t.startSession=function(){try{var e=function(){return Promise.resolve(t.avController.startPlayback(!0)).then(function(){function e(){function e(){return t.connection}var n=function(){var e;if("custom"!==t.options.microphoneProvider)return Promise.resolve(Oc.initializeMicrophone(t.options.microphoneOptions,t.options.microphoneProvider,null!=(e=t.options.elevenLabsOptions)?e:Hc,t.user,t.headInfo,t.microphoneAccess,t.sendMessage)).then(function(e){t.microphone=e})}();return n&&n.then?n.then(e):e()}var n=function(){if(t.cachedResponseQueue.length){var e=t.cachedResponseQueue[t.cachedResponseQueue.length-1];return Promise.resolve(new Promise(function(e){return setTimeout(e,50)})).then(function(){return Promise.resolve(t.videoOutput.playCachedVideo(e.video_url)).then(function(){t.handleMessage(e.textEventData)})})}}();return n&&n.then?n.then(e):e()})},t=this;t.sessionStarted=!0;var n=function(){if("suspended"===t.audioOutput.context.state)return Promise.resolve(t.audioOutput.context.resume()).then(function(){})}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},t.toggleMicrophone=function(){try{var e=function(){if(!t.microphoneAccess&&"OFF"===t.microphone.status())throw new Error("Microphone access not granted.");return Promise.resolve(t.microphone.toggleMicrophone()).then(function(){})},t=this;if("custom"===t.options.microphoneProvider)throw new Error("Cannot toggle microphone for custom provider.");var n=function(){var e;if(!t.microphone)return Promise.resolve(Oc.initializeMicrophone(t.options.microphoneOptions,t.options.microphoneProvider,null!=(e=t.options.elevenLabsOptions)?e:Hc,t.user,t.headInfo,t.microphoneAccess,t.sendMessage)).then(function(e){t.microphone=e})}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(e){return Promise.reject(e)}},t.getMicrophoneStatus=function(){return this.microphone?this.microphone.status():"OFF"},t.endSession=function(){return this.endSessionWithDetails({reason:"user"})},t.sendMessage=function(e){if(!this.connection)throw new Error("Connection not established");var t=this.user.id+"::"+this.user.orgId+"::"+this.user.headId+"::"+this.user.sessionId.toString().padStart(5,"0"),n={id:this.messageCounter++,timestamp:(new Date).toISOString(),speaker:"user",text:e,isSent:!1,user_id:this.user.id,username:this.user.username,event:exports.EventType.TEXT,visible:!0,session_id:t};return this.connection.sendMessage(n)},t.keepSession=function(){if(!this.connection)throw new Error("Connection not established");var e=this.user.id+"::"+this.user.orgId+"::"+this.user.headId+"::"+this.user.sessionId.toString().padStart(5,"0"),t={id:this.messageCounter,timestamp:(new Date).toISOString(),speaker:"user",text:"",isSent:!1,user_id:this.user.id,username:this.user.username,event:exports.EventType.KEEP_SESSION,visible:!0,session_id:e};return this.connection.sendMessage(t)},e}();exports.Conversation=Kc,exports.isBinaryEvent=y,exports.isConversationEndEvent=function(e){return e.event===exports.EventType.CONVERSATION_END},exports.isJoinEvent=p,exports.isKeepSessionEvent=S,exports.isPongEvent=b,exports.isResponseEvent=g,exports.isStreamingErrorEvent=v,exports.isStreamingEvent=f,exports.isTextEvent=m,exports.isTimeoutEvent=T,exports.isTimeoutWarningEvent=k;
|
|
2
2
|
//# sourceMappingURL=lib.js.map
|