livekit-client 2.5.8 → 2.5.10

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. package/dist/livekit-client.e2ee.worker.js +1 -1
  2. package/dist/livekit-client.e2ee.worker.js.map +1 -1
  3. package/dist/livekit-client.e2ee.worker.mjs +543 -5128
  4. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  5. package/dist/livekit-client.esm.mjs +104 -98
  6. package/dist/livekit-client.esm.mjs.map +1 -1
  7. package/dist/livekit-client.umd.js +1 -1
  8. package/dist/livekit-client.umd.js.map +1 -1
  9. package/dist/src/api/SignalClient.d.ts.map +1 -1
  10. package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
  11. package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts +25 -5
  12. package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts.map +1 -1
  13. package/dist/src/index.d.ts +2 -1
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/room/PCTransportManager.d.ts.map +1 -1
  16. package/dist/src/room/RTCEngine.d.ts.map +1 -1
  17. package/dist/src/room/Room.d.ts.map +1 -1
  18. package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
  19. package/dist/src/room/track/LocalTrack.d.ts +1 -1
  20. package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
  21. package/dist/src/room/track/LocalVideoTrack.d.ts.map +1 -1
  22. package/dist/src/room/utils.d.ts +0 -10
  23. package/dist/src/room/utils.d.ts.map +1 -1
  24. package/dist/ts4.2/src/e2ee/worker/ParticipantKeyHandler.d.ts +25 -5
  25. package/dist/ts4.2/src/index.d.ts +2 -1
  26. package/dist/ts4.2/src/room/track/LocalTrack.d.ts +1 -1
  27. package/dist/ts4.2/src/room/utils.d.ts +0 -10
  28. package/package.json +3 -2
  29. package/src/api/SignalClient.ts +2 -1
  30. package/src/e2ee/worker/FrameCryptor.test.ts +311 -113
  31. package/src/e2ee/worker/FrameCryptor.ts +10 -5
  32. package/src/e2ee/worker/ParticipantKeyHandler.test.ts +169 -5
  33. package/src/e2ee/worker/ParticipantKeyHandler.ts +50 -20
  34. package/src/e2ee/worker/__snapshots__/ParticipantKeyHandler.test.ts.snap +356 -0
  35. package/src/index.ts +1 -1
  36. package/src/room/PCTransportManager.ts +2 -1
  37. package/src/room/RTCEngine.ts +3 -1
  38. package/src/room/Room.ts +1 -1
  39. package/src/room/participant/LocalParticipant.ts +4 -1
  40. package/src/room/track/LocalTrack.ts +2 -1
  41. package/src/room/track/LocalVideoTrack.ts +2 -1
  42. package/src/room/track/options.ts +5 -5
  43. package/src/room/utils.ts +0 -38
  44. package/src/utils/AsyncQueue.test.ts +2 -2
  45. package/src/utils/AsyncQueue.ts +1 -1
