livekit-client 1.12.2 → 1.13.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (114) 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 +83 -9
  4. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  5. package/dist/livekit-client.esm.mjs +2239 -1975
  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 +2 -5
  10. package/dist/src/api/SignalClient.d.ts.map +1 -1
  11. package/dist/src/connectionHelper/checks/turn.d.ts.map +1 -1
  12. package/dist/src/connectionHelper/checks/webrtc.d.ts.map +1 -1
  13. package/dist/src/connectionHelper/checks/websocket.d.ts.map +1 -1
  14. package/dist/src/e2ee/E2eeManager.d.ts +5 -0
  15. package/dist/src/e2ee/E2eeManager.d.ts.map +1 -1
  16. package/dist/src/e2ee/KeyProvider.d.ts +4 -2
  17. package/dist/src/e2ee/KeyProvider.d.ts.map +1 -1
  18. package/dist/src/e2ee/constants.d.ts +2 -0
  19. package/dist/src/e2ee/constants.d.ts.map +1 -1
  20. package/dist/src/e2ee/types.d.ts +7 -1
  21. package/dist/src/e2ee/types.d.ts.map +1 -1
  22. package/dist/src/e2ee/utils.d.ts +1 -0
  23. package/dist/src/e2ee/utils.d.ts.map +1 -1
  24. package/dist/src/e2ee/worker/FrameCryptor.d.ts +4 -2
  25. package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
  26. package/dist/src/e2ee/worker/ParticipantKeyHandler.d.ts.map +1 -1
  27. package/dist/src/e2ee/worker/SifGuard.d.ts +11 -0
  28. package/dist/src/e2ee/worker/SifGuard.d.ts.map +1 -0
  29. package/dist/src/options.d.ts +5 -0
  30. package/dist/src/options.d.ts.map +1 -1
  31. package/dist/src/proto/livekit_models_pb.d.ts.map +1 -1
  32. package/dist/src/proto/livekit_rtc_pb.d.ts.map +1 -1
  33. package/dist/src/room/DeviceManager.d.ts +1 -0
  34. package/dist/src/room/DeviceManager.d.ts.map +1 -1
  35. package/dist/src/room/RTCEngine.d.ts.map +1 -1
  36. package/dist/src/room/Room.d.ts +1 -1
  37. package/dist/src/room/Room.d.ts.map +1 -1
  38. package/dist/src/room/defaults.d.ts.map +1 -1
  39. package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
  40. package/dist/src/room/participant/Participant.d.ts +5 -0
  41. package/dist/src/room/participant/Participant.d.ts.map +1 -1
  42. package/dist/src/room/participant/RemoteParticipant.d.ts +0 -5
  43. package/dist/src/room/participant/RemoteParticipant.d.ts.map +1 -1
  44. package/dist/src/room/participant/publishUtils.d.ts +1 -1
  45. package/dist/src/room/participant/publishUtils.d.ts.map +1 -1
  46. package/dist/src/room/timers.d.ts +2 -2
  47. package/dist/src/room/timers.d.ts.map +1 -1
  48. package/dist/src/room/track/LocalAudioTrack.d.ts +9 -1
  49. package/dist/src/room/track/LocalAudioTrack.d.ts.map +1 -1
  50. package/dist/src/room/track/LocalTrack.d.ts +3 -3
  51. package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
  52. package/dist/src/room/track/LocalVideoTrack.d.ts +6 -0
  53. package/dist/src/room/track/LocalVideoTrack.d.ts.map +1 -1
  54. package/dist/src/room/track/RemoteAudioTrack.d.ts.map +1 -1
  55. package/dist/src/room/track/options.d.ts +1 -0
  56. package/dist/src/room/track/options.d.ts.map +1 -1
  57. package/dist/src/room/track/processor/types.d.ts +13 -2
  58. package/dist/src/room/track/processor/types.d.ts.map +1 -1
  59. package/dist/src/room/types.d.ts +1 -1
  60. package/dist/src/room/types.d.ts.map +1 -1
  61. package/dist/ts4.2/src/api/SignalClient.d.ts +2 -5
  62. package/dist/ts4.2/src/e2ee/E2eeManager.d.ts +5 -0
  63. package/dist/ts4.2/src/e2ee/KeyProvider.d.ts +4 -2
  64. package/dist/ts4.2/src/e2ee/constants.d.ts +2 -0
  65. package/dist/ts4.2/src/e2ee/types.d.ts +7 -1
  66. package/dist/ts4.2/src/e2ee/utils.d.ts +1 -0
  67. package/dist/ts4.2/src/e2ee/worker/FrameCryptor.d.ts +4 -2
  68. package/dist/ts4.2/src/e2ee/worker/SifGuard.d.ts +11 -0
  69. package/dist/ts4.2/src/options.d.ts +5 -0
  70. package/dist/ts4.2/src/room/DeviceManager.d.ts +1 -0
  71. package/dist/ts4.2/src/room/Room.d.ts +1 -1
  72. package/dist/ts4.2/src/room/participant/Participant.d.ts +5 -0
  73. package/dist/ts4.2/src/room/participant/RemoteParticipant.d.ts +0 -5
  74. package/dist/ts4.2/src/room/participant/publishUtils.d.ts +1 -1
  75. package/dist/ts4.2/src/room/timers.d.ts +2 -2
  76. package/dist/ts4.2/src/room/track/LocalAudioTrack.d.ts +9 -1
  77. package/dist/ts4.2/src/room/track/LocalTrack.d.ts +3 -3
  78. package/dist/ts4.2/src/room/track/LocalVideoTrack.d.ts +6 -0
  79. package/dist/ts4.2/src/room/track/options.d.ts +1 -0
  80. package/dist/ts4.2/src/room/track/processor/types.d.ts +13 -2
  81. package/dist/ts4.2/src/room/types.d.ts +1 -1
  82. package/package.json +15 -16
  83. package/src/api/SignalClient.ts +13 -9
  84. package/src/connectionHelper/checks/turn.ts +1 -0
  85. package/src/connectionHelper/checks/webrtc.ts +9 -7
  86. package/src/connectionHelper/checks/websocket.ts +1 -0
  87. package/src/e2ee/E2eeManager.ts +27 -2
  88. package/src/e2ee/KeyProvider.ts +9 -4
  89. package/src/e2ee/constants.ts +3 -0
  90. package/src/e2ee/types.ts +9 -1
  91. package/src/e2ee/utils.ts +9 -0
  92. package/src/e2ee/worker/FrameCryptor.ts +46 -17
  93. package/src/e2ee/worker/ParticipantKeyHandler.ts +1 -0
  94. package/src/e2ee/worker/SifGuard.ts +47 -0
  95. package/src/e2ee/worker/e2ee.worker.ts +14 -0
  96. package/src/options.ts +6 -0
  97. package/src/proto/livekit_models_pb.ts +14 -0
  98. package/src/proto/livekit_rtc_pb.ts +14 -0
  99. package/src/room/DeviceManager.ts +7 -2
  100. package/src/room/RTCEngine.ts +7 -5
  101. package/src/room/Room.ts +27 -7
  102. package/src/room/defaults.ts +1 -0
  103. package/src/room/participant/LocalParticipant.ts +14 -2
  104. package/src/room/participant/Participant.ts +16 -0
  105. package/src/room/participant/RemoteParticipant.ts +0 -12
  106. package/src/room/participant/publishUtils.ts +4 -2
  107. package/src/room/track/LocalAudioTrack.ts +45 -0
  108. package/src/room/track/LocalTrack.ts +4 -4
  109. package/src/room/track/LocalVideoTrack.ts +49 -8
  110. package/src/room/track/RemoteAudioTrack.ts +9 -1
  111. package/src/room/track/RemoteTrackPublication.ts +2 -2
  112. package/src/room/track/options.ts +17 -16
  113. package/src/room/track/processor/types.ts +17 -2
  114. package/src/room/types.ts +5 -1
