livekit-client 2.22.4 → 2.23.0
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/livekit-client.e2ee.worker.js +1 -1
- package/dist/livekit-client.e2ee.worker.js.map +1 -1
- package/dist/livekit-client.e2ee.worker.mjs +69 -7
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
- package/dist/livekit-client.esm.mjs +1133 -289
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.fm.worker.js.map +1 -1
- package/dist/livekit-client.fm.worker.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/api/SignalClient.d.ts.map +1 -1
- package/dist/src/api/WebSocketStream.d.ts +1 -0
- package/dist/src/api/WebSocketStream.d.ts.map +1 -1
- package/dist/src/api/utils.d.ts +1 -1
- package/dist/src/api/utils.d.ts.map +1 -1
- package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
- package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
- package/dist/src/e2ee/worker/naluUtils.d.ts +12 -1
- package/dist/src/e2ee/worker/naluUtils.d.ts.map +1 -1
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/room/DefaultReconnectPolicy.d.ts.map +1 -1
- package/dist/src/room/PCTransport.d.ts +26 -4
- package/dist/src/room/PCTransport.d.ts.map +1 -1
- package/dist/src/room/RTCEngine.d.ts +8 -0
- package/dist/src/room/RTCEngine.d.ts.map +1 -1
- package/dist/src/room/Room.d.ts +53 -0
- package/dist/src/room/Room.d.ts.map +1 -1
- package/dist/src/room/data-channel/DataChannelManager.d.ts +9 -8
- package/dist/src/room/data-channel/DataChannelManager.d.ts.map +1 -1
- package/dist/src/room/data-channel/FlowControlledDataChannel.d.ts +25 -12
- package/dist/src/room/data-channel/FlowControlledDataChannel.d.ts.map +1 -1
- package/dist/src/room/data-channel/LossyDataChannel.d.ts.map +1 -1
- package/dist/src/room/data-channel/ReliableDataChannel.d.ts.map +1 -1
- package/dist/src/room/data-stream/incoming/IncomingDataStreamManager.d.ts.map +1 -1
- package/dist/src/room/participant/LocalParticipant.d.ts +4 -0
- package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
- package/dist/src/room/participant/Participant.d.ts +1 -1
- package/dist/src/room/participant/Participant.d.ts.map +1 -1
- package/dist/src/room/rpc/utils.d.ts.map +1 -1
- package/dist/src/room/track/LocalAudioTrack.d.ts +24 -1
- package/dist/src/room/track/LocalAudioTrack.d.ts.map +1 -1
- package/dist/src/room/track/LocalTrack.d.ts +18 -0
- package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
- package/dist/src/room/track/LocalVideoTrack.d.ts +7 -0
- package/dist/src/room/track/LocalVideoTrack.d.ts.map +1 -1
- package/dist/src/room/track/RemoteAudioTrack.d.ts +6 -0
- package/dist/src/room/track/RemoteAudioTrack.d.ts.map +1 -1
- package/dist/src/room/track/processor/types.d.ts +11 -0
- package/dist/src/room/track/processor/types.d.ts.map +1 -1
- package/dist/src/room/track/utils.d.ts.map +1 -1
- package/dist/src/room/utils.d.ts +28 -1
- package/dist/src/room/utils.d.ts.map +1 -1
- package/dist/ts4.2/api/WebSocketStream.d.ts +1 -0
- package/dist/ts4.2/api/utils.d.ts +1 -1
- package/dist/ts4.2/e2ee/worker/naluUtils.d.ts +12 -1
- package/dist/ts4.2/index.d.ts +2 -2
- package/dist/ts4.2/room/PCTransport.d.ts +26 -4
- package/dist/ts4.2/room/RTCEngine.d.ts +8 -0
- package/dist/ts4.2/room/Room.d.ts +53 -0
- package/dist/ts4.2/room/data-channel/DataChannelManager.d.ts +9 -8
- package/dist/ts4.2/room/data-channel/FlowControlledDataChannel.d.ts +25 -12
- package/dist/ts4.2/room/participant/LocalParticipant.d.ts +4 -0
- package/dist/ts4.2/room/participant/Participant.d.ts +1 -1
- package/dist/ts4.2/room/track/LocalAudioTrack.d.ts +24 -1
- package/dist/ts4.2/room/track/LocalTrack.d.ts +18 -0
- package/dist/ts4.2/room/track/LocalVideoTrack.d.ts +7 -0
- package/dist/ts4.2/room/track/RemoteAudioTrack.d.ts +6 -0
- package/dist/ts4.2/room/track/processor/types.d.ts +11 -0
- package/dist/ts4.2/room/utils.d.ts +28 -1
- package/package.json +1 -1
- package/src/api/SignalClient.test.ts +234 -0
- package/src/api/SignalClient.ts +58 -23
- package/src/api/WebSocketStream.test.ts +11 -0
- package/src/api/WebSocketStream.ts +22 -1
- package/src/api/utils.ts +1 -1
- package/src/e2ee/E2eeManager.test.ts +43 -0
- package/src/e2ee/E2eeManager.ts +6 -2
- package/src/e2ee/worker/FrameCryptor.test.ts +212 -90
- package/src/e2ee/worker/FrameCryptor.ts +21 -4
- package/src/e2ee/worker/naluUtils.test.ts +123 -0
- package/src/e2ee/worker/naluUtils.ts +57 -2
- package/src/index.ts +2 -0
- package/src/room/DefaultReconnectPolicy.test.ts +58 -0
- package/src/room/DefaultReconnectPolicy.ts +14 -2
- package/src/room/PCTransport.test.ts +144 -2
- package/src/room/PCTransport.ts +151 -9
- package/src/room/RTCEngine.test.ts +234 -2
- package/src/room/RTCEngine.ts +102 -7
- package/src/room/Room.test.ts +116 -0
- package/src/room/Room.ts +286 -74
- package/src/room/data-channel/DataChannelManager.test.ts +24 -7
- package/src/room/data-channel/DataChannelManager.ts +43 -38
- package/src/room/data-channel/FlowControlledDataChannel.test.ts +60 -18
- package/src/room/data-channel/FlowControlledDataChannel.ts +40 -22
- package/src/room/data-channel/LossyDataChannel.test.ts +38 -0
- package/src/room/data-channel/LossyDataChannel.ts +10 -1
- package/src/room/data-channel/ReliableDataChannel.test.ts +72 -0
- package/src/room/data-channel/ReliableDataChannel.ts +16 -5
- package/src/room/data-stream/incoming/IncomingDataStreamManager.test.ts +31 -0
- package/src/room/data-stream/incoming/IncomingDataStreamManager.ts +11 -0
- package/src/room/participant/LocalParticipant.test.ts +136 -1
- package/src/room/participant/LocalParticipant.ts +66 -17
- package/src/room/participant/Participant.ts +6 -3
- package/src/room/participant/restartOnDefaultAudioDevice.test.ts +177 -0
- package/src/room/rpc/utils.test.ts +32 -0
- package/src/room/rpc/utils.ts +7 -0
- package/src/room/track/LocalAudioTrack.ts +101 -10
- package/src/room/track/LocalTrack.ts +70 -13
- package/src/room/track/LocalVideoTrack.ts +7 -0
- package/src/room/track/RemoteAudioTrack.ts +56 -11
- package/src/room/track/processor/types.ts +11 -0
- package/src/room/track/utils.test.ts +5 -0
- package/src/room/track/utils.ts +29 -5
- package/src/room/utils.test.ts +126 -0
- package/src/room/utils.ts +84 -21
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,a,o,s,c=(t||(t=1,i=n.exports,a=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},a=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 s(){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(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,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 u(r,i,a){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?o(console,r):void 0!==console.log?o(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var o,s,d,l=this,h="loglevel";function f(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(h),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.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),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:o},l.setLevel=function(e,n){return d=p(e),!1!==n&&function(e){var n=(r[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(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.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(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(o=p(a.getLevel())),c.call(l),a===l)for(var e in i)i[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(d=p(y)),c.call(l)}(a=new l).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=i[e];return t||(t=i[e]=new l(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return i},a.default=a,a},(r=n).exports?r.exports=a():i.log=a()),n.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"}(o||(o={})),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",e.DataTracks="livekit-data-tracks",e.Region="livekit-region",e.ICE="livekit-ice",e.Stats="livekit-stats"}(s||(s={}));let d=c.getLogger(s.Default);function u(e,t){const n=c.getLogger(e);return n.setDefaultLevel(d.getLevel()),t?function(e,t){const n=n=>(r,i)=>{const a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n("trace"),r.debug=n("debug"),r.info=n("info"),r.warn=n("warn"),r.error=n("error"),r}(n,t):n}Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(o.info);const l=c.getLogger(s.E2EE),h=new Set,f=l.setLevel.bind(l);l.setLevel=(e,t)=>{f(e,t);const n=l.getLevel();h.forEach((e=>e(n)))};var p,y=Object.defineProperty,m=(e,t,n)=>((e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class g{constructor(){m(this,"_locking"),m(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(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(p||(p={}));const v="AES-GCM",b={key:10,delta:3,audio:1,empty:0},k={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function w(e,t){if(!e)throw new Error(t)}function T(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 I(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 S(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 E=Symbol("@bufbuild/protobuf/enum-type");function N(e){const t=e[E];return w(t,"missing enum type on enum object"),t}function C(e,t,n,r){e[E]=A(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function A(e,t,n){const r=Object.create(null),i=Object.create(null),a=[];for(const e of t){const t=U(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName:e=>r[e],findNumber:e=>i[e]}}function L(e,t,n){const r={};for(const e of t){const t=U(e);r[t.localName]=t.no,r[t.no]=t.localName}return C(r,e,t),r}function U(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class R{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,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,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),r=n.writerFactory();return t.writeMessage(this,r,n),r.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 O(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(127&r)<<n,!(128&r))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 r=this.buf[this.pos++];if(t|=(127&r)<<n,!(128&r))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function F(e,t,n){for(let r=0;r<28;r+=7){const i=e>>>r,a=!(i>>>7==0&&0==t),o=255&(a?128|i:i);if(n.push(o),!a)return}const r=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),a=255&(i?128|r:r);if(n.push(a),!i)return}n.push(t>>>31&1)}}const D=4294967296;function P(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let r=0,i=0;function a(t,a){const o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=D&&(i+=r/D|0,r%=D)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?M(r,i):x(r,i)}function _(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(D*t+e);const r=16777215&(e>>>24|t<<8),i=t>>16&65535;let a=(16777215&e)+6777216*r+6710656*i,o=r+8147497*i,s=2*i;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+B(o)+B(a)}function x(e,t){return{lo:0|e,hi:0|t}}function M(e,t){return t=~t,e?e=1+~e:t+=1,x(e,t)}const B=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 K(){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 V=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"),r=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const r="bigint"==typeof e?e:BigInt(e);if(r>n||r<t)throw new Error("int64 invalid: ".concat(e));return r},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<r)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=>w(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>w(/^[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),P(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),P(e)),dec:(e,t)=>function(e,t){let n=x(e,t);const r=2147483648&n.hi;r&&(n=M(n.lo,n.hi));const i=_(n.lo,n.hi);return r?"-"+i:i}(e,t),uDec:(e,t)=>_(e,t)}}();var q,W,G;function J(e,t,n){if(t===n)return!0;if(e==q.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 q.UINT64:case q.FIXED64:case q.INT64:case q.SFIXED64:case q.SINT64:return t==n}return!1}function X(e,t){switch(e){case q.BOOL:return!1;case q.UINT64:case q.FIXED64:case q.INT64:case q.SFIXED64:case q.SINT64:return 0==t?V.zero:"0";case q.DOUBLE:case q.FLOAT:return 0;case q.BYTES:return new Uint8Array(0);case q.STRING:return"";default:return 0}}function H(e,t){switch(e){case q.BOOL:return!1===t;case q.STRING:return""===t;case q.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function z(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,o,s=[],c=!0,d=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){d=!0,i=e}finally{try{if(!c&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(d)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return z(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?z(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!function(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"}(q||(q={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(W||(W={})),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"}(G||(G={}));class Q{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(I(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return T(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){S(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){I(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){T(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return T(e),j(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=V.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=V.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=V.enc(e);return F(t.lo,t.hi,this.buf),this}sint64(e){let t=V.enc(e),n=t.hi>>31;return F(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=V.uEnc(e);return F(t.lo,t.hi,this.buf),this}}class ${constructor(e,t){this.varint64=O,this.uint32=K,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 G.Varint:for(;128&this.buf[this.pos++];);break;case G.Bit64:this.pos+=4;case G.Bit32:this.pos+=4;break;case G.LengthDelimited:let n=this.uint32();this.pos+=n;break;case G.StartGroup:for(;;){const e=Y(this.tag(),2),n=e[0],r=e[1];if(r===G.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(r,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return V.dec(...this.varint64())}uint64(){return V.uDec(...this.varint64())}sint64(){let e=Y(this.varint64(),2),t=e[0],n=e[1],r=-(1&t);return t=(t>>>1|(1&n)<<31)^r,n=n>>>1^r,V.dec(t,n)}bool(){let e=Y(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return V.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return V.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 Z(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 X(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 ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),te=[];for(let e=0;e<ee.length;e++)te[ee[e].charCodeAt(0)]=e;te["-".charCodeAt(0)]=ee.indexOf("+"),te["_".charCodeAt(0)]=ee.indexOf("/");const ne={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,r=new Uint8Array(t),i=0,a=0,o=0;for(let t=0;t<e.length;t++){if(n=te[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":a=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:o=n,a=1;break;case 1:r[i++]=o<<2|(48&n)>>4,o=n,a=2;break;case 2:r[i++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:r[i++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return r.subarray(0,i)},enc(e){let t,n="",r=0,i=0;for(let a=0;a<e.length;a++)switch(t=e[a],r){case 0:n+=ee[t>>2],i=(3&t)<<4,r=1;break;case 1:n+=ee[i|t>>4],i=(15&t)<<2,r=2;break;case 2:n+=ee[i|t>>6],n+=ee[63&t],r=0}return r&&(n+=ee[i],n+="=",1==r&&(n+="=")),n}};function re(e,t,n){oe(t,e);const r=t.runtime.bin.makeReadOptions(n),i=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),a=Y(Z(t),2),o=a[0],s=a[1];for(const e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function ie(e,t,n,r){oe(t,e);const i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(ae(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=a.writerFactory();let s=t.field;s.opt||s.repeated||"enum"!=s.kind&&"scalar"!=s.kind||(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);const c=i.readerFactory(o.finish());for(;c.pos<c.len;){const t=Y(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function ae(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 oe(e,t){w(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function se(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:!H(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ce(e,t){const n=e.localName,r=!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]=r?e.T.values[0].no:void 0;break;case"scalar":t[n]=r?X(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function de(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(R.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 ue(e,t){return de(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}q.DOUBLE,q.FLOAT,q.INT64,q.UINT64,q.INT32,q.UINT32,q.BOOL,q.STRING,q.BYTES;const le={ignoreUnknownFields:!1},he={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function fe(e){return e?Object.assign(Object.assign({},le),e):le}function pe(e){return e?Object.assign(Object.assign({},he),e):he}const ye=Symbol(),me=Symbol();function ge(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 ve(e,t,n,r,i){let a=n.localName;if(n.repeated){if(w("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,r));break;case"enum":const t=we(n.T,e,r.ignoreUnknownFields,!0);t!==me&&o.push(t);break;case"scalar":try{o.push(ke(n.T,e,n.L,!0))}catch(t){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(e));throw t instanceof Error&&t.message.length>0&&(r+=": ".concat(t.message)),new Error(r)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t)));const s=e[a];for(const e of Object.entries(t)){var o=Y(e,2);const a=o[0],c=o[1];if(null===c)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=be(n.K,a)}catch(e){let r="cannot decode map key for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}switch(n.V.kind){case"message":s[d]=n.V.T.fromJson(c,r);break;case"enum":const e=we(n.V.T,c,r.ignoreUnknownFields,!0);e!==me&&(s[d]=e);break;case"scalar":try{s[d]=ke(n.V.T,c,W.BIGINT,!0)}catch(e){let r="cannot decode map value for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];de(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=we(n.T,t,r.ignoreUnknownFields,!1);switch(c){case ye:ce(n,e);break;case me:break;default:e[a]=c}break;case"scalar":try{const r=ke(n.T,t,n.L,!1);if(r===ye)ce(n,e);else e[a]=r}catch(e){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}function be(e,t){if(e===q.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ke(e,t,W.BIGINT,!0).toString()}function ke(e,t,n,r){if(null===t)return r?X(e,n):ye;switch(e){case q.DOUBLE:case q.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 r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==q.FLOAT&&S(r),r;case q.INT32:case q.FIXED32:case q.SFIXED32:case q.SINT32:case q.UINT32:let i;if("number"==typeof t?i=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),void 0===i)break;return e==q.UINT32||e==q.FIXED32?I(i):T(i),i;case q.INT64:case q.SFIXED64:case q.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=V.parse(t);return n?a.toString():a;case q.FIXED64:case q.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=V.uParse(t);return n?o.toString():o;case q.BOOL:if("boolean"!=typeof t)break;return t;case q.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case q.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ne.dec(t)}throw new Error}function we(e,t,n,r){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:r?e.values[0].no:ye;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(void 0!==r)return r.no;if(n)return me}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(ge(t)))}function Te(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Ie(e,t,n){if("map"==e.kind){w("object"==typeof t&&null!=t);const o={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of s){var r=Y(t,2);const n=r[0],i=r[1];o[n.toString()]=Ee(e.V.T,i)}break;case"message":for(const e of s){var i=Y(e,2);const t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case"enum":const t=e.V.T;for(const e of s){var a=Y(e,2);const r=a[0],i=a[1];o[r.toString()]=Se(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){w(Array.isArray(t));const r=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)r.push(Ee(e.T,t[n]));break;case"enum":for(let i=0;i<t.length;i++)r.push(Se(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case"scalar":return Ee(e.T,t);case"enum":return Se(e.T,t,n.enumAsInteger);case"message":return ue(e.T,t).toJson(n)}}function Se(e,t,n){var r;if(w("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const i=e.findNumber(t);return null!==(r=null==i?void 0:i.name)&&void 0!==r?r:t}function Ee(e,t){switch(e){case q.INT32:case q.SFIXED32:case q.SINT32:case q.FIXED32:case q.UINT32:return w("number"==typeof t),t;case q.FLOAT:case q.DOUBLE:return w("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case q.STRING:return w("string"==typeof t),t;case q.BOOL:return w("boolean"==typeof t),t;case q.UINT64:case q.FIXED64:case q.INT64:case q.SFIXED64:case q.SINT64:return w("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case q.BYTES:return w(t instanceof Uint8Array),ne.enc(t)}}const Ne=Symbol("@bufbuild/protobuf/unknown-fields"),Ce={readUnknownFields:!0,readerFactory:e=>new $(e)},Ae={writeUnknownFields:!0,writerFactory:()=>new Q};function Le(e){return e?Object.assign(Object.assign({},Ce),e):Ce}function Ue(e){return e?Object.assign(Object.assign({},Ae),e):Ae}function Re(e,t,n,r,i){let a=n.repeated,o=n.localName;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 s="enum"==n.kind?q.INT32:n.T;let c=De;if("scalar"==n.kind&&n.L>0&&(c=Fe),a){let n=e[o];if(r==G.LengthDelimited&&s!=q.STRING&&s!=q.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case"message":const d=n.T;a?e[o].push(Oe(t,new d,i,n)):de(e[o])?Oe(t,e[o],i,n):(e[o]=Oe(t,new d,i,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let u=function(e,t,n){const r=t.uint32(),i=t.pos+r;let a,o;for(;t.pos<i;){switch(Y(t.tag(),1)[0]){case 1:a=De(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=De(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Oe(t,new e.V.T,n,void 0)}}}void 0===a&&(a=X(e.K,W.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=X(e.V.T,W.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[a,o]}(n,t,i),l=Y(u,2),h=l[0],f=l[1];e[o][h]=f}}function Oe(e,t,n,r){const i=t.getType().runtime.bin,a=null==r?void 0:r.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Fe(e,t){const n=De(e,t);return"bigint"==typeof n?n.toString():n}function De(e,t){switch(t){case q.STRING:return e.string();case q.BOOL:return e.bool();case q.DOUBLE:return e.double();case q.FLOAT:return e.float();case q.INT32:return e.int32();case q.INT64:return e.int64();case q.UINT64:return e.uint64();case q.FIXED64:return e.fixed64();case q.BYTES:return e.bytes();case q.FIXED32:return e.fixed32();case q.SFIXED32:return e.sfixed32();case q.SFIXED64:return e.sfixed64();case q.SINT64:return e.sint64();case q.UINT32:return e.uint32();case q.SINT32:return e.sint32()}}function Pe(e,t,n,r){w(void 0!==t);const i=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?q.INT32:e.T;if(i)if(w(Array.isArray(t)),e.packed)!function(e,t,n,r){if(!r.length)return;e.tag(n,G.LengthDelimited).fork();let i=Y(Be(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}(n,o,e.no,t);else for(const r of t)Me(n,o,e.no,r);else Me(n,o,e.no,t);break;case"message":if(i){w(Array.isArray(t));for(const i of t)xe(n,r,e,i)}else xe(n,r,e,t);break;case"map":w("object"==typeof t&&null!=t);for(const i of Object.entries(t)){var a=Y(i,2);_e(n,r,e,a[0],a[1])}}}function _e(e,t,n,r,i){e.tag(n.no,G.LengthDelimited),e.fork();let a=r;switch(n.K){case q.INT32:case q.FIXED32:case q.UINT32:case q.SFIXED32:case q.SINT32:a=Number.parseInt(r);break;case q.BOOL:w("true"==r||"false"==r),a="true"==r}switch(Me(e,n.K,1,a),n.V.kind){case"scalar":Me(e,n.V.T,2,i);break;case"enum":Me(e,q.INT32,2,i);break;case"message":w(void 0!==i),e.tag(2,G.LengthDelimited).bytes(i.toBinary(t))}e.join()}function xe(e,t,n,r){const i=ue(n.T,r);n.delimited?e.tag(n.no,G.StartGroup).raw(i.toBinary(t)).tag(n.no,G.EndGroup):e.tag(n.no,G.LengthDelimited).bytes(i.toBinary(t))}function Me(e,t,n,r){w(void 0!==r);let i=Y(Be(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function Be(e){let t=G.Varint;switch(e){case q.BYTES:case q.STRING:t=G.LengthDelimited;break;case q.DOUBLE:case q.FIXED64:case q.SFIXED64:t=G.Bit64;break;case q.FIXED32:case q.SFIXED32:case q.FLOAT:t=G.Bit32}return[t,q[e].toLowerCase()]}function je(e){if(void 0===e)return e;if(de(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ke(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Ve{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 qe(e,t){const n=Ge(e);return t?n:Ye(ze(n))}const We=Ge;function Ge(e){let t=!1;const n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){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(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join("")}const Je=new Set(["constructor","toString","toJSON","valueOf"]),Xe=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),He=e=>"".concat(e,"$"),ze=e=>Xe.has(e)?He(e):e,Ye=e=>Je.has(e)?He(e):e;class Qe{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=qe(e,!1)}addField(e){w(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 $e=(Ze=e=>new Ve(e,(e=>function(e){var t,n,r,i,a,o;const s=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=qe(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:We(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(r=d.L)&&void 0!==r?r:W.BIGINT),e.delimited=null!==(i=d.delimited)&&void 0!==i&&i,e.req=null!==(a=d.req)&&void 0!==a&&a,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=q.BYTES&&d.T!=q.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Qe(t)),e.oneof=c,c.addField(e)}s.push(e)}return s}(e))),et=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,r=e;if(t.repeated)r[n]=[];else switch(t.kind){case"oneof":r[n]={case:void 0};break;case"enum":r[n]=0;break;case"map":r[n]={};break;case"scalar":r[n]=X(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:fe,makeWriteOptions:pe,readMessage(e,t,n,r){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(ge(t)));r=null!=r?r:new e;const i=new Map,a=n.typeRegistry;for(const s of Object.entries(t)){var o=Y(s,2);const t=o[0],c=o[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=i.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));i.set(d.oneof,t)}ve(r,c,d,n,e)}else{let i=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;const e=Y(Z(o),2),t=e[0],a=e[1];ve(t,c,o.field,n,o),ie(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return r},writeMessage(e,t){const n=e.getType(),r={};let i;try{for(i of n.fields.byNumber()){if(!se(i,e)){if(i.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Te(i))continue}const n=Ie(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t);void 0!==n&&(r[t.useProtoFieldName?i.name:i.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const i of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,i.no);if(o&&ae(e,o)){const n=re(e,o,t),i=Ie(o.field,n,t);void 0!==i&&(r[o.field.jsonName]=i)}}}catch(e){const t=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),r=e instanceof Error?e.message:String(e);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>ke(e,t,null!=n?n:W.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||H(e,t)?Ee(e,t):void 0},debug:ge},bin:{makeReadOptions:Le,makeWriteOptions:Ue,listUnknownFields(e){var t;return null!==(t=e[Ne])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ne]},writeUnknownFields(e,t){const n=e[Ne];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){const i=e;Array.isArray(i[Ne])||(i[Ne]=[]),i[Ne].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){const a=e.getType(),o=i?t.len:t.pos+n;let s,c;for(;t.pos<o;){var d=Y(t.tag(),2);if(s=d[0],c=d[1],!0===i&&c==G.EndGroup)break;const n=a.fields.find(s);if(n)Re(e,t,n,c,r);else{const n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n)}}if(i&&(c!=G.EndGroup||s!==n))throw new Error("invalid end group tag")},readField:Re,writeMessage(e,t,n){const r=e.getType();for(const i of r.fields.byNumber())if(se(i,e))Pe(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n);else if(i.req)throw new Error("cannot encode field ".concat(r.typeName,".").concat(i.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){void 0!==t&&Pe(e,t,n,r)}},util:Object.assign(Object.assign({},{setEnumType:C,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,a=t,o=e;if(null!=o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let s=o[n].value;t&&"message"==t.kind&&!de(s,t.T)?s=new t.T(s):t&&"scalar"===t.kind&&t.T===q.BYTES&&(s=Ke(s)),a[n]={case:e,value:s};break;case"scalar":case"enum":let c=o[n];i.T===q.BYTES&&(c=i.repeated?c.map(Ke):Ke(c)),a[n]=c;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===q.BYTES)for(const e of Object.entries(o[n])){var r=Y(e,2);const t=r[0],i=r[1];a[n][t]=Ke(i)}else Object.assign(a[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case"message":const d=i.T;if(i.repeated)a[n]=o[n].map((e=>de(e,d)?e:new d(e)));else{const e=o[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?a[n]=Ke(e):a[n]=e:a[n]=de(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case"message":return r.every(((t,n)=>e.T.equals(t,i[n])));case"scalar":return r.every(((t,n)=>J(e.T,t,i[n])));case"enum":return r.every(((e,t)=>J(q.INT32,e,i[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=r,n=i;return e.T.fieldWrapper&&(void 0===t||de(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||de(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return J(q.INT32,r,i);case"scalar":return J(e.T,r,i);case"oneof":if(r.case!==i.case)return!1;const a=e.findField(r.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(r.value,i.value);case"enum":return J(q.INT32,r.value,i.value);case"scalar":return J(a.T,r.value,i.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(r[e],i[e])));case"enum":return o.every((e=>J(q.INT32,r[e],i[e])));case"scalar":const n=e.V.T;return o.every((e=>J(n,r[e],i[e])))}}})),clone(e){const t=e.getType(),n=new t,r=n;for(const n of t.fields.byMember()){const t=e[n.localName];let a;if(n.repeated)a=t.map(je);else if("map"==n.kind){a=r[n.localName];for(const e of Object.entries(t)){var i=Y(e,2);const t=i[0],n=i[1];a[t]=je(n)}}else a="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:je(t.value)}:{case:void 0}:je(t);r[n.localName]=a}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}),{newFieldList:Ze,initFields:et}),makeMessageType(e,t,n){return function(e,t,n,r){var i;const a=null!==(i=null==r?void 0:r.localName)&&void 0!==i?i:t.substring(t.lastIndexOf(".")+1),o={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(o.prototype,new R),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:L,makeEnumType:A,getEnumType:N,makeExtension(e,t,n){return function(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){const n="function"==typeof r?r():r;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}(this,e,t,n)}});var Ze,et;const tt=$e.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),nt=$e.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"}]),rt=$e.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);class it extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var at,ot,st,ct,dt,ut,lt,ht,ft,pt;!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",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(at||(at={})),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",e[e.HeaderTooLarge=9]="HeaderTooLarge",e[e.PayloadTooLarge=10]="PayloadTooLarge"}(ot||(ot={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(st||(st={})),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}}(st||(st={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(ct||(ct={}));class yt extends it{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ct.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(dt||(dt={})),function(e){e.KeyRatcheted="keyRatcheted"}(ut||(ut={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(lt||(lt={})),function(e){e.Error="cryptorError"}(ht||(ht={}));class mt extends(pt=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}ft=mt,mt.resolve=e=>Reflect.get(pt,"resolve",ft).call(ft,e);const gt=/version\/(\d+(\.?_?\d+)+)/i;let vt;function bt(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const n=navigator.userAgent.toLowerCase();if(void 0===vt||t){const e=kt.find((e=>e.test.test(n)));vt=null==e?void 0:e.describe(n)}return vt}const kt=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:wt(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Tt(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:wt(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Tt(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:wt(gt,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Tt(e)})}];function wt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const r=t.match(e);return r&&r.length>=n&&r[n]||""}function Tt(e){return e.includes("mac os")?wt(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var It,St={exports:{}};var Et,Nt,Ct,At,Lt=function(){if(It)return St.exports;It=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 r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}St.exports=i,St.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,a,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,a,c,d;if(o(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,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 u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]: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}(i):f(i,i.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 f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function p(e,t,n,r){if("function"==typeof e.on)r.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 i(a){r.once&&e.removeEventListener(t,i),n(a)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),i.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},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(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},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,a=this._events;if(void 0!==a)i=i&&void 0===a.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=f(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,a,s;if(o(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;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 i,a=Object.keys(n);for(r=0;r<a.length;++r)"removeListener"!==(i=a[r])&&this.removeAllListeners(i);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(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},St.exports}();function Ut(e){const t={};for(const r of Object.entries(e)){var n=Y(r,2);const e=n[0],i=n[1];void 0!==i&&(t[e]=i)}return t}function Rt(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function Ot(e){return Math.round(1e4*e)/1e4}function Ft(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?Ot(t/n):void 0}function Dt(e,t){if(void 0!==e.playoutDelay)return Ot(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,r=null==t?void 0:t.totalSamplesCount;return void 0!==n&&r?Ot(n/r):void 0}!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",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}(Et||(Et={})),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"}(Nt||(Nt={})),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",e.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported",e.RequestSubscribedCodecRefresh="requestSubscribedCodecRefresh"}(Ct||(Ct={})),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"}(At||(At={}));class Pt{constructor(e,t,n,r,i){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:r,priority:i}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const _t=["vp8","h264","vp9","av1","h265"];var xt,Mt;function Bt(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?Bt(e.track):{})}}!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(xt||(xt={})),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}}(Mt||(Mt={})),new Pt(160,90,9e4,20),new Pt(320,180,16e4,20),new Pt(384,216,18e4,20),new Pt(640,360,45e4,20),new Pt(960,540,8e5,25),new Pt(1280,720,17e5,30),new Pt(1920,1080,3e6,30),new Pt(2560,1440,5e6,30),new Pt(3840,2160,8e6,30),new Pt(160,120,7e4,20),new Pt(240,180,125e3,20),new Pt(320,240,14e4,20),new Pt(480,360,33e4,20),new Pt(640,480,5e5,20),new Pt(720,540,6e5,25),new Pt(960,720,13e5,30),new Pt(1440,1080,23e5,30),new Pt(1920,1440,38e5,30),new Pt(640,360,2e5,3,"medium"),new Pt(640,360,4e5,15,"medium"),new Pt(1280,720,8e5,5,"medium"),new Pt(1280,720,15e5,15,"medium"),new Pt(1280,720,2e6,30,"medium"),new Pt(1920,1080,25e5,15,"medium"),new Pt(1920,1080,5e6,30,"medium"),new Pt(0,0,7e6,30,"medium");const jt=[];var Kt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Kt||(Kt={}));class Vt extends Lt.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Vt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=d,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=u(null!==(r=n.loggerName)&&void 0!==r?r:s.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Vt.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Bt(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Vt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Vt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(jt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&jt.splice(jt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,r;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;r="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();r.includes(e)||(r.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));Wt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(Wt()||function(){var e;return"Firefox"===(null===(e=bt())||void 0===e?void 0:e.name)}())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(r?At.AudioPlaybackStarted:At.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(r?At.AudioPlaybackFailed:At.VideoPlaybackFailed,t):"AbortError"===t.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:t}),r&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(At.ElementAttached,e),e}detach(e){try{if(e){qt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(At.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{qt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(At.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",function(e){var t,n;const r=new Map,i=[],a=[],o=[];let s;e.forEach((e=>r.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=r.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?r.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");a.push(Ut({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:Rt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:Ft(e),playoutDelay:Dt(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");o.push(Ut({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:Rt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:Rt(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":s=e;break;case"candidate-pair":i.push(e)}}));const u=null==s?void 0:s.selectedCandidatePairId,l=null!==(n=null!==(t=u?r.get(u):void 0)&&void 0!==t?t:i.find((e=>e.selected)))&&void 0!==n?n:i.find((e=>e.nominated)),h=(null==l?void 0:l.localCandidateId)?r.get(l.localCandidateId):void 0,f=(null==l?void 0:l.remoteCandidateId)?r.get(l.remoteCandidateId):void 0,p=Ut({ice:null==s?void 0:s.iceState,dtls:null==s?void 0:s.dtlsState,route:h&&f?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(f.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==l?void 0:l.currentRoundTripTime,availableOutgoingBitrate:null==l?void 0:l.availableOutgoingBitrate,availableIncomingBitrate:null==l?void 0:l.availableIncomingBitrate,bytesSent:null==l?void 0:l.bytesSent,bytesReceived:null==l?void 0:l.bytesReceived,candidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges});return{connection:Object.keys(p).length>0?p:void 0,outbound:o.length>0?o:void 0,inbound:a.length>0?a:void 0}}(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=u(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),jt.forEach((e=>{e.parentElement||(t=!1)})),t&&jt.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Vt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Gt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Gt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function qt(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Wt(){var e;return"Safari"===(null===(e=bt())||void 0===e?void 0:e.name)}function Gt(){return"undefined"!=typeof document}function Jt(e,t){return e instanceof Error?e.name&&e.message?"".concat(e.name,": ").concat(e.message):e.name:"Encountered unknown ".concat(t," error: ").concat(String(e))}function Xt(e){return"type"in e}function Ht(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function zt(t,n){return e(this,void 0,void 0,(function*(){const e=Ht(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:v,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){let t,n,r;!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"}(r=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return tt.AUDIO;case t.Video:return tt.VIDEO;default:return tt.DATA}},e.kindFromProto=function(e){switch(e){case tt.AUDIO:return t.Audio;case tt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return nt.CAMERA;case n.Microphone:return nt.MICROPHONE;case n.ScreenShare:return nt.SCREEN_SHARE;case n.ScreenShareAudio:return nt.SCREEN_SHARE_AUDIO;default:return nt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case nt.CAMERA:return n.Camera;case nt.MICROPHONE:return n.Microphone;case nt.SCREEN_SHARE:return n.ScreenShare;case nt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case rt.ACTIVE:return r.Active;case rt.PAUSED:return r.Paused;default:return r.Unknown}}}(Vt||(Vt={}));class Yt{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-Yt.sendCount%65535),Yt.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=Yt.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:v,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const o=yield n.getKeySet(r);if(!o)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:v,iv:t},o.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(a.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let s,c;l.debug("DataCryptor: ratcheting key attempt ".concat(a.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:o)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),s=yield zt(c.cryptoKey,n.keyProviderOptions));const d=yield Yt.decrypt(e,t,n,r,i,{ratchetCount:a.ratchetCount+1,encryptionKey:null==s?void 0:s.encryptionKey});return d&&s&&(null!=i?i:o)===n.getKeySet(r)&&(n.setKeySet(s,r,c),n.setCurrentKeyIndex(r)),d}throw l.warn("DataCryptor: maximum ratchet attempts exceeded"),new yt("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),ct.InvalidKey,n.participantIdentity)}throw new yt("DataCryptor: Decryption failed: ".concat(Jt(s,"decryption")),ct.InvalidKey,n.participantIdentity)}}()}))}}Yt.sendCount=0;class Qt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6e4,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5;this.throttleMs=e,this.windowMs=t,this.maxPerWindow=n,this.lastAt=new Map,this.counts=new Map}reset(){this.lastAt.clear(),this.counts.clear()}countFor(e){var t;return null!==(t=this.counts.get(e))&&void 0!==t?t:0}shouldEmit(e,t){var n,r;const i=Date.now(),a=null!==(n=this.lastAt.get(e))&&void 0!==n?n:0,o=null!==(r=this.counts.get(e))&&void 0!==r?r:0;return i-a>this.windowMs?(this.counts.set(e,0),this.lastAt.set(e,i),!0):!(i-a<this.throttleMs)&&(o>=this.maxPerWindow?(o===this.maxPerWindow&&(null==t||t(),this.counts.set(e,o+1)),!1):(this.lastAt.set(e,i),this.counts.set(e,o+1),!0))}}function $t(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}const Zt=Uint8Array.from(["L".charCodeAt(0),"K".charCodeAt(0),"T".charCodeAt(0),"S".charCodeAt(0)]);function en(e,t,n){const r=t!==BigInt(0),i=0!==n;if(!r&&!i)return e;const a=(r?10:0)+(i?6:0)+5,o=new Uint8Array(e.length+a);let s=0;return o.set(e,s),s+=e.length,r&&(o[s++]=254,o[s++]=247,function(e,t,n){const r=Number(n>>BigInt(32)&BigInt(4294967295)),i=Number(n&BigInt(4294967295));e[t]=r>>>24^255,e[t+1]=r>>>16&255^255,e[t+2]=r>>>8&255^255,e[t+3]=255&r^255,e[t+4]=i>>>24^255,e[t+5]=i>>>16&255^255,e[t+6]=i>>>8&255^255,e[t+7]=255&i^255}(o,s,t),s+=8),i&&(o[s++]=253,o[s++]=251,function(e,t,n){for(let r=3;r>=0;r-=1)e[t+(3-r)]=n>>8*r&255^255}(o,s,n),s+=4),o[s++]=255^a,o.set(Zt,s),o}function tn(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<5)return{data:t};if(!function(e,t){for(let n=0;n<Zt.length;n+=1)if(e[t+n]!==Zt[n])return!1;return!0}(t,t.length-Zt.length))return{data:t};const n=255^t[t.length-5];if(n<5||n>t.length)return{data:t};const r=t.length-n,i=t.length-5,a=t.subarray(0,r);let o=r,s=!1;const c={userTimestamp:BigInt(0),frameId:0};for(;o+2<=i;){const e=255^t[o++],n=255^t[o++];if(o+n>i)break;if(1===e&&8===n)c.userTimestamp=nn(t,o),s=!0;else if(2===e&&4===n)c.frameId=rn(t,o,n),s=!0;else if(3===e){const e=new Uint8Array(n);for(let r=0;r<n;r+=1)e[r]=255^t[o+r];c.userData=e,s=!0}o+=n}return s?{data:a,metadata:c}:{data:t}}function nn(e,t){const n=BigInt(((255^e[t])<<24|(255^e[t+1])<<16|(255^e[t+2])<<8|255^e[t+3])>>>0),r=BigInt(((255^e[t+4])<<24|(255^e[t+5])<<16|(255^e[t+6])<<8|255^e[t+7])>>>0);return n<<BigInt(32)|r}function rn(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r<<8|255^e[t+i];return r>>>0}function an(e){try{const t=e.getMetadata();if("number"==typeof t.synchronizationSource)return t.synchronizationSource}catch(e){}return 0}var on,sn;function cn(e){return 31&e}function dn(e){return e>>1&63}function un(e){return e===on.SLICE_IDR||e===on.SLICE_NON_IDR}function ln(e){return e===sn.TRAIL_N||e===sn.TRAIL_R||e===sn.TSA_N||e===sn.TSA_R||e===sn.STSA_N||e===sn.STSA_R||e===sn.RADL_N||e===sn.RADL_R||e===sn.RASL_N||e===sn.RASL_R||e===sn.BLA_W_LP||e===sn.BLA_W_RADL||e===sn.BLA_N_LP||e===sn.IDR_W_RADL||e===sn.IDR_N_LP||e===sn.CRA_NUT}function hn(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let a=r;for(;a>n&&0===e[a-1];)a--;if(0===n){if(a!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let o=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(o=4),n=r+=o}return t}(e),r=null!=t?t:function(e,t){for(const n of t){if(un(cn(e[n])))return"h264";if(ln(dn(e[n])))return"h265"}return"unknown"}(e,n);if("unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(ln(dn(e[r])))return r+2}else if(un(cn(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(on||(on={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(sn||(sn={}));const fn="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",pn="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",yn="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",mn="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",gn="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function vn(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case fn:return"vp8";case pn:case yn:case mn:return"h264";case gn:return"opus";default:return null}}))}const bn=new Map;class kn extends Lt.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class wn extends kn{constructor(e){var t;super(),this.hasFrameMetadata=!1,this.frameMetadataFrameId=0,this.errorLimiter=new Qt,this.UNDECRYPTED_TRACK_GRACE_MS=2e3,this.loggedNALUFallbacks=new Set,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){l.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(l.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){l.debug("unsetting participant",this.logContext),clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,this.participantIdentity=void 0,this.errorLimiter.reset()}isEnabled(){return this.participantIdentity?bn.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setTrackId(e){this.trackId!==e&&(l.debug("re-pointing cryptor at new trackId",Object.assign(Object.assign({},this.logContext),{newTrackId:e})),this.trackId=e)}hasActiveTransform(){return!!this.currentTransform}scheduleUndecryptedTrackWatchdog(e){clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,"decode"===e&&(this.undecryptedTrackTimeout=setTimeout((()=>{!this.currentTransform&&this.isEnabled()&&(l.warn("encrypted track has no active decrypt transform",this.logContext),this.emitThrottledError(new yt("no active decrypt transform for encrypted track ".concat(this.trackId),ct.InternalError,this.participantIdentity)))}),this.UNDECRYPTED_TRACK_GRACE_MS))}ensureTransform(){if(this.currentTransform)return!0;if(!this.retainedStreams||void 0===this.trackId)return l.warn("no streams retained, cannot re-establish transform",this.logContext),!1;const e=this.retainedStreams,t=e.readable,n=e.writable,r=e.operation;return l.info("re-establishing transform",Object.assign(Object.assign({},this.logContext),{operation:r})),this.setupTransform(r,t,n,this.trackId)}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setHasFrameMetadata(e){this.hasFrameMetadata=e}setFrameMetadataOpts(e){this.frameMetadataOpts=e,this.frameMetadataFrameId=0}setupTransform(e,t,n,r,i,a){var o;i&&(l.info("setting codec on cryptor to",{codec:i}),this.videoCodec=i),"encode"===e&&this.setFrameMetadataOpts(a),l.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,this.retainedStreams={readable:t,writable:n,operation:e},clearTimeout(this.undecryptedTrackTimeout);const s=Symbol("transform"),c="encode"===e?this.encodeFunction:this.decodeFunction,d=new TransformStream({transform:c.bind(this)});this.currentTransform={readable:t,writable:n,transformer:d,trackId:r,symbol:s};try{t.pipeThrough(d).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?l.debug("destination stream closed"):(l.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(ht.Error,e instanceof yt?e:new yt(e.message,void 0,this.participantIdentity)))})).finally((()=>{var t;(null===(t=this.currentTransform)||void 0===t?void 0:t.symbol)===s&&(l.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0),this.scheduleUndecryptedTrackWatchdog(e)}))}catch(e){return(null===(o=this.currentTransform)||void 0===o?void 0:o.symbol)===s&&(this.currentTransform=void 0),l.error("failed to set up transform",Object.assign({error:e},this.logContext)),this.emit(ht.Error,e instanceof yt?e:new yt(e.message,ct.InternalError,this.participantIdentity)),!1}return!0}setSifTrailer(e){l.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}emitThrottledError(e){const t="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(!this.errorLimiter.shouldEmit(t,(()=>{l.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:t}))})))return;const n=this.errorLimiter.countFor(t);n>1&&l.debug("Decryption error (".concat(n," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:ct[e.reason]})),this.emit(ht.Error,e)}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(0===t.data.byteLength)return n.enqueue(t);if(!this.isEnabled())return this.appendFrameMetadata(t),n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new yt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),ct.MissingKey,this.participantIdentity));const i=r.encryptionKey,a=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,s.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=a;try{const e=yield crypto.subtle.encrypt({name:v,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,s.unencryptedBytes));let a=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);a.set(new Uint8Array(e)),a.set(new Uint8Array(r),e.byteLength),a.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(a=function(e){const t=[];for(var n=0,r=0;r<e.length;++r){var i=e[r];i<=3&&n>=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(a));var o=new Uint8Array(c.byteLength+a.byteLength);return o.set(c),o.set(a,c.byteLength),t.data=o.buffer,this.appendFrameMetadata(t),n.enqueue(t)}catch(e){l.error("error while encrypting",Object.assign(Object.assign({},this.logContext),{error:e}))}}else l.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new yt("encryption key missing for encoding",ct.MissingKey,this.participantIdentity))}))}appendFrameMetadata(e){var t;$t(this.frameMetadataOpts)&&Xt(e)&&((null===(t=this.frameMetadataOpts)||void 0===t?void 0:t.frameId)&&(this.frameMetadataFrameId=4294967295===this.frameMetadataFrameId?1:this.frameMetadataFrameId+1),function(e,t,n){if(!$t(t)||0===e.data.byteLength)return!1;const r=(null==t?void 0:t.timestamp)?BigInt(Date.now())*BigInt(1e3):BigInt(0),i=(null==t?void 0:t.frameId)?n:0,a=new Uint8Array(e.data),o=en(a,r,i);o.byteLength!==a.byteLength&&(e.data=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength))}(e,this.frameMetadataOpts,this.frameMetadataFrameId))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(this.hasFrameMetadata&&Xt(t))try{const e=function(e,t){if(0===e.data.byteLength)return{};const n=tn(e.data);if(!n.metadata)return{};const r=n.data.buffer.slice(n.data.byteOffset,n.data.byteOffset+n.data.byteLength),i=function(e){try{const t=e.getMetadata();if("number"==typeof t.rtpTimestamp)return t.rtpTimestamp;if("number"==typeof t.timestamp)return t.timestamp}catch(e){}if("number"==typeof e.timestamp)return e.timestamp}(e);return void 0!==i&&t?{data:r,payload:{trackId:t,rtpTimestamp:i,ssrc:an(e),metadata:n.metadata}}:{data:r}}(t,this.trackId);if(e.data&&(t.data=e.data),e.payload&&this.participantIdentity){const t={kind:"packetTrailerMetadata",data:e.payload};postMessage(t)}}catch(e){}if(0===t.data.byteLength)return n.enqueue(t);const e=this.isEnabled();if(void 0===e)return void 0===this.participantIdentity?void l.debug("dropping frame for unassigned cryptor",this.logContext):void this.emitThrottledError(new yt("encryption state unknown for track ".concat(this.trackId,", dropping frame"),ct.InternalError,this.participantIdentity));if(!e)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield vn(t.data))?(l.debug("enqueue SIF",this.logContext),n.enqueue(t)):void l.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const r=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(r))if(this.keys.getKeySet(r))try{const e=yield this.decryptFrame(t,r);if(this.keys.decryptionSuccess(r),e)return n.enqueue(e)}catch(e){e instanceof yt&&e.reason===ct.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(e),this.keys.decryptionFailure(r)):l.warn("decoding frame failed",{error:e})}else l.warn("skipping decryption due to missing key at index ".concat(r)),this.emitThrottledError(new yt("missing key at index ".concat(r," for participant ").concat(this.participantIdentity),ct.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(r)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!i.encryptionKey&&!o)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=function(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),h=yield crypto.subtle.decrypt({name:v,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=i.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,u,l)),f=new ArrayBuffer(t.byteLength+h.byteLength),p=new Uint8Array(f);return p.set(new Uint8Array(e.data,0,t.byteLength)),p.set(new Uint8Array(h),t.byteLength),e.data=f,e}catch(a){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let a,s;l.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:o)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),a=yield zt(s.cryptoKey,n.keyProviderOptions));const c=yield n.decryptFrame(e,t,r||o,{ratchetCount:i.ratchetCount+1,encryptionKey:null==a?void 0:a.encryptionKey});return c&&a&&(null!=r?r:o)===n.keys.getKeySet(t)&&(n.keys.setKeySet(a,t,s),n.keys.setCurrentKeyIndex(t)),c}throw l.warn("maximum ratchet attempts exceeded"),new yt("valid key missing for participant ".concat(n.participantIdentity),ct.InvalidKey,n.participantIdentity)}throw new yt("Decryption failed: ".concat(Jt(a,"decryption")),ct.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const a=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-a%65535),this.sendCounts.set(e,a+1),r}getUnencryptedBytes(e){var t;if(!Xt(e))return{unencryptedBytes:b.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(l.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:b[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};const r=e.getMetadata().payloadType,i="".concat(this.participantIdentity,"-").concat(this.trackId,"-").concat(r);try{const t="h264"===n||"h265"===n?n:void 0,r=hn(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return this.loggedNALUFallbacks.delete(i),{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(e){this.logNALUFallbackOnce(i,r,e)}return{unencryptedBytes:b[e.type],requiresNALUProcessing:!1}}logNALUFallbackOnce(e,t,n){this.loggedNALUFallbacks.has(e)||(this.loggedNALUFallbacks.add(e),l.warn("NALU processing failed, falling back to VP8 handling",Object.assign({error:n,payloadType:t},this.logContext)))}getVideoCodec(e){const t=e.getMetadata();if(t.mimeType){const e=t.mimeType.split("/")[1].toLowerCase();if(_t.includes(e))return e}if(0===this.rtpMap.size)return;const n=t.payloadType;return n?this.rtpMap.get(n):void 0}}class Tn extends Lt.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&l.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const a=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=i.material,o=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=Ht(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:v},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(o,a.algorithm.name,"derive"),c={chainKey:o,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,a),a}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const a=yield zt(e,n.keyProviderOptions),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;l.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(a,o,r),o>=0&&i&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(ut.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const In=[],Sn=new Map;let En,Nn,Cn=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new g,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:p.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=p.RUNNING,yield t()}finally{e.status=p.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},An=!1,Ln=k,Un=new Map;const Rn=new Qt;function On(e,t,n){let r=In.filter((e=>e.getTrackId()===t));if(0===r.length&&void 0!==n&&n!==t){const i=In.filter((e=>e.getTrackId()===n));i.length>0&&(l.info("reusing cryptor from previous trackId",{participantIdentity:e,trackId:t,previousTrackId:n}),i[0].setTrackId(t),r=i)}if(r.length>1){const n=r.map((e=>({participant:e.getParticipantIdentity()}))).join(",");l.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:n})}let i=r[0];if(i)e!==i.getParticipantIdentity()&&i.setParticipant(e,Fn(e));else{if(l.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!Ln)throw Error("Missing keyProvider options");i=new wn({participantIdentity:e,keys:Fn(e),keyProviderOptions:Ln,sifTrailer:Nn}),i.setRtpMap(Un),function(e){e.on(ht.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(ct[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(i),In.push(i)}return i}function Fn(e){if(An)return Dn();let t=Sn.get(e);return t||(t=new Tn(e,Ln),t.on(ut.KeyRatcheted,Pn),Sn.set(e,t)),t}function Dn(){return En||(l.debug("creating new shared key handler"),En=new Tn("shared-key",Ln)),En}function Pn(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}l.setDefaultLevel("info"),l.methodFactory=e=>(t,n)=>{postMessage({kind:"log",data:{level:e,msg:t,context:n}})},l.setLevel(l.getLevel()),onmessage=t=>{Cn.run((()=>e(void 0,void 0,void 0,(function*(){const n=t.data,r=n.kind,i=n.data;switch(r){case"init":l.setLevel(i.loglevel),l.info("e2ee worker initialized"),Ln=i.keyProviderOptions,An=!!i.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"setLogLevel":l.setLevel(i.level);break;case"enable":o=i.enabled,s=i.participantIdentity,l.debug("setting encryption enabled for all tracks of ".concat(s),{enable:o}),bn.set(s,o),l.info("updated e2ee enabled status for ".concat(i.participantIdentity," to ").concat(i.enabled)),postMessage(t.data);break;case"decode":let n=On(i.participantIdentity,i.trackId);n.setHasFrameMetadata(i.hasPacketTrailer),n.setupTransform(r,i.readableStream,i.writableStream,i.trackId,i.codec);break;case"encode":let c=On(i.participantIdentity,i.trackId);c.setHasFrameMetadata(i.hasPacketTrailer),c.setupTransform(r,i.readableStream,i.writableStream,i.trackId,i.codec,i.packetTrailer);break;case"encryptDataRequest":const d=yield Yt.encrypt(i.payload,Fn(i.participantIdentity)),u=d.payload,h=d.iv,f=d.keyIndex;postMessage({kind:"encryptDataResponse",data:{payload:u,iv:h,keyIndex:f,uuid:i.uuid}});break;case"decryptDataRequest":try{const e=(yield Yt.decrypt(i.payload,i.iv,Fn(i.participantIdentity),i.keyIndex)).payload;postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:i.uuid}})}catch(e){const t="".concat(i.participantIdentity,"-datadecrypt");Rn.shouldEmit(t,(()=>{l.warn("Suppressing further data decryption errors for ".concat(i.participantIdentity),{errorKey:t})}))&&l.error("DataCryptor decryption failed",{error:e,participantIdentity:i.participantIdentity,uuid:i.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:i.uuid}})}break;case"setKey":An?yield function(t,n,r){return e(this,void 0,void 0,(function*(){l.info("set shared key",{index:n}),yield Dn().setKey(t,n,r)}))}(i.key,i.keyIndex,i.updateCurrentKeyIndex):i.participantIdentity?(l.info("set participant sender key ".concat(i.participantIdentity," index ").concat(i.keyIndex)),yield Fn(i.participantIdentity).setKey(i.key,i.keyIndex,i.updateCurrentKeyIndex)):l.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=In.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&l.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():l.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(i.trackId,i.participantIdentity);break;case"updateCodec":const p=On(i.participantIdentity,i.trackId,i.previousTrackId);i.codec&&p.setVideoCodec(i.codec),p.setHasFrameMetadata(i.hasPacketTrailer),l.info("updated codec",{participantIdentity:i.participantIdentity,trackId:i.trackId,previousTrackId:i.previousTrackId,codec:i.codec,hasPacketTrailer:i.hasPacketTrailer}),void 0===i.previousTrackId||p.ensureTransform()||l.error("could not re-establish transform for reused receiver",{participantIdentity:i.participantIdentity,trackId:i.trackId,previousTrackId:i.previousTrackId});break;case"setRTPMap":Un=i.map,In.forEach((e=>{e.getParticipantIdentity()===i.participantIdentity&&e.setRtpMap(i.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(An){const e=Dn();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=Fn(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else l.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(i);break;case"setSifTrailer":a=i.trailer,Nn=a,In.forEach((e=>{e.setSifTrailer(a)}))}var a,o,s}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,r=n.options,i=r.kind,a=r.participantIdentity,o=r.trackId,s=r.codec,c=r.hasPacketTrailer;Cn.run((()=>e(void 0,void 0,void 0,(function*(){const e=On(a,o);e.setHasFrameMetadata(c),l.debug("onrtctransform setup",{participantIdentity:a,trackId:o,codec:s}),e.setupTransform(i,n.readable,n.writable,o,s,"encode"===i?r.packetTrailer:void 0)}))))})}));
|
|
1
|
+
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,a,o,s,c=(t||(t=1,i=n.exports,a=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},a=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 s(){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(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,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 u(r,i,a){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?o(console,r):void 0!==console.log?o(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var o,s,d,l=this,h="loglevel";function f(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(h),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function p(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.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),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:o},l.setLevel=function(e,n){return d=p(e),!1!==n&&function(e){var n=(r[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(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.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(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(a!==l&&(o=p(a.getLevel())),c.call(l),a===l)for(var e in i)i[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(d=p(y)),c.call(l)}(a=new l).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=i[e];return t||(t=i[e]=new l(e,a.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=h),a},a.getLoggers=function(){return i},a.default=a,a},(r=n).exports?r.exports=a():i.log=a()),n.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"}(o||(o={})),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",e.DataTracks="livekit-data-tracks",e.Region="livekit-region",e.ICE="livekit-ice",e.Stats="livekit-stats"}(s||(s={}));let d=c.getLogger(s.Default);function u(e,t){const n=c.getLogger(e);return n.setDefaultLevel(d.getLevel()),t?function(e,t){const n=n=>(r,i)=>{const a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n("trace"),r.debug=n("debug"),r.info=n("info"),r.warn=n("warn"),r.error=n("error"),r}(n,t):n}Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(o.info);const l=c.getLogger(s.E2EE),h=new Set,f=l.setLevel.bind(l);l.setLevel=(e,t)=>{f(e,t);const n=l.getLevel();h.forEach((e=>e(n)))};var p,y=Object.defineProperty,m=(e,t,n)=>((e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class g{constructor(){m(this,"_locking"),m(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(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(p||(p={}));const v="AES-GCM",b={key:10,delta:3,audio:1,empty:0},k={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16,keySize:128};function w(e,t){if(!e)throw new Error(t)}function T(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 I(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 S(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 E=Symbol("@bufbuild/protobuf/enum-type");function N(e){const t=e[E];return w(t,"missing enum type on enum object"),t}function C(e,t,n,r){e[E]=A(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function A(e,t,n){const r=Object.create(null),i=Object.create(null),a=[];for(const e of t){const t=U(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName:e=>r[e],findNumber:e=>i[e]}}function L(e,t,n){const r={};for(const e of t){const t=U(e);r[t.localName]=t.no,r[t.no]=t.localName}return C(r,e,t),r}function U(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class R{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,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,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),r=n.writerFactory();return t.writeMessage(this,r,n),r.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 O(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(127&r)<<n,!(128&r))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 r=this.buf[this.pos++];if(t|=(127&r)<<n,!(128&r))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function F(e,t,n){for(let r=0;r<28;r+=7){const i=e>>>r,a=!(i>>>7==0&&0==t),o=255&(a?128|i:i);if(n.push(o),!a)return}const r=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),a=255&(i?128|r:r);if(n.push(a),!i)return}n.push(t>>>31&1)}}const D=4294967296;function P(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let r=0,i=0;function a(t,a){const o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=D&&(i+=r/D|0,r%=D)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?M(r,i):x(r,i)}function _(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(D*t+e);const r=16777215&(e>>>24|t<<8),i=t>>16&65535;let a=(16777215&e)+6777216*r+6710656*i,o=r+8147497*i,s=2*i;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+B(o)+B(a)}function x(e,t){return{lo:0|e,hi:0|t}}function M(e,t){return t=~t,e?e=1+~e:t+=1,x(e,t)}const B=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 K(){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 V=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"),r=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const r="bigint"==typeof e?e:BigInt(e);if(r>n||r<t)throw new Error("int64 invalid: ".concat(e));return r},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<r)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=>w(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>w(/^[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),P(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),P(e)),dec:(e,t)=>function(e,t){let n=x(e,t);const r=2147483648&n.hi;r&&(n=M(n.lo,n.hi));const i=_(n.lo,n.hi);return r?"-"+i:i}(e,t),uDec:(e,t)=>_(e,t)}}();var q,W,G;function J(e,t,n){if(t===n)return!0;if(e==q.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 q.UINT64:case q.FIXED64:case q.INT64:case q.SFIXED64:case q.SINT64:return t==n}return!1}function X(e,t){switch(e){case q.BOOL:return!1;case q.UINT64:case q.FIXED64:case q.INT64:case q.SFIXED64:case q.SINT64:return 0==t?V.zero:"0";case q.DOUBLE:case q.FLOAT:return 0;case q.BYTES:return new Uint8Array(0);case q.STRING:return"";default:return 0}}function H(e,t){switch(e){case q.BOOL:return!1===t;case q.STRING:return""===t;case q.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}function z(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,o,s=[],c=!0,d=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){d=!0,i=e}finally{try{if(!c&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(d)throw i}}return s}}(e,t)||function(e,t){if(e){if("string"==typeof e)return z(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?z(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!function(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"}(q||(q={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(W||(W={})),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"}(G||(G={}));class Q{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(I(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return T(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){S(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){I(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){T(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return T(e),j(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=V.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=V.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=V.enc(e);return F(t.lo,t.hi,this.buf),this}sint64(e){let t=V.enc(e),n=t.hi>>31;return F(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=V.uEnc(e);return F(t.lo,t.hi,this.buf),this}}class ${constructor(e,t){this.varint64=O,this.uint32=K,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 G.Varint:for(;128&this.buf[this.pos++];);break;case G.Bit64:this.pos+=4;case G.Bit32:this.pos+=4;break;case G.LengthDelimited:let n=this.uint32();this.pos+=n;break;case G.StartGroup:for(;;){const e=Y(this.tag(),2),n=e[0],r=e[1];if(r===G.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(r,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return V.dec(...this.varint64())}uint64(){return V.uDec(...this.varint64())}sint64(){let e=Y(this.varint64(),2),t=e[0],n=e[1],r=-(1&t);return t=(t>>>1|(1&n)<<31)^r,n=n>>>1^r,V.dec(t,n)}bool(){let e=Y(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return V.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return V.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 Z(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 X(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 ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),te=[];for(let e=0;e<ee.length;e++)te[ee[e].charCodeAt(0)]=e;te["-".charCodeAt(0)]=ee.indexOf("+"),te["_".charCodeAt(0)]=ee.indexOf("/");const ne={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,r=new Uint8Array(t),i=0,a=0,o=0;for(let t=0;t<e.length;t++){if(n=te[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":a=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(a){case 0:o=n,a=1;break;case 1:r[i++]=o<<2|(48&n)>>4,o=n,a=2;break;case 2:r[i++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:r[i++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return r.subarray(0,i)},enc(e){let t,n="",r=0,i=0;for(let a=0;a<e.length;a++)switch(t=e[a],r){case 0:n+=ee[t>>2],i=(3&t)<<4,r=1;break;case 1:n+=ee[i|t>>4],i=(15&t)<<2,r=2;break;case 2:n+=ee[i|t>>6],n+=ee[63&t],r=0}return r&&(n+=ee[i],n+="=",1==r&&(n+="=")),n}};function re(e,t,n){oe(t,e);const r=t.runtime.bin.makeReadOptions(n),i=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),a=Y(Z(t),2),o=a[0],s=a[1];for(const e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function ie(e,t,n,r){oe(t,e);const i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(ae(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=a.writerFactory();let s=t.field;s.opt||s.repeated||"enum"!=s.kind&&"scalar"!=s.kind||(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);const c=i.readerFactory(o.finish());for(;c.pos<c.len;){const t=Y(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function ae(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 oe(e,t){w(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function se(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:!H(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ce(e,t){const n=e.localName,r=!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]=r?e.T.values[0].no:void 0;break;case"scalar":t[n]=r?X(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function de(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(R.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 ue(e,t){return de(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}q.DOUBLE,q.FLOAT,q.INT64,q.UINT64,q.INT32,q.UINT32,q.BOOL,q.STRING,q.BYTES;const le={ignoreUnknownFields:!1},he={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function fe(e){return e?Object.assign(Object.assign({},le),e):le}function pe(e){return e?Object.assign(Object.assign({},he),e):he}const ye=Symbol(),me=Symbol();function ge(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 ve(e,t,n,r,i){let a=n.localName;if(n.repeated){if(w("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,r));break;case"enum":const t=we(n.T,e,r.ignoreUnknownFields,!0);t!==me&&o.push(t);break;case"scalar":try{o.push(ke(n.T,e,n.L,!0))}catch(t){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(e));throw t instanceof Error&&t.message.length>0&&(r+=": ".concat(t.message)),new Error(r)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t)));const s=e[a];for(const e of Object.entries(t)){var o=Y(e,2);const a=o[0],c=o[1];if(null===c)throw new Error("cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: map value null"));let d;try{d=be(n.K,a)}catch(e){let r="cannot decode map key for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}switch(n.V.kind){case"message":s[d]=n.V.T.fromJson(c,r);break;case"enum":const e=we(n.V.T,c,r.ignoreUnknownFields,!0);e!==me&&(s[d]=e);break;case"scalar":try{s[d]=ke(n.V.T,c,W.BIGINT,!0)}catch(e){let r="cannot decode map value for field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];de(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=we(n.T,t,r.ignoreUnknownFields,!1);switch(c){case ye:ce(n,e);break;case me:break;default:e[a]=c}break;case"scalar":try{const r=ke(n.T,t,n.L,!1);if(r===ye)ce(n,e);else e[a]=r}catch(e){let r="cannot decode field ".concat(i.typeName,".").concat(n.name," from JSON: ").concat(ge(t));throw e instanceof Error&&e.message.length>0&&(r+=": ".concat(e.message)),new Error(r)}}}function be(e,t){if(e===q.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ke(e,t,W.BIGINT,!0).toString()}function ke(e,t,n,r){if(null===t)return r?X(e,n):ye;switch(e){case q.DOUBLE:case q.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 r=Number(t);if(Number.isNaN(r))break;if(!Number.isFinite(r))break;return e==q.FLOAT&&S(r),r;case q.INT32:case q.FIXED32:case q.SFIXED32:case q.SINT32:case q.UINT32:let i;if("number"==typeof t?i=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),void 0===i)break;return e==q.UINT32||e==q.FIXED32?I(i):T(i),i;case q.INT64:case q.SFIXED64:case q.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=V.parse(t);return n?a.toString():a;case q.FIXED64:case q.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=V.uParse(t);return n?o.toString():o;case q.BOOL:if("boolean"!=typeof t)break;return t;case q.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case q.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return ne.dec(t)}throw new Error}function we(e,t,n,r){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:r?e.values[0].no:ye;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const r=e.findName(t);if(void 0!==r)return r.no;if(n)return me}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(ge(t)))}function Te(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function Ie(e,t,n){if("map"==e.kind){w("object"==typeof t&&null!=t);const o={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const t of s){var r=Y(t,2);const n=r[0],i=r[1];o[n.toString()]=Ee(e.V.T,i)}break;case"message":for(const e of s){var i=Y(e,2);const t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case"enum":const t=e.V.T;for(const e of s){var a=Y(e,2);const r=a[0],i=a[1];o[r.toString()]=Se(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){w(Array.isArray(t));const r=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)r.push(Ee(e.T,t[n]));break;case"enum":for(let i=0;i<t.length;i++)r.push(Se(e.T,t[i],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case"scalar":return Ee(e.T,t);case"enum":return Se(e.T,t,n.enumAsInteger);case"message":return ue(e.T,t).toJson(n)}}function Se(e,t,n){var r;if(w("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const i=e.findNumber(t);return null!==(r=null==i?void 0:i.name)&&void 0!==r?r:t}function Ee(e,t){switch(e){case q.INT32:case q.SFIXED32:case q.SINT32:case q.FIXED32:case q.UINT32:return w("number"==typeof t),t;case q.FLOAT:case q.DOUBLE:return w("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case q.STRING:return w("string"==typeof t),t;case q.BOOL:return w("boolean"==typeof t),t;case q.UINT64:case q.FIXED64:case q.INT64:case q.SFIXED64:case q.SINT64:return w("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case q.BYTES:return w(t instanceof Uint8Array),ne.enc(t)}}const Ne=Symbol("@bufbuild/protobuf/unknown-fields"),Ce={readUnknownFields:!0,readerFactory:e=>new $(e)},Ae={writeUnknownFields:!0,writerFactory:()=>new Q};function Le(e){return e?Object.assign(Object.assign({},Ce),e):Ce}function Ue(e){return e?Object.assign(Object.assign({},Ae),e):Ae}function Re(e,t,n,r,i){let a=n.repeated,o=n.localName;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 s="enum"==n.kind?q.INT32:n.T;let c=De;if("scalar"==n.kind&&n.L>0&&(c=Fe),a){let n=e[o];if(r==G.LengthDelimited&&s!=q.STRING&&s!=q.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case"message":const d=n.T;a?e[o].push(Oe(t,new d,i,n)):de(e[o])?Oe(t,e[o],i,n):(e[o]=Oe(t,new d,i,n),!d.fieldWrapper||n.oneof||n.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let u=function(e,t,n){const r=t.uint32(),i=t.pos+r;let a,o;for(;t.pos<i;){switch(Y(t.tag(),1)[0]){case 1:a=De(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=De(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Oe(t,new e.V.T,n,void 0)}}}void 0===a&&(a=X(e.K,W.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=X(e.V.T,W.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[a,o]}(n,t,i),l=Y(u,2),h=l[0],f=l[1];e[o][h]=f}}function Oe(e,t,n,r){const i=t.getType().runtime.bin,a=null==r?void 0:r.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Fe(e,t){const n=De(e,t);return"bigint"==typeof n?n.toString():n}function De(e,t){switch(t){case q.STRING:return e.string();case q.BOOL:return e.bool();case q.DOUBLE:return e.double();case q.FLOAT:return e.float();case q.INT32:return e.int32();case q.INT64:return e.int64();case q.UINT64:return e.uint64();case q.FIXED64:return e.fixed64();case q.BYTES:return e.bytes();case q.FIXED32:return e.fixed32();case q.SFIXED32:return e.sfixed32();case q.SFIXED64:return e.sfixed64();case q.SINT64:return e.sint64();case q.UINT32:return e.uint32();case q.SINT32:return e.sint32()}}function Pe(e,t,n,r){w(void 0!==t);const i=e.repeated;switch(e.kind){case"scalar":case"enum":let o="enum"==e.kind?q.INT32:e.T;if(i)if(w(Array.isArray(t)),e.packed)!function(e,t,n,r){if(!r.length)return;e.tag(n,G.LengthDelimited).fork();let i=Y(Be(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}(n,o,e.no,t);else for(const r of t)Me(n,o,e.no,r);else Me(n,o,e.no,t);break;case"message":if(i){w(Array.isArray(t));for(const i of t)xe(n,r,e,i)}else xe(n,r,e,t);break;case"map":w("object"==typeof t&&null!=t);for(const i of Object.entries(t)){var a=Y(i,2);_e(n,r,e,a[0],a[1])}}}function _e(e,t,n,r,i){e.tag(n.no,G.LengthDelimited),e.fork();let a=r;switch(n.K){case q.INT32:case q.FIXED32:case q.UINT32:case q.SFIXED32:case q.SINT32:a=Number.parseInt(r);break;case q.BOOL:w("true"==r||"false"==r),a="true"==r}switch(Me(e,n.K,1,a),n.V.kind){case"scalar":Me(e,n.V.T,2,i);break;case"enum":Me(e,q.INT32,2,i);break;case"message":w(void 0!==i),e.tag(2,G.LengthDelimited).bytes(i.toBinary(t))}e.join()}function xe(e,t,n,r){const i=ue(n.T,r);n.delimited?e.tag(n.no,G.StartGroup).raw(i.toBinary(t)).tag(n.no,G.EndGroup):e.tag(n.no,G.LengthDelimited).bytes(i.toBinary(t))}function Me(e,t,n,r){w(void 0!==r);let i=Y(Be(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function Be(e){let t=G.Varint;switch(e){case q.BYTES:case q.STRING:t=G.LengthDelimited;break;case q.DOUBLE:case q.FIXED64:case q.SFIXED64:t=G.Bit64;break;case q.FIXED32:case q.SFIXED32:case q.FLOAT:t=G.Bit32}return[t,q[e].toLowerCase()]}function je(e){if(void 0===e)return e;if(de(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ke(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Ve{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 qe(e,t){const n=Ge(e);return t?n:Ye(ze(n))}const We=Ge;function Ge(e){let t=!1;const n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){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(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join("")}const Je=new Set(["constructor","toString","toJSON","valueOf"]),Xe=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),He=e=>"".concat(e,"$"),ze=e=>Xe.has(e)?He(e):e,Ye=e=>Je.has(e)?He(e):e;class Qe{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=qe(e,!1)}addField(e){w(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 $e=(Ze=e=>new Ve(e,(e=>function(e){var t,n,r,i,a,o;const s=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=qe(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:We(d.name),e.repeated=null!==(n=d.repeated)&&void 0!==n&&n,"scalar"==d.kind&&(e.L=null!==(r=d.L)&&void 0!==r?r:W.BIGINT),e.delimited=null!==(i=d.delimited)&&void 0!==i&&i,e.req=null!==(a=d.req)&&void 0!==a&&a,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=q.BYTES&&d.T!=q.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new Qe(t)),e.oneof=c,c.addField(e)}s.push(e)}return s}(e))),et=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,r=e;if(t.repeated)r[n]=[];else switch(t.kind){case"oneof":r[n]={case:void 0};break;case"enum":r[n]=0;break;case"map":r[n]={};break;case"scalar":r[n]=X(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:fe,makeWriteOptions:pe,readMessage(e,t,n,r){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(ge(t)));r=null!=r?r:new e;const i=new Map,a=n.typeRegistry;for(const s of Object.entries(t)){var o=Y(s,2);const t=o[0],c=o[1],d=e.fields.findJsonName(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.kind)continue;const n=i.get(d.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(d.oneof.name,'" present: "').concat(n,'", "').concat(t,'"'));i.set(d.oneof,t)}ve(r,c,d,n,e)}else{let i=!1;if((null==a?void 0:a.findExtension)&&t.startsWith("[")&&t.endsWith("]")){const o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;const e=Y(Z(o),2),t=e[0],a=e[1];ve(t,c,o.field,n,o),ie(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(t,'" is unknown'))}}return r},writeMessage(e,t){const n=e.getType(),r={};let i;try{for(i of n.fields.byNumber()){if(!se(i,e)){if(i.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Te(i))continue}const n=Ie(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t);void 0!==n&&(r[t.useProtoFieldName?i.name:i.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const i of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,i.no);if(o&&ae(e,o)){const n=re(e,o,t),i=Ie(o.field,n,t);void 0!==i&&(r[o.field.jsonName]=i)}}}catch(e){const t=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),r=e instanceof Error?e.message:String(e);throw new Error(t+(r.length>0?": ".concat(r):""))}return r},readScalar:(e,t,n)=>ke(e,t,null!=n?n:W.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||H(e,t)?Ee(e,t):void 0},debug:ge},bin:{makeReadOptions:Le,makeWriteOptions:Ue,listUnknownFields(e){var t;return null!==(t=e[Ne])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Ne]},writeUnknownFields(e,t){const n=e[Ne];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){const i=e;Array.isArray(i[Ne])||(i[Ne]=[]),i[Ne].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){const a=e.getType(),o=i?t.len:t.pos+n;let s,c;for(;t.pos<o;){var d=Y(t.tag(),2);if(s=d[0],c=d[1],!0===i&&c==G.EndGroup)break;const n=a.fields.find(s);if(n)Re(e,t,n,c,r);else{const n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n)}}if(i&&(c!=G.EndGroup||s!==n))throw new Error("invalid end group tag")},readField:Re,writeMessage(e,t,n){const r=e.getType();for(const i of r.fields.byNumber())if(se(i,e))Pe(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n);else if(i.req)throw new Error("cannot encode field ".concat(r.typeName,".").concat(i.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){void 0!==t&&Pe(e,t,n,r)}},util:Object.assign(Object.assign({},{setEnumType:C,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,a=t,o=e;if(null!=o[n])switch(i.kind){case"oneof":const e=o[n].case;if(void 0===e)continue;const t=i.findField(e);let s=o[n].value;t&&"message"==t.kind&&!de(s,t.T)?s=new t.T(s):t&&"scalar"===t.kind&&t.T===q.BYTES&&(s=Ke(s)),a[n]={case:e,value:s};break;case"scalar":case"enum":let c=o[n];i.T===q.BYTES&&(c=i.repeated?c.map(Ke):Ke(c)),a[n]=c;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===q.BYTES)for(const e of Object.entries(o[n])){var r=Y(e,2);const t=r[0],i=r[1];a[n][t]=Ke(i)}else Object.assign(a[n],o[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case"message":const d=i.T;if(i.repeated)a[n]=o[n].map((e=>de(e,d)?e:new d(e)));else{const e=o[n];d.fieldWrapper?"google.protobuf.BytesValue"===d.typeName?a[n]=Ke(e):a[n]=e:a[n]=de(e,d)?e:new d(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case"message":return r.every(((t,n)=>e.T.equals(t,i[n])));case"scalar":return r.every(((t,n)=>J(e.T,t,i[n])));case"enum":return r.every(((e,t)=>J(q.INT32,e,i[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=r,n=i;return e.T.fieldWrapper&&(void 0===t||de(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||de(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return J(q.INT32,r,i);case"scalar":return J(e.T,r,i);case"oneof":if(r.case!==i.case)return!1;const a=e.findField(r.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(r.value,i.value);case"enum":return J(q.INT32,r.value,i.value);case"scalar":return J(a.T,r.value,i.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case"message":const t=e.V.T;return o.every((e=>t.equals(r[e],i[e])));case"enum":return o.every((e=>J(q.INT32,r[e],i[e])));case"scalar":const n=e.V.T;return o.every((e=>J(n,r[e],i[e])))}}})),clone(e){const t=e.getType(),n=new t,r=n;for(const n of t.fields.byMember()){const t=e[n.localName];let a;if(n.repeated)a=t.map(je);else if("map"==n.kind){a=r[n.localName];for(const e of Object.entries(t)){var i=Y(e,2);const t=i[0],n=i[1];a[t]=je(n)}}else a="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:je(t.value)}:{case:void 0}:je(t);r[n.localName]=a}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}),{newFieldList:Ze,initFields:et}),makeMessageType(e,t,n){return function(e,t,n,r){var i;const a=null!==(i=null==r?void 0:r.localName)&&void 0!==i?i:t.substring(t.lastIndexOf(".")+1),o={[a]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[a];return Object.setPrototypeOf(o.prototype,new R),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:L,makeEnumType:A,getEnumType:N,makeExtension(e,t,n){return function(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){const n="function"==typeof r?r():r;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}(this,e,t,n)}});var Ze,et;const tt=$e.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),nt=$e.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"}]),rt=$e.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]);class it extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,void 0!==(null==n?void 0:n.cause)&&(this.cause=null==n?void 0:n.cause)}}var at,ot,st,ct,dt,ut,lt,ht,ft,pt;!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",e[e.WebSocket=6]="WebSocket",e[e.ServiceNotFound=7]="ServiceNotFound"}(at||(at={})),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",e[e.HeaderTooLarge=9]="HeaderTooLarge",e[e.PayloadTooLarge=10]="PayloadTooLarge"}(ot||(ot={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(st||(st={})),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}}(st||(st={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(ct||(ct={}));class yt extends it{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ct.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(dt||(dt={})),function(e){e.KeyRatcheted="keyRatcheted"}(ut||(ut={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(lt||(lt={})),function(e){e.Error="cryptorError"}(ht||(ht={}));class mt extends(pt=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}ft=mt,mt.resolve=e=>Reflect.get(pt,"resolve",ft).call(ft,e);const gt=/version\/(\d+(\.?_?\d+)+)/i;let vt;function bt(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("undefined"==typeof navigator)return;const n=navigator.userAgent.toLowerCase();if(void 0===vt||t){const e=kt.find((e=>e.test.test(n)));vt=null==e?void 0:e.describe(n)}return vt}const kt=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:wt(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Tt(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:wt(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Tt(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:wt(gt,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:Tt(e)})}];function wt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const r=t.match(e);return r&&r.length>=n&&r[n]||""}function Tt(e){return e.includes("mac os")?wt(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}var It,St={exports:{}};var Et,Nt,Ct,At,Lt=function(){if(It)return St.exports;It=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 r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}St.exports=i,St.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,a,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,a,c,d;if(o(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,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 u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]: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}(i):f(i,i.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 f(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function p(e,t,n,r){if("function"==typeof e.on)r.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 i(a){r.once&&e.removeEventListener(t,i),n(a)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),i.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},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(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},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,a=this._events;if(void 0!==a)i=i&&void 0===a.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var c=a[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=f(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,a,s;if(o(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;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 i,a=Object.keys(n);for(r=0;r<a.length;++r)"removeListener"!==(i=a[r])&&this.removeAllListeners(i);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(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},St.exports}();function Ut(e){const t={};for(const r of Object.entries(e)){var n=Y(r,2);const e=n[0],i=n[1];void 0!==i&&(t[e]=i)}return t}function Rt(e,t){return e&&t?"".concat(e,"x").concat(t):void 0}function Ot(e){return Math.round(1e4*e)/1e4}function Ft(e){const t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return void 0!==t&&n?Ot(t/n):void 0}function Dt(e,t){if(void 0!==e.playoutDelay)return Ot(e.playoutDelay);const n=null==t?void 0:t.totalPlayoutDelay,r=null==t?void 0:t.totalSamplesCount;return void 0!==n&&r?Ot(n/r):void 0}!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",e.DataTrackPublished="dataTrackPublished",e.DataTrackUnpublished="dataTrackUnpublished",e.LocalDataTrackPublished="localDataTrackPublished",e.LocalDataTrackUnpublished="localDataTrackUnpublished"}(Et||(Et={})),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"}(Nt||(Nt={})),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",e.PublishDataTrackResponse="publishDataTrackResponse",e.UnPublishDataTrackResponse="unPublishDataTrackResponse",e.DataTrackSubscriberHandles="dataTrackSubscriberHandles",e.DataTrackPacketReceived="dataTrackPacketReceived",e.Joined="joined",e.TokenRefreshed="tokenRefreshed",e.ServerRegionsReported="serverRegionsReported",e.RequestSubscribedCodecRefresh="requestSubscribedCodecRefresh"}(Ct||(Ct={})),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"}(At||(At={}));class Pt{constructor(e,t,n,r,i){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:r,priority:i}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const _t=["vp8","h264","vp9","av1","h265"];var xt,Mt;function Bt(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?Bt(e.track):{})}}!function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"}(xt||(xt={})),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}}(Mt||(Mt={})),new Pt(160,90,9e4,20),new Pt(320,180,16e4,20),new Pt(384,216,18e4,20),new Pt(640,360,45e4,20),new Pt(960,540,8e5,25),new Pt(1280,720,17e5,30),new Pt(1920,1080,3e6,30),new Pt(2560,1440,5e6,30),new Pt(3840,2160,8e6,30),new Pt(160,120,7e4,20),new Pt(240,180,125e3,20),new Pt(320,240,14e4,20),new Pt(480,360,33e4,20),new Pt(640,480,5e5,20),new Pt(720,540,6e5,25),new Pt(960,720,13e5,30),new Pt(1440,1080,23e5,30),new Pt(1920,1440,38e5,30),new Pt(640,360,2e5,3,"medium"),new Pt(640,360,4e5,15,"medium"),new Pt(1280,720,8e5,5,"medium"),new Pt(1280,720,15e5,15,"medium"),new Pt(1280,720,2e6,30,"medium"),new Pt(1920,1080,25e5,15,"medium"),new Pt(1920,1080,5e6,30,"medium"),new Pt(0,0,7e6,30,"medium");const jt=[];var Kt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(Kt||(Kt={}));class Vt extends Lt.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Vt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=d,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=u(null!==(r=n.loggerName)&&void 0!==r?r:s.Track,(()=>this.logContext)),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Vt.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Bt(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Vt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===Vt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(jt.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&jt.splice(jt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,r;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;r="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();r.includes(e)||(r.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));Wt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(Wt()||function(){var e;return"Firefox"===(null===(e=bt())||void 0===e?void 0:e.name)}())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),r=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(r?At.AudioPlaybackStarted:At.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(r?At.AudioPlaybackFailed:At.VideoPlaybackFailed,t):"AbortError"===t.name?this.log.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(r?"audio":"video"),{error:t}),r&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(At.ElementAttached,e),e}detach(e){try{if(e){qt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(At.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{qt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(At.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),void 0!==this.timeSyncHandle&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then((e=>{e&&this.log.info("final track stats",function(e){var t,n;const r=new Map,i=[],a=[],o=[];let s;e.forEach((e=>r.set(e.id,e)));const c=e=>{var t;return e.codecId?null===(t=r.get(e.codecId))||void 0===t?void 0:t.mimeType:void 0},d=(e,t)=>e[t]?r.get(e[t]):void 0;e.forEach((e=>{switch(e.type){case"inbound-rtp":{const t=d(e,"playoutId");a.push(Ut({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:c(e),decoder:e.decoderImplementation,resolution:Rt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:Ft(e),playoutDelay:Dt(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case"outbound-rtp":{const t=d(e,"remoteId"),n=d(e,"mediaSourceId");o.push(Ut({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:null==n?void 0:n.trackIdentifier,active:e.active,codec:c(e),encoder:e.encoderImplementation,resolution:Rt(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:Rt(null==n?void 0:n.width,null==n?void 0:n.height),captureFps:null==n?void 0:n.framesPerSecond,audioLevel:null==n?void 0:n.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:"none"===e.qualityLimitationReason?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:null==t?void 0:t.packetsLost,remoteFractionLost:null==t?void 0:t.fractionLost,remoteJitter:null==t?void 0:t.jitter,remoteRoundTripTime:null==t?void 0:t.roundTripTime}));break}case"transport":s=e;break;case"candidate-pair":i.push(e)}}));const u=null==s?void 0:s.selectedCandidatePairId,l=null!==(n=null!==(t=u?r.get(u):void 0)&&void 0!==t?t:i.find((e=>e.selected)))&&void 0!==n?n:i.find((e=>e.nominated)),h=(null==l?void 0:l.localCandidateId)?r.get(l.localCandidateId):void 0,f=(null==l?void 0:l.remoteCandidateId)?r.get(l.remoteCandidateId):void 0,p=Ut({ice:null==s?void 0:s.iceState,dtls:null==s?void 0:s.dtlsState,route:h&&f?"".concat(h.candidateType,"/").concat(h.protocol," -> ").concat(f.candidateType):void 0,network:null==h?void 0:h.networkType,currentRoundTripTime:null==l?void 0:l.currentRoundTripTime,availableOutgoingBitrate:null==l?void 0:l.availableOutgoingBitrate,availableIncomingBitrate:null==l?void 0:l.availableIncomingBitrate,bytesSent:null==l?void 0:l.bytesSent,bytesReceived:null==l?void 0:l.bytesReceived,candidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges});return{connection:Object.keys(p).length>0?p:void 0,outbound:o.length>0?o:void 0,inbound:a.length>0?a:void 0}}(e))})).catch((e=>this.log.debug("could not collect final track stats",{error:e}))))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=u(e.loggerName,(()=>this.logContext)))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),jt.forEach((e=>{e.parentElement||(t=!1)})),t&&jt.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==Vt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Gt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Gt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function qt(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}function Wt(){var e;return"Safari"===(null===(e=bt())||void 0===e?void 0:e.name)}function Gt(){return"undefined"!=typeof document}function Jt(e,t){return e instanceof Error?e.name&&e.message?"".concat(e.name,": ").concat(e.message):e.name:"Encountered unknown ".concat(t," error: ").concat(String(e))}function Xt(e){return"type"in e}function Ht(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function zt(t,n){return e(this,void 0,void 0,(function*(){const e=Ht(t.algorithm.name,n.ratchetSalt),r=yield crypto.subtle.deriveKey(e,t,{name:v,length:n.keySize},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){let t,n,r;!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"}(r=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return tt.AUDIO;case t.Video:return tt.VIDEO;default:return tt.DATA}},e.kindFromProto=function(e){switch(e){case tt.AUDIO:return t.Audio;case tt.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return nt.CAMERA;case n.Microphone:return nt.MICROPHONE;case n.ScreenShare:return nt.SCREEN_SHARE;case n.ScreenShareAudio:return nt.SCREEN_SHARE_AUDIO;default:return nt.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case nt.CAMERA:return n.Camera;case nt.MICROPHONE:return n.Microphone;case nt.SCREEN_SHARE:return n.ScreenShare;case nt.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case rt.ACTIVE:return r.Active;case rt.PAUSED:return r.Paused;default:return r.Unknown}}}(Vt||(Vt={}));class Yt{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-Yt.sendCount%65535),Yt.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=Yt.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:v,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const o=yield n.getKeySet(r);if(!o)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:v,iv:t},o.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(a.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let s,c;l.debug("DataCryptor: ratcheting key attempt ".concat(a.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:o)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),s=yield zt(c.cryptoKey,n.keyProviderOptions));const d=yield Yt.decrypt(e,t,n,r,i,{ratchetCount:a.ratchetCount+1,encryptionKey:null==s?void 0:s.encryptionKey});return d&&s&&(null!=i?i:o)===n.getKeySet(r)&&(n.setKeySet(s,r,c),n.setCurrentKeyIndex(r)),d}throw l.warn("DataCryptor: maximum ratchet attempts exceeded"),new yt("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),ct.InvalidKey,n.participantIdentity)}throw new yt("DataCryptor: Decryption failed: ".concat(Jt(s,"decryption")),ct.InvalidKey,n.participantIdentity)}}()}))}}Yt.sendCount=0;class Qt{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:6e4,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5;this.throttleMs=e,this.windowMs=t,this.maxPerWindow=n,this.lastAt=new Map,this.counts=new Map}reset(){this.lastAt.clear(),this.counts.clear()}countFor(e){var t;return null!==(t=this.counts.get(e))&&void 0!==t?t:0}shouldEmit(e,t){var n,r;const i=Date.now(),a=null!==(n=this.lastAt.get(e))&&void 0!==n?n:0,o=null!==(r=this.counts.get(e))&&void 0!==r?r:0;return i-a>this.windowMs?(this.counts.set(e,0),this.lastAt.set(e,i),!0):!(i-a<this.throttleMs)&&(o>=this.maxPerWindow?(o===this.maxPerWindow&&(null==t||t(),this.counts.set(e,o+1)),!1):(this.lastAt.set(e,i),this.counts.set(e,o+1),!0))}}function $t(e){return!(!(null==e?void 0:e.timestamp)&&!(null==e?void 0:e.frameId))}const Zt=Uint8Array.from(["L".charCodeAt(0),"K".charCodeAt(0),"T".charCodeAt(0),"S".charCodeAt(0)]);function en(e,t,n){const r=t!==BigInt(0),i=0!==n;if(!r&&!i)return e;const a=(r?10:0)+(i?6:0)+5,o=new Uint8Array(e.length+a);let s=0;return o.set(e,s),s+=e.length,r&&(o[s++]=254,o[s++]=247,function(e,t,n){const r=Number(n>>BigInt(32)&BigInt(4294967295)),i=Number(n&BigInt(4294967295));e[t]=r>>>24^255,e[t+1]=r>>>16&255^255,e[t+2]=r>>>8&255^255,e[t+3]=255&r^255,e[t+4]=i>>>24^255,e[t+5]=i>>>16&255^255,e[t+6]=i>>>8&255^255,e[t+7]=255&i^255}(o,s,t),s+=8),i&&(o[s++]=253,o[s++]=251,function(e,t,n){for(let r=3;r>=0;r-=1)e[t+(3-r)]=n>>8*r&255^255}(o,s,n),s+=4),o[s++]=255^a,o.set(Zt,s),o}function tn(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<5)return{data:t};if(!function(e,t){for(let n=0;n<Zt.length;n+=1)if(e[t+n]!==Zt[n])return!1;return!0}(t,t.length-Zt.length))return{data:t};const n=255^t[t.length-5];if(n<5||n>t.length)return{data:t};const r=t.length-n,i=t.length-5,a=t.subarray(0,r);let o=r,s=!1;const c={userTimestamp:BigInt(0),frameId:0};for(;o+2<=i;){const e=255^t[o++],n=255^t[o++];if(o+n>i)break;if(1===e&&8===n)c.userTimestamp=nn(t,o),s=!0;else if(2===e&&4===n)c.frameId=rn(t,o,n),s=!0;else if(3===e){const e=new Uint8Array(n);for(let r=0;r<n;r+=1)e[r]=255^t[o+r];c.userData=e,s=!0}o+=n}return s?{data:a,metadata:c}:{data:t}}function nn(e,t){const n=BigInt(((255^e[t])<<24|(255^e[t+1])<<16|(255^e[t+2])<<8|255^e[t+3])>>>0),r=BigInt(((255^e[t+4])<<24|(255^e[t+5])<<16|(255^e[t+6])<<8|255^e[t+7])>>>0);return n<<BigInt(32)|r}function rn(e,t,n){let r=0;for(let i=0;i<n;i+=1)r=r<<8|255^e[t+i];return r>>>0}function an(e){try{const t=e.getMetadata();if("number"==typeof t.synchronizationSource)return t.synchronizationSource}catch(e){}return 0}var on,sn;function cn(e){return 31&e}function dn(e){return e>>1&63}function un(e){return e===on.SLICE_IDR||e===on.SLICE_NON_IDR}function ln(e){return e===sn.TRAIL_N||e===sn.TRAIL_R||e===sn.TSA_N||e===sn.TSA_R||e===sn.STSA_N||e===sn.STSA_R||e===sn.RADL_N||e===sn.RADL_R||e===sn.RASL_N||e===sn.RASL_R||e===sn.BLA_W_LP||e===sn.BLA_W_RADL||e===sn.BLA_N_LP||e===sn.IDR_W_RADL||e===sn.IDR_N_LP||e===sn.CRA_NUT}function hn(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let a=r;for(;a>n&&0===e[a-1];)a--;if(0===n){if(a!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let o=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(o=4),n=r+=o}return t}(e);let r=function(e,t){for(const n of t)if(un(cn(e[n])))return"h264";for(const n of t)if(ln(dn(e[n])))return"h265";return"unknown"}(e,n);if("unknown"===r&&(r=null!=t?t:"unknown"),"unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(ln(dn(e[r])))return r+2}else if(un(cn(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(on||(on={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(sn||(sn={}));const fn="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",pn="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",yn="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",mn="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",gn="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function vn(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case fn:return"vp8";case pn:case yn:case mn:return"h264";case gn:return"opus";default:return null}}))}const bn=new Map;class kn extends Lt.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class wn extends kn{constructor(e){var t;super(),this.hasFrameMetadata=!1,this.frameMetadataFrameId=0,this.errorLimiter=new Qt,this.UNDECRYPTED_TRACK_GRACE_MS=2e3,this.loggedNALUFallbacks=new Set,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){l.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{newParticipant:e,hadPreviousParticipant:!!this.participantIdentity})),this.participantIdentity&&this.participantIdentity!==e&&(l.warn("cryptor has already a participant set, cleaning up before switching",{oldParticipant:this.participantIdentity,newParticipant:e,trackId:this.trackId}),this.unsetParticipant()),this.participantIdentity=e,this.keys=t}unsetParticipant(){l.debug("unsetting participant",this.logContext),clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,this.participantIdentity=void 0,this.errorLimiter.reset()}isEnabled(){return this.participantIdentity?bn.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setTrackId(e){this.trackId!==e&&(l.debug("re-pointing cryptor at new trackId",Object.assign(Object.assign({},this.logContext),{newTrackId:e})),this.trackId=e)}hasActiveTransform(){return!!this.currentTransform}scheduleUndecryptedTrackWatchdog(e){clearTimeout(this.undecryptedTrackTimeout),this.undecryptedTrackTimeout=void 0,"decode"===e&&(this.undecryptedTrackTimeout=setTimeout((()=>{!this.currentTransform&&this.isEnabled()&&(l.warn("encrypted track has no active decrypt transform",this.logContext),this.emitThrottledError(new yt("no active decrypt transform for encrypted track ".concat(this.trackId),ct.InternalError,this.participantIdentity)))}),this.UNDECRYPTED_TRACK_GRACE_MS))}ensureTransform(){if(this.currentTransform)return!0;if(!this.retainedStreams||void 0===this.trackId)return l.warn("no streams retained, cannot re-establish transform",this.logContext),!1;const e=this.retainedStreams,t=e.readable,n=e.writable,r=e.operation;return l.info("re-establishing transform",Object.assign(Object.assign({},this.logContext),{operation:r})),this.setupTransform(r,t,n,this.trackId)}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setHasFrameMetadata(e){this.hasFrameMetadata=e}setFrameMetadataOpts(e){this.frameMetadataOpts=e,this.frameMetadataFrameId=0}setupTransform(e,t,n,r,i,a){var o;i&&(l.info("setting codec on cryptor to",{codec:i}),this.videoCodec=i),"encode"===e&&this.setFrameMetadataOpts(a),l.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:i,hasCurrentTransform:!!this.currentTransform},this.logContext)),this.trackId=r,this.retainedStreams={readable:t,writable:n,operation:e},clearTimeout(this.undecryptedTrackTimeout);const s=Symbol("transform"),c="encode"===e?this.encodeFunction:this.decodeFunction,d=new TransformStream({transform:c.bind(this)});this.currentTransform={readable:t,writable:n,transformer:d,trackId:r,symbol:s};try{t.pipeThrough(d).pipeTo(n).catch((e=>{e instanceof TypeError&&"Destination stream closed"===e.message?l.debug("destination stream closed"):(l.warn("transform error",Object.assign({error:e},this.logContext)),this.emit(ht.Error,e instanceof yt?e:new yt(e.message,void 0,this.participantIdentity)))})).finally((()=>{var t;(null===(t=this.currentTransform)||void 0===t?void 0:t.symbol)===s&&(l.debug("transform completed",Object.assign(Object.assign({},this.logContext),{trackId:r})),this.currentTransform=void 0),this.scheduleUndecryptedTrackWatchdog(e)}))}catch(e){return(null===(o=this.currentTransform)||void 0===o?void 0:o.symbol)===s&&(this.currentTransform=void 0),l.error("failed to set up transform",Object.assign({error:e},this.logContext)),this.emit(ht.Error,e instanceof yt?e:new yt(e.message,ct.InternalError,this.participantIdentity)),!1}return!0}setSifTrailer(e){l.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}emitThrottledError(e){const t="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(!this.errorLimiter.shouldEmit(t,(()=>{l.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:t}))})))return;const n=this.errorLimiter.countFor(t);n>1&&l.debug("Decryption error (".concat(n," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:ct[e.reason]})),this.emit(ht.Error,e)}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(0===t.data.byteLength)return n.enqueue(t);if(!this.isEnabled())return this.appendFrameMetadata(t),n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new yt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),ct.MissingKey,this.participantIdentity));const i=r.encryptionKey,a=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t),c=new Uint8Array(t.data,0,s.unencryptedBytes);s.requiresNALUProcessing&&(c=function(e){const t=[];for(let n=0;n+2<e.length;)0!==e[n+2]?(1!==e[n+2]||0!==e[n]||0!==e[n+1]||0!==n&&0===e[n-1]||t.push(n),n+=3):n+=1;if(0===t.length)return e;const n=new Uint8Array(e.length+t.length);let r=0;for(let i=0;i<t.length;i++){const a=t[i];n.set(e.subarray(r,a),r+i),r=a}return n.set(e.subarray(r),r+t.length),n}(c));const d=new Uint8Array(2);d[0]=12,d[1]=a;try{const e=yield crypto.subtle.encrypt({name:v,iv:r,additionalData:c},i,new Uint8Array(t.data,s.unencryptedBytes));let a=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);a.set(new Uint8Array(e)),a.set(new Uint8Array(r),e.byteLength),a.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(a=function(e){const t=[];for(var n=0,r=0;r<e.length;++r){var i=e[r];i<=3&&n>=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(a));var o=new Uint8Array(c.byteLength+a.byteLength);return o.set(c),o.set(a,c.byteLength),t.data=o.buffer,this.appendFrameMetadata(t),n.enqueue(t)}catch(e){l.error("error while encrypting",Object.assign(Object.assign({},this.logContext),{error:e}))}}else l.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new yt("encryption key missing for encoding",ct.MissingKey,this.participantIdentity))}))}appendFrameMetadata(e){var t;$t(this.frameMetadataOpts)&&Xt(e)&&((null===(t=this.frameMetadataOpts)||void 0===t?void 0:t.frameId)&&(this.frameMetadataFrameId=4294967295===this.frameMetadataFrameId?1:this.frameMetadataFrameId+1),function(e,t,n){if(!$t(t)||0===e.data.byteLength)return!1;const r=(null==t?void 0:t.timestamp)?BigInt(Date.now())*BigInt(1e3):BigInt(0),i=(null==t?void 0:t.frameId)?n:0,a=new Uint8Array(e.data),o=en(a,r,i);o.byteLength!==a.byteLength&&(e.data=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength))}(e,this.frameMetadataOpts,this.frameMetadataFrameId))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(this.hasFrameMetadata&&Xt(t))try{const e=function(e,t){if(0===e.data.byteLength)return{};const n=tn(e.data);if(!n.metadata)return{};const r=n.data.buffer.slice(n.data.byteOffset,n.data.byteOffset+n.data.byteLength),i=function(e){try{const t=e.getMetadata();if("number"==typeof t.rtpTimestamp)return t.rtpTimestamp;if("number"==typeof t.timestamp)return t.timestamp}catch(e){}if("number"==typeof e.timestamp)return e.timestamp}(e);return void 0!==i&&t?{data:r,payload:{trackId:t,rtpTimestamp:i,ssrc:an(e),metadata:n.metadata}}:{data:r}}(t,this.trackId);if(e.data&&(t.data=e.data),e.payload&&this.participantIdentity){const t={kind:"packetTrailerMetadata",data:e.payload};postMessage(t)}}catch(e){}if(0===t.data.byteLength)return n.enqueue(t);const e=this.isEnabled();if(void 0===e)return void 0===this.participantIdentity?void l.debug("dropping frame for unassigned cryptor",this.logContext):void this.emitThrottledError(new yt("encryption state unknown for track ".concat(this.trackId,", dropping frame"),ct.InternalError,this.participantIdentity));if(!e)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield vn(t.data))?(l.debug("enqueue SIF",this.logContext),n.enqueue(t)):void l.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const r=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(r))if(this.keys.getKeySet(r))try{const e=yield this.decryptFrame(t,r);if(this.keys.decryptionSuccess(r),e)return n.enqueue(e)}catch(e){e instanceof yt&&e.reason===ct.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(e),this.keys.decryptionFailure(r)):l.warn("decoding frame failed",{error:e})}else l.warn("skipping decryption due to missing key at index ".concat(r)),this.emitThrottledError(new yt("missing key at index ".concat(r," for participant ").concat(this.participantIdentity),ct.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(r)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!i.encryptionKey&&!o)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=function(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),h=yield crypto.subtle.decrypt({name:v,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=i.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,u,l)),f=new ArrayBuffer(t.byteLength+h.byteLength),p=new Uint8Array(f);return p.set(new Uint8Array(e.data,0,t.byteLength)),p.set(new Uint8Array(h),t.byteLength),e.data=f,e}catch(a){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let a,s;l.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:o)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),a=yield zt(s.cryptoKey,n.keyProviderOptions));const c=yield n.decryptFrame(e,t,r||o,{ratchetCount:i.ratchetCount+1,encryptionKey:null==a?void 0:a.encryptionKey});return c&&a&&(null!=r?r:o)===n.keys.getKeySet(t)&&(n.keys.setKeySet(a,t,s),n.keys.setCurrentKeyIndex(t)),c}throw l.warn("maximum ratchet attempts exceeded"),new yt("valid key missing for participant ".concat(n.participantIdentity),ct.InvalidKey,n.participantIdentity)}throw new yt("Decryption failed: ".concat(Jt(a,"decryption")),ct.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const a=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-a%65535),this.sendCounts.set(e,a+1),r}getUnencryptedBytes(e){var t;if(!Xt(e))return{unencryptedBytes:b.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(l.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:b[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};const r=e.getMetadata().payloadType,i="".concat(this.participantIdentity,"-").concat(this.trackId,"-").concat(r);try{const t="h264"===n||"h265"===n?n:void 0,r=hn(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return this.loggedNALUFallbacks.delete(i),{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(t){this.logNALUFallbackOnce(i,e,r,n,t)}return{unencryptedBytes:b[e.type],requiresNALUProcessing:!1}}logNALUFallbackOnce(e,t,n,r,i){this.loggedNALUFallbacks.has(e)||(this.loggedNALUFallbacks.add(e),l.warn("NALU processing failed, falling back to VP8 handling",Object.assign({error:i,payloadType:n,detectedCodec:r,frameType:t.type,byteLength:t.data.byteLength,firstBytes:Array.from(new Uint8Array(t.data,0,Math.min(16,t.data.byteLength))).map((e=>e.toString(16).padStart(2,"0"))).join(" ")},this.logContext)))}getVideoCodec(e){const t=e.getMetadata();if(t.mimeType){const e=t.mimeType.split("/")[1].toLowerCase();if(_t.includes(e))return e}if(0===this.rtpMap.size)return;const n=t.payloadType;return n?this.rtpMap.get(n):void 0}}class Tn extends Lt.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&l.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const a=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=i.material,o=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=Ht(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:v},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(o,a.algorithm.name,"derive"),c={chainKey:o,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,a),a}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){yield t.setKeyFromMaterial(e,n,null,r),r&&t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function*(){const a=yield zt(e,n.keyProviderOptions),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;l.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(a,o,r),o>=0&&i&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(ut.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const In=[],Sn=new Map;let En,Nn,Cn=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new g,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:p.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=p.RUNNING,yield t()}finally{e.status=p.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},An=!1,Ln=k,Un=new Map;const Rn=new Qt;function On(e,t,n){let r=In.filter((e=>e.getTrackId()===t));if(0===r.length&&void 0!==n&&n!==t){const i=In.filter((e=>e.getTrackId()===n));i.length>0&&(l.info("reusing cryptor from previous trackId",{participantIdentity:e,trackId:t,previousTrackId:n}),i[0].setTrackId(t),r=i)}if(r.length>1){const n=r.map((e=>({participant:e.getParticipantIdentity()}))).join(",");l.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:n})}let i=r[0];if(i)e!==i.getParticipantIdentity()&&i.setParticipant(e,Fn(e));else{if(l.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!Ln)throw Error("Missing keyProvider options");i=new wn({participantIdentity:e,keys:Fn(e),keyProviderOptions:Ln,sifTrailer:Nn}),i.setRtpMap(Un),function(e){e.on(ht.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(ct[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(i),In.push(i)}return i}function Fn(e){if(An)return Dn();let t=Sn.get(e);return t||(t=new Tn(e,Ln),t.on(ut.KeyRatcheted,Pn),Sn.set(e,t)),t}function Dn(){return En||(l.debug("creating new shared key handler"),En=new Tn("shared-key",Ln)),En}function Pn(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}l.setDefaultLevel("info"),l.methodFactory=e=>(t,n)=>{postMessage({kind:"log",data:{level:e,msg:t,context:n}})},l.setLevel(l.getLevel()),onmessage=t=>{Cn.run((()=>e(void 0,void 0,void 0,(function*(){const n=t.data,r=n.kind,i=n.data;switch(r){case"init":l.setLevel(i.loglevel),l.info("e2ee worker initialized"),Ln=i.keyProviderOptions,An=!!i.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"setLogLevel":l.setLevel(i.level);break;case"enable":o=i.enabled,s=i.participantIdentity,l.debug("setting encryption enabled for all tracks of ".concat(s),{enable:o}),bn.set(s,o),l.info("updated e2ee enabled status for ".concat(i.participantIdentity," to ").concat(i.enabled)),postMessage(t.data);break;case"decode":let n=On(i.participantIdentity,i.trackId);n.setHasFrameMetadata(i.hasPacketTrailer),n.setupTransform(r,i.readableStream,i.writableStream,i.trackId,i.codec);break;case"encode":let c=On(i.participantIdentity,i.trackId);c.setHasFrameMetadata(i.hasPacketTrailer),c.setupTransform(r,i.readableStream,i.writableStream,i.trackId,i.codec,i.packetTrailer);break;case"encryptDataRequest":const d=yield Yt.encrypt(i.payload,Fn(i.participantIdentity)),u=d.payload,h=d.iv,f=d.keyIndex;postMessage({kind:"encryptDataResponse",data:{payload:u,iv:h,keyIndex:f,uuid:i.uuid}});break;case"decryptDataRequest":try{const e=(yield Yt.decrypt(i.payload,i.iv,Fn(i.participantIdentity),i.keyIndex)).payload;postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:i.uuid}})}catch(e){const t="".concat(i.participantIdentity,"-datadecrypt");Rn.shouldEmit(t,(()=>{l.warn("Suppressing further data decryption errors for ".concat(i.participantIdentity),{errorKey:t})}))&&l.error("DataCryptor decryption failed",{error:e,participantIdentity:i.participantIdentity,uuid:i.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:i.uuid}})}break;case"setKey":An?yield function(t,n,r){return e(this,void 0,void 0,(function*(){l.info("set shared key",{index:n}),yield Dn().setKey(t,n,r)}))}(i.key,i.keyIndex,i.updateCurrentKeyIndex):i.participantIdentity?(l.info("set participant sender key ".concat(i.participantIdentity," index ").concat(i.keyIndex)),yield Fn(i.participantIdentity).setKey(i.key,i.keyIndex,i.updateCurrentKeyIndex)):l.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=In.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&l.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():l.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(i.trackId,i.participantIdentity);break;case"updateCodec":const p=On(i.participantIdentity,i.trackId,i.previousTrackId);i.codec&&p.setVideoCodec(i.codec),p.setHasFrameMetadata(i.hasPacketTrailer),l.info("updated codec",{participantIdentity:i.participantIdentity,trackId:i.trackId,previousTrackId:i.previousTrackId,codec:i.codec,hasPacketTrailer:i.hasPacketTrailer}),void 0===i.previousTrackId||p.ensureTransform()||l.error("could not re-establish transform for reused receiver",{participantIdentity:i.participantIdentity,trackId:i.trackId,previousTrackId:i.previousTrackId});break;case"setRTPMap":Un=i.map,In.forEach((e=>{e.getParticipantIdentity()===i.participantIdentity&&e.setRtpMap(i.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(An){const e=Dn();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=Fn(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else l.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(i);break;case"setSifTrailer":a=i.trailer,Nn=a,In.forEach((e=>{e.setSifTrailer(a)}))}var a,o,s}))))},self.RTCTransformEvent&&(self.onrtctransform=t=>{const n=t.transformer,r=n.options,i=r.kind,a=r.participantIdentity,o=r.trackId,s=r.codec,c=r.hasPacketTrailer;Cn.run((()=>e(void 0,void 0,void 0,(function*(){const e=On(a,o);e.setHasFrameMetadata(c),l.debug("onrtctransform setup",{participantIdentity:a,trackId:o,codec:s}),e.setupTransform(i,n.readable,n.writable,o,s,"encode"===i?r.packetTrailer:void 0)}))))})}));
|
|
2
2
|
//# sourceMappingURL=livekit-client.e2ee.worker.js.map
|