@@ -1,2 +1,2 @@
1
- !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,i){return new(n||(n=Promise))((function(r,a){function o(e){try{c(i.next(e))}catch(e){a(e)}}function s(e){try{c(i.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var i,r,a,o,s,c=(t||(t=1,r=n.exports,a=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],r={},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(),r=0;r<i.length;r++){var a=i[r];this[a]=r<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 u(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function d(i,r,a){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?s:void 0!==console[i]?o(console,i):void 0!==console.log?o(console,"log"):e)}(i)||u.apply(this,arguments)}function l(e,n){var o,s,u,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,i=encodeURIComponent(h),r=n.indexOf(i+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r+i.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||d,l.getLevel=function(){return null!=u?u:null!=s?s:o},l.setLevel=function(e,n){return u=p(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(u),c.call(l)},l.setDefaultLevel=function(e){s=p(e),f()||l.setLevel(e,!1)},l.resetLevel=function(){u=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 r)r[e].rebuild()},o=p(a?a.getLevel():"WARN");var y=f();null!=y&&(u=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=r[e];return t||(t=r[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 r},a.default=a,a},(i=n).exports?i.exports=a():r.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.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"}(s||(s={}));let u=c.getLogger("livekit");function d(e){const t=c.getLogger(e);return t.setDefaultLevel(u.getLevel()),t}Object.values(s).map((e=>c.getLogger(e))),u.setDefaultLevel(o.info);const l=c.getLogger("lk-e2ee");function h(e,t){if(!e)throw new Error(t)}const f=34028234663852886e22,p=-34028234663852886e22,y=4294967295,m=2147483647,g=-2147483648;function b(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>m||e<g)throw new Error("invalid int 32: "+e)}function v(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>y||e<0)throw new Error("invalid uint 32: "+e)}function k(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>f||e<p))throw new Error("invalid float 32: "+e)}const w=Symbol("@bufbuild/protobuf/enum-type");function S(e){const t=e[w];return h(t,"missing enum type on enum object"),t}function I(e,t,n,i){e[w]=T(t,n.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function T(e,t,n){const i=Object.create(null),r=Object.create(null),a=[];for(const e of t){const t=N(e);a.push(t),i[e.name]=t,r[e.no]=t}return{typeName:e,values:a,findName:e=>i[e],findNumber:e=>r[e]}}function E(e,t,n){const i={};for(const e of t){const t=N(e);i[t.localName]=t.no,i[t.no]=t.localName}return I(i,e,t),i}function N(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class C{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,r=i.makeReadOptions(t);return i.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function A(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function L(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,a=!(r>>>7==0&&0==t),o=255&(a?128|r:r);if(n.push(o),!a)return}const i=e>>>28&15|(7&t)<<4,r=!(t>>3==0);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),a=255&(r?128|i:i);if(n.push(a),!r)return}n.push(t>>>31&1)}}const O=4294967296;function U(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function a(t,a){const o=Number(e.slice(t,a));r*=n,i=i*n+o,i>=O&&(r+=i/O|0,i%=O)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?R(i,r):D(i,r)}function F(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(O*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let r=(16777215&e)+6777216*n+6710656*i,a=n+8147497*i,o=2*i;const s=1e7;return r>=s&&(a+=Math.floor(r/s),r%=s),a>=s&&(o+=Math.floor(a/s),a%=s),o.toString()+P(a)+P(r)}function D(e,t){return{lo:0|e,hi:0|t}}function R(e,t){return t=~t,e?e=1+~e:t+=1,D(e,t)}const P=e=>{const t=String(e);return"0000000".slice(t.length)+t};function x(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 B(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const _=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("int64 invalid: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<i)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>h(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>h(/^[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),U(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),U(e)),dec:(e,t)=>function(e,t){let n=D(e,t);const i=2147483648&n.hi;i&&(n=R(n.lo,n.hi));const r=F(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>F(e,t)}}();var M,K,V;function j(e,t,n){if(t===n)return!0;if(e==M.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return t==n}return!1}function G(e,t){switch(e){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return 0==t?_.zero:"0";case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}function q(e,t){switch(e){case M.BOOL:return!1===t;case M.STRING:return""===t;case M.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(M||(M={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(K||(K={})),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"}(V||(V={}));class J{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(v(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return b(e),x(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){k(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){v(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){b(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return b(e),x(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=_.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=_.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=_.enc(e);return L(t.lo,t.hi,this.buf),this}sint64(e){let t=_.enc(e),n=t.hi>>31;return L(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=_.uEnc(e);return L(t.lo,t.hi,this.buf),this}}class X{constructor(e,t){this.varint64=A,this.uint32=B,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 V.Varint:for(;128&this.buf[this.pos++];);break;case V.Bit64:this.pos+=4;case V.Bit32:this.pos+=4;break;case V.LengthDelimited:let n=this.uint32();this.pos+=n;break;case V.StartGroup:for(;;){const[e,n]=this.tag();if(n===V.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return _.dec(...this.varint64())}uint64(){return _.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,_.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return _.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return _.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 W(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 G(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 H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Y=[];for(let e=0;e<H.length;e++)Y[H[e].charCodeAt(0)]=e;Y["-".charCodeAt(0)]=H.indexOf("+"),Y["_".charCodeAt(0)]=H.indexOf("/");const z={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,i=new Uint8Array(t),r=0,a=0,o=0;for(let t=0;t<e.length;t++){if(n=Y[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:i[r++]=o<<2|(48&n)>>4,o=n,a=2;break;case 2:i[r++]=(15&o)<<4|(60&n)>>2,o=n,a=3;break;case 3:i[r++]=(3&o)<<6|n,a=0}}if(1==a)throw Error("invalid base64 string.");return i.subarray(0,r)},enc(e){let t,n="",i=0,r=0;for(let a=0;a<e.length;a++)switch(t=e[a],i){case 0:n+=H[t>>2],r=(3&t)<<4,i=1;break;case 1:n+=H[r|t>>4],r=(15&t)<<2,i=2;break;case 2:n+=H[r|t>>6],n+=H[63&t],i=0}return i&&(n+=H[r],n+="=",1==i&&(n+="=")),n}};function Q(e,t,n){ee(t,e);const i=t.runtime.bin.makeReadOptions(n),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=W(t);for(const e of r)t.runtime.bin.readField(a,i.readerFactory(e.data),t.field,e.wireType,i);return o()}function $(e,t,n,i){ee(t,e);const r=t.runtime.bin.makeReadOptions(i),a=t.runtime.bin.makeWriteOptions(i);if(Z(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=r.readerFactory(o.finish());for(;c.pos<c.len;){const[t,n]=c.tag(),i=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,i)}}function Z(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 ee(e,t){h(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function te(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:!q(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function ne(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?G(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function ie(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(C.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 re(e,t){return ie(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}M.DOUBLE,M.FLOAT,M.INT64,M.UINT64,M.INT32,M.UINT32,M.BOOL,M.STRING,M.BYTES;const ae={ignoreUnknownFields:!1},oe={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function se(e){return e?Object.assign(Object.assign({},ae),e):ae}function ce(e){return e?Object.assign(Object.assign({},oe),e):oe}const ue=Symbol(),de=Symbol();function le(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 he(e,t,n,i,r){let a=n.localName;if(n.repeated){if(h("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(t)));const o=e[a];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(e)));switch(n.kind){case"message":o.push(n.T.fromJson(e,i));break;case"enum":const t=ye(n.T,e,i.ignoreUnknownFields,!0);t!==de&&o.push(t);break;case"scalar":try{o.push(pe(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(t)));const o=e[a];for(const[e,a]of Object.entries(t)){if(null===a)throw new Error("cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: map value null"));let s;try{s=fe(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":o[s]=n.V.T.fromJson(a,i);break;case"enum":const e=ye(n.V.T,a,i.ignoreUnknownFields,!0);e!==de&&(o[s]=e);break;case"scalar":try{o[s]=pe(n.V.T,a,K.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a="value"),n.kind){case"message":const o=n.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let s=e[a];ie(s)?s.fromJson(t,i):(e[a]=s=o.fromJson(t,i),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case"enum":const c=ye(n.T,t,i.ignoreUnknownFields,!1);switch(c){case ue:ne(n,e);break;case de:break;default:e[a]=c}break;case"scalar":try{const i=pe(n.T,t,n.L,!1);if(i===ue)ne(n,e);else e[a]=i}catch(e){let i="cannot decode field ".concat(r.typeName,".").concat(n.name," from JSON: ").concat(le(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function fe(e,t){if(e===M.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return pe(e,t,K.BIGINT,!0).toString()}function pe(e,t,n,i){if(null===t)return i?G(e,n):ue;switch(e){case M.DOUBLE:case M.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const i=Number(t);if(Number.isNaN(i))break;if(!Number.isFinite(i))break;return e==M.FLOAT&&k(i),i;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==M.UINT32||e==M.FIXED32?v(r):b(r),r;case M.INT64:case M.SFIXED64:case M.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=_.parse(t);return n?a.toString():a;case M.FIXED64:case M.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=_.uParse(t);return n?o.toString():o;case M.BOOL:if("boolean"!=typeof t)break;return t;case M.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case M.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return z.dec(t)}throw new Error}function ye(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:ue;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(void 0!==i)return i.no;if(n)return de}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(le(t)))}function me(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function ge(e,t,n){if("map"==e.kind){h("object"==typeof t&&null!=t);const i={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of r)i[t.toString()]=ve(e.V.T,n);break;case"message":for(const[e,t]of r)i[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,a]of r)i[e.toString()]=be(t,a,n.enumAsInteger)}return n.emitDefaultValues||r.length>0?i:void 0}if(e.repeated){h(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++)i.push(ve(e.T,t[n]));break;case"enum":for(let r=0;r<t.length;r++)i.push(be(e.T,t[r],n.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)i.push(t[e].toJson(n))}return n.emitDefaultValues||i.length>0?i:void 0}switch(e.kind){case"scalar":return ve(e.T,t);case"enum":return be(e.T,t,n.enumAsInteger);case"message":return re(e.T,t).toJson(n)}}function be(e,t,n){var i;if(h("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.findNumber(t);return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function ve(e,t){switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:case M.FIXED32:case M.UINT32:return h("number"==typeof t),t;case M.FLOAT:case M.DOUBLE:return h("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case M.STRING:return h("string"==typeof t),t;case M.BOOL:return h("boolean"==typeof t),t;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return h("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case M.BYTES:return h(t instanceof Uint8Array),z.enc(t)}}const ke=Symbol("@bufbuild/protobuf/unknown-fields"),we={readUnknownFields:!0,readerFactory:e=>new X(e)},Se={writeUnknownFields:!0,writerFactory:()=>new J};function Ie(e){return e?Object.assign(Object.assign({},we),e):we}function Te(e){return e?Object.assign(Object.assign({},Se),e):Se}function Ee(e,t,n,i,r){let{repeated:a,localName:o}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),n.kind){case"scalar":case"enum":const s="enum"==n.kind?M.INT32:n.T;let c=Ae;if("scalar"==n.kind&&n.L>0&&(c=Ce),a){let n=e[o];if(i==V.LengthDelimited&&s!=M.STRING&&s!=M.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 u=n.T;a?e[o].push(Ne(t,new u,r,n)):ie(e[o])?Ne(t,e[o],r,n):(e[o]=Ne(t,new u,r,n),!u.fieldWrapper||n.oneof||n.repeated||(e[o]=u.fieldWrapper.unwrapField(e[o])));break;case"map":let[d,l]=function(e,t,n){const i=t.uint32(),r=t.pos+i;let a,o;for(;t.pos<r;){const[i]=t.tag();switch(i){case 1:a=Ae(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Ae(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Ne(t,new e.V.T,n,void 0)}}}void 0===a&&(a=G(e.K,K.BIGINT));"string"!=typeof a&&"number"!=typeof a&&(a=a.toString());if(void 0===o)switch(e.V.kind){case"scalar":o=G(e.V.T,K.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[a,o]}(n,t,r);e[o][d]=l}}function Ne(e,t,n,i){const r=t.getType().runtime.bin,a=null==i?void 0:i.delimited;return r.readMessage(t,e,a?i.no:e.uint32(),n,a),t}function Ce(e,t){const n=Ae(e,t);return"bigint"==typeof n?n.toString():n}function Ae(e,t){switch(t){case M.STRING:return e.string();case M.BOOL:return e.bool();case M.DOUBLE:return e.double();case M.FLOAT:return e.float();case M.INT32:return e.int32();case M.INT64:return e.int64();case M.UINT64:return e.uint64();case M.FIXED64:return e.fixed64();case M.BYTES:return e.bytes();case M.FIXED32:return e.fixed32();case M.SFIXED32:return e.sfixed32();case M.SFIXED64:return e.sfixed64();case M.SINT64:return e.sint64();case M.UINT32:return e.uint32();case M.SINT32:return e.sint32()}}function Le(e,t,n,i){h(void 0!==t);const r=e.repeated;switch(e.kind){case"scalar":case"enum":let a="enum"==e.kind?M.INT32:e.T;if(r)if(h(Array.isArray(t)),e.packed)!function(e,t,n,i){if(!i.length)return;e.tag(n,V.LengthDelimited).fork();let[,r]=De(t);for(let t=0;t<i.length;t++)e[r](i[t]);e.join()}(n,a,e.no,t);else for(const i of t)Fe(n,a,e.no,i);else Fe(n,a,e.no,t);break;case"message":if(r){h(Array.isArray(t));for(const r of t)Ue(n,i,e,r)}else Ue(n,i,e,t);break;case"map":h("object"==typeof t&&null!=t);for(const[r,a]of Object.entries(t))Oe(n,i,e,r,a)}}function Oe(e,t,n,i,r){e.tag(n.no,V.LengthDelimited),e.fork();let a=i;switch(n.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:a=Number.parseInt(i);break;case M.BOOL:h("true"==i||"false"==i),a="true"==i}switch(Fe(e,n.K,1,a),n.V.kind){case"scalar":Fe(e,n.V.T,2,r);break;case"enum":Fe(e,M.INT32,2,r);break;case"message":h(void 0!==r),e.tag(2,V.LengthDelimited).bytes(r.toBinary(t))}e.join()}function Ue(e,t,n,i){const r=re(n.T,i);n.delimited?e.tag(n.no,V.StartGroup).raw(r.toBinary(t)).tag(n.no,V.EndGroup):e.tag(n.no,V.LengthDelimited).bytes(r.toBinary(t))}function Fe(e,t,n,i){h(void 0!==i);let[r,a]=De(t);e.tag(n,r)[a](i)}function De(e){let t=V.Varint;switch(e){case M.BYTES:case M.STRING:t=V.LengthDelimited;break;case M.DOUBLE:case M.FIXED64:case M.SFIXED64:t=V.Bit64;break;case M.FIXED32:case M.SFIXED32:case M.FLOAT:t=V.Bit32}return[t,M[e].toLowerCase()]}function Re(e){if(void 0===e)return e;if(ie(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Pe(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class xe{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 Be(e,t){const n=Me(e);return t?n:qe(Ge(n))}const _e=Me;function Me(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}const Ke=new Set(["constructor","toString","toJSON","valueOf"]),Ve=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),je=e=>"".concat(e,"$"),Ge=e=>Ve.has(e)?je(e):e,qe=e=>Ke.has(e)?je(e):e;class Je{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Be(e,!1)}addField(e){h(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 Xe=(We=e=>new xe(e,(e=>function(e,t){var n,i,r,a,o,s;const c=[];let u;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=Be(t.name,void 0!==t.oneof),e.jsonName=null!==(n=t.jsonName)&&void 0!==n?n:_e(t.name),e.repeated=null!==(i=t.repeated)&&void 0!==i&&i,"scalar"==t.kind&&(e.L=null!==(r=t.L)&&void 0!==r?r:K.BIGINT),e.delimited=null!==(a=t.delimited)&&void 0!==a&&a,e.req=null!==(o=t.req)&&void 0!==o&&o,e.opt=null!==(s=t.opt)&&void 0!==s&&s,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=M.BYTES&&t.T!=M.STRING),void 0!==t.oneof){const n="string"==typeof t.oneof?t.oneof:t.oneof.name;u&&u.name==n||(u=new Je(n)),e.oneof=u,u.addField(e)}c.push(e)}return c}(e))),He=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=G(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:se,makeWriteOptions:ce,readMessage(e,t,n,i){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(le(t)));i=null!=i?i:new e;const r=new Map,a=n.typeRegistry;for(const[o,s]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===s&&"scalar"==t.kind)continue;const n=r.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(o,'"'));r.set(t.oneof,o)}he(i,s,t,n,e)}else{let t=!1;if((null==a?void 0:a.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const r=a.findExtension(o.substring(1,o.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;const[e,a]=W(r);he(e,s,r.field,n,r),$(i,r,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let r;try{for(r of n.fields.byNumber()){if(!te(r,e)){if(r.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!me(r))continue}const n=ge(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t);void 0!==n&&(i[t.useProtoFieldName?r.name:r.jsonName]=n)}const a=t.typeRegistry;if(null==a?void 0:a.findExtensionFor)for(const r of n.runtime.bin.listUnknownFields(e)){const o=a.findExtensionFor(n.typeName,r.no);if(o&&Z(e,o)){const n=Q(e,o,t),r=ge(o.field,n,t);void 0!==r&&(i[o.field.jsonName]=r)}}}catch(e){const t=r?"cannot encode field ".concat(n.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>pe(e,t,null!=n?n:K.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||q(e,t)?ve(e,t):void 0},debug:le},bin:{makeReadOptions:Ie,makeWriteOptions:Te,listUnknownFields(e){var t;return null!==(t=e[ke])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ke]},writeUnknownFields(e,t){const n=e[ke];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const r=e;Array.isArray(r[ke])||(r[ke]=[]),r[ke].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,r){const a=e.getType(),o=r?t.len:t.pos+n;let s,c;for(;t.pos<o&&([s,c]=t.tag(),!0!==r||c!=V.EndGroup);){const n=a.fields.find(s);if(n)Ee(e,t,n,c,i);else{const n=t.skip(c,s);i.readUnknownFields&&this.onUnknownField(e,s,c,n)}}if(r&&(c!=V.EndGroup||s!==n))throw new Error("invalid end group tag")},readField:Ee,writeMessage(e,t,n){const i=e.getType();for(const r of i.fields.byNumber())if(te(r,e))Le(r,r.oneof?e[r.oneof.localName].value:e[r.localName],t,n);else if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,i){void 0!==t&&Le(e,t,n,i)}},util:Object.assign(Object.assign({},{setEnumType:I,initPartial(e,t){if(void 0===e)return;const n=t.getType();for(const i of n.fields.byMember()){const n=i.localName,r=t,a=e;if(null!=a[n])switch(i.kind){case"oneof":const e=a[n].case;if(void 0===e)continue;const t=i.findField(e);let o=a[n].value;t&&"message"==t.kind&&!ie(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===M.BYTES&&(o=Pe(o)),r[n]={case:e,value:o};break;case"scalar":case"enum":let s=a[n];i.T===M.BYTES&&(s=i.repeated?s.map(Pe):Pe(s)),r[n]=s;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===M.BYTES)for(const[e,t]of Object.entries(a[n]))r[n][e]=Pe(t);else Object.assign(r[n],a[n]);break;case"message":const e=i.V.T;for(const t of Object.keys(a[n])){let i=a[n][t];e.fieldWrapper||(i=new e(i)),r[n][t]=i}}break;case"message":const c=i.T;if(i.repeated)r[n]=a[n].map((e=>ie(e,c)?e:new c(e)));else{const e=a[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?r[n]=Pe(e):r[n]=e:r[n]=ie(e,c)?e:new c(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],r=n[e.localName];if(e.repeated){if(i.length!==r.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,r[n])));case"scalar":return i.every(((t,n)=>j(e.T,t,r[n])));case"enum":return i.every(((e,t)=>j(M.INT32,e,r[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(i,r);case"enum":return j(M.INT32,i,r);case"scalar":return j(e.T,i,r);case"oneof":if(i.case!==r.case)return!1;const t=e.findField(i.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(i.value,r.value);case"enum":return j(M.INT32,i.value,r.value);case"scalar":return j(t.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const n=Object.keys(i).concat(Object.keys(r));switch(e.V.kind){case"message":const t=e.V.T;return n.every((e=>t.equals(i[e],r[e])));case"enum":return n.every((e=>j(M.INT32,i[e],r[e])));case"scalar":const a=e.V.T;return n.every((e=>j(a,i[e],r[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let r;if(n.repeated)r=t.map(Re);else if("map"==n.kind){r=i[n.localName];for(const[e,n]of Object.entries(t))r[e]=Re(n)}else r="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Re(t.value)}:{case:void 0}:Re(t);i[n.localName]=r}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:We,initFields:He}),makeMessageType(e,t,n){return function(e,t,n,i){var r;const a=null!==(r=null==i?void 0:i.localName)&&void 0!==r?r: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 C),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:E,makeEnumType:T,getEnumType:S,makeExtension(e,t,n){return function(e,t,n,i){let r;return{typeName:t,extendee:n,get field(){if(!r){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),r=e.util.newFieldList([n]).list()[0]}return r},runtime:e}}(this,e,t,n)}});var We,He;const Ye=Xe.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ze=Xe.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"}]),Qe=Xe.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),$e=/version\/(\d+(\.?_?\d+)+)/i;let Ze;function et(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===Ze||t){const e=tt.find((e=>{let{test:t}=e;return t.test(n)}));Ze=null==e?void 0:e.describe(n)}return Ze}const tt=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:nt(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:it(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:nt(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:it(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:nt($e,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:it(e)})}];function nt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function it(e){return e.includes("mac os")?nt(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class rt{constructor(e,t,n,i,r){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,priority:r}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}var at;!function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:2e4},e.music={maxBitrate:32e3},e.musicStereo={maxBitrate:48e3},e.musicHighQuality={maxBitrate:64e3},e.musicHighQualityStereo={maxBitrate:96e3}}(at||(at={})),new rt(160,90,9e4,20),new rt(320,180,16e4,20),new rt(384,216,18e4,20),new rt(640,360,45e4,20),new rt(960,540,8e5,25),new rt(1280,720,17e5,30),new rt(1920,1080,3e6,30),new rt(2560,1440,5e6,30),new rt(3840,2160,8e6,30),new rt(160,120,7e4,20),new rt(240,180,125e3,20),new rt(320,240,14e4,20),new rt(480,360,33e4,20),new rt(640,480,5e5,20),new rt(720,540,6e5,25),new rt(960,720,13e5,30),new rt(1440,1080,23e5,30),new rt(1920,1440,38e5,30),new rt(640,360,2e5,3,"medium"),new rt(640,360,4e5,15,"medium"),new rt(1280,720,8e5,5,"medium"),new rt(1280,720,15e5,15,"medium"),new rt(1280,720,2e6,30,"medium"),new rt(1920,1080,25e5,15,"medium"),new rt(1920,1080,5e6,30,"medium"),new rt(0,0,7e6,30,"medium");var ot,st={exports:{}};var ct,ut,dt,lt,ht=function(){if(ot)return st.exports;ot=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}st.exports=r,st.exports.once=function(e,t){return new Promise((function(n,i){function r(n){e.removeListener(t,a),i(n)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",r),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,r,{once:!0})}))},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.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?r.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var r,a,c,u;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]=i?[n,c]:[c,n]:i?c.unshift(n):c.push(n),(r=s(e))>0&&c.length>r&&!c.warned){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,u=d,console&&console.warn&&console.warn(u)}return e}function u(){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 d(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=u.bind(i);return r.listener=n,i.wrapFn=r,r}function l(e,t,n){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?n?[r.listener||r]:[r]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(r):f(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function p(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(a){i.once&&e.removeEventListener(t,r),n(a)}))}}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),r.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return s(this)},r.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,a=this._events;if(void 0!==a)r=r&&void 0===a.error;else if(!r)return!1;if(r){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 u=c.length,d=f(c,u);for(i=0;i<u;++i)n(d[i],this,t)}return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,i,r,a,s;if(o(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){s=n[a].listener,r=a;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,r),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,s||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var r,a=Object.keys(n);for(i=0;i<a.length;++i)"removeListener"!==(r=a[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},r.prototype.listeners=function(e){return l(this,e,!0)},r.prototype.rawListeners=function(e){return l(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},st.exports}();!function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",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.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"}(ct||(ct={})),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.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.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage"}(ut||(ut={})),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"}(dt||(dt={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",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"}(lt||(lt={}));const ft=[];var pt,yt;!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(pt||(pt={}));class mt extends ht.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=mt.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=u,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=d(null!==(i=n.loggerName)&&void 0!==i?i:s.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=mt.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===mt.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===mt.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(ft.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&ft.splice(ft.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),function(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks();i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e));vt()&&t instanceof HTMLVideoElement||(t.autoplay=!0);t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0);t.srcObject!==n&&(t.srcObject=n,(vt()||"Firefox"===(null===(r=et())||void 0===r?void 0:r.name))&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0));var r}(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),i=n.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(i?lt.AudioPlaybackStarted:lt.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(i?lt.AudioPlaybackFailed:lt.VideoPlaybackFailed,t):"AbortError"===t.name?u.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):u.warn("could not playback ".concat(i?"audio":"video"),t),i&&e&&n.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(lt.ElementAttached,e),e}detach(e){try{if(e){gt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(lt.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{gt(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(lt.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=d(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),ft.forEach((e=>{e.parentElement||(t=!1)})),t&&ft.push(e)}}handleAppVisibilityChanged(){return e(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==mt.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){kt()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){kt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function gt(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 bt(e){return e instanceof mt?{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 vt(){var e;return"Safari"===(null===(e=et())||void 0===e?void 0:e.name)}function kt(){return"undefined"!=typeof document}!function(e){let t,n,i;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Ye.AUDIO;case t.Video:return Ye.VIDEO;default:return Ye.DATA}},e.kindFromProto=function(e){switch(e){case Ye.AUDIO:return t.Audio;case Ye.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return ze.CAMERA;case n.Microphone:return ze.MICROPHONE;case n.ScreenShare:return ze.SCREEN_SHARE;case n.ScreenShareAudio:return ze.SCREEN_SHARE_AUDIO;default:return ze.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case ze.CAMERA:return n.Camera;case ze.MICROPHONE:return n.Microphone;case ze.SCREEN_SHARE:return n.ScreenShare;case ze.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Qe.ACTIVE:return i.Active;case Qe.PAUSED:return i.Paused;default:return i.Unknown}}}(mt||(mt={}));class wt{constructor(){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"}(yt||(yt={}));const St="AES-GCM",It={key:10,delta:3,audio:1,empty:0},Tt={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};class Et extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}var Nt,Ct,At,Lt,Ot,Ut,Ft;!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"}(Nt||(Nt={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(Ct||(Ct={})),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}}(Ct||(Ct={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(At||(At={}));class Dt extends Et{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:At.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}function Rt(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 Pt(t,n){return e(this,void 0,void 0,(function*(){const e=Rt(t.algorithm.name,n),i=yield crypto.subtle.deriveKey(e,t,{name:St,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:i}}))}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(Lt||(Lt={})),function(e){e.KeyRatcheted="keyRatcheted"}(Ot||(Ot={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(Ut||(Ut={})),function(e){e.Error="cryptorError"}(Ft||(Ft={}));class xt{constructor(){this.consecutiveSifCount=0,this.lastSifReceivedAt=0,this.userFramesSinceSif=0}recordSif(){var e;this.consecutiveSifCount+=1,null!==(e=this.sifSequenceStartedAt)&&void 0!==e||(this.sifSequenceStartedAt=Date.now()),this.lastSifReceivedAt=Date.now()}recordUserFrame(){void 0!==this.sifSequenceStartedAt&&(this.userFramesSinceSif+=1,(this.userFramesSinceSif>this.consecutiveSifCount||Date.now()-this.lastSifReceivedAt>2e3)&&this.reset())}isSifAllowed(){return this.consecutiveSifCount<100&&(void 0===this.sifSequenceStartedAt||Date.now()-this.sifSequenceStartedAt<2e3)}reset(){this.userFramesSinceSif=0,this.consecutiveSifCount=0,this.sifSequenceStartedAt=void 0}}const Bt=new Map;class _t extends ht.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class Mt extends _t{constructor(e){var t;super(),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([]),this.sifGuard=new xt}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),{participant:e})),this.participantIdentity&&l.error("cryptor has already a participant set, participant should have been unset before",Object.assign({},this.logContext)),this.participantIdentity=e,this.keys=t,this.sifGuard.reset()}unsetParticipant(){l.debug("unsetting participant",this.logContext),this.participantIdentity=void 0}isEnabled(){return this.participantIdentity?Bt.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,i,r){r&&(l.info("setting codec on cryptor to",{codec:r}),this.videoCodec=r),l.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:i,codec:r},this.logContext));const a="encode"===e?this.encodeFunction:this.decodeFunction,o=new TransformStream({transform:a.bind(this)});t.pipeThrough(o).pipeTo(n).catch((e=>{l.warn(e),this.emit(Ft.Error,e instanceof Dt?e:new Dt(e.message,void 0,this.participantIdentity))})),this.trackId=i}setSifTrailer(e){l.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const i=this.keys.getKeySet();if(!i)return void this.emit(Ft.Error,new Dt("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),At.MissingKey,this.participantIdentity));const{encryptionKey:r}=i,a=this.keys.getCurrentKeyIndex();if(r){const i=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),u=new Uint8Array(2);u[0]=12,u[1]=a;try{const e=yield crypto.subtle.encrypt({name:St,iv:i,additionalData:new Uint8Array(t.data,0,c.byteLength)},r,new Uint8Array(t.data,s.unencryptedBytes));let a=new Uint8Array(e.byteLength+i.byteLength+u.byteLength);a.set(new Uint8Array(e)),a.set(new Uint8Array(i),e.byteLength),a.set(u,e.byteLength+i.byteLength),s.isH264&&(a=function(e){const t=[];for(var n=0,i=0;i<e.length;++i){var r=e[i];r<=3&&n>=2&&(t.push(3),n=0),t.push(r),0==r?++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,n.enqueue(t)}catch(e){l.error(e)}}else l.debug("failed to encrypt, emitting error",this.logContext),this.emit(Ft.Error,new Dt("encryption key missing for encoding",At.MissingKey,this.participantIdentity))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.isEnabled()||0===t.data.byteLength)return l.debug("skipping empty frame",this.logContext),this.sifGuard.recordUserFrame(),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 l.debug("enqueue SIF",this.logContext),this.sifGuard.recordSif(),this.sifGuard.isSifAllowed()?(t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),n.enqueue(t)):void l.warn("SIF limit reached, dropping frame");this.sifGuard.recordUserFrame();const e=new Uint8Array(t.data)[t.data.byteLength-1];if(this.keys.getKeySet(e)&&this.keys.hasValidKey)try{const i=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(),i)return n.enqueue(i)}catch(e){e instanceof Dt&&e.reason===At.InvalidKey?this.keys.hasValidKey&&(this.emit(Ft.Error,e),this.keys.decryptionFailure()):l.warn("decoding frame failed",{error:e})}else!this.keys.getKeySet(e)&&this.keys.hasValidKey&&(l.warn("skipping decryption due to missing key at index ".concat(e)),this.emit(Ft.Error,new Dt("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),At.MissingKey,this.participantIdentity)),this.keys.decryptionFailure())}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var a;const o=n.keys.getKeySet(t);if(!r.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.isH264&&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,i=0;i<e.length;)n-i>=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)}(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),i=n[0],u=new Uint8Array(e.data,e.data.byteLength-i-n.byteLength,i),d=t.byteLength,l=e.data.byteLength-(t.byteLength+i+n.byteLength),h=yield crypto.subtle.decrypt({name:St,iv:u,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(a=r.encryptionKey)&&void 0!==a?a:o.encryptionKey,new Uint8Array(e.data,d,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(r.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let a;if(l.debug("ratcheting key attempt ".concat(r.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=i?i:o)===n.keys.getKeySet(t)){const e=yield n.keys.ratchetKey(t,!1);a=yield Pt(e,n.keyProviderOptions.ratchetSalt)}const s=yield n.decryptFrame(e,t,i||o,{ratchetCount:r.ratchetCount+1,encryptionKey:null==a?void 0:a.encryptionKey});return s&&a&&(null!=i?i:o)===n.keys.getKeySet(t)&&(n.keys.setKeySet(a,t,!0),n.keys.setCurrentKeyIndex(t)),s}throw l.warn("maximum ratchet attempts exceeded"),new Dt("valid key missing for participant ".concat(n.participantIdentity),At.InvalidKey,n.participantIdentity)}throw new Dt("Decryption failed: ".concat(a.message),At.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const i=new ArrayBuffer(12),r=new DataView(i);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 r.setUint32(0,e),r.setUint32(4,t),r.setUint32(8,t-a%65535),this.sendCounts.set(e,a+1),i}getUnencryptedBytes(e){var t,n={unencryptedBytes:0,isH264:!1};if(function(e){return"type"in e}(e)){let i=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(i!==this.detectedCodec&&(l.debug("detected different codec",Object.assign({detectedCodec:i,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=i),"av1"===i)throw new Error("".concat(i," is not yet supported for end to end encryption"));if("vp8"===i)n.unencryptedBytes=It[e.type];else if("vp9"===i)return n.unencryptedBytes=0,n;const r=new Uint8Array(e.data);try{const e=function(e){const t=[];let n=0,i=0,r=e.length-2;for(;i<r;){for(;i<r&&(0!==e[i]||0!==e[i+1]||1!==e[i+2]);)i++;i>=r&&(i=e.length);let a=i;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);n=i+=3}return t}(r);if(n.isH264="h264"===i||e.some((e=>[jt.SLICE_IDR,jt.SLICE_NON_IDR].includes(Kt(r[e])))),n.isH264){for(const t of e){switch(Kt(r[t])){case jt.SLICE_IDR:case jt.SLICE_NON_IDR:return n.unencryptedBytes=t+2,n}}throw new TypeError("Could not find NALU")}}catch(e){}return n.unencryptedBytes=It[e.type],n}return n.unencryptedBytes=It.audio,n}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}function Kt(e){return e&Vt}const Vt=31;var jt;!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"}(jt||(jt={}));class Gt extends ht.EventEmitter{get hasValidKey(){return this._hasValidKey}constructor(e,t){if(super(),this.decryptionFailureCount=0,this._hasValidKey=!0,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.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e,this.resetKeyStatus()}decryptionFailure(){this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCount+=1,this.decryptionFailureCount>this.keyProviderOptions.failureTolerance&&(l.warn("key for ".concat(this.participantIdentity," is being marked as invalid")),this._hasValidKey=!1))}decryptionSuccess(){this.resetKeyStatus()}resetKeyStatus(){this.decryptionFailureCount=0,this._hasValidKey=!0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const i=null!=t?t:this.getCurrentKeyIndex(),r=this.ratchetPromiseMap.get(i);if(void 0!==r)return r;const a=new Promise(((t,r)=>e(this,void 0,void 0,(function*(){try{const r=this.getKeySet(i);if(!r)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const a=r.material,o=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:St},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"])}()}))}(yield function(t,n){return e(this,void 0,void 0,(function*(){const e=Rt(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(a,this.keyProviderOptions.ratchetSalt),a.algorithm.name,"derive");n&&(this.setKeyFromMaterial(o,i,!0),this.emit(Ot.KeyRatcheted,o,this.participantIdentity,i)),t(o)}catch(e){r(e)}finally{this.ratchetPromiseMap.delete(i)}}))));return this.ratchetPromiseMap.set(i,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;return function*(){yield t.setKeyFromMaterial(e,n),t.resetKeyStatus()}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){const r=yield Pt(e,n.keyProviderOptions.ratchetSalt),a=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(r,a,i),a>=0&&(n.currentKeyIndex=a)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(Ot.KeyRatcheted,e.material,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus()}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const qt=[],Jt=new Map;let Xt,Wt,Ht=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new wt,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:yt.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=yt.RUNNING,yield t()}finally{e.status=yt.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())}},Yt=!1,zt=Tt,Qt=new Map;function $t(e,t){let n=qt.filter((e=>e.getTrackId()===t));if(n.length>1){const i=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");l.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:i})}let i=n[0];if(i)e!==i.getParticipantIdentity()&&i.setParticipant(e,Zt(e));else{if(l.info("creating new cryptor for",{participantIdentity:e}),!zt)throw Error("Missing keyProvider options");i=new Mt({participantIdentity:e,keys:Zt(e),keyProviderOptions:zt,sifTrailer:Wt}),i.setRtpMap(Qt),function(e){e.on(Ft.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(At[e.reason],": ").concat(e.message))}};postMessage(t)}))}(i),qt.push(i)}return i}function Zt(e){if(Yt)return en();let t=Jt.get(e);return t||(t=new Gt(e,zt),t.on(Ot.KeyRatcheted,tn),Jt.set(e,t)),t}function en(){return Xt||(l.debug("creating new shared key handler"),Xt=new Gt("shared-key",zt)),Xt}function tn(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,material:e}})}l.setDefaultLevel("info"),onmessage=t=>{Ht.run((()=>e(void 0,void 0,void 0,(function*(){const{kind:n,data:i}=t.data;switch(n){case"init":l.setLevel(i.loglevel),l.info("worker initialized"),zt=i.keyProviderOptions,Yt=!!i.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":a=i.enabled,o=i.participantIdentity,l.debug("setting encryption enabled for all tracks of ".concat(o),{enable:a}),Bt.set(o,a),l.info("updated e2ee enabled status for ".concat(i.participantIdentity," to ").concat(i.enabled)),postMessage(t.data);break;case"decode":$t(i.participantIdentity,i.trackId).setupTransform(n,i.readableStream,i.writableStream,i.trackId,i.codec);break;case"encode":$t(i.participantIdentity,i.trackId).setupTransform(n,i.readableStream,i.writableStream,i.trackId,i.codec);break;case"setKey":Yt?yield function(t,n){return e(this,void 0,void 0,(function*(){l.info("set shared key",{index:n}),yield en().setKey(t,n)}))}(i.key,i.keyIndex):i.participantIdentity?(l.info("set participant sender key ".concat(i.participantIdentity," index ").concat(i.keyIndex)),yield Zt(i.participantIdentity).setKey(i.key,i.keyIndex)):l.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=qt.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 i=n[0];i?i.unsetParticipant():l.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(i.trackId,i.participantIdentity);break;case"updateCodec":$t(i.participantIdentity,i.trackId).setVideoCodec(i.codec);break;case"setRTPMap":Qt=i.map,qt.forEach((e=>{e.getParticipantIdentity()===i.participantIdentity&&e.setRtpMap(i.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(Yt){const e=en();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=Zt(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":r=i.trailer,Wt=r,qt.forEach((e=>{e.setSifTrailer(r)}))}var r,a,o}))))},self.RTCTransformEvent&&(l.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;l.debug("transformer",t),t.handled=!0;const{kind:n,participantIdentity:i,trackId:r,codec:a}=t.options,o=$t(i,r);l.debug("transform",{codec:a}),o.setupTransform(n,t.readable,t.writable,r,a)})}));
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,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(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(s,a)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,o,s,a,c=(t||(t=1,i=n.exports,o=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={},o=null;function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),i=0;i<r.length;i++){var o=r[i];this[o]=i<n?e:this.methodFactory(o,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,o){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?a:void 0!==console[r]?s(console,r):void 0!==console.log?s(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var s,a,d,l=this,y="loglevel";function p(){var e;if(typeof window!==t&&y){try{e=window.localStorage[y]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(y),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 h(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?y+=":"+e:"symbol"==typeof e&&(y=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!=a?a:s},l.setLevel=function(e,n){return d=h(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&y){try{return void(window.localStorage[y]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){a=h(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==t&&y){try{window.localStorage.removeItem(y)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"=; 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(o!==l&&(s=h(o.getLevel())),c.call(l),o===l)for(var e in i)i[e].rebuild()},s=h(o?o.getLevel():"WARN");var f=p();null!=f&&(d=h(f)),c.call(l)}(o=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,o.methodFactory)),t};var y=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return i},o.default=o,o},(r=n).exports?r.exports=o():i.log=o()),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"}(s||(s={})),function(e){e.Default="livekit",e.Room="livekit-room",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"}(a||(a={}));let d=c.getLogger("livekit");Object.values(a).map((e=>c.getLogger(e))),d.setDefaultLevel(s.info);const u=c.getLogger("lk-e2ee");var l,y=Object.defineProperty,p=(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 h{constructor(){p(this,"_locking"),p(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"}(l||(l={}));const f="AES-GCM",v={key:10,delta:3,audio:1,empty:0},g={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};class m extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}var w,I,b,k,S,L,E;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest"}(w||(w={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(I||(I={})),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}}(I||(I={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(b||(b={}));class C extends m{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b.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"}(k||(k={})),function(e){e.KeyRatcheted="keyRatcheted"}(S||(S={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(L||(L={})),function(e){e.Error="cryptorError"}(E||(E={}));var T,A={exports:{}};var K=function(){if(T)return A.exports;T=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)}A.exports=i,A.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(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 o=10;function s(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,c,d;if(s(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),c=o[t]),void 0===c)c=o[t]=n,++e._eventsCount;else if("function"==typeof c?c=o[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=a(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):p(i,i.length)}function y(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(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(o){r.once&&e.removeEventListener(t,i),n(o)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},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+".");o=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 a(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=p(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 s(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,o,a;if(s(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,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;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,a||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,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[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):y.call(e,t)},i.prototype.listenerCount=y,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},A.exports}();function _(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 x(t,n){return e(this,void 0,void 0,(function*(){const e=_(t.algorithm.name,n),r=yield crypto.subtle.deriveKey(e,t,{name:f,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}class P{constructor(){this.consecutiveSifCount=0,this.lastSifReceivedAt=0,this.userFramesSinceSif=0}recordSif(){var e;this.consecutiveSifCount+=1,null!==(e=this.sifSequenceStartedAt)&&void 0!==e||(this.sifSequenceStartedAt=Date.now()),this.lastSifReceivedAt=Date.now()}recordUserFrame(){void 0!==this.sifSequenceStartedAt&&(this.userFramesSinceSif+=1,(this.userFramesSinceSif>this.consecutiveSifCount||Date.now()-this.lastSifReceivedAt>2e3)&&this.reset())}isSifAllowed(){return this.consecutiveSifCount<100&&(void 0===this.sifSequenceStartedAt||Date.now()-this.sifSequenceStartedAt<2e3)}reset(){this.userFramesSinceSif=0,this.consecutiveSifCount=0,this.sifSequenceStartedAt=void 0}}const R=new Map;class O extends K.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class F extends O{constructor(e){var t;super(),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([]),this.sifGuard=new P}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){u.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{participant:e})),this.participantIdentity&&u.error("cryptor has already a participant set, participant should have been unset before",Object.assign({},this.logContext)),this.participantIdentity=e,this.keys=t,this.sifGuard.reset()}unsetParticipant(){u.debug("unsetting participant",this.logContext),this.participantIdentity=void 0}isEnabled(){return this.participantIdentity?R.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i){i&&(u.info("setting codec on cryptor to",{codec:i}),this.videoCodec=i),u.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:i},this.logContext));const o="encode"===e?this.encodeFunction:this.decodeFunction,s=new TransformStream({transform:o.bind(this)});t.pipeThrough(s).pipeTo(n).catch((e=>{u.warn(e),this.emit(E.Error,e instanceof C?e:new C(e.message,void 0,this.participantIdentity))})),this.trackId=r}setSifTrailer(e){u.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emit(E.Error,new C("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),b.MissingKey,this.participantIdentity));const{encryptionKey:i}=r,o=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let a=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,a.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=o;try{const e=yield crypto.subtle.encrypt({name:f,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,a.unencryptedBytes));let o=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);o.set(new Uint8Array(e)),o.set(new Uint8Array(r),e.byteLength),o.set(d,e.byteLength+r.byteLength),a.isH264&&(o=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)}(o));var s=new Uint8Array(c.byteLength+o.byteLength);return s.set(c),s.set(o,c.byteLength),t.data=s.buffer,n.enqueue(t)}catch(e){u.error(e)}}else u.debug("failed to encrypt, emitting error",this.logContext),this.emit(E.Error,new C("encryption key missing for encoding",b.MissingKey,this.participantIdentity))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.isEnabled()||0===t.data.byteLength)return u.debug("skipping empty frame",this.logContext),this.sifGuard.recordUserFrame(),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 u.debug("enqueue SIF",this.logContext),this.sifGuard.recordSif(),this.sifGuard.isSifAllowed()?(t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),n.enqueue(t)):void u.warn("SIF limit reached, dropping frame");this.sifGuard.recordUserFrame();const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof C&&t.reason===b.InvalidKey?this.keys.hasValidKey&&(this.emit(E.Error,t),this.keys.decryptionFailure(e)):u.warn("decoding frame failed",{error:t})}else u.warn("skipping decryption due to missing key at index ".concat(e)),this.emit(E.Error,new C("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),b.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)}))}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 o;const s=n.keys.getKeySet(t);if(!i.encryptionKey&&!s)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let a=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,a.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(a.isH264&&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),y=yield crypto.subtle.decrypt({name:f,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:s.encryptionKey,new Uint8Array(e.data,u,l)),p=new ArrayBuffer(t.byteLength+y.byteLength),h=new Uint8Array(p);return h.set(new Uint8Array(e.data,0,t.byteLength)),h.set(new Uint8Array(y),t.byteLength),e.data=p,e}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let o;if(u.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:s)===n.keys.getKeySet(t)){const e=yield n.keys.ratchetKey(t,!1);o=yield x(e,n.keyProviderOptions.ratchetSalt)}const a=yield n.decryptFrame(e,t,r||s,{ratchetCount:i.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return a&&o&&(null!=r?r:s)===n.keys.getKeySet(t)&&(n.keys.setKeySet(o,t,!0),n.keys.setCurrentKeyIndex(t)),a}throw u.warn("maximum ratchet attempts exceeded"),new C("valid key missing for participant ".concat(n.participantIdentity),b.InvalidKey,n.participantIdentity)}throw new C("Decryption failed: ".concat(o.message),b.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 o=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-o%65535),this.sendCounts.set(e,o+1),r}getUnencryptedBytes(e){var t,n={unencryptedBytes:0,isH264:!1};if(function(e){return"type"in e}(e)){let r=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(r!==this.detectedCodec&&(u.debug("detected different codec",Object.assign({detectedCodec:r,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=r),"av1"===r)throw new Error("".concat(r," is not yet supported for end to end encryption"));if("vp8"===r)n.unencryptedBytes=v[e.type];else if("vp9"===r)return n.unencryptedBytes=0,n;const i=new Uint8Array(e.data);try{const e=function(e){const t=[];let n=0,r=0,i=e.length-2;for(;r<i;){for(;r<i&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let o=r;for(;o>n&&0===e[o-1];)o--;if(0===n){if(o!==n)throw TypeError("byte stream contains leading data")}else t.push(n);n=r+=3}return t}(i);if(n.isH264="h264"===r||e.some((e=>[M.SLICE_IDR,M.SLICE_NON_IDR].includes(U(i[e])))),n.isH264){for(const t of e){switch(U(i[t])){case M.SLICE_IDR:case M.SLICE_NON_IDR:return n.unencryptedBytes=t+2,n}}throw new TypeError("Could not find NALU")}}catch(e){}return n.unencryptedBytes=v[e.type],n}return n.unencryptedBytes=v.audio,n}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}function U(e){return e&N}const N=31;var M;!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"}(M||(M={}));class D extends K.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&&u.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 o=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 o=i.material,s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:f},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"])}()}))}(yield function(t,n){return e(this,void 0,void 0,(function*(){const e=_(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(o,this.keyProviderOptions.ratchetSalt),o.algorithm.name,"derive");n&&(yield this.setKeyFromMaterial(s,r,!0),this.emit(S.KeyRatcheted,s,this.participantIdentity,r)),t(s)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,o),o}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;return function*(){yield t.setKeyFromMaterial(e,n),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];return function*(){const i=yield x(e,n.keyProviderOptions.ratchetSalt),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;u.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(i,o,r),o>=0&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(S.KeyRatcheted,e.material,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 j=[],B=new Map;let q,G,z=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new h,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:l.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=l.RUNNING,yield t()}finally{e.status=l.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())}},W=!1,X=g,H=new Map;function V(e,t){let n=j.filter((e=>e.getTrackId()===t));if(n.length>1){const r=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");u.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,Y(e));else{if(u.info("creating new cryptor for",{participantIdentity:e}),!X)throw Error("Missing keyProvider options");r=new F({participantIdentity:e,keys:Y(e),keyProviderOptions:X,sifTrailer:G}),r.setRtpMap(H),function(e){e.on(E.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(b[e.reason],": ").concat(e.message))}};postMessage(t)}))}(r),j.push(r)}return r}function Y(e){if(W)return Q();let t=B.get(e);return t||(t=new D(e,X),t.on(S.KeyRatcheted,J),B.set(e,t)),t}function Q(){return q||(u.debug("creating new shared key handler"),q=new D("shared-key",X)),q}function J(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,material:e}})}u.setDefaultLevel("info"),onmessage=t=>{z.run((()=>e(void 0,void 0,void 0,(function*(){const{kind:n,data:r}=t.data;switch(n){case"init":u.setLevel(r.loglevel),u.info("worker initialized"),X=r.keyProviderOptions,W=!!r.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":o=r.enabled,s=r.participantIdentity,u.debug("setting encryption enabled for all tracks of ".concat(s),{enable:o}),R.set(s,o),u.info("updated e2ee enabled status for ".concat(r.participantIdentity," to ").concat(r.enabled)),postMessage(t.data);break;case"decode":V(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.codec);break;case"encode":V(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.codec);break;case"setKey":W?yield function(t,n){return e(this,void 0,void 0,(function*(){u.info("set shared key",{index:n}),yield Q().setKey(t,n)}))}(r.key,r.keyIndex):r.participantIdentity?(u.info("set participant sender key ".concat(r.participantIdentity," index ").concat(r.keyIndex)),yield Y(r.participantIdentity).setKey(r.key,r.keyIndex)):u.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=j.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&u.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():u.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(r.trackId,r.participantIdentity);break;case"updateCodec":V(r.participantIdentity,r.trackId).setVideoCodec(r.codec);break;case"setRTPMap":H=r.map,j.forEach((e=>{e.getParticipantIdentity()===r.participantIdentity&&e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(W){const e=Q();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=Y(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else u.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(r);break;case"setSifTrailer":i=r.trailer,G=i,j.forEach((e=>{e.setSifTrailer(i)}))}var i,o,s}))))},self.RTCTransformEvent&&(u.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;u.debug("transformer",t),t.handled=!0;const{kind:n,participantIdentity:r,trackId:i,codec:o}=t.options,s=V(r,i);u.debug("transform",{codec:o}),s.setupTransform(n,t.readable,t.writable,i,o)})}));
2
2
  //# sourceMappingURL=livekit-client.e2ee.worker.js.map