@@ -1,2 +1,2 @@
1
- !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,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())}))}var t,n,r,i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},o={exports:{}};n=i,r=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"];function i(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 o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function s(t,n){for(var i=0;i<r.length;i++){var o=r[i];this[o]=i<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,r){return function(){typeof console!==t&&(s.call(this,n,r),this[e].apply(this,arguments))}}function c(r,s,c){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?o:void 0!==console[r]?i(console,r):void 0!==console.log?i(console,"log"):e)}(r)||a.apply(this,arguments)}function d(e,n,i){var o,a=this;n=null==n?"WARN":n;var d="loglevel";function u(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=n.indexOf(encodeURIComponent(d)+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=i||c,a.getLevel=function(){return o},a.setLevel=function(n,i){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==i&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),s.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,u()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var l=u();null==l&&(l=n),a.setLevel(l,!1)}var u=new d,l={};u.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=l[e];return t||(t=l[e]=new d(e,u.getLevel(),u.methodFactory)),t};var y=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=y),u},u.getLoggers=function(){return l},u.default=u,u},(t=o).exports?t.exports=r():n.log=r();var s,a=o.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={}));a.getLogger("livekit").setDefaultLevel(s.info);const c=a.getLogger("lk-e2ee"),d="AES-GCM",u={key:10,delta:3,audio:1,empty:0},l={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10};class y extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}var h,p;!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(h||(h={})),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}}(h||(h={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(p||(p={}));class f extends y{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p.InternalError;super(40,e),this.reason=t}}var v,g={exports:{}},m="object"==typeof Reflect?Reflect:null,w=m&&"function"==typeof m.apply?m.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};v=m&&"function"==typeof m.ownKeys?m.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var b=Number.isNaN||function(e){return e!=e};function I(){I.init.call(this)}g.exports=I,g.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))}A(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&A(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 L=10;function E(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function k(e){return void 0===e._maxListeners?I.defaultMaxListeners:e._maxListeners}function S(e,t,n,r){var i,o,s,a;if(E(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),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=k(e))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function K(){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 _(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=K.bind(r);return i.listener=n,r.wrapFn=i,i}function C(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 T(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 A(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)}))}}Object.defineProperty(I,"defaultMaxListeners",{enumerable:!0,get:function(){return L},set:function(e){if("number"!=typeof e||e<0||b(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");L=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||b(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 k(this)},I.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.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 a=i[e];if(void 0===a)return!1;if("function"==typeof a)w(a,this,t);else{var c=a.length,d=P(a,c);for(n=0;n<c;++n)w(d[n],this,t)}return!0},I.prototype.addListener=function(e,t){return S(this,e,t,!1)},I.prototype.on=I.prototype.addListener,I.prototype.prependListener=function(e,t){return S(this,e,t,!0)},I.prototype.once=function(e,t){return E(t),this.on(e,_(this,e,t)),this},I.prototype.prependOnceListener=function(e,t){return E(t),this.prependListener(e,_(this,e,t)),this},I.prototype.removeListener=function(e,t){var n,r,i,o,s;if(E(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){s=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,s||t)}return this},I.prototype.off=I.prototype.removeListener,I.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,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 C(this,e,!0)},I.prototype.rawListeners=function(e){return C(this,e,!1)},I.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):T.call(e,t)},I.prototype.listenerCount=T,I.prototype.eventNames=function(){return this._eventsCount>0?v(this._events):[]};var x=g.exports;const R="cryptorError";var O;function F(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 U(t,n){return e(this,void 0,void 0,(function*(){const e=F(t.algorithm.name,n),r=yield crypto.subtle.deriveKey(e,t,{name:d,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!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}}(O||(O={}));class M extends x.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class N extends M{constructor(e){var t;super(),this.sendCounts=new Map,this.keys=e.keys,this.participantId=e.participantId,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.unencryptedFrameByteTrailer=null!==(t=e.unencryptedFrameBytes)&&void 0!==t?t:(new TextEncoder).encode("LKROCKS")}setParticipant(e,t){this.participantId=e,this.keys=t}unsetParticipant(){this.participantId=void 0}getParticipantId(){return this.participantId}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i){i&&(console.info("setting codec on cryptor to",i),this.videoCodec=i);const o="encode"===e?this.encodeFunction:this.decodeFunction,s=new TransformStream({transform:o.bind(this)});t.pipeThrough(s).pipeTo(n).catch((e=>{console.error(e),this.emit("cryptorError",e instanceof f?e:new f(e.message))})),this.trackId=r}encodeFunction(t,n){var r;return e(this,void 0,void 0,(function*(){if(!this.keys.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const{encryptionKey:e}=this.keys.getKeySet(),i=this.keys.getCurrentKeyIndex();if(e){const o=this.makeIV(null!==(r=t.getMetadata().synchronizationSource)&&void 0!==r?r:-1,t.timestamp),s=new Uint8Array(t.data,0,this.getUnencryptedBytes(t)),a=new Uint8Array(2);a[0]=12,a[1]=i;try{const r=yield crypto.subtle.encrypt({name:d,iv:o,additionalData:new Uint8Array(t.data,0,s.byteLength)},e,new Uint8Array(t.data,this.getUnencryptedBytes(t))),i=new ArrayBuffer(s.byteLength+r.byteLength+o.byteLength+a.byteLength),c=new Uint8Array(i);return c.set(s),c.set(new Uint8Array(r),s.byteLength),c.set(new Uint8Array(o),s.byteLength+r.byteLength),c.set(a,s.byteLength+r.byteLength+o.byteLength),t.data=i,n.enqueue(t)}catch(e){c.error(e)}}else this.emit(R,new f("encryption key missing for encoding",p.MissingKey))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.keys.isEnabled()||0===t.data.byteLength||function(e,t){const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.unencryptedFrameByteTrailer))return n.enqueue(t);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(this.keys.getKeySet(e)&&this.keys.hasValidKey)try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(),r)return n.enqueue(r)}catch(e){e instanceof f&&e.reason===p.InvalidKey?this.keys.hasValidKey&&(c.warn("invalid key"),this.emit(R,new f("invalid key for participant ".concat(this.participantId),p.InvalidKey)),this.keys.decryptionFailure()):c.warn("decoding frame failed",{error:e})}return n.enqueue(t)}))}decryptFrame(t,n){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};var o;return e(this,void 0,void 0,(function*(){const e=this.keys.getKeySet(n);try{const n=new Uint8Array(t.data,0,this.getUnencryptedBytes(t)),r=new Uint8Array(t.data,t.data.byteLength-2,2),s=r[0],a=new Uint8Array(t.data,t.data.byteLength-s-r.byteLength,s),c=n.byteLength,u=t.data.byteLength-(n.byteLength+s+r.byteLength),l=yield crypto.subtle.decrypt({name:d,iv:a,additionalData:new Uint8Array(t.data,0,n.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:e.encryptionKey,new Uint8Array(t.data,c,u)),y=new ArrayBuffer(n.byteLength+l.byteLength),h=new Uint8Array(y);return h.set(new Uint8Array(t.data,0,n.byteLength)),h.set(new Uint8Array(l),n.byteLength),t.data=y,t}catch(o){if(!(this.keyProviderOptions.ratchetWindowSize>0))throw new f("Decryption failed, most likely because of an invalid key",p.InvalidKey);if(i.ratchetCount<this.keyProviderOptions.ratchetWindowSize){let o;if(c.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(this.keyProviderOptions.ratchetWindowSize,", for kind ").concat(t instanceof RTCEncodedAudioFrame?"audio":"video")),e===this.keys.getKeySet(n)){const e=yield this.keys.ratchetKey(n,!1);o=yield U(e,this.keyProviderOptions.ratchetSalt)}const s=yield this.decryptFrame(t,n,r||e,{ratchetCount:i.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return s&&o&&(this.keys.setKeySet(o,n,!0),this.keys.setCurrentKeyIndex(n)),s}r&&(c.debug("resetting to initial material"),this.keys.setKeyFromMaterial(r.material,n)),c.warn("maximum ratchet attempts exceeded, resetting key"),this.emit(R,new f("valid key missing for participant ".concat(this.participantId),p.MissingKey))}}))}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;if(function(e){return"type"in e}(e)){let n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if("av1"===n||"vp9"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return u[e.type];const r=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}(r);if("h264"===n||e.some((e=>[j.SLICE_IDR,j.SLICE_NON_IDR].includes(D(r[e]))))){for(const t of e){switch(D(r[t])){case j.SLICE_IDR:case j.SLICE_NON_IDR:return t+2}}throw new TypeError("Could not find NALU")}}catch(e){}return u[e.type]}return u.audio}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}function D(e){return e&B}const B=31;var j;!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"}(j||(j={}));class V extends x.EventEmitter{get hasValidKey(){return this._hasValidKey}constructor(e,t,n){super(),this.decryptionFailureCount=0,this._hasValidKey=!0,this.currentKeyIndex=0,this.cryptoKeyRing=new Array(16),this.enabled=t,this.keyProviderOptions=n,this.ratchetPromiseMap=new Map,this.participantId=e,this.resetKeyStatus()}setEnabled(e){this.enabled=e}decryptionFailure(){this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCount+=1,this.decryptionFailureCount>this.keyProviderOptions.failureTolerance&&(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 r=null!=t?t:t=this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const o=new Promise(((i,o)=>e(this,void 0,void 0,(function*(){try{const o=this.getKeySet(r).material,s=yield function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:d},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return e(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",t,n,!1,"derive"===r?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))}(yield function(t,n){return e(this,void 0,void 0,(function*(){const e=F(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(o,this.keyProviderOptions.ratchetSalt),o.algorithm.name,"derive");n&&this.setKeyFromMaterial(s,r,!0),this.emit("keyRatcheted",s,t,this.participantId),i(s)}catch(e){o(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,o),o}setKey(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e(this,void 0,void 0,(function*(){yield this.setKeyFromMaterial(t,n),this.resetKeyStatus()}))}setKeyFromMaterial(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e(this,void 0,void 0,(function*(){c.debug("setting new key"),n>=0&&(this.currentKeyIndex=n%this.cryptoKeyRing.length);const e=yield U(t,this.keyProviderOptions.ratchetSalt);this.setKeySet(e,this.currentKeyIndex,r)}))}setKeySet(t,n){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e(this,void 0,void 0,(function*(){this.cryptoKeyRing[n%this.cryptoKeyRing.length]=t,r&&this.emit("keyRatcheted",t.material,n,this.participantId)}))}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus()}))}isEnabled(){return this.enabled}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const X=[],z=new Map;let W,q,H=[],Q=!1,Y=!1,G=l;function J(e,t){let n=X.find((e=>e.getTrackId()===t));if(n)e!==n.getParticipantId()&&n.setParticipant(e,Z(e));else{if(c.info("creating new cryptor for",{participantId:e}),!G)throw Error("Missing keyProvider options");n=new N({participantId:e,keys:Z(e),keyProviderOptions:G}),ee(n),X.push(n)}return n}function Z(e){if(!e)return W;let t=z.get(e);return t||(t=new V(e,!0,G),q&&t.setKey(q),z.set(e,t)),t}function $(e){let t=H.find((t=>t.getTrackId()===e));if(!t){if(!G)throw new TypeError("Missing keyProvider options");t=new N({keys:W,participantId:"publisher",keyProviderOptions:G}),ee(t),H.push(t)}return t}function ee(e){e.on("cryptorError",(e=>{const t={kind:"error",data:{error:new Error("".concat(p[e.reason],": ").concat(e.message))}};postMessage(t)}))}function te(e,t){postMessage({kind:"ratchetKey",data:{keyIndex:t,material:e}})}c.setDefaultLevel("info"),onmessage=t=>{const{kind:n,data:r}=t.data;switch(n){case"init":c.info("worker initialized"),G=r.keyProviderOptions,Y=!!r.keyProviderOptions.sharedKey;const d={kind:"enable",data:{enabled:Q}};W=new V(void 0,Q,G),W.on("keyRatcheted",te),postMessage(d);break;case"enable":s=r.enabled,(a=r.participantId)?Z(a).setEnabled(s):(Q=s,W.setEnabled(s)),c.info("updated e2ee enabled status"),postMessage(t.data);break;case"decode":J(r.participantId,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.codec);break;case"encode":$(r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.codec);break;case"setKey":Y?(c.debug("set shared key"),function(e,t){c.debug("setting shared key"),q=e,null==W||W.setKey(e,t);for(const[,n]of z)n.setKey(e,t)}(r.key,r.keyIndex)):r.participantId?Z(r.participantId).setKey(r.key,r.keyIndex):c.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":i=r.trackId,null===(o=X.find((e=>e.getTrackId()===i)))||void 0===o||o.unsetParticipant();break;case"updateCodec":J(r.participantId,r.trackId).setVideoCodec(r.codec);break;case"setRTPMap":H.forEach((e=>{e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){const e=Z(t.participantId);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}))}(r)}var i,o,s,a},self.RTCTransformEvent&&(c.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;c.debug("transformer",t),t.handled=!0;const{kind:n,participantId:r,trackId:i,codec:o}=t.options,s="encode"===n?$(i):J(r,i);c.debug("transform",{codec:o}),s.setupTransform(n,t.readable,t.writable,i,o)})}));
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())}))}var t,n,r,i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},o={exports:{}};n=i,r=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"];function i(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 o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function s(t,n){for(var i=0;i<r.length;i++){var o=r[i];this[o]=i<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,r){return function(){typeof console!==t&&(s.call(this,n,r),this[e].apply(this,arguments))}}function c(r,s,c){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?o:void 0!==console[r]?i(console,r):void 0!==console.log?i(console,"log"):e)}(r)||a.apply(this,arguments)}function d(e,n,i){var o,a=this;n=null==n?"WARN":n;var d="loglevel";function u(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=n.indexOf(encodeURIComponent(d)+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=i||c,a.getLevel=function(){return o},a.setLevel=function(n,i){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==i&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),s.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,u()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var l=u();null==l&&(l=n),a.setLevel(l,!1)}var u=new d,l={};u.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=l[e];return t||(t=l[e]=new d(e,u.getLevel(),u.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return u.noConflict=function(){return typeof window!==t&&window.log===u&&(window.log=h),u},u.getLoggers=function(){return l},u.default=u,u},(t=o).exports?t.exports=r():n.log=r();var s,a=o.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={}));a.getLogger("livekit").setDefaultLevel(s.info);const c=a.getLogger("lk-e2ee"),d="AES-GCM",u={key:10,delta:3,audio:1,empty:0},l={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10};class h extends Error{constructor(e,t){super(t||"an error has occured"),this.code=e}}var y,f;!function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(y||(y={})),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}}(y||(y={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(f||(f={}));class p extends h{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f.InternalError;super(40,e),this.reason=t}}var v,g={exports:{}},m="object"==typeof Reflect?Reflect:null,w=m&&"function"==typeof m.apply?m.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};v=m&&"function"==typeof m.ownKeys?m.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var S=Number.isNaN||function(e){return e!=e};function b(){b.init.call(this)}g.exports=b,g.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))}P(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&P(e,"error",t,n)}(e,i,{once:!0})}))},b.EventEmitter=b,b.prototype._events=void 0,b.prototype._eventsCount=0,b.prototype._maxListeners=void 0;var I=10;function L(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function E(e){return void 0===e._maxListeners?b.defaultMaxListeners:e._maxListeners}function k(e,t,n,r){var i,o,s,a;if(L(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),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=E(e))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function K(){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 C(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=K.bind(r);return i.listener=n,r.wrapFn=i,i}function _(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):T(i,i.length)}function A(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 T(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function P(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}Object.defineProperty(b,"defaultMaxListeners",{enumerable:!0,get:function(){return I},set:function(e){if("number"!=typeof e||e<0||S(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");I=e}}),b.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},b.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||S(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},b.prototype.getMaxListeners=function(){return E(this)},b.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.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 a=i[e];if(void 0===a)return!1;if("function"==typeof a)w(a,this,t);else{var c=a.length,d=T(a,c);for(n=0;n<c;++n)w(d[n],this,t)}return!0},b.prototype.addListener=function(e,t){return k(this,e,t,!1)},b.prototype.on=b.prototype.addListener,b.prototype.prependListener=function(e,t){return k(this,e,t,!0)},b.prototype.once=function(e,t){return L(t),this.on(e,C(this,e,t)),this},b.prototype.prependOnceListener=function(e,t){return L(t),this.prependListener(e,C(this,e,t)),this},b.prototype.removeListener=function(e,t){var n,r,i,o,s;if(L(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){s=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,s||t)}return this},b.prototype.off=b.prototype.removeListener,b.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},b.prototype.listeners=function(e){return _(this,e,!0)},b.prototype.rawListeners=function(e){return _(this,e,!1)},b.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):A.call(e,t)},b.prototype.listenerCount=A,b.prototype.eventNames=function(){return this._eventsCount>0?v(this._events):[]};var x=g.exports;const R="cryptorError";var F;function U(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 O(t,n){return e(this,void 0,void 0,(function*(){const e=U(t.algorithm.name,n),r=yield crypto.subtle.deriveKey(e,t,{name:d,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!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}}(F||(F={}));class M{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}}class D extends x.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class N extends D{constructor(e){var t;super(),this.sendCounts=new Map,this.keys=e.keys,this.participantId=e.participantId,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([]),this.sifGuard=new M}setParticipant(e,t){this.participantId=e,this.keys=t,this.sifGuard.reset()}unsetParticipant(){this.participantId=void 0}getParticipantId(){return this.participantId}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i){i&&(c.info("setting codec on cryptor to",{codec:i}),this.videoCodec=i);const o="encode"===e?this.encodeFunction:this.decodeFunction,s=new TransformStream({transform:o.bind(this)});t.pipeThrough(s).pipeTo(n).catch((e=>{c.warn(e),this.emit("cryptorError",e instanceof p?e:new p(e.message))})),this.trackId=r}encodeFunction(t,n){var r;return e(this,void 0,void 0,(function*(){if(!this.keys.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const{encryptionKey:e}=this.keys.getKeySet(),i=this.keys.getCurrentKeyIndex();if(e){const o=this.makeIV(null!==(r=t.getMetadata().synchronizationSource)&&void 0!==r?r:-1,t.timestamp),s=new Uint8Array(t.data,0,this.getUnencryptedBytes(t)),a=new Uint8Array(2);a[0]=12,a[1]=i;try{const r=yield crypto.subtle.encrypt({name:d,iv:o,additionalData:new Uint8Array(t.data,0,s.byteLength)},e,new Uint8Array(t.data,this.getUnencryptedBytes(t))),i=new ArrayBuffer(s.byteLength+r.byteLength+o.byteLength+a.byteLength),c=new Uint8Array(i);return c.set(s),c.set(new Uint8Array(r),s.byteLength),c.set(new Uint8Array(o),s.byteLength+r.byteLength),c.set(a,s.byteLength+r.byteLength+o.byteLength),t.data=i,n.enqueue(t)}catch(e){c.error(e)}}else this.emit(R,new p("encryption key missing for encoding",f.MissingKey))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.keys.isEnabled()||0===t.data.byteLength)return 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 this.sifGuard.recordSif(),this.sifGuard.isSifAllowed()?n.enqueue(t):void c.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 r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(),r)return n.enqueue(r)}catch(e){e instanceof p&&e.reason===f.InvalidKey?this.keys.hasValidKey&&(c.warn("invalid key"),this.emit(R,new p("invalid key for participant ".concat(this.participantId),f.InvalidKey)),this.keys.decryptionFailure()):c.warn("decoding frame failed",{error:e})}else!this.keys.getKeySet(e)&&this.keys.hasValidKey&&(c.warn("skipping decryption due to missing key at index"),this.emit(R,new p("missing key at index for participant ".concat(this.participantId),f.MissingKey)))}))}decryptFrame(t,n){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};var o;return e(this,void 0,void 0,(function*(){const e=this.keys.getKeySet(n);try{const n=new Uint8Array(t.data,0,this.getUnencryptedBytes(t)),r=new Uint8Array(t.data,t.data.byteLength-2,2),s=r[0],a=new Uint8Array(t.data,t.data.byteLength-s-r.byteLength,s),c=n.byteLength,u=t.data.byteLength-(n.byteLength+s+r.byteLength),l=yield crypto.subtle.decrypt({name:d,iv:a,additionalData:new Uint8Array(t.data,0,n.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:e.encryptionKey,new Uint8Array(t.data,c,u)),h=new ArrayBuffer(n.byteLength+l.byteLength),y=new Uint8Array(h);return y.set(new Uint8Array(t.data,0,n.byteLength)),y.set(new Uint8Array(l),n.byteLength),t.data=h,t}catch(o){if(this.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<this.keyProviderOptions.ratchetWindowSize){let o;if(c.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(this.keyProviderOptions.ratchetWindowSize,", for kind ").concat(t instanceof RTCEncodedAudioFrame?"audio":"video")),e===this.keys.getKeySet(n)){const e=yield this.keys.ratchetKey(n,!1);o=yield O(e,this.keyProviderOptions.ratchetSalt)}const s=yield this.decryptFrame(t,n,r||e,{ratchetCount:i.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return s&&o&&(this.keys.setKeySet(o,n,!0),this.keys.setCurrentKeyIndex(n)),s}throw r&&(c.debug("resetting to initial material"),this.keys.setKeyFromMaterial(r.material,n)),c.warn("maximum ratchet attempts exceeded, resetting key"),new p("valid key missing for participant ".concat(this.participantId),f.InvalidKey)}throw new p("Decryption failed, most likely because of an invalid key",f.InvalidKey)}}))}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;if(function(e){return"type"in e}(e)){let n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if("av1"===n||"vp9"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return u[e.type];const r=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}(r);if("h264"===n||e.some((e=>[j.SLICE_IDR,j.SLICE_NON_IDR].includes(B(r[e]))))){for(const t of e){switch(B(r[t])){case j.SLICE_IDR:case j.SLICE_NON_IDR:return t+2}}throw new TypeError("Could not find NALU")}}catch(e){}return u[e.type]}return u.audio}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}setSifTrailer(e){this.sifTrailer=e}}function B(e){return e&V}const V=31;var j;!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"}(j||(j={}));class q extends x.EventEmitter{get hasValidKey(){return this._hasValidKey}constructor(e,t,n){super(),this.decryptionFailureCount=0,this._hasValidKey=!0,this.currentKeyIndex=0,this.cryptoKeyRing=new Array(16),this.enabled=t,this.keyProviderOptions=n,this.ratchetPromiseMap=new Map,this.participantId=e,this.resetKeyStatus()}setEnabled(e){this.enabled=e}decryptionFailure(){this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCount+=1,this.decryptionFailureCount>this.keyProviderOptions.failureTolerance&&(c.warn("key for ".concat(this.participantId," 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 r=null!=t?t:t=this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const o=new Promise(((i,o)=>e(this,void 0,void 0,(function*(){try{const o=this.getKeySet(r).material,s=yield function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:d},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return e(this,void 0,void 0,(function*(){return crypto.subtle.importKey("raw",t,n,!1,"derive"===r?["deriveBits","deriveKey"]:["encrypt","decrypt"])}))}(yield function(t,n){return e(this,void 0,void 0,(function*(){const e=U(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(o,this.keyProviderOptions.ratchetSalt),o.algorithm.name,"derive");n&&this.setKeyFromMaterial(s,r,!0),this.emit("keyRatcheted",s,t,this.participantId),i(s)}catch(e){o(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,o),o}setKey(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e(this,void 0,void 0,(function*(){yield this.setKeyFromMaterial(t,n),this.resetKeyStatus()}))}setKeyFromMaterial(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e(this,void 0,void 0,(function*(){c.debug("setting new key"),n>=0&&(this.currentKeyIndex=n%this.cryptoKeyRing.length);const e=yield O(t,this.keyProviderOptions.ratchetSalt);this.setKeySet(e,this.currentKeyIndex,r)}))}setKeySet(t,n){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e(this,void 0,void 0,(function*(){this.cryptoKeyRing[n%this.cryptoKeyRing.length]=t,r&&this.emit("keyRatcheted",t.material,n,this.participantId)}))}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus()}))}isEnabled(){return this.enabled}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const X=[],G=new Map;let z,W,H,Q=[],Y=!1,J=!1,Z=l;function $(e,t){let n=X.find((e=>e.getTrackId()===t));if(n)e!==n.getParticipantId()&&n.setParticipant(e,ee(e));else{if(c.info("creating new cryptor for",{participantId:e}),!Z)throw Error("Missing keyProvider options");n=new N({participantId:e,keys:ee(e),keyProviderOptions:Z,sifTrailer:H}),ne(n),X.push(n)}return n}function ee(e){if(!e)return z;let t=G.get(e);return t||(t=new q(e,!0,Z),W&&t.setKey(W),G.set(e,t)),t}function te(e){let t=Q.find((t=>t.getTrackId()===e));if(!t){if(!Z)throw new TypeError("Missing keyProvider options");t=new N({keys:z,participantId:"publisher",keyProviderOptions:Z}),ne(t),Q.push(t)}return t}function ne(e){e.on("cryptorError",(e=>{const t={kind:"error",data:{error:new Error("".concat(f[e.reason],": ").concat(e.message))}};postMessage(t)}))}function re(e,t){postMessage({kind:"ratchetKey",data:{keyIndex:t,material:e}})}c.setDefaultLevel("info"),onmessage=t=>{const{kind:n,data:r}=t.data;switch(n){case"init":c.info("worker initialized"),Z=r.keyProviderOptions,J=!!r.keyProviderOptions.sharedKey;const u={kind:"enable",data:{enabled:Y}};z=new q(void 0,Y,Z),z.on("keyRatcheted",re),postMessage(u);break;case"enable":a=r.enabled,(d=r.participantId)?ee(d).setEnabled(a):(Y=a,z.setEnabled(a)),c.info("updated e2ee enabled status"),postMessage(t.data);break;case"decode":$(r.participantId,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.codec);break;case"encode":te(r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.codec);break;case"setKey":J?(c.debug("set shared key"),function(e,t){c.debug("setting shared key"),W=e,null==z||z.setKey(e,t);for(const[,n]of G)n.setKey(e,t)}(r.key,r.keyIndex)):r.participantId?ee(r.participantId).setKey(r.key,r.keyIndex):c.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":o=r.trackId,null===(s=X.find((e=>e.getTrackId()===o)))||void 0===s||s.unsetParticipant();break;case"updateCodec":$(r.participantId,r.trackId).setVideoCodec(r.codec);break;case"setRTPMap":Q.forEach((e=>{e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){const e=ee(t.participantId);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}))}(r);break;case"setSifTrailer":i=r.trailer,H=i,X.forEach((e=>{e.setSifTrailer(i)}))}var i,o,s,a,d},self.RTCTransformEvent&&(c.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;c.debug("transformer",t),t.handled=!0;const{kind:n,participantId:r,trackId:i,codec:o}=t.options,s="encode"===n?te(i):$(r,i);c.debug("transform",{codec:o}),s.setupTransform(n,t.readable,t.writable,i,o)})}));
2
2
  //# sourceMappingURL=livekit-client.e2ee.worker.js.map