From 07d452ab2133ac86054ff97b20410fec62c0bbdc Mon Sep 17 00:00:00 2001 From: Yuki Ito Date: Tue, 14 Dec 2021 10:38:36 +0900 Subject: [PATCH] =?UTF-8?q?=E6=88=90=E6=9E=9C=E7=89=A9=E3=82=92=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dist/sora.js | 6 +++--- dist/sora.min.js | 2 +- dist/sora.mjs | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/dist/sora.js b/dist/sora.js index 122512dd..f47ab642 100644 --- a/dist/sora.js +++ b/dist/sora.js @@ -1,7 +1,7 @@ /** * sora-js-sdk * WebRTC SFU Sora JavaScript SDK - * @version: 2021.2.0-canary.11 + * @version: 2021.2.0 * @author: Shiguredo Inc. * @license: Apache-2.0 **/ @@ -1635,7 +1635,7 @@ } const message = { type: "connect", - sora_client: "Sora JavaScript SDK 2021.2.0-canary.11", + sora_client: "Sora JavaScript SDK 2021.2.0", environment: window.navigator.userAgent, role: role, channel_id: channelId, @@ -4373,7 +4373,7 @@ * @public */ version: function () { - return "2021.2.0-canary.11"; + return "2021.2.0"; }, /** * WebRTC のユーティリティ関数群 diff --git a/dist/sora.min.js b/dist/sora.min.js index 7cc511db..57a77701 100644 --- a/dist/sora.min.js +++ b/dist/sora.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Sora=t()}(this,(function(){"use strict";class e{constructor(){if(!!!RTCRtpSender.prototype.createEncodedStreams)throw new Error("E2EE is not supported in this browser.");this.worker=null,this.onWorkerDisconnect=null}startWorker(){const e=atob("InVzZSBzdHJpY3QiOwovKiBlc2xpbnQtZGlzYWJsZSBAdHlwZXNjcmlwdC1lc2xpbnQvbm8tdW51c2VkLXZhcnMgKi8K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h0RGVjb2Rlci5kZWNvZGUoY29ubmVjdGlvbklkQnVmZmVyKTsKICAgICAgICBjb25zdCBbcywgY291bnQsIGtleUlkXSA9IHBhcnNlU0ZyYW1lSGVhZGVyKHNmcmFtZUhlYWRlckJ1ZmZlcik7CiAgICAgICAgLy8g5LuK5Zue44GvIHMgZmxhZyDjga8gMCDjga7jgb8KICAgICAgICBpZiAocyAhPT0gMCkgewogICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoIlVORVhQRUNURUQtUy1GTEFHIik7CiAgICAgICAgfQogICAgICAgIGNvbnN0IGRlcml2ZUtleSA9IGdldFJlbW90ZURlcml2ZUtleShjb25uZWN0aW9uSWQsIGtleUlkKTsKICAgICAgICBpZiAoIWRlcml2ZUtleSkgewogICAgICAgICAgICByZXR1cm47CiAgICAgICAgfQogICAgICAgIGNvbnN0IGl2ID0gZ2VuZXJhdGVJVihjb3VudCwgY29ubmVjdGlvbklkLCBrZXlJZCk7CiAgICAgICAgaWYgKCFpdikgewogICAgICAgICAgICByZXR1cm47CiAgICAgICAgfQogICAgICAgIGNvbnN0IGZyYW1lQWRkID0gZW5jb2RlRnJhbWVBZGQoZnJhbWVNZXRhZGF0YSwgc2ZyYW1lSGVhZGVyLCBjb25uZWN0aW9uSWQpOwogICAgICAgIGNyeXB0by5zdWJ0bGUKICAgICAgICAgICAgLmRlY3J5cHQoewogICAgICAgICAgICBuYW1lOiAiQUVTLUdDTSIsCiAgICAgICAgICAgIGl2OiBpdiwKICAgICAgICAgICAgYWRkaXRpb25hbERhdGE6IGZyYW1lQWRkLAogICAgICAgIH0sIGRlcml2ZUtleSwgbmV3IFVpbnQ4QXJyYXkoZW5jcnlwdGVkRnJhbWVCdWZmZXIpKQogICAgICAgICAgICAudGhlbigocGxhaW5UZXh0KSA9PiB7CiAgICAgICAgICAgIGNvbnN0IG5ld0RhdGEgPSBuZXcgQXJyYXlCdWZmZXIoZnJhbWVNZXRhZGF0YUJ1ZmZlci5ieXRlTGVuZ3Ro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ID0gZXZlbnQuZGF0YTsKICAgIGlmICh0eXBlID09PSAic2VsZlNlY3JldEtleU1hdGVyaWFsIikgewogICAgICAgIGNvbnN0IHsgc2VsZlNlY3JldEtleU1hdGVyaWFsLCBzZWxmQ29ubmVjdGlvbklkLCBzZWxmS2V5SWQsIHdhaXRpbmdUaW1lIH0gPSBldmVudC5kYXRhOwogICAgICAgIGNvbnN0IHRpbWVvdXRJZCA9IHNldFRpbWVvdXQoKCkgPT4gewogICAgICAgICAgICBjcnlwdG8uc3VidGxlCiAgICAgICAgICAgICAgICAuaW1wb3J0S2V5KCJyYXciLCBzZWxmU2VjcmV0S2V5TWF0ZXJpYWwuYnVmZmVyLCAiSEtERiIsIGZhbHNlLCBbImRlcml2ZUJpdHMiLCAiZGVyaXZlS2V5Il0pCiAgICAgICAgICAgICAgICAudGhlbigobWF0ZXJpYWwpID0+IHsKICAgICAgICAgICAgICAgIGdlbmVyYXRlRGVyaXZlS2V5KG1hdGVyaWFsKS50aGVuKChkZXJpdmVLZXkpID0+IHsKICAgICAgICAgICAgICAgICAgICBzZXRTZWxmRGVyaXZlS2V5KHNlbGZDb25uZWN0aW9uSWQsIHNlbGZLZXlJZCwgZGVyaXZlS2V5KTsKICAgICAgICAgICAgICAgIH0pOwogICAgICAgICAgICAgICAgZ2VuZXJhdGVXcml0ZUlWKG1hdGVyaWFsKS50aGVuKCh3cml0ZUlWKSA9PiB7CiAgICAgICAgICAgICAgICAgICAgc2V0V3JpdGVJVihzZWxmQ29ubmVjdGlvbklkLCBzZWxmS2V5SWQsIHdyaXRlSVYpOwogICAgICAgICAgICAgICAgfSk7CiAgICAgICAgICAgICAgICBjbGVhclRpbWVvdXQodGltZW91dElkKTsKICAgICAgICAgICAgfSk7CiAgICAgICAgfSwgd2FpdGluZ1RpbWUgfHwgMCk7CiAgICAgICAgLy8gVE9ETzogKzEwMDAg44Gn6Y2155Sf5oiQ5b6M44Gr5a6f6KGM44GV44KM44KL44KI44GG44Gr44GX44Gm44GE44KL44GM55+t44GE5aC05ZCI44Gv5Ly444Gw44GZCiAgICAgICAgY29uc3QgcmVtb3ZhbFdhaXRpbmdUaW1lID0gKHdhaXRpbmdUaW1lIHx8IDApICsgMTAwMDsKICAgICAgICBpZiAocmVtb3ZhbFRpbWVvdXRJZCkgewogICAgICAgICAgICAvLyDli5XkvZzmuIjjgb/jgr/jgqTjg57jg7zmnInjgooKICAgICAgICAgICAgaWYgKHdhaXRpbmdUaW1lKSB7CiAgICAgICAgICAgICAgICAvLyBjb25uZWN0aW9uLmRlc3Ryb3llZAogICAgICAgICAgICAgICAgY2xlYXJUaW1lb3V0KHJlbW92YWxUaW1lb3V0SWQpOwogICAgICAgICAgICAgICAgcmVtb3ZhbFRpbWVvdXRJZCA9IHNldFRpbWVvdXQoKCkgPT4gewogICAgICAgICAgICAgICAgICAgIHJlbW92ZU9sZFJlbW90ZURlcml2ZUtleXMoKTsKICAgICAgICAgICAgICAgICAgICBjbGVhclRpbWVvdXQocmVtb3ZhbFRpbWVvdXRJZCk7CiAgICAgICAgICAgICAgICAgICAgcmVtb3ZhbFRpbWVvdXRJZCA9IDA7CiAgICAgICAgICAgICAgICB9LCByZW1vdmFsV2FpdGluZ1RpbWUpOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIGVsc2UgewogICAgICAgICAgICAvLyDli5XkvZzmuIjjgb/jgr/jgqTjg57jg7zjgarjgZcKICAgICAgICAgICAgLy8gY29ubmVjdGlvbi5jcmVhdGVkIOOBruWgtOWQiOOCguWwkeOBl+Wun+ihjOOCkumBheOCieOBm+OCiwogICAgICAgICAgICByZW1vdmFsVGltZW91dElkID0gc2V0VGltZW91dCgoKSA9PiB7CiAgICAgICAgICAgICAgICByZW1vdmVPbGRSZW1vdGVEZXJpdmVLZXlzKCk7CiAgICAgICAgICAgICAgICBjbGVhclRpbWVvdXQocmVtb3ZhbFRpbWVvdXRJZCk7CiAgICAgICAgICAgICAgICByZW1vdmFsVGltZW91dElkID0gMDsKICAgICAgICAgICAgfSwgcmVtb3ZhbFdhaXRpbmdUaW1lKTsKICAgICAgICB9CiAgICB9CiAgICBlbHNlIGlmICh0eXBlID09PSAicmVtb3RlU2VjcmV0S2V5TWF0ZXJpYWxzIikgewogICAgICAgIGNvbnN0IHsgcmVtb3RlU2VjcmV0S2V5TWF0ZXJpYWxzIH0gPSBldmVudC5kYXRhOwogICAgICAgIGZvciAoY29uc3QgW2Nvbm5lY3Rpb25JZCwgcmVtb3RlU2VjcmV0S2V5TWF0ZXJpYWxdIG9mIE9iamVjdC5lbnRyaWVzKHJlbW90ZVNlY3JldEtleU1hdGVyaWFscykpIHsKICAgICAgICAgICAgY29uc3QgeyBrZXlJZCwgc2VjcmV0S2V5TWF0ZXJpYWwgfSA9IHJlbW90ZVNlY3JldEtleU1hdGVyaWFsOwogICAgICAgICAgICBjcnlwdG8uc3VidGxlCiAgICAgICAgICAgICAgICAuaW1wb3J0S2V5KCJyYXciLCBzZWNyZXRLZXlNYXRlcmlhbC5idWZmZXIsICJIS0RGIiwgZmFsc2UsIFsiZGVyaXZlQml0cyIsICJkZXJpdmVLZXkiXSkKICAgICAgICAgICAgICAgIC50aGVuKChtYXRlcmlhbCkgPT4gewogICAgICAgICAgICAgICAgZ2VuZXJhdGVEZXJpdmVLZXkobWF0ZXJpYWwpLnRoZW4oKGRlcml2ZUtleSkgPT4gewogICAgICAgICAgICAgICAgICAgIHNldFJlbW90ZURlcml2ZUtleShjb25uZWN0aW9uSWQsIGtleUlkLCBkZXJpdmVLZXkpOwogICAgICAgICAgICAgICAgfSk7CiAgICAgICAgICAgICAgICBnZW5lcmF0ZVdyaXRlSVYobWF0ZXJpYWwpLnRoZW4oKHdyaXRlSVYpID0+IHsKICAgICAgICAgICAgICAgICAgICBzZXRXcml0ZUlWKGNvbm5lY3Rpb25JZCwga2V5SWQsIHdyaXRlSVYpOwogICAgICAgICAgICAgICAgfSk7CiAgICAgICAgICAgICAgICBzZXRMYXRlc3RSZW1vdGVLZXlJZChjb25uZWN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GVhcigpOwogICAgICAgIHJlbW90ZURlcml2ZUtleU1hcC5jbGVhcigpOwogICAgICAgIGxhdGVzdFJlbW90ZUtleUlkTWFwLmNsZWFyKCk7CiAgICAgICAgc2VsZkRlcml2ZUtleU1hcC5jbGVhcigpOwogICAgfQp9Owo=");this.worker=new Worker(URL.createObjectURL(new Blob([e],{type:"application/javascript"}))),this.worker.onmessage=e=>{const{operation:t}=e.data;"disconnect"===t&&"function"==typeof this.onWorkerDisconnect&&this.onWorkerDisconnect()}}clearWorker(){this.worker&&this.worker.postMessage({type:"clear"})}terminateWorker(){this.worker&&this.worker.terminate()}async init(){const{preKeyBundle:e}=await window.e2ee.init();return e}setupSenderTransform(e){if(!e.track)return;const t=e.createEncodedStreams(),n=t.readableStream||t.readable,i=t.writableStream||t.writable;if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");const s={type:"encrypt",readableStream:n,writableStream:i};this.worker.postMessage(s,[n,i])}setupReceiverTransform(e){const t=e.createEncodedStreams(),n=t.readableStream||t.readable,i=t.writableStream||t.writable;if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");const s={type:"decrypt",readableStream:n,writableStream:i};this.worker.postMessage(s,[n,i])}postRemoteSecretKeyMaterials(e){if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");this.worker.postMessage({type:"remoteSecretKeyMaterials",remoteSecretKeyMaterials:e.remoteSecretKeyMaterials})}postRemoveRemoteDeriveKey(e){if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");this.worker.postMessage({type:"removeRemoteDeriveKey",connectionId:e})}postSelfSecretKeyMaterial(e,t,n,i=0){if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");this.worker.postMessage({type:"selfSecretKeyMaterial",selfConnectionId:e,selfKeyId:t,selfSecretKeyMaterial:n,waitingTime:i})}startSession(e,t){const[n,i]=window.e2ee.startSession(e,t.identityKey,t.signedPreKey,t.preKeySignature);if(i)throw i;return n}stopSession(e){const[t,n]=window.e2ee.stopSession(e);if(n)throw n;return t}receiveMessage(e){const[t,n]=window.e2ee.receiveMessage(e);if(n)throw n;return t}start(e){const[t,n]=window.e2ee.start(e);if(n)throw n;return t}addPreKeyBundle(e,t){const n=window.e2ee.addPreKeyBundle(e,t.identityKey,t.signedPreKey,t.preKeySignature);if(n)throw n}selfFingerprint(){return window.e2ee.selfFingerprint()}remoteFingerprints(){return window.e2ee.remoteFingerprints()}static async loadWasm(e){if(void 0===!window.e2ee)return void console.warn("E2ee wasm is already loaded. Will not be reload.");if((()=>{if("undefined"!=typeof global);else if("undefined"!=typeof window)window.global=window;else{if("undefined"==typeof self)throw new Error("cannot export Go (neither global, window nor self is defined)");self.global=self}if(global.require||"undefined"==typeof require||(global.require=require),!global.fs&&global.require){const e=require("fs");0!==Object.keys(e)&&(global.fs=e)}const e=()=>{const e=new Error("not implemented");return e.code="ENOSYS",e};if(!global.fs){let t="";global.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1},writeSync(e,i){t+=n.decode(i);const s=t.lastIndexOf("\n");return-1!=s&&(console.log(t.substr(0,s)),t=t.substr(s+1)),i.length},write(t,n,i,s,a,o){0===i&&s===n.length&&null===a?o(null,this.writeSync(t,n)):o(e())},chmod(t,n,i){i(e())},chown(t,n,i,s){s(e())},close(t,n){n(e())},fchmod(t,n,i){i(e())},fchown(t,n,i,s){s(e())},fstat(t,n){n(e())},fsync(e,t){t(null)},ftruncate(t,n,i){i(e())},lchown(t,n,i,s){s(e())},link(t,n,i){i(e())},lstat(t,n){n(e())},mkdir(t,n,i){i(e())},open(t,n,i,s){s(e())},read(t,n,i,s,a,o){o(e())},readdir(t,n){n(e())},readlink(t,n){n(e())},rename(t,n,i){i(e())},rmdir(t,n){n(e())},stat(t,n){n(e())},symlink(t,n,i){i(e())},truncate(t,n,i){i(e())},unlink(t,n){n(e())},utimes(t,n,i,s){s(e())}}}if(global.process||(global.process={getuid:()=>-1,getgid:()=>-1,geteuid:()=>-1,getegid:()=>-1,getgroups(){throw e()},pid:-1,ppid:-1,umask(){throw e()},cwd(){throw e()},chdir(){throw e()}}),!global.crypto){const e=require("crypto");global.crypto={getRandomValues(t){e.randomFillSync(t)}}}global.performance||(global.performance={now(){const[e,t]=process.hrtime();return 1e3*e+t/1e6}}),global.TextEncoder||(global.TextEncoder=require("util").TextEncoder),global.TextDecoder||(global.TextDecoder=require("util").TextDecoder);const t=new TextEncoder("utf-8"),n=new TextDecoder("utf-8");if(global.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=e=>{0!==e&&console.warn("exit code:",e)},this._exitPromise=new Promise((e=>{this._resolveExitPromise=e})),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;const e=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},i=e=>this.mem.getUint32(e+0,!0)+4294967296*this.mem.getInt32(e+4,!0),s=e=>{const t=this.mem.getFloat64(e,!0);if(0===t)return;if(!isNaN(t))return t;const n=this.mem.getUint32(e,!0);return this._values[n]},a=(e,t)=>{const n=2146959360;if("number"==typeof t&&0!==t)return isNaN(t)?(this.mem.setUint32(e+4,n,!0),void this.mem.setUint32(e,0,!0)):void this.mem.setFloat64(e,t,!0);if(void 0===t)return void this.mem.setFloat64(e,0,!0);let i=this._ids.get(t);void 0===i&&(i=this._idPool.pop(),void 0===i&&(i=this._values.length),this._values[i]=t,this._goRefCounts[i]=0,this._ids.set(t,i)),this._goRefCounts[i]++;let s=0;switch(typeof t){case"object":null!==t&&(s=1);break;case"string":s=2;break;case"symbol":s=3;break;case"function":s=4}this.mem.setUint32(e+4,n|s,!0),this.mem.setUint32(e,i,!0)},o=e=>{const t=i(e+0),n=i(e+8);return new Uint8Array(this._inst.exports.mem.buffer,t,n)},g=e=>{const t=i(e+0),n=i(e+8),a=new Array(n);for(let e=0;e{const t=i(e+0),s=i(e+8);return n.decode(new DataView(this._inst.exports.mem.buffer,t,s))},c=Date.now()-performance.now();this.importObject={go:{"runtime.wasmExit":e=>{const t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{const t=i(e+8),n=i(e+16),s=this.mem.getInt32(e+24,!0);fs.writeSync(t,new Uint8Array(this._inst.exports.mem.buffer,n,s))},"runtime.resetMemoryDataView":e=>{this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":t=>{e(t+8,1e6*(c+performance.now()))},"runtime.walltime1":t=>{const n=(new Date).getTime();e(t+8,n/1e3),this.mem.setInt32(t+16,n%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{const t=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(t,setTimeout((()=>{for(this._resume();this._scheduledTimeouts.has(t);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()}),i(e+8)+1)),this.mem.setInt32(e+16,t,!0)},"runtime.clearTimeoutEvent":e=>{const t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{crypto.getRandomValues(o(e+8))},"syscall/js.finalizeRef":e=>{const t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,0===this._goRefCounts[t]){const e=this._values[t];this._values[t]=null,this._ids.delete(e),this._idPool.push(t)}},"syscall/js.stringVal":e=>{a(e+24,l(e+8))},"syscall/js.valueGet":e=>{const t=Reflect.get(s(e+8),l(e+16));e=this._inst.exports.getsp(),a(e+32,t)},"syscall/js.valueSet":e=>{Reflect.set(s(e+8),l(e+16),s(e+32))},"syscall/js.valueDelete":e=>{Reflect.deleteProperty(s(e+8),l(e+16))},"syscall/js.valueIndex":e=>{a(e+24,Reflect.get(s(e+8),i(e+16)))},"syscall/js.valueSetIndex":e=>{Reflect.set(s(e+8),i(e+16),s(e+24))},"syscall/js.valueCall":e=>{try{const t=s(e+8),n=Reflect.get(t,l(e+16)),i=g(e+32),o=Reflect.apply(n,t,i);e=this._inst.exports.getsp(),a(e+56,o),this.mem.setUint8(e+64,1)}catch(t){a(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{try{const t=s(e+8),n=g(e+16),i=Reflect.apply(t,void 0,n);e=this._inst.exports.getsp(),a(e+40,i),this.mem.setUint8(e+48,1)}catch(t){a(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{try{const t=s(e+8),n=g(e+16),i=Reflect.construct(t,n);e=this._inst.exports.getsp(),a(e+40,i),this.mem.setUint8(e+48,1)}catch(t){a(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":t=>{e(t+16,parseInt(s(t+8).length))},"syscall/js.valuePrepareString":n=>{const i=t.encode(String(s(n+8)));a(n+16,i),e(n+24,i.length)},"syscall/js.valueLoadString":e=>{const t=s(e+8);o(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{this.mem.setUint8(e+24,s(e+8)instanceof s(e+16)?1:0)},"syscall/js.copyBytesToGo":t=>{const n=o(t+8),i=s(t+32);if(!(i instanceof Uint8Array||i instanceof Uint8ClampedArray))return void this.mem.setUint8(t+48,0);const a=i.subarray(0,n.length);n.set(a),e(t+40,a.length),this.mem.setUint8(t+48,1)},"syscall/js.copyBytesToJS":t=>{const n=s(t+8),i=o(t+16);if(!(n instanceof Uint8Array||n instanceof Uint8ClampedArray))return void this.mem.setUint8(t+48,0);const a=i.subarray(0,n.length);n.set(a),e(t+40,a.length),this.mem.setUint8(t+48,1)},debug:e=>{console.log(e)}}}}async run(e){this._inst=e,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,global,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[global,5],[this,6]]),this._idPool=[],this.exited=!1;let n=4096;const i=e=>{const i=n,s=t.encode(e+"\0");return new Uint8Array(this.mem.buffer,n,s.length).set(s),n+=s.length,n%8!=0&&(n+=8-n%8),i},s=this.argv.length,a=[];this.argv.forEach((e=>{a.push(i(e))})),a.push(0),Object.keys(this.env).sort().forEach((e=>{a.push(i(`${e}=${this.env[e]}`))})),a.push(0);const o=n;a.forEach((e=>{this.mem.setUint32(n,e,!0),this.mem.setUint32(n+4,0,!0),n+=8})),this._inst.exports.run(s,o),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(e){const t=this;return function(){const n={id:e,this:this,args:arguments};return t._pendingEvent=n,t._resume(),n.result}}},global.require&&global.require.main===module&&global.process&&global.process.versions&&!global.process.versions.electron){process.argv.length<3&&(console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"),process.exit(1));const e=new Go;e.argv=process.argv.slice(2),e.env=Object.assign({TMPDIR:require("os").tmpdir()},process.env),e.exit=process.exit,WebAssembly.instantiate(fs.readFileSync(process.argv[2]),e.importObject).then((t=>(process.on("exit",(t=>{0!==t||e.exited||(e._pendingEvent={id:0},e._resume())})),e.run(t.instance)))).catch((e=>{console.error(e),process.exit(1)}))}})(),!window.Go)throw new Error(`Failed to load module Go. window.Go is ${window.Go}.`);const t=new Go,{instance:n}=await WebAssembly.instantiateStreaming(fetch(e),t.importObject);if(t.run(n),!window.e2ee)throw new Error(`Failed to load module e2ee. window.e2ee is ${window.e2ee}.`)}static version(){return"2021.1.0"}static wasmVersion(){return window.e2ee.version()}}var t=Uint8Array,n=Uint16Array,i=Uint32Array,s=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),a=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),g=function(e,t){for(var s=new n(31),a=0;a<31;++a)s[a]=t+=1<>>1|(21845&m)<<1;u=(61680&(u=(52428&u)>>>2|(13107&u)<<2))>>>4|(3855&u)<<4,I[m]=((65280&u)>>>8|(255&u)<<8)>>>1}var A=function(e,t,i){for(var s=e.length,a=0,o=new n(t);a>>c]=r}else for(g=new n(s),a=0;a>>15-e[a]);return g},b=new t(288);for(m=0;m<144;++m)b[m]=8;for(m=144;m<256;++m)b[m]=9;for(m=256;m<280;++m)b[m]=7;for(m=280;m<288;++m)b[m]=8;var p=new t(32);for(m=0;m<32;++m)p[m]=5;var Z=A(b,9,0),w=A(b,9,1),S=A(p,5,0),V=A(p,5,1),f=function(e){for(var t=e[0],n=1;nt&&(t=e[n]);return t},y=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&n},W=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},G=function(e){return(e+7)/8|0},k=function(e,s,a){(null==s||s<0)&&(s=0),(null==a||a>e.length)&&(a=e.length);var o=new(e instanceof n?n:e instanceof i?i:t)(a-s);return o.set(e.subarray(s,a)),o},R=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],v=function(e,t,n){var i=new Error(t||R[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,v),!n)throw i;return i},T=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},X=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},O=function(e,i){for(var s=[],a=0;aI&&(I=g[a].s);var m=new n(I+1),u=E(s[d-1],m,0);if(u>i){a=0;var A=0,b=u-i,p=1<i))break;A+=p-(1<>>=b;A>0;){var w=g[a].s;m[w]=0&&A;--a){var S=g[a].s;m[S]==i&&(--m[S],++A)}u=i}return[new t(m),u]},E=function(e,t,n){return-1==e.s?Math.max(E(e.l,t,n+1),E(e.r,t,n+1)):t[e.s]=n},N=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new n(++t),s=0,a=e[0],o=1,g=function(e){i[s++]=e},l=1;l<=t;++l)if(e[l]==a&&l!=t)++o;else{if(!a&&o>2){for(;o>138;o-=138)g(32754);o>2&&(g(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(g(a),--o;o>6;o-=6)g(8304);o>2&&(g(o-3<<5|8208),o=0)}for(;o--;)g(a);o=1,a=e[l]}return[i.subarray(0,s),t]},B=function(e,t){for(var n=0,i=0;i>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var a=0;a4&&!D[o[U-1]];--U);var M,j,Q,H,x=h+5<<3,P=B(l,b)+B(c,p)+r,z=B(l,u)+B(c,f)+r+14+3*U+B(K,D)+(2*K[16]+3*K[17]+7*K[18]);if(x<=P&&x<=z)return Y(t,I,e.subarray(d,d+h));if(T(t,I,1+(z15&&(T(t,I,ee[L]>>>5&127),I+=ee[L]>>>12)}}}else M=Z,j=b,Q=S,H=p;for(L=0;L255){te=g[L]>>>18&31;X(t,I,M[te+257]),I+=j[te+257],te>7&&(T(t,I,g[L]>>>23&31),I+=s[te]);var ne=31&g[L];X(t,I,Q[ne]),I+=H[ne],ne>3&&(X(t,I,g[L]>>>5&8191),I+=a[ne])}else X(t,I,M[g[L]]),I+=j[g[L]];return X(t,I,M[256]),I+j[256]},L=new i([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),J=new t(0),D=function(e,o,g,l,c){return function(e,o,g,l,c,C){var d=e.length,I=new t(l+d+5*(1+Math.ceil(d/7e3))+c),m=I.subarray(l,I.length-c),u=0;if(!o||d<8)for(var A=0;A<=d;A+=65535){var b=A+65535;b>>13,w=8191&p,S=(1<7e3||N>24576)&&j>423){u=K(e,m,0,v,T,X,E,N,D,A-D,u),N=O=E=0,D=A;for(var Q=0;Q<286;++Q)T[Q]=0;for(Q=0;Q<30;++Q)X[Q]=0}var H=2,x=0,P=w,z=U-M&32767;if(j>2&&F==R(A-z))for(var _=Math.min(Z,j)-1,q=Math.min(32767,A),$=Math.min(258,j);z<=q&&--P&&U!=M;){if(e[A+H]==e[A+H-z]){for(var ee=0;ee<$&&e[A+ee]==e[A+ee-z];++ee);if(ee>H){if(H=ee,x=z,ee>_)break;var te=Math.min(z,ee-2),ne=0;for(Q=0;Qne&&(ne=se,M=ie)}}}z+=(U=M)-(M=V[U])+32768&32767}if(x){v[N++]=268435456|r[H]<<18|h[x];var ae=31&r[H],oe=31&h[x];E+=s[ae]+a[oe],++T[257+ae],++X[oe],B=A+H,++O}else v[N++]=e[A],++T[e[A]]}}u=K(e,m,C,v,T,X,E,N,D,A-D,u),!C&&7&u&&(u=Y(m,u+1,J))}return k(I,0,l+G(u)+c)}(e,null==o.level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+o.mem,g,l,!c)};function F(e,t){t||(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,s=t,a=0|n.length,o=0;o!=a;){for(var g=Math.min(o+2655,a);o>16),s=(65535&s)+15*(s>>16)}e=i,t=s},d:function(){return(255&(e%=65521))<<24|e>>>8<<16|(255&(t%=65521))<<8|t>>>8}}}();n.p(e);var i=D(e,t,2,4);return function(e,t){var n=t.level,i=0==n?0:n<6?1:9==n?3:2;e[0]=120,e[1]=i<<6|(i?32-2*i:1)}(i,t),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(i,i.length-4,n.d()),i}function U(e,n){return function(e,n,i){var g=e.length;if(!g||i&&i.f&&!i.l)return n||new t(0);var l=!n||i,r=!i||i.i;i||(i={}),n||(n=new t(3*g));var C=function(e){var i=n.length;if(e>i){var s=new t(Math.max(2*i,e));s.set(n),n=s}},h=i.f||0,I=i.p||0,m=i.b||0,u=i.l,b=i.d,p=i.m,Z=i.n,S=8*g;do{if(!u){h=y(e,I,1);var R=y(e,I+1,3);if(I+=3,!R){var T=e[(F=G(I)+4)-4]|e[F-3]<<8,X=F+T;if(X>g){r&&v(0);break}l&&C(m+T),n.set(e.subarray(F,X),m),i.b=m+=T,i.p=I=8*X,i.f=h;continue}if(1==R)u=w,b=V,p=9,Z=5;else if(2==R){var O=y(e,I,31)+257,E=y(e,I+10,15)+4,N=O+y(e,I+5,31)+1;I+=14;for(var B=new t(N),Y=new t(19),K=0;K>>4)<16)B[K++]=F;else{var M=0,j=0;for(16==F?(j=3+y(e,I,3),I+=2,M=B[K-1]):17==F?(j=3+y(e,I,7),I+=3):18==F&&(j=11+y(e,I,127),I+=7);j--;)B[K++]=M}}var Q=B.subarray(0,O),H=B.subarray(O);p=f(Q),Z=f(H),u=A(Q,p,1),b=A(H,Z,1)}else v(1);if(I>S){r&&v(0);break}}l&&C(m+131072);for(var x=(1<>>4;if((I+=15&M)>S){r&&v(0);break}if(M||v(2),_<256)n[m++]=_;else{if(256==_){z=I,u=null;break}var q=_-254;if(_>264){var $=s[K=_-257];q=y(e,I,(1<<$)-1)+c[K],I+=$}var ee=b[W(e,I)&P],te=ee>>>4;if(ee||v(3),I+=15&ee,H=d[te],te>3&&($=a[te],H+=W(e,I)&(1<<$)-1,I+=$),I>S){r&&v(0);break}l&&C(m+131072);for(var ne=m+q;m>>4>7||(i[0]<<8|i[1])%31)&&v(6,"invalid zlib data"),32&i[1]&&v(6,"invalid zlib data: preset dictionaries not supported"),e.subarray(2,-4)),n);var i}var M="undefined"!=typeof TextDecoder&&new TextDecoder;try{M.decode(J,{stream:!0}),1}catch(e){}function j(e){if("object"!=typeof e||null===e)throw new Error("Failed to parse options dataChannels. Options dataChannels element must be type 'object'");const t=e,n={};return"string"==typeof t.label&&(n.label=t.label),"string"==typeof t.direction&&(n.direction=t.direction),"boolean"==typeof t.ordered&&(n.ordered=t.ordered),"boolean"==typeof t.compress&&(n.compress=t.compress),"number"==typeof t.maxPacketLifeTime&&(n.max_packet_life_time=t.maxPacketLifeTime),"number"==typeof t.maxRetransmits&&(n.max_retransmits=t.maxRetransmits),"string"==typeof t.protocol&&(n.protocol=t.protocol),n}function Q(){return"safari"===function(){const e=window.navigator.userAgent.toLocaleLowerCase();return-1!==e.indexOf("edge")?"edge":-1!==e.indexOf("chrome")&&-1===e.indexOf("edge")?"chrome":-1!==e.indexOf("safari")&&-1===e.indexOf("chrome")?"safari":-1!==e.indexOf("opera")?"opera":-1!==e.indexOf("firefox")?"firefox":null}()}function H(e,t,n,i,s,a){if("sendrecv"!==t&&"sendonly"!==t&&"recvonly"!==t)throw new Error("Unknown role type");if(null==n)throw new Error("channelId can not be null or undefined");const o={type:"connect",sora_client:"Sora JavaScript SDK 2021.2.0-canary.11",environment:window.navigator.userAgent,role:t,channel_id:n,sdp:e,audio:!0,video:!0};if(void 0!==i&&(o.metadata=i),a&&(o.redirect=!0),"signalingNotifyMetadata"in s&&(o.signaling_notify_metadata=s.signalingNotifyMetadata),"multistream"in s&&!0===s.multistream&&(o.multistream=!0,"spotlight"in s&&(o.spotlight=s.spotlight,"spotlightNumber"in s&&(o.spotlight_number=s.spotlightNumber)),!0===o.spotlight)){const e=["none","r0","r1","r2"];void 0!==s.spotlightFocusRid&&0<=e.indexOf(s.spotlightFocusRid)&&(o.spotlight_focus_rid=s.spotlightFocusRid),void 0!==s.spotlightUnfocusRid&&0<=e.indexOf(s.spotlightUnfocusRid)&&(o.spotlight_unfocus_rid=s.spotlightUnfocusRid)}if("simulcast"in s||"simulcastRid"in s){"simulcast"in s&&!0===s.simulcast&&(o.simulcast=!0);const e=["r0","r1","r2"];void 0!==s.simulcastRid&&0<=e.indexOf(s.simulcastRid)&&(o.simulcast_rid=s.simulcastRid)}"clientId"in s&&void 0!==s.clientId&&(o.client_id=s.clientId),"dataChannelSignaling"in s&&"boolean"==typeof s.dataChannelSignaling&&(o.data_channel_signaling=s.dataChannelSignaling),"ignoreDisconnectWebSocket"in s&&"boolean"==typeof s.ignoreDisconnectWebSocket&&(o.ignore_disconnect_websocket=s.ignoreDisconnectWebSocket);const g=["audioCodecType","audioBitRate"],l=["audioOpusParamsChannels","audioOpusParamsClockRate","audioOpusParamsMaxplaybackrate","audioOpusParamsStereo","audioOpusParamsSpropStereo","audioOpusParamsMinptime","audioOpusParamsPtime","audioOpusParamsUseinbandfec","audioOpusParamsUsedtx"],c=["videoCodecType","videoBitRate"],r=Object.assign({},s);Object.keys(r).forEach((e=>{"audio"===e&&"boolean"==typeof r[e]||"video"===e&&"boolean"==typeof r[e]||0<=g.indexOf(e)&&null!==r[e]||0<=l.indexOf(e)&&null!==r[e]||0<=c.indexOf(e)&&null!==r[e]||delete r[e]})),void 0!==r.audio&&(o.audio=r.audio);const C=Object.keys(r).some((e=>0<=g.indexOf(e)));o.audio&&C&&(o.audio={},"audioCodecType"in r&&(o.audio.codec_type=r.audioCodecType),"audioBitRate"in r&&(o.audio.bit_rate=r.audioBitRate));const d=Object.keys(r).some((e=>0<=l.indexOf(e)));o.audio&&d&&("object"!=typeof o.audio&&(o.audio={}),o.audio.opus_params={},"audioOpusParamsChannels"in r&&(o.audio.opus_params.channels=r.audioOpusParamsChannels),"audioOpusParamsClockRate"in r&&(o.audio.opus_params.clock_rate=r.audioOpusParamsClockRate),"audioOpusParamsMaxplaybackrate"in r&&(o.audio.opus_params.maxplaybackrate=r.audioOpusParamsMaxplaybackrate),"audioOpusParamsStereo"in r&&(o.audio.opus_params.stereo=r.audioOpusParamsStereo),"audioOpusParamsSpropStereo"in r&&(o.audio.opus_params.sprop_stereo=r.audioOpusParamsSpropStereo),"audioOpusParamsMinptime"in r&&(o.audio.opus_params.minptime=r.audioOpusParamsMinptime),"audioOpusParamsPtime"in r&&(o.audio.opus_params.ptime=r.audioOpusParamsPtime),"audioOpusParamsUseinbandfec"in r&&(o.audio.opus_params.useinbandfec=r.audioOpusParamsUseinbandfec),"audioOpusParamsUsedtx"in r&&(o.audio.opus_params.usedtx=r.audioOpusParamsUsedtx)),void 0!==r.video&&(o.video=r.video);const h=Object.keys(r).some((e=>0<=c.indexOf(e)));if(o.video&&h&&(o.video={},"videoCodecType"in r&&(o.video.codec_type=r.videoCodecType),"videoBitRate"in r&&(o.video.bit_rate=r.videoBitRate)),o.simulcast&&!function(){if(!window.RTCRtpSender)return!1;if(!RTCRtpSender.getCapabilities)return!1;const e=RTCRtpSender.getCapabilities("video");if(!e)return!1;const t=e.headerExtensions.map((e=>e.uri));return["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"].every((e=>t.includes(e)))}()&&"recvonly"!==t)throw new Error("Simulcast can not be used with this browser");if(!0===s.e2ee){if(void 0===o.signaling_notify_metadata&&(o.signaling_notify_metadata={}),null===o.signaling_notify_metadata||"object"!=typeof o.signaling_notify_metadata)throw new Error("E2EE failed. Options signalingNotifyMetadata must be type 'object'");!0===o.video&&(o.video={}),o.video&&(o.video.codec_type="VP8"),o.e2ee=!0}return Array.isArray(s.dataChannels)&&0{},push:()=>{},addstream:()=>{},track:()=>{},removestream:()=>{},removetrack:()=>{},notify:()=>{},log:()=>{},timeout:()=>{},timeline:()=>{},signaling:()=>{},message:()=>{},datachannel:()=>{}},this.authMetadata=null,this.e2ee=null,this.connectionTimeoutTimerId=0,this.monitorSignalingWebSocketEventTimerId=0,this.monitorIceConnectionStateChangeTimerId=0,this.soraDataChannels={},this.mids={audio:"",video:""},this.signalingSwitched=!1,this.signalingOfferMessageDataChannels={}}on(e,t){"addstream"===e?console.warn("@deprecated addstream callback will be removed in a future version. Use track callback."):"removestream"===e&&console.warn("@deprecated removestream callback will be removed in a future version. Use removetrack callback."),e in this.callbacks&&(this.callbacks[e]=t)}stopAudioTrack(e){for(const t of e.getAudioTracks())t.enabled=!1;return new Promise((t=>{setTimeout((async()=>{for(const t of e.getAudioTracks())if(t.stop(),e.removeTrack(t),null!==this.pc){const e=this.pc.getSenders().find((e=>e.track&&e.track.id===t.id));e&&await e.replaceTrack(null)}t()}),100)}))}stopVideoTrack(e){for(const t of e.getVideoTracks())t.enabled=!1;return new Promise((t=>{setTimeout((async()=>{for(const t of e.getVideoTracks())if(t.stop(),e.removeTrack(t),null!==this.pc){const e=this.pc.getSenders().find((e=>e.track&&e.track.id===t.id));e&&await e.replaceTrack(null)}t()}),100)}))}async replaceAudioTrack(e,t){await this.stopAudioTrack(e);const n=this.getAudioTransceiver();if(null===n)throw new Error("Unable to set an audio track. Audio track sender is undefined");e.addTrack(t),await n.sender.replaceTrack(t)}async replaceVideoTrack(e,t){await this.stopVideoTrack(e);const n=this.getVideoTransceiver();if(null===n)throw new Error("Unable to set video track. Video track sender is undefined");e.addTrack(t),await n.sender.replaceTrack(t)}stopStream(){return new Promise(((e,t)=>(this.debug&&console.warn("@deprecated closing MediaStream in disconnect will be removed in a future version. Close every track in the MediaStream by yourself."),this.stream?(this.stream.getTracks().forEach((e=>{e.stop()})),this.stream=null,e()):e())))}async signalingTerminate(){await this.stopStream();for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&t.close(),delete this.soraDataChannels[e]}this.ws&&(this.ws.close(),this.ws=null),this.pc&&this.pc.close(),this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection()}async abendPeerConnectionState(e){this.clearMonitorIceConnectionStateChange(),await this.stopStream(),this.pc&&(this.pc.ondatachannel=null,this.pc.oniceconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.pc.onconnectionstatechange=null),this.ws&&(this.ws.onclose=e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason})},this.ws.onmessage=null,this.ws.onerror=null);for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onclose=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label)},t.onmessage=null,t.onerror=null)}for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&t.close(),delete this.soraDataChannels[e]}this.ws&&(this.ws.close(),this.ws=null),this.pc&&this.pc.close(),this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection();const t=this.soraCloseEvent("abend",e);this.callbacks.disconnect(t),this.writeSoraTimelineLog("disconnect-abend",t)}async abend(e,t){this.clearMonitorIceConnectionStateChange(),await this.stopStream(),this.pc&&(this.pc.ondatachannel=null,this.pc.oniceconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.pc.onconnectionstatechange=null),this.ws&&(this.ws.onclose=e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason})},this.ws.onmessage=null,this.ws.onerror=null);for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onclose=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label)},t.onmessage=null,t.onerror=null)}if(this.soraDataChannels.signaling){const t={type:"disconnect",reason:e};if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const e=F((new TextEncoder).encode(JSON.stringify(t)),{});if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(e),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,t)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}else if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(JSON.stringify(t)),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,t)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onerror=null,t.close()),delete this.soraDataChannels[e]}if(await this.disconnectWebSocket(e),await this.disconnectPeerConnection(),this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection(),"WEBSOCKET-ONCLOSE"===e&&t&&(1e3===t.code||1005===t.code)){const e=this.soraCloseEvent("normal","DISCONNECT",t);return this.writeSoraTimelineLog("disconnect-normal",e),void this.callbacks.disconnect(e)}const n=this.soraCloseEvent("abend",e,t);this.writeSoraTimelineLog("disconnect-abend",n),this.callbacks.disconnect(this.soraCloseEvent("abend",e,t))}initializeConnection(){this.clientId=null,this.connectionId=null,this.remoteConnectionIds=[],this.stream=null,this.ws=null,this.pc=null,this.encodings=[],this.authMetadata=null,this.e2ee=null,this.soraDataChannels={},this.mids={audio:"",video:""},this.signalingSwitched=!1,this.signalingOfferMessageDataChannels={},this.clearConnectionTimeout()}disconnectWebSocket(e){let t=0;return this.signalingSwitched?(this.ws&&(this.ws.close(),this.ws=null),Promise.resolve(null)):new Promise(((n,i)=>{if(!this.ws)return n(null);if(this.ws.onclose=e=>(this.ws&&(this.ws.close(),this.ws=null),clearTimeout(t),this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason}),n({code:e.code,reason:e.reason})),1!==this.ws.readyState)return this.ws.close(),this.ws=null,n(null);{const i={type:"disconnect",reason:e};this.ws.send(JSON.stringify(i)),this.writeWebSocketSignalingLog("send-disconnect",i),t=setTimeout((()=>{this.ws&&(this.ws.close(),this.ws=null),n({code:1006,reason:""})}),this.disconnectWaitTimeout)}}))}disconnectDataChannel(){const e=()=>{for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onerror=null,t.close()),delete this.soraDataChannels[e]}};return new Promise(((t,n)=>{if(!this.soraDataChannels.signaling)return e(),t({code:4999,reason:""});const i=setTimeout((()=>(e(),n())),this.disconnectWaitTimeout),s=[];for(const n of Object.keys(this.soraDataChannels)){const a=this.soraDataChannels[n];if(a){a.onerror=()=>(clearTimeout(i),e(),t({code:4999,reason:""}));const n=()=>new Promise(((e,t)=>{let n=0;const i=setInterval((()=>{n++,"closed"===a.readyState&&(clearInterval(i),e()),this.disconnectWaitTimeout<100*n&&(e(),clearInterval(i))}),100)}));s.push(n())}}Promise.all(s).then((()=>{0===Object.keys(this.soraDataChannels).length?t(null):t({code:4999,reason:""})})).finally((()=>{e(),clearTimeout(i)}));const a={type:"disconnect",reason:"NO-ERROR"};if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const e=F((new TextEncoder).encode(JSON.stringify(a)),{});if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(e),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,a)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}else if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(JSON.stringify(a)),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,a)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}))}disconnectPeerConnection(){return new Promise(((e,t)=>(this.pc&&"closed"!==this.pc.connectionState&&this.pc.close(),e())))}async disconnect(){this.clearMonitorIceConnectionStateChange(),await this.stopStream(),this.pc&&(this.pc.ondatachannel=null,this.pc.oniceconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.pc.onconnectionstatechange=null),this.ws&&(this.ws.onclose=e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason})},this.ws.onmessage=null,this.ws.onerror=null);for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onmessage=null,t.onclose=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label)})}let e=null;if(this.signalingSwitched){try{const t=await this.disconnectDataChannel();null!==t&&(e=this.soraCloseEvent("normal","DISCONNECT",t))}catch(t){e=this.soraCloseEvent("abend","DISCONNECT-TIMEOUT")}await this.disconnectWebSocket("NO-ERROR"),await this.disconnectPeerConnection()}else{const t=await this.disconnectWebSocket("NO-ERROR");await this.disconnectPeerConnection(),null!==t&&(e=this.soraCloseEvent("normal","DISCONNECT",t))}this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection(),e&&("abend"===e.type?this.writeSoraTimelineLog("disconnect-abend",e):"normal"===e.type&&this.writeSoraTimelineLog("disconnect-normal",e),this.callbacks.disconnect(e))}setupE2EE(){!0===this.options.e2ee&&(this.e2ee=new e,this.e2ee.onWorkerDisconnect=async()=>{await this.abend("INTERNAL-ERROR",{reason:"CRASH-E2EE-WORKER"})},this.e2ee.startWorker())}startE2EE(){if(!0===this.options.e2ee&&this.e2ee){if(!this.connectionId){const e=new Error;throw e.message="E2EE failed. Self connectionId is null",e}this.e2ee.clearWorker();const e=this.e2ee.start(this.connectionId);this.e2ee.postSelfSecretKeyMaterial(this.connectionId,e.selfKeyId,e.selfSecretKeyMaterial)}}async getSignalingWebSocket(e){if("string"==typeof e){const t=e;return new Promise(((e,n)=>{const i=new WebSocket(t);i.onclose=e=>{const t=new z(`Signaling failed. CloseEventCode:${e.code} CloseEventReason:'${e.reason}'`);t.code=e.code,t.reason=e.reason,this.writeWebSocketTimelineLog("onclose",t),n(t)},i.onopen=t=>{e(i)}}))}if(Array.isArray(e)){let t=!1;const n=e=>new Promise(((n,i)=>{const s=new WebSocket(e),a=setTimeout((()=>{this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"timeout",url:s.url}),s&&!t&&(s.onclose=null,s.onerror=null,s.onopen=null,s.close(),i())}),this.signalingCandidateTimeout);s.onclose=e=>{this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"close",url:s.url,message:"WebSocket closed",code:e.code,reason:e.reason}),s&&s.close(),clearInterval(a),i()},s.onerror=e=>{this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"error",url:s.url,message:"Failed to connect WebSocket"}),s&&(s.onclose=null,s.close()),clearInterval(a),i()},s.onopen=e=>{s&&(clearInterval(a),t?(this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"open",url:s.url,selected:!1}),s.onerror=null,s.onclose=null,s.onopen=null,s.close(),i()):(this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"open",url:s.url,selected:!0}),s.onerror=null,s.onclose=null,s.onopen=null,t=!0,n(s)))}}));try{return await Promise.any(e.map((e=>n(e))))}catch(e){throw new z("Signaling failed. All signaling URL candidates failed to connect")}}throw new z("Signaling failed. Invalid format signaling URL candidates")}async signaling(e,t=!1){const n=await this.createOffer();return this.trace("CREATE OFFER",n),new Promise(((i,s)=>{this.writeWebSocketSignalingLog("new-websocket",e.url),e.binaryType="arraybuffer",e.onclose=async e=>{const t=new z(`Signaling failed. CloseEventCode:${e.code} CloseEventReason:'${e.reason}'`);t.code=e.code,t.reason=e.reason,this.writeWebSocketTimelineLog("onclose",t),await this.signalingTerminate(),s(t)},e.onmessage=async e=>{if(e.data instanceof ArrayBuffer)return this.writeWebSocketSignalingLog("onmessage-e2ee",e.data),void this.signalingOnMessageE2EE(e.data);const t=JSON.parse(e.data);if("offer"==t.type)this.writeWebSocketSignalingLog("onmessage-offer",t),this.signalingOnMessageTypeOffer(t),i(t);else if("update"==t.type)this.writeWebSocketSignalingLog("onmessage-update",t),await this.signalingOnMessageTypeUpdate(t);else if("re-offer"==t.type)this.writeWebSocketSignalingLog("onmessage-re-offer",t),await this.signalingOnMessageTypeReOffer(t);else if("ping"==t.type)await this.signalingOnMessageTypePing(t);else if("push"==t.type)this.callbacks.push(t,"websocket");else if("notify"==t.type)"connection.created"===t.event_type?this.writeWebSocketTimelineLog("notify-connection.created",t):"connection.destroyed"===t.event_type&&this.writeWebSocketTimelineLog("notify-connection.destroyed",t),this.signalingOnMessageTypeNotify(t,"websocket");else if("switched"==t.type)this.writeWebSocketSignalingLog("onmessage-switched",t),this.signalingOnMessageTypeSwitched(t);else if("redirect"==t.type){this.writeWebSocketSignalingLog("onmessage-redirect",t);const e=await this.signalingOnMessageTypeRedirect(t);i(e)}},(async()=>{let i;try{i=H(n.sdp||"",this.role,this.channelId,this.metadata,this.options,t)}catch(e){return void s(e)}if(i.e2ee&&this.e2ee){const e=await this.e2ee.init();i.signaling_notify_metadata.pre_key_bundle=e}this.trace("SIGNALING CONNECT MESSAGE",i),e&&(e.send(JSON.stringify(i)),this.writeWebSocketSignalingLog(`send-${i.type}`,i),this.ws=e)})()}))}async connectPeerConnection(e){let t=Object.assign({},e.config);if(this.e2ee&&(t=Object.assign({encodedInsertableStreams:!0},t)),void 0!==window.RTCPeerConnection.generateCertificate){const e=await window.RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"});t=Object.assign({certificates:[e]},t)}this.trace("PEER CONNECTION CONFIG",t),this.writePeerConnectionTimelineLog("new-peerconnection",t),this.pc=new window.RTCPeerConnection(t,this.constraints),this.pc.oniceconnectionstatechange=e=>{this.pc&&(this.writePeerConnectionTimelineLog("oniceconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),this.trace("ONICECONNECTIONSTATECHANGE ICECONNECTIONSTATE",this.pc.iceConnectionState))},this.pc.onicegatheringstatechange=e=>{this.pc&&this.writePeerConnectionTimelineLog("onicegatheringstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState})},this.pc.onconnectionstatechange=e=>{this.pc&&this.writePeerConnectionTimelineLog("onconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState})},this.pc.ondatachannel=e=>{this.onDataChannel(e)}}async setRemoteDescription(e){if(!this.pc)return;const t=new RTCSessionDescription({type:"offer",sdp:e.sdp});await this.pc.setRemoteDescription(t),this.writePeerConnectionTimelineLog("set-remote-description",t)}async createAnswer(e){if(!this.pc)return;for(const e of Object.values(this.mids)){const t=this.pc.getTransceivers().find((t=>t.mid===e));t&&"recvonly"===t.direction&&(t.direction="sendrecv")}if(this.options.simulcast&&("sendrecv"===this.role||"sendonly"===this.role)){const t=this.pc.getTransceivers().find((e=>{if(null!==e.mid&&null!==e.sender.track&&(null===e.currentDirection||"sendonly"===e.currentDirection))return""!==this.mids.video&&this.mids.video===e.mid||0<=e.mid.indexOf("video")?e:void 0}));if(t){await this.setSenderParameters(t,this.encodings),await this.setRemoteDescription(e),this.trace("TRANSCEIVER SENDER GET_PARAMETERS",t.sender.getParameters()),await this.setSenderParameters(t,this.encodings);const n=await this.pc.createAnswer();return await this.pc.setLocalDescription(n),void this.trace("TRANSCEIVER SENDER GET_PARAMETERS",t.sender.getParameters())}}const t=await this.pc.createAnswer();this.writePeerConnectionTimelineLog("create-answer",t),await this.pc.setLocalDescription(t),this.writePeerConnectionTimelineLog("set-local-description",t)}sendAnswer(){if(this.pc&&this.ws&&this.pc.localDescription){this.trace("ANSWER SDP",this.pc.localDescription.sdp);const e={type:"answer",sdp:this.pc.localDescription.sdp};this.ws.send(JSON.stringify(e)),this.writeWebSocketSignalingLog("send-answer",e)}}onIceCandidate(){return new Promise(((e,t)=>{this.pc&&(this.pc.oniceconnectionstatechange=t=>{this.pc&&(this.writePeerConnectionTimelineLog("oniceconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),this.trace("ONICECONNECTIONSTATECHANGE ICECONNECTIONSTATE",this.pc.iceConnectionState),"connected"===this.pc.iceConnectionState&&e())},this.pc.onicecandidate=t=>{if(this.writePeerConnectionTimelineLog("onicecandidate",t.candidate),this.pc&&this.trace("ONICECANDIDATE ICEGATHERINGSTATE",this.pc.iceGatheringState),null===t.candidate)e();else{const e=t.candidate.toJSON(),n=Object.assign(e,{type:"candidate"});this.trace("ONICECANDIDATE CANDIDATE MESSAGE",n),this.sendSignalingMessage(n)}})}))}waitChangeConnectionStateConnected(){return new Promise(((e,t)=>{if(this.pc&&void 0===this.pc.connectionState)return void e();const n=setInterval((()=>{if(this.pc)this.pc&&"connected"===this.pc.connectionState&&(clearInterval(n),e());else{const e=new Error;e.message="PeerConnection connectionState did not change to 'connected'",clearInterval(n),t(e)}}),10)}))}monitorSignalingWebSocketEvent(){return new Promise(((e,t)=>{this.monitorSignalingWebSocketEventTimerId=setInterval((()=>{this.ws&&(this.clearMonitorSignalingWebSocketEvent(),this.ws.onclose=async e=>{const n=new z(`Signaling failed. CloseEventCode:${e.code} CloseEventReason:'${e.reason}'`);n.code=e.code,n.reason=e.reason,this.writeWebSocketTimelineLog("onclose",n),await this.signalingTerminate(),t(n)},this.ws.onerror=async e=>{const n=new z("Signaling failed. WebSocket onerror was called");this.writeWebSocketSignalingLog("onerror",n),await this.signalingTerminate(),t(n)})}),100)}))}monitorWebSocketEvent(){this.ws&&(this.ws.onclose=async e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason}),await this.abend("WEBSOCKET-ONCLOSE",{code:e.code,reason:e.reason})},this.ws.onerror=async e=>{this.writeWebSocketSignalingLog("onerror"),await this.abend("WEBSOCKET-ONERROR")})}monitorPeerConnectionState(){this.pc&&(this.pc.oniceconnectionstatechange=async e=>{this.pc&&void 0===this.pc.connectionState&&(this.writePeerConnectionTimelineLog("oniceconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),this.trace("ONICECONNECTIONSTATECHANGE ICECONNECTIONSTATE",this.pc.iceConnectionState),clearTimeout(this.monitorIceConnectionStateChangeTimerId),"failed"===this.pc.iceConnectionState?await this.abendPeerConnectionState("ICE-CONNECTION-STATE-FAILED"):"disconnected"===this.pc.iceConnectionState&&(this.monitorIceConnectionStateChangeTimerId=setTimeout((async()=>{this.pc&&"disconnected"===this.pc.iceConnectionState&&await this.abendPeerConnectionState("ICE-CONNECTION-STATE-DISCONNECTED-TIMEOUT")}),1e4)))},this.pc.onconnectionstatechange=async e=>{this.pc&&(this.writePeerConnectionTimelineLog("onconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),"failed"===this.pc.connectionState&&await this.abendPeerConnectionState("CONNECTION-STATE-FAILED"))})}setConnectionTimeout(){return new Promise(((e,t)=>{0{if(!this.pc||this.pc&&void 0!==this.pc.connectionState&&"connected"!==this.pc.connectionState){const e=new Error;e.message="Signaling connection timeout",this.callbacks.timeout(),this.trace("DISCONNECT","Signaling connection timeout"),this.writePeerConnectionTimelineLog("signaling-connection-timeout",{connectionTimeout:this.connectionTimeout}),await this.signalingTerminate(),t(e)}}),this.connectionTimeout))}))}clearConnectionTimeout(){clearTimeout(this.connectionTimeoutTimerId)}clearMonitorSignalingWebSocketEvent(){clearInterval(this.monitorSignalingWebSocketEventTimerId)}clearMonitorIceConnectionStateChange(){clearInterval(this.monitorIceConnectionStateChangeTimerId)}trace(e,t){this.callbacks.log(e,t),this.debug&&function(e,t,n){const i=e=>{if(e&&"object"==typeof e){let t=null;try{t=Object.keys(JSON.parse(JSON.stringify(e)))}catch(e){}t&&Array.isArray(t)?t.forEach((t=>{console.group(t),i(e[t]),console.groupEnd()})):console.info(e)}else console.info(e)};let s="";window.performance&&(s="["+(window.performance.now()/1e3).toFixed(3)+"]"),e&&(s=s+"["+e+"]"),void 0!==console.info&&void 0!==console.group?(console.group(s+" "+t),i(n),console.groupEnd()):console.log(s+" "+t+"\n",n)}(this.clientId,e,t)}writeWebSocketSignalingLog(e,t){this.callbacks.signaling(_(e,t,"websocket")),this.writeWebSocketTimelineLog(e,t)}writeDataChannelSignalingLog(e,t,n){this.callbacks.signaling(_(e,n,"datachannel")),this.writeDataChannelTimelineLog(e,t,n)}writeWebSocketTimelineLog(e,t){const n=q(e,t,"websocket");this.callbacks.timeline(n)}writeDataChannelTimelineLog(e,t,n){const i=q(e,n,"datachannel",t.id,t.label);this.callbacks.timeline(i)}writePeerConnectionTimelineLog(e,t){const n=q(e,t,"peerconnection");this.callbacks.timeline(n)}writeSoraTimelineLog(e,t){const n=q(e,t,"sora");this.callbacks.timeline(n)}async createOffer(){const e=new window.RTCPeerConnection({iceServers:[]});if(Q()){e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"});const t=await e.createOffer();return e.close(),this.writePeerConnectionTimelineLog("create-offer",t),t}const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});return e.close(),this.writePeerConnectionTimelineLog("create-offer",t),t}signalingOnMessageE2EE(e){if(this.e2ee){const t=new Uint8Array(e),n=this.e2ee.receiveMessage(t);this.e2ee.postRemoteSecretKeyMaterials(n),n.messages.forEach((e=>{this.sendE2EEMessage(e.buffer)}))}}signalingOnMessageTypeOffer(e){if(this.clientId=e.client_id,this.connectionId=e.connection_id,void 0!==e.metadata&&(this.authMetadata=e.metadata),Array.isArray(e.encodings)&&(this.encodings=e.encodings),void 0!==e.mid&&void 0!==e.mid.audio&&(this.mids.audio=e.mid.audio),void 0!==e.mid&&void 0!==e.mid.video&&(this.mids.video=e.mid.video),e.data_channels)for(const t of e.data_channels)this.signalingOfferMessageDataChannels[t.label]=t;this.trace("SIGNALING OFFER MESSAGE",e),this.trace("OFFER SDP",e.sdp)}sendUpdateAnswer(){this.pc&&this.ws&&this.pc.localDescription&&(this.trace("ANSWER SDP",this.pc.localDescription.sdp),this.sendSignalingMessage({type:"update",sdp:this.pc.localDescription.sdp}))}sendReAnswer(){this.pc&&this.pc.localDescription&&(this.trace("RE ANSWER SDP",this.pc.localDescription.sdp),this.sendSignalingMessage({type:"re-answer",sdp:this.pc.localDescription.sdp}))}async signalingOnMessageTypeUpdate(e){this.trace("SIGNALING UPDATE MESSGE",e),this.trace("UPDATE SDP",e.sdp),await this.setRemoteDescription(e),await this.createAnswer(e),this.sendUpdateAnswer()}async signalingOnMessageTypeReOffer(e){this.trace("SIGNALING RE OFFER MESSGE",e),this.trace("RE OFFER SDP",e.sdp),await this.setRemoteDescription(e),await this.createAnswer(e),this.sendReAnswer()}async signalingOnMessageTypePing(e){const t={type:"pong"};if(e.stats){const e=await this.getStats();t.stats=e}this.ws&&this.ws.send(JSON.stringify(t))}signalingOnMessageTypeNotify(e,t){if("connection.created"===e.event_type){const t=e.connection_id;if(this.connectionId!==t){const n=P(x(e));if(n&&this.e2ee&&t){const e=this.e2ee.startSession(t,n);this.e2ee.postRemoteSecretKeyMaterials(e),e.messages.forEach((e=>{this.sendE2EEMessage(e.buffer)})),this.e2ee.postSelfSecretKeyMaterial(e.selfConnectionId,e.selfKeyId,e.selfSecretKeyMaterial)}}const n=function(e){return e.data&&Array.isArray(e.data)?e.data:e.metadata_list&&Array.isArray(e.metadata_list)?e.metadata_list:[]}(e);n.forEach((e=>{const t=P(x(e)),n=e.connection_id;n&&this.e2ee&&t&&this.e2ee.addPreKeyBundle(n,t)}))}else if("connection.destroyed"===e.event_type){const t=P(x(e)),n=e.connection_id;if(t&&this.e2ee&&n){const e=this.e2ee.stopSession(n);this.e2ee.postSelfSecretKeyMaterial(e.selfConnectionId,e.selfKeyId,e.selfSecretKeyMaterial,5e3),e.messages.forEach((e=>{this.sendE2EEMessage(e.buffer)})),this.e2ee.postRemoveRemoteDeriveKey(n)}}this.callbacks.notify(e,t)}signalingOnMessageTypeSwitched(e){if(this.signalingSwitched=!0,this.ws){e.ignore_disconnect_websocket&&(this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.writeWebSocketSignalingLog("close"));for(const e of this.datachannels)this.callbacks.datachannel($(e))}}async signalingOnMessageTypeRedirect(e){this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null);const t=await this.getSignalingWebSocket(e.location);return await this.signaling(t,!0)}async setSenderParameters(e,t){const n=e.sender.getParameters();n.encodings=t,await e.sender.setParameters(n),this.trace("TRANSCEIVER SENDER SET_PARAMETERS",n),this.writePeerConnectionTimelineLog("transceiver-sender-set-parameters",n)}async getStats(){const e=[];if(!this.pc)return e;return(await this.pc.getStats()).forEach((t=>{e.push(t)})),e}onDataChannel(e){const t=e.channel;var n;this.writeDataChannelTimelineLog("ondatachannel",t,{binaryType:(n=t).binaryType,bufferedAmount:n.bufferedAmount,bufferedAmountLowThreshold:n.bufferedAmountLowThreshold,id:n.id,label:n.label,maxPacketLifeTime:n.maxPacketLifeTime,maxRetransmits:n.maxRetransmits,negotiated:n.negotiated,ordered:n.ordered,protocol:n.protocol,readyState:n.readyState,reliable:n.reliable}),e.channel.onbufferedamountlow=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onbufferedamountlow",t)},e.channel.onopen=e=>{const t=e.currentTarget;t.bufferedAmountLowThreshold=65536,t.binaryType="arraybuffer",this.soraDataChannels[t.label]=t,this.trace("OPEN DATA CHANNEL",t.label),"signaling"===t.label&&this.ws?this.writeDataChannelSignalingLog("onopen",t):this.writeDataChannelTimelineLog("onopen",t)},e.channel.onclose=async e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label),await this.disconnect()},e.channel.onerror=async e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onerror",t),this.trace("ERROR DATA CHANNEL",t.label),await this.abend("DATA-CHANNEL-ONERROR",{params:{label:t.label}})},"signaling"===e.channel.label?e.channel.onmessage=async e=>{const t=e.currentTarget;let n=e.data;if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const t=U(new Uint8Array(e.data));n=(new TextDecoder).decode(t)}const i=JSON.parse(n);this.writeDataChannelSignalingLog(`onmessage-${i.type}`,t,i),"re-offer"===i.type&&await this.signalingOnMessageTypeReOffer(i)}:"notify"===e.channel.label?e.channel.onmessage=e=>{const t=e.currentTarget;let n=e.data;if(this.signalingOfferMessageDataChannels.notify&&!0===this.signalingOfferMessageDataChannels.notify.compress){const t=U(new Uint8Array(e.data));n=(new TextDecoder).decode(t)}const i=JSON.parse(n);"connection.created"===i.event_type?this.writeDataChannelTimelineLog("notify-connection.created",t,i):"connection.destroyed"===i.event_type&&this.writeDataChannelTimelineLog("notify-connection.destroyed",t,i),this.signalingOnMessageTypeNotify(i,"datachannel")}:"push"===e.channel.label?e.channel.onmessage=e=>{let t=e.data;if(this.signalingOfferMessageDataChannels.push&&!0===this.signalingOfferMessageDataChannels.push.compress){const n=U(new Uint8Array(e.data));t=(new TextDecoder).decode(n)}const n=JSON.parse(t);this.callbacks.push(n,"datachannel")}:"e2ee"===e.channel.label?e.channel.onmessage=e=>{const t=e.currentTarget,n=e.data;this.signalingOnMessageE2EE(n),this.writeDataChannelSignalingLog("onmessage-e2ee",t,n)}:"stats"===e.channel.label?e.channel.onmessage=async e=>{let t=e.data;if(this.signalingOfferMessageDataChannels.stats&&!0===this.signalingOfferMessageDataChannels.stats.compress){const n=U(new Uint8Array(e.data));t=(new TextDecoder).decode(n)}if("req-stats"===JSON.parse(t).type){const e=await this.getStats();this.sendStatsMessage(e)}}:/^#.*/.exec(e.channel.label)&&(e.channel.onmessage=e=>{if(null===e.target)return;const t=e.target;let n=e.data;const i=this.signalingOfferMessageDataChannels[t.label];void 0!==i&&!0===i.compress&&(n=U(new Uint8Array(e.data)).buffer),this.callbacks.message(function(e,t){const n=new Event("message");return n.label=e,n.data=t,n}(t.label,n))})}sendSignalingMessage(e){if(this.soraDataChannels.signaling){if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const t=F((new TextEncoder).encode(JSON.stringify(e)),{});this.soraDataChannels.signaling.send(t)}else this.soraDataChannels.signaling.send(JSON.stringify(e));this.writeDataChannelSignalingLog(`send-${e.type}`,this.soraDataChannels.signaling,e)}else null!==this.ws&&(this.ws.send(JSON.stringify(e)),this.writeWebSocketSignalingLog(`send-${e.type}`,e))}sendE2EEMessage(e){this.soraDataChannels.e2ee?(this.soraDataChannels.e2ee.send(e),this.writeDataChannelSignalingLog("send-e2ee",this.soraDataChannels.e2ee,e)):null!==this.ws&&(this.ws.send(e),this.writeWebSocketSignalingLog("send-e2ee",e))}sendStatsMessage(e){if(this.soraDataChannels.stats){const t={type:"stats",reports:e};if(this.signalingOfferMessageDataChannels.stats&&!0===this.signalingOfferMessageDataChannels.stats.compress){const e=F((new TextEncoder).encode(JSON.stringify(t)),{});this.soraDataChannels.stats.send(e)}else this.soraDataChannels.stats.send(JSON.stringify(t))}}getAudioTransceiver(){if(this.pc&&this.mids.audio){return this.pc.getTransceivers().find((e=>e.mid===this.mids.audio))||null}return null}getVideoTransceiver(){if(this.pc&&this.mids.video){return this.pc.getTransceivers().find((e=>e.mid===this.mids.video))||null}return null}soraCloseEvent(e,t,n){const i=class extends Event{constructor(e,t,n){super(e),n&&(n.code&&(this.code=n.code),n.reason&&(this.reason=n.reason),n.params&&(this.params=n.params)),this.title=t}};return new i(e,t,n)}sendMessage(e,t){const n=this.soraDataChannels[e];if(null===this.pc)return;if(void 0===n)throw new Error("Could not find DataChannel");const i=this.signalingOfferMessageDataChannels[e];if(void 0!==i&&!0===i.compress){const e=F(t,{});n.send(e)}else n.send(t)}get e2eeSelfFingerprint(){if(this.options.e2ee&&this.e2ee)return this.e2ee.selfFingerprint()}get e2eeRemoteFingerprints(){if(this.options.e2ee&&this.e2ee)return this.e2ee.remoteFingerprints()}get audio(){return null!==this.getAudioTransceiver()}get video(){return null!==this.getVideoTransceiver()}get signalingUrl(){return this.signalingUrlCandidates}get connectedSignalingUrl(){return this.ws?this.ws.url:""}get datachannels(){if(!this.signalingSwitched)return[];const e=Object.keys(this.signalingOfferMessageDataChannels).filter((e=>/^#.*/.exec(e))),t=[];for(const n of e){const e=this.soraDataChannels[n];if(!e)continue;const i=this.signalingOfferMessageDataChannels[n];if(!i)continue;const s={label:e.label,ordered:e.ordered,protocol:e.protocol,compress:i.compress,direction:i.direction};"number"==typeof e.maxPacketLifeTime&&(s.maxPacketLifeTime=e.maxPacketLifeTime),"number"==typeof e.maxRetransmits&&(s.maxRetransmits=e.maxRetransmits),t.push(s)}return t}}class te extends ee{async connect(e){return this.options.multistream?await Promise.race([this.multiStream(e).finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]):await Promise.race([this.singleStream(e).finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]),this.monitorWebSocketEvent(),this.monitorPeerConnectionState(),e}async singleStream(e){await this.disconnect(),this.setupE2EE();const t=await this.getSignalingWebSocket(this.signalingUrlCandidates),n=await this.signaling(t);return this.startE2EE(),await this.connectPeerConnection(n),await this.setRemoteDescription(n),e.getTracks().forEach((t=>{this.pc&&this.pc.addTrack(t,e)})),this.stream=e,await this.createAnswer(n),this.sendAnswer(),this.pc&&this.e2ee&&this.pc.getSenders().forEach((e=>{this.e2ee&&this.e2ee.setupSenderTransform(e)})),await this.onIceCandidate(),await this.waitChangeConnectionStateConnected(),e}async multiStream(e){await this.disconnect(),this.setupE2EE();const t=await this.getSignalingWebSocket(this.signalingUrlCandidates),n=await this.signaling(t);return this.startE2EE(),await this.connectPeerConnection(n),this.pc&&(this.pc.ontrack=e=>{const t=e.streams[0];if(!t)return;const n={"stream.id":t.id,id:e.track.id,label:e.track.label,enabled:e.track.enabled,kind:e.track.kind,muted:e.track.muted,readyState:e.track.readyState};this.writePeerConnectionTimelineLog("ontrack",n),"default"!==t.id&&t.id!==this.connectionId&&(this.e2ee&&this.e2ee.setupReceiverTransform(e.receiver),this.callbacks.track(e),t.onremovetrack=e=>{if(this.callbacks.removetrack(e),e.target){const t=this.remoteConnectionIds.indexOf(e.target.id);-1{this.pc&&this.pc.addTrack(t,e)})),this.stream=e,await this.createAnswer(n),this.sendAnswer(),this.pc&&this.e2ee&&this.pc.getSenders().forEach((e=>{this.e2ee&&this.e2ee.setupSenderTransform(e)})),await this.onIceCandidate(),await this.waitChangeConnectionStateConnected(),e}}class ne extends ee{async connect(){if(this.options.multistream)return await Promise.race([this.multiStream().finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]),this.monitorWebSocketEvent(),void this.monitorPeerConnectionState();{const e=await Promise.race([this.singleStream().finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]);return this.monitorWebSocketEvent(),this.monitorPeerConnectionState(),e}}async singleStream(){await this.disconnect(),this.setupE2EE();const e=await this.getSignalingWebSocket(this.signalingUrlCandidates),t=await this.signaling(e);return this.startE2EE(),await this.connectPeerConnection(t),this.pc&&(this.pc.ontrack=e=>{this.stream=e.streams[0];const t=this.stream.id;if("default"===t)return;const n={"stream.id":t,id:e.track.id,label:e.track.label,enabled:e.track.enabled,kind:e.track.kind,muted:e.track.muted,readyState:e.track.readyState};this.writePeerConnectionTimelineLog("ontrack",n),this.e2ee&&this.e2ee.setupReceiverTransform(e.receiver),this.callbacks.track(e),this.stream.onremovetrack=e=>{if(this.callbacks.removetrack(e),e.target){const t=this.remoteConnectionIds.indexOf(e.target.id);-1{const t=e.streams[0];if("default"===t.id)return;if(t.id===this.connectionId)return;const n={"stream.id":t.id,id:e.track.id,label:e.track.label,enabled:e.track.enabled,kind:e.track.kind,muted:e.track.muted,readyState:e.track.readyState};this.writePeerConnectionTimelineLog("ontrack",n),this.e2ee&&this.e2ee.setupReceiverTransform(e.receiver),this.callbacks.track(e),t.onremovetrack=e=>{if(this.callbacks.removetrack(e),e.target){const t=this.remoteConnectionIds.indexOf(e.target.id);-1{const{operation:t}=e.data;"disconnect"===t&&"function"==typeof this.onWorkerDisconnect&&this.onWorkerDisconnect()}}clearWorker(){this.worker&&this.worker.postMessage({type:"clear"})}terminateWorker(){this.worker&&this.worker.terminate()}async init(){const{preKeyBundle:e}=await window.e2ee.init();return e}setupSenderTransform(e){if(!e.track)return;const t=e.createEncodedStreams(),n=t.readableStream||t.readable,i=t.writableStream||t.writable;if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");const s={type:"encrypt",readableStream:n,writableStream:i};this.worker.postMessage(s,[n,i])}setupReceiverTransform(e){const t=e.createEncodedStreams(),n=t.readableStream||t.readable,i=t.writableStream||t.writable;if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");const s={type:"decrypt",readableStream:n,writableStream:i};this.worker.postMessage(s,[n,i])}postRemoteSecretKeyMaterials(e){if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");this.worker.postMessage({type:"remoteSecretKeyMaterials",remoteSecretKeyMaterials:e.remoteSecretKeyMaterials})}postRemoveRemoteDeriveKey(e){if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");this.worker.postMessage({type:"removeRemoteDeriveKey",connectionId:e})}postSelfSecretKeyMaterial(e,t,n,i=0){if(!this.worker)throw new Error("Worker is null. Call startWorker in advance.");this.worker.postMessage({type:"selfSecretKeyMaterial",selfConnectionId:e,selfKeyId:t,selfSecretKeyMaterial:n,waitingTime:i})}startSession(e,t){const[n,i]=window.e2ee.startSession(e,t.identityKey,t.signedPreKey,t.preKeySignature);if(i)throw i;return n}stopSession(e){const[t,n]=window.e2ee.stopSession(e);if(n)throw n;return t}receiveMessage(e){const[t,n]=window.e2ee.receiveMessage(e);if(n)throw n;return t}start(e){const[t,n]=window.e2ee.start(e);if(n)throw n;return t}addPreKeyBundle(e,t){const n=window.e2ee.addPreKeyBundle(e,t.identityKey,t.signedPreKey,t.preKeySignature);if(n)throw n}selfFingerprint(){return window.e2ee.selfFingerprint()}remoteFingerprints(){return window.e2ee.remoteFingerprints()}static async loadWasm(e){if(void 0===!window.e2ee)return void console.warn("E2ee wasm is already loaded. Will not be reload.");if((()=>{if("undefined"!=typeof global);else if("undefined"!=typeof window)window.global=window;else{if("undefined"==typeof self)throw new Error("cannot export Go (neither global, window nor self is defined)");self.global=self}if(global.require||"undefined"==typeof require||(global.require=require),!global.fs&&global.require){const e=require("fs");0!==Object.keys(e)&&(global.fs=e)}const e=()=>{const e=new Error("not implemented");return e.code="ENOSYS",e};if(!global.fs){let t="";global.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1},writeSync(e,i){t+=n.decode(i);const s=t.lastIndexOf("\n");return-1!=s&&(console.log(t.substr(0,s)),t=t.substr(s+1)),i.length},write(t,n,i,s,a,o){0===i&&s===n.length&&null===a?o(null,this.writeSync(t,n)):o(e())},chmod(t,n,i){i(e())},chown(t,n,i,s){s(e())},close(t,n){n(e())},fchmod(t,n,i){i(e())},fchown(t,n,i,s){s(e())},fstat(t,n){n(e())},fsync(e,t){t(null)},ftruncate(t,n,i){i(e())},lchown(t,n,i,s){s(e())},link(t,n,i){i(e())},lstat(t,n){n(e())},mkdir(t,n,i){i(e())},open(t,n,i,s){s(e())},read(t,n,i,s,a,o){o(e())},readdir(t,n){n(e())},readlink(t,n){n(e())},rename(t,n,i){i(e())},rmdir(t,n){n(e())},stat(t,n){n(e())},symlink(t,n,i){i(e())},truncate(t,n,i){i(e())},unlink(t,n){n(e())},utimes(t,n,i,s){s(e())}}}if(global.process||(global.process={getuid:()=>-1,getgid:()=>-1,geteuid:()=>-1,getegid:()=>-1,getgroups(){throw e()},pid:-1,ppid:-1,umask(){throw e()},cwd(){throw e()},chdir(){throw e()}}),!global.crypto){const e=require("crypto");global.crypto={getRandomValues(t){e.randomFillSync(t)}}}global.performance||(global.performance={now(){const[e,t]=process.hrtime();return 1e3*e+t/1e6}}),global.TextEncoder||(global.TextEncoder=require("util").TextEncoder),global.TextDecoder||(global.TextDecoder=require("util").TextDecoder);const t=new TextEncoder("utf-8"),n=new TextDecoder("utf-8");if(global.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=e=>{0!==e&&console.warn("exit code:",e)},this._exitPromise=new Promise((e=>{this._resolveExitPromise=e})),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;const e=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},i=e=>this.mem.getUint32(e+0,!0)+4294967296*this.mem.getInt32(e+4,!0),s=e=>{const t=this.mem.getFloat64(e,!0);if(0===t)return;if(!isNaN(t))return t;const n=this.mem.getUint32(e,!0);return this._values[n]},a=(e,t)=>{const n=2146959360;if("number"==typeof t&&0!==t)return isNaN(t)?(this.mem.setUint32(e+4,n,!0),void this.mem.setUint32(e,0,!0)):void this.mem.setFloat64(e,t,!0);if(void 0===t)return void this.mem.setFloat64(e,0,!0);let i=this._ids.get(t);void 0===i&&(i=this._idPool.pop(),void 0===i&&(i=this._values.length),this._values[i]=t,this._goRefCounts[i]=0,this._ids.set(t,i)),this._goRefCounts[i]++;let s=0;switch(typeof t){case"object":null!==t&&(s=1);break;case"string":s=2;break;case"symbol":s=3;break;case"function":s=4}this.mem.setUint32(e+4,n|s,!0),this.mem.setUint32(e,i,!0)},o=e=>{const t=i(e+0),n=i(e+8);return new Uint8Array(this._inst.exports.mem.buffer,t,n)},g=e=>{const t=i(e+0),n=i(e+8),a=new Array(n);for(let e=0;e{const t=i(e+0),s=i(e+8);return n.decode(new DataView(this._inst.exports.mem.buffer,t,s))},c=Date.now()-performance.now();this.importObject={go:{"runtime.wasmExit":e=>{const t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{const t=i(e+8),n=i(e+16),s=this.mem.getInt32(e+24,!0);fs.writeSync(t,new Uint8Array(this._inst.exports.mem.buffer,n,s))},"runtime.resetMemoryDataView":e=>{this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":t=>{e(t+8,1e6*(c+performance.now()))},"runtime.walltime1":t=>{const n=(new Date).getTime();e(t+8,n/1e3),this.mem.setInt32(t+16,n%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{const t=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(t,setTimeout((()=>{for(this._resume();this._scheduledTimeouts.has(t);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()}),i(e+8)+1)),this.mem.setInt32(e+16,t,!0)},"runtime.clearTimeoutEvent":e=>{const t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{crypto.getRandomValues(o(e+8))},"syscall/js.finalizeRef":e=>{const t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,0===this._goRefCounts[t]){const e=this._values[t];this._values[t]=null,this._ids.delete(e),this._idPool.push(t)}},"syscall/js.stringVal":e=>{a(e+24,l(e+8))},"syscall/js.valueGet":e=>{const t=Reflect.get(s(e+8),l(e+16));e=this._inst.exports.getsp(),a(e+32,t)},"syscall/js.valueSet":e=>{Reflect.set(s(e+8),l(e+16),s(e+32))},"syscall/js.valueDelete":e=>{Reflect.deleteProperty(s(e+8),l(e+16))},"syscall/js.valueIndex":e=>{a(e+24,Reflect.get(s(e+8),i(e+16)))},"syscall/js.valueSetIndex":e=>{Reflect.set(s(e+8),i(e+16),s(e+24))},"syscall/js.valueCall":e=>{try{const t=s(e+8),n=Reflect.get(t,l(e+16)),i=g(e+32),o=Reflect.apply(n,t,i);e=this._inst.exports.getsp(),a(e+56,o),this.mem.setUint8(e+64,1)}catch(t){a(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{try{const t=s(e+8),n=g(e+16),i=Reflect.apply(t,void 0,n);e=this._inst.exports.getsp(),a(e+40,i),this.mem.setUint8(e+48,1)}catch(t){a(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{try{const t=s(e+8),n=g(e+16),i=Reflect.construct(t,n);e=this._inst.exports.getsp(),a(e+40,i),this.mem.setUint8(e+48,1)}catch(t){a(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":t=>{e(t+16,parseInt(s(t+8).length))},"syscall/js.valuePrepareString":n=>{const i=t.encode(String(s(n+8)));a(n+16,i),e(n+24,i.length)},"syscall/js.valueLoadString":e=>{const t=s(e+8);o(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{this.mem.setUint8(e+24,s(e+8)instanceof s(e+16)?1:0)},"syscall/js.copyBytesToGo":t=>{const n=o(t+8),i=s(t+32);if(!(i instanceof Uint8Array||i instanceof Uint8ClampedArray))return void this.mem.setUint8(t+48,0);const a=i.subarray(0,n.length);n.set(a),e(t+40,a.length),this.mem.setUint8(t+48,1)},"syscall/js.copyBytesToJS":t=>{const n=s(t+8),i=o(t+16);if(!(n instanceof Uint8Array||n instanceof Uint8ClampedArray))return void this.mem.setUint8(t+48,0);const a=i.subarray(0,n.length);n.set(a),e(t+40,a.length),this.mem.setUint8(t+48,1)},debug:e=>{console.log(e)}}}}async run(e){this._inst=e,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,global,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[global,5],[this,6]]),this._idPool=[],this.exited=!1;let n=4096;const i=e=>{const i=n,s=t.encode(e+"\0");return new Uint8Array(this.mem.buffer,n,s.length).set(s),n+=s.length,n%8!=0&&(n+=8-n%8),i},s=this.argv.length,a=[];this.argv.forEach((e=>{a.push(i(e))})),a.push(0),Object.keys(this.env).sort().forEach((e=>{a.push(i(`${e}=${this.env[e]}`))})),a.push(0);const o=n;a.forEach((e=>{this.mem.setUint32(n,e,!0),this.mem.setUint32(n+4,0,!0),n+=8})),this._inst.exports.run(s,o),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(e){const t=this;return function(){const n={id:e,this:this,args:arguments};return t._pendingEvent=n,t._resume(),n.result}}},global.require&&global.require.main===module&&global.process&&global.process.versions&&!global.process.versions.electron){process.argv.length<3&&(console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"),process.exit(1));const e=new Go;e.argv=process.argv.slice(2),e.env=Object.assign({TMPDIR:require("os").tmpdir()},process.env),e.exit=process.exit,WebAssembly.instantiate(fs.readFileSync(process.argv[2]),e.importObject).then((t=>(process.on("exit",(t=>{0!==t||e.exited||(e._pendingEvent={id:0},e._resume())})),e.run(t.instance)))).catch((e=>{console.error(e),process.exit(1)}))}})(),!window.Go)throw new Error(`Failed to load module Go. window.Go is ${window.Go}.`);const t=new Go,{instance:n}=await WebAssembly.instantiateStreaming(fetch(e),t.importObject);if(t.run(n),!window.e2ee)throw new Error(`Failed to load module e2ee. window.e2ee is ${window.e2ee}.`)}static version(){return"2021.1.0"}static wasmVersion(){return window.e2ee.version()}}var t=Uint8Array,n=Uint16Array,i=Uint32Array,s=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),a=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),g=function(e,t){for(var s=new n(31),a=0;a<31;++a)s[a]=t+=1<>>1|(21845&m)<<1;u=(61680&(u=(52428&u)>>>2|(13107&u)<<2))>>>4|(3855&u)<<4,I[m]=((65280&u)>>>8|(255&u)<<8)>>>1}var A=function(e,t,i){for(var s=e.length,a=0,o=new n(t);a>>c]=r}else for(g=new n(s),a=0;a>>15-e[a]);return g},b=new t(288);for(m=0;m<144;++m)b[m]=8;for(m=144;m<256;++m)b[m]=9;for(m=256;m<280;++m)b[m]=7;for(m=280;m<288;++m)b[m]=8;var p=new t(32);for(m=0;m<32;++m)p[m]=5;var Z=A(b,9,0),w=A(b,9,1),S=A(p,5,0),V=A(p,5,1),f=function(e){for(var t=e[0],n=1;nt&&(t=e[n]);return t},y=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&n},W=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},G=function(e){return(e+7)/8|0},k=function(e,s,a){(null==s||s<0)&&(s=0),(null==a||a>e.length)&&(a=e.length);var o=new(e instanceof n?n:e instanceof i?i:t)(a-s);return o.set(e.subarray(s,a)),o},R=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],v=function(e,t,n){var i=new Error(t||R[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,v),!n)throw i;return i},T=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},X=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},O=function(e,i){for(var s=[],a=0;aI&&(I=g[a].s);var m=new n(I+1),u=E(s[d-1],m,0);if(u>i){a=0;var A=0,b=u-i,p=1<i))break;A+=p-(1<>>=b;A>0;){var w=g[a].s;m[w]=0&&A;--a){var S=g[a].s;m[S]==i&&(--m[S],++A)}u=i}return[new t(m),u]},E=function(e,t,n){return-1==e.s?Math.max(E(e.l,t,n+1),E(e.r,t,n+1)):t[e.s]=n},N=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new n(++t),s=0,a=e[0],o=1,g=function(e){i[s++]=e},l=1;l<=t;++l)if(e[l]==a&&l!=t)++o;else{if(!a&&o>2){for(;o>138;o-=138)g(32754);o>2&&(g(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(g(a),--o;o>6;o-=6)g(8304);o>2&&(g(o-3<<5|8208),o=0)}for(;o--;)g(a);o=1,a=e[l]}return[i.subarray(0,s),t]},B=function(e,t){for(var n=0,i=0;i>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var a=0;a4&&!D[o[U-1]];--U);var M,j,Q,H,x=h+5<<3,P=B(l,b)+B(c,p)+r,z=B(l,u)+B(c,f)+r+14+3*U+B(K,D)+(2*K[16]+3*K[17]+7*K[18]);if(x<=P&&x<=z)return Y(t,I,e.subarray(d,d+h));if(T(t,I,1+(z15&&(T(t,I,ee[L]>>>5&127),I+=ee[L]>>>12)}}}else M=Z,j=b,Q=S,H=p;for(L=0;L255){te=g[L]>>>18&31;X(t,I,M[te+257]),I+=j[te+257],te>7&&(T(t,I,g[L]>>>23&31),I+=s[te]);var ne=31&g[L];X(t,I,Q[ne]),I+=H[ne],ne>3&&(X(t,I,g[L]>>>5&8191),I+=a[ne])}else X(t,I,M[g[L]]),I+=j[g[L]];return X(t,I,M[256]),I+j[256]},L=new i([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),J=new t(0),D=function(e,o,g,l,c){return function(e,o,g,l,c,C){var d=e.length,I=new t(l+d+5*(1+Math.ceil(d/7e3))+c),m=I.subarray(l,I.length-c),u=0;if(!o||d<8)for(var A=0;A<=d;A+=65535){var b=A+65535;b>>13,w=8191&p,S=(1<7e3||N>24576)&&j>423){u=K(e,m,0,v,T,X,E,N,D,A-D,u),N=O=E=0,D=A;for(var Q=0;Q<286;++Q)T[Q]=0;for(Q=0;Q<30;++Q)X[Q]=0}var H=2,x=0,P=w,z=U-M&32767;if(j>2&&F==R(A-z))for(var _=Math.min(Z,j)-1,q=Math.min(32767,A),$=Math.min(258,j);z<=q&&--P&&U!=M;){if(e[A+H]==e[A+H-z]){for(var ee=0;ee<$&&e[A+ee]==e[A+ee-z];++ee);if(ee>H){if(H=ee,x=z,ee>_)break;var te=Math.min(z,ee-2),ne=0;for(Q=0;Qne&&(ne=se,M=ie)}}}z+=(U=M)-(M=V[U])+32768&32767}if(x){v[N++]=268435456|r[H]<<18|h[x];var ae=31&r[H],oe=31&h[x];E+=s[ae]+a[oe],++T[257+ae],++X[oe],B=A+H,++O}else v[N++]=e[A],++T[e[A]]}}u=K(e,m,C,v,T,X,E,N,D,A-D,u),!C&&7&u&&(u=Y(m,u+1,J))}return k(I,0,l+G(u)+c)}(e,null==o.level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+o.mem,g,l,!c)};function F(e,t){t||(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,s=t,a=0|n.length,o=0;o!=a;){for(var g=Math.min(o+2655,a);o>16),s=(65535&s)+15*(s>>16)}e=i,t=s},d:function(){return(255&(e%=65521))<<24|e>>>8<<16|(255&(t%=65521))<<8|t>>>8}}}();n.p(e);var i=D(e,t,2,4);return function(e,t){var n=t.level,i=0==n?0:n<6?1:9==n?3:2;e[0]=120,e[1]=i<<6|(i?32-2*i:1)}(i,t),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(i,i.length-4,n.d()),i}function U(e,n){return function(e,n,i){var g=e.length;if(!g||i&&i.f&&!i.l)return n||new t(0);var l=!n||i,r=!i||i.i;i||(i={}),n||(n=new t(3*g));var C=function(e){var i=n.length;if(e>i){var s=new t(Math.max(2*i,e));s.set(n),n=s}},h=i.f||0,I=i.p||0,m=i.b||0,u=i.l,b=i.d,p=i.m,Z=i.n,S=8*g;do{if(!u){h=y(e,I,1);var R=y(e,I+1,3);if(I+=3,!R){var T=e[(F=G(I)+4)-4]|e[F-3]<<8,X=F+T;if(X>g){r&&v(0);break}l&&C(m+T),n.set(e.subarray(F,X),m),i.b=m+=T,i.p=I=8*X,i.f=h;continue}if(1==R)u=w,b=V,p=9,Z=5;else if(2==R){var O=y(e,I,31)+257,E=y(e,I+10,15)+4,N=O+y(e,I+5,31)+1;I+=14;for(var B=new t(N),Y=new t(19),K=0;K>>4)<16)B[K++]=F;else{var M=0,j=0;for(16==F?(j=3+y(e,I,3),I+=2,M=B[K-1]):17==F?(j=3+y(e,I,7),I+=3):18==F&&(j=11+y(e,I,127),I+=7);j--;)B[K++]=M}}var Q=B.subarray(0,O),H=B.subarray(O);p=f(Q),Z=f(H),u=A(Q,p,1),b=A(H,Z,1)}else v(1);if(I>S){r&&v(0);break}}l&&C(m+131072);for(var x=(1<>>4;if((I+=15&M)>S){r&&v(0);break}if(M||v(2),_<256)n[m++]=_;else{if(256==_){z=I,u=null;break}var q=_-254;if(_>264){var $=s[K=_-257];q=y(e,I,(1<<$)-1)+c[K],I+=$}var ee=b[W(e,I)&P],te=ee>>>4;if(ee||v(3),I+=15&ee,H=d[te],te>3&&($=a[te],H+=W(e,I)&(1<<$)-1,I+=$),I>S){r&&v(0);break}l&&C(m+131072);for(var ne=m+q;m>>4>7||(i[0]<<8|i[1])%31)&&v(6,"invalid zlib data"),32&i[1]&&v(6,"invalid zlib data: preset dictionaries not supported"),e.subarray(2,-4)),n);var i}var M="undefined"!=typeof TextDecoder&&new TextDecoder;try{M.decode(J,{stream:!0}),1}catch(e){}function j(e){if("object"!=typeof e||null===e)throw new Error("Failed to parse options dataChannels. Options dataChannels element must be type 'object'");const t=e,n={};return"string"==typeof t.label&&(n.label=t.label),"string"==typeof t.direction&&(n.direction=t.direction),"boolean"==typeof t.ordered&&(n.ordered=t.ordered),"boolean"==typeof t.compress&&(n.compress=t.compress),"number"==typeof t.maxPacketLifeTime&&(n.max_packet_life_time=t.maxPacketLifeTime),"number"==typeof t.maxRetransmits&&(n.max_retransmits=t.maxRetransmits),"string"==typeof t.protocol&&(n.protocol=t.protocol),n}function Q(){return"safari"===function(){const e=window.navigator.userAgent.toLocaleLowerCase();return-1!==e.indexOf("edge")?"edge":-1!==e.indexOf("chrome")&&-1===e.indexOf("edge")?"chrome":-1!==e.indexOf("safari")&&-1===e.indexOf("chrome")?"safari":-1!==e.indexOf("opera")?"opera":-1!==e.indexOf("firefox")?"firefox":null}()}function H(e,t,n,i,s,a){if("sendrecv"!==t&&"sendonly"!==t&&"recvonly"!==t)throw new Error("Unknown role type");if(null==n)throw new Error("channelId can not be null or undefined");const o={type:"connect",sora_client:"Sora JavaScript SDK 2021.2.0",environment:window.navigator.userAgent,role:t,channel_id:n,sdp:e,audio:!0,video:!0};if(void 0!==i&&(o.metadata=i),a&&(o.redirect=!0),"signalingNotifyMetadata"in s&&(o.signaling_notify_metadata=s.signalingNotifyMetadata),"multistream"in s&&!0===s.multistream&&(o.multistream=!0,"spotlight"in s&&(o.spotlight=s.spotlight,"spotlightNumber"in s&&(o.spotlight_number=s.spotlightNumber)),!0===o.spotlight)){const e=["none","r0","r1","r2"];void 0!==s.spotlightFocusRid&&0<=e.indexOf(s.spotlightFocusRid)&&(o.spotlight_focus_rid=s.spotlightFocusRid),void 0!==s.spotlightUnfocusRid&&0<=e.indexOf(s.spotlightUnfocusRid)&&(o.spotlight_unfocus_rid=s.spotlightUnfocusRid)}if("simulcast"in s||"simulcastRid"in s){"simulcast"in s&&!0===s.simulcast&&(o.simulcast=!0);const e=["r0","r1","r2"];void 0!==s.simulcastRid&&0<=e.indexOf(s.simulcastRid)&&(o.simulcast_rid=s.simulcastRid)}"clientId"in s&&void 0!==s.clientId&&(o.client_id=s.clientId),"dataChannelSignaling"in s&&"boolean"==typeof s.dataChannelSignaling&&(o.data_channel_signaling=s.dataChannelSignaling),"ignoreDisconnectWebSocket"in s&&"boolean"==typeof s.ignoreDisconnectWebSocket&&(o.ignore_disconnect_websocket=s.ignoreDisconnectWebSocket);const g=["audioCodecType","audioBitRate"],l=["audioOpusParamsChannels","audioOpusParamsClockRate","audioOpusParamsMaxplaybackrate","audioOpusParamsStereo","audioOpusParamsSpropStereo","audioOpusParamsMinptime","audioOpusParamsPtime","audioOpusParamsUseinbandfec","audioOpusParamsUsedtx"],c=["videoCodecType","videoBitRate"],r=Object.assign({},s);Object.keys(r).forEach((e=>{"audio"===e&&"boolean"==typeof r[e]||"video"===e&&"boolean"==typeof r[e]||0<=g.indexOf(e)&&null!==r[e]||0<=l.indexOf(e)&&null!==r[e]||0<=c.indexOf(e)&&null!==r[e]||delete r[e]})),void 0!==r.audio&&(o.audio=r.audio);const C=Object.keys(r).some((e=>0<=g.indexOf(e)));o.audio&&C&&(o.audio={},"audioCodecType"in r&&(o.audio.codec_type=r.audioCodecType),"audioBitRate"in r&&(o.audio.bit_rate=r.audioBitRate));const d=Object.keys(r).some((e=>0<=l.indexOf(e)));o.audio&&d&&("object"!=typeof o.audio&&(o.audio={}),o.audio.opus_params={},"audioOpusParamsChannels"in r&&(o.audio.opus_params.channels=r.audioOpusParamsChannels),"audioOpusParamsClockRate"in r&&(o.audio.opus_params.clock_rate=r.audioOpusParamsClockRate),"audioOpusParamsMaxplaybackrate"in r&&(o.audio.opus_params.maxplaybackrate=r.audioOpusParamsMaxplaybackrate),"audioOpusParamsStereo"in r&&(o.audio.opus_params.stereo=r.audioOpusParamsStereo),"audioOpusParamsSpropStereo"in r&&(o.audio.opus_params.sprop_stereo=r.audioOpusParamsSpropStereo),"audioOpusParamsMinptime"in r&&(o.audio.opus_params.minptime=r.audioOpusParamsMinptime),"audioOpusParamsPtime"in r&&(o.audio.opus_params.ptime=r.audioOpusParamsPtime),"audioOpusParamsUseinbandfec"in r&&(o.audio.opus_params.useinbandfec=r.audioOpusParamsUseinbandfec),"audioOpusParamsUsedtx"in r&&(o.audio.opus_params.usedtx=r.audioOpusParamsUsedtx)),void 0!==r.video&&(o.video=r.video);const h=Object.keys(r).some((e=>0<=c.indexOf(e)));if(o.video&&h&&(o.video={},"videoCodecType"in r&&(o.video.codec_type=r.videoCodecType),"videoBitRate"in r&&(o.video.bit_rate=r.videoBitRate)),o.simulcast&&!function(){if(!window.RTCRtpSender)return!1;if(!RTCRtpSender.getCapabilities)return!1;const e=RTCRtpSender.getCapabilities("video");if(!e)return!1;const t=e.headerExtensions.map((e=>e.uri));return["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"].every((e=>t.includes(e)))}()&&"recvonly"!==t)throw new Error("Simulcast can not be used with this browser");if(!0===s.e2ee){if(void 0===o.signaling_notify_metadata&&(o.signaling_notify_metadata={}),null===o.signaling_notify_metadata||"object"!=typeof o.signaling_notify_metadata)throw new Error("E2EE failed. Options signalingNotifyMetadata must be type 'object'");!0===o.video&&(o.video={}),o.video&&(o.video.codec_type="VP8"),o.e2ee=!0}return Array.isArray(s.dataChannels)&&0{},push:()=>{},addstream:()=>{},track:()=>{},removestream:()=>{},removetrack:()=>{},notify:()=>{},log:()=>{},timeout:()=>{},timeline:()=>{},signaling:()=>{},message:()=>{},datachannel:()=>{}},this.authMetadata=null,this.e2ee=null,this.connectionTimeoutTimerId=0,this.monitorSignalingWebSocketEventTimerId=0,this.monitorIceConnectionStateChangeTimerId=0,this.soraDataChannels={},this.mids={audio:"",video:""},this.signalingSwitched=!1,this.signalingOfferMessageDataChannels={}}on(e,t){"addstream"===e?console.warn("@deprecated addstream callback will be removed in a future version. Use track callback."):"removestream"===e&&console.warn("@deprecated removestream callback will be removed in a future version. Use removetrack callback."),e in this.callbacks&&(this.callbacks[e]=t)}stopAudioTrack(e){for(const t of e.getAudioTracks())t.enabled=!1;return new Promise((t=>{setTimeout((async()=>{for(const t of e.getAudioTracks())if(t.stop(),e.removeTrack(t),null!==this.pc){const e=this.pc.getSenders().find((e=>e.track&&e.track.id===t.id));e&&await e.replaceTrack(null)}t()}),100)}))}stopVideoTrack(e){for(const t of e.getVideoTracks())t.enabled=!1;return new Promise((t=>{setTimeout((async()=>{for(const t of e.getVideoTracks())if(t.stop(),e.removeTrack(t),null!==this.pc){const e=this.pc.getSenders().find((e=>e.track&&e.track.id===t.id));e&&await e.replaceTrack(null)}t()}),100)}))}async replaceAudioTrack(e,t){await this.stopAudioTrack(e);const n=this.getAudioTransceiver();if(null===n)throw new Error("Unable to set an audio track. Audio track sender is undefined");e.addTrack(t),await n.sender.replaceTrack(t)}async replaceVideoTrack(e,t){await this.stopVideoTrack(e);const n=this.getVideoTransceiver();if(null===n)throw new Error("Unable to set video track. Video track sender is undefined");e.addTrack(t),await n.sender.replaceTrack(t)}stopStream(){return new Promise(((e,t)=>(this.debug&&console.warn("@deprecated closing MediaStream in disconnect will be removed in a future version. Close every track in the MediaStream by yourself."),this.stream?(this.stream.getTracks().forEach((e=>{e.stop()})),this.stream=null,e()):e())))}async signalingTerminate(){await this.stopStream();for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&t.close(),delete this.soraDataChannels[e]}this.ws&&(this.ws.close(),this.ws=null),this.pc&&this.pc.close(),this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection()}async abendPeerConnectionState(e){this.clearMonitorIceConnectionStateChange(),await this.stopStream(),this.pc&&(this.pc.ondatachannel=null,this.pc.oniceconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.pc.onconnectionstatechange=null),this.ws&&(this.ws.onclose=e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason})},this.ws.onmessage=null,this.ws.onerror=null);for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onclose=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label)},t.onmessage=null,t.onerror=null)}for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&t.close(),delete this.soraDataChannels[e]}this.ws&&(this.ws.close(),this.ws=null),this.pc&&this.pc.close(),this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection();const t=this.soraCloseEvent("abend",e);this.callbacks.disconnect(t),this.writeSoraTimelineLog("disconnect-abend",t)}async abend(e,t){this.clearMonitorIceConnectionStateChange(),await this.stopStream(),this.pc&&(this.pc.ondatachannel=null,this.pc.oniceconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.pc.onconnectionstatechange=null),this.ws&&(this.ws.onclose=e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason})},this.ws.onmessage=null,this.ws.onerror=null);for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onclose=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label)},t.onmessage=null,t.onerror=null)}if(this.soraDataChannels.signaling){const t={type:"disconnect",reason:e};if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const e=F((new TextEncoder).encode(JSON.stringify(t)),{});if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(e),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,t)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}else if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(JSON.stringify(t)),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,t)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onerror=null,t.close()),delete this.soraDataChannels[e]}if(await this.disconnectWebSocket(e),await this.disconnectPeerConnection(),this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection(),"WEBSOCKET-ONCLOSE"===e&&t&&(1e3===t.code||1005===t.code)){const e=this.soraCloseEvent("normal","DISCONNECT",t);return this.writeSoraTimelineLog("disconnect-normal",e),void this.callbacks.disconnect(e)}const n=this.soraCloseEvent("abend",e,t);this.writeSoraTimelineLog("disconnect-abend",n),this.callbacks.disconnect(this.soraCloseEvent("abend",e,t))}initializeConnection(){this.clientId=null,this.connectionId=null,this.remoteConnectionIds=[],this.stream=null,this.ws=null,this.pc=null,this.encodings=[],this.authMetadata=null,this.e2ee=null,this.soraDataChannels={},this.mids={audio:"",video:""},this.signalingSwitched=!1,this.signalingOfferMessageDataChannels={},this.clearConnectionTimeout()}disconnectWebSocket(e){let t=0;return this.signalingSwitched?(this.ws&&(this.ws.close(),this.ws=null),Promise.resolve(null)):new Promise(((n,i)=>{if(!this.ws)return n(null);if(this.ws.onclose=e=>(this.ws&&(this.ws.close(),this.ws=null),clearTimeout(t),this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason}),n({code:e.code,reason:e.reason})),1!==this.ws.readyState)return this.ws.close(),this.ws=null,n(null);{const i={type:"disconnect",reason:e};this.ws.send(JSON.stringify(i)),this.writeWebSocketSignalingLog("send-disconnect",i),t=setTimeout((()=>{this.ws&&(this.ws.close(),this.ws=null),n({code:1006,reason:""})}),this.disconnectWaitTimeout)}}))}disconnectDataChannel(){const e=()=>{for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onerror=null,t.close()),delete this.soraDataChannels[e]}};return new Promise(((t,n)=>{if(!this.soraDataChannels.signaling)return e(),t({code:4999,reason:""});const i=setTimeout((()=>(e(),n())),this.disconnectWaitTimeout),s=[];for(const n of Object.keys(this.soraDataChannels)){const a=this.soraDataChannels[n];if(a){a.onerror=()=>(clearTimeout(i),e(),t({code:4999,reason:""}));const n=()=>new Promise(((e,t)=>{let n=0;const i=setInterval((()=>{n++,"closed"===a.readyState&&(clearInterval(i),e()),this.disconnectWaitTimeout<100*n&&(e(),clearInterval(i))}),100)}));s.push(n())}}Promise.all(s).then((()=>{0===Object.keys(this.soraDataChannels).length?t(null):t({code:4999,reason:""})})).finally((()=>{e(),clearTimeout(i)}));const a={type:"disconnect",reason:"NO-ERROR"};if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const e=F((new TextEncoder).encode(JSON.stringify(a)),{});if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(e),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,a)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}else if("open"===this.soraDataChannels.signaling.readyState)try{this.soraDataChannels.signaling.send(JSON.stringify(a)),this.writeDataChannelSignalingLog("send-disconnect",this.soraDataChannels.signaling,a)}catch(e){const t=e.message;this.writeDataChannelSignalingLog("failed-to-send-disconnect",this.soraDataChannels.signaling,t)}}))}disconnectPeerConnection(){return new Promise(((e,t)=>(this.pc&&"closed"!==this.pc.connectionState&&this.pc.close(),e())))}async disconnect(){this.clearMonitorIceConnectionStateChange(),await this.stopStream(),this.pc&&(this.pc.ondatachannel=null,this.pc.oniceconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.pc.onconnectionstatechange=null),this.ws&&(this.ws.onclose=e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason})},this.ws.onmessage=null,this.ws.onerror=null);for(const e of Object.keys(this.soraDataChannels)){const t=this.soraDataChannels[e];t&&(t.onmessage=null,t.onclose=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label)})}let e=null;if(this.signalingSwitched){try{const t=await this.disconnectDataChannel();null!==t&&(e=this.soraCloseEvent("normal","DISCONNECT",t))}catch(t){e=this.soraCloseEvent("abend","DISCONNECT-TIMEOUT")}await this.disconnectWebSocket("NO-ERROR"),await this.disconnectPeerConnection()}else{const t=await this.disconnectWebSocket("NO-ERROR");await this.disconnectPeerConnection(),null!==t&&(e=this.soraCloseEvent("normal","DISCONNECT",t))}this.e2ee&&this.e2ee.terminateWorker(),this.initializeConnection(),e&&("abend"===e.type?this.writeSoraTimelineLog("disconnect-abend",e):"normal"===e.type&&this.writeSoraTimelineLog("disconnect-normal",e),this.callbacks.disconnect(e))}setupE2EE(){!0===this.options.e2ee&&(this.e2ee=new e,this.e2ee.onWorkerDisconnect=async()=>{await this.abend("INTERNAL-ERROR",{reason:"CRASH-E2EE-WORKER"})},this.e2ee.startWorker())}startE2EE(){if(!0===this.options.e2ee&&this.e2ee){if(!this.connectionId){const e=new Error;throw e.message="E2EE failed. Self connectionId is null",e}this.e2ee.clearWorker();const e=this.e2ee.start(this.connectionId);this.e2ee.postSelfSecretKeyMaterial(this.connectionId,e.selfKeyId,e.selfSecretKeyMaterial)}}async getSignalingWebSocket(e){if("string"==typeof e){const t=e;return new Promise(((e,n)=>{const i=new WebSocket(t);i.onclose=e=>{const t=new z(`Signaling failed. CloseEventCode:${e.code} CloseEventReason:'${e.reason}'`);t.code=e.code,t.reason=e.reason,this.writeWebSocketTimelineLog("onclose",t),n(t)},i.onopen=t=>{e(i)}}))}if(Array.isArray(e)){let t=!1;const n=e=>new Promise(((n,i)=>{const s=new WebSocket(e),a=setTimeout((()=>{this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"timeout",url:s.url}),s&&!t&&(s.onclose=null,s.onerror=null,s.onopen=null,s.close(),i())}),this.signalingCandidateTimeout);s.onclose=e=>{this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"close",url:s.url,message:"WebSocket closed",code:e.code,reason:e.reason}),s&&s.close(),clearInterval(a),i()},s.onerror=e=>{this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"error",url:s.url,message:"Failed to connect WebSocket"}),s&&(s.onclose=null,s.close()),clearInterval(a),i()},s.onopen=e=>{s&&(clearInterval(a),t?(this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"open",url:s.url,selected:!1}),s.onerror=null,s.onclose=null,s.onopen=null,s.close(),i()):(this.writeWebSocketSignalingLog("signaling-url-canidate",{type:"open",url:s.url,selected:!0}),s.onerror=null,s.onclose=null,s.onopen=null,t=!0,n(s)))}}));try{return await Promise.any(e.map((e=>n(e))))}catch(e){throw new z("Signaling failed. All signaling URL candidates failed to connect")}}throw new z("Signaling failed. Invalid format signaling URL candidates")}async signaling(e,t=!1){const n=await this.createOffer();return this.trace("CREATE OFFER",n),new Promise(((i,s)=>{this.writeWebSocketSignalingLog("new-websocket",e.url),e.binaryType="arraybuffer",e.onclose=async e=>{const t=new z(`Signaling failed. CloseEventCode:${e.code} CloseEventReason:'${e.reason}'`);t.code=e.code,t.reason=e.reason,this.writeWebSocketTimelineLog("onclose",t),await this.signalingTerminate(),s(t)},e.onmessage=async e=>{if(e.data instanceof ArrayBuffer)return this.writeWebSocketSignalingLog("onmessage-e2ee",e.data),void this.signalingOnMessageE2EE(e.data);const t=JSON.parse(e.data);if("offer"==t.type)this.writeWebSocketSignalingLog("onmessage-offer",t),this.signalingOnMessageTypeOffer(t),i(t);else if("update"==t.type)this.writeWebSocketSignalingLog("onmessage-update",t),await this.signalingOnMessageTypeUpdate(t);else if("re-offer"==t.type)this.writeWebSocketSignalingLog("onmessage-re-offer",t),await this.signalingOnMessageTypeReOffer(t);else if("ping"==t.type)await this.signalingOnMessageTypePing(t);else if("push"==t.type)this.callbacks.push(t,"websocket");else if("notify"==t.type)"connection.created"===t.event_type?this.writeWebSocketTimelineLog("notify-connection.created",t):"connection.destroyed"===t.event_type&&this.writeWebSocketTimelineLog("notify-connection.destroyed",t),this.signalingOnMessageTypeNotify(t,"websocket");else if("switched"==t.type)this.writeWebSocketSignalingLog("onmessage-switched",t),this.signalingOnMessageTypeSwitched(t);else if("redirect"==t.type){this.writeWebSocketSignalingLog("onmessage-redirect",t);const e=await this.signalingOnMessageTypeRedirect(t);i(e)}},(async()=>{let i;try{i=H(n.sdp||"",this.role,this.channelId,this.metadata,this.options,t)}catch(e){return void s(e)}if(i.e2ee&&this.e2ee){const e=await this.e2ee.init();i.signaling_notify_metadata.pre_key_bundle=e}this.trace("SIGNALING CONNECT MESSAGE",i),e&&(e.send(JSON.stringify(i)),this.writeWebSocketSignalingLog(`send-${i.type}`,i),this.ws=e)})()}))}async connectPeerConnection(e){let t=Object.assign({},e.config);if(this.e2ee&&(t=Object.assign({encodedInsertableStreams:!0},t)),void 0!==window.RTCPeerConnection.generateCertificate){const e=await window.RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"});t=Object.assign({certificates:[e]},t)}this.trace("PEER CONNECTION CONFIG",t),this.writePeerConnectionTimelineLog("new-peerconnection",t),this.pc=new window.RTCPeerConnection(t,this.constraints),this.pc.oniceconnectionstatechange=e=>{this.pc&&(this.writePeerConnectionTimelineLog("oniceconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),this.trace("ONICECONNECTIONSTATECHANGE ICECONNECTIONSTATE",this.pc.iceConnectionState))},this.pc.onicegatheringstatechange=e=>{this.pc&&this.writePeerConnectionTimelineLog("onicegatheringstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState})},this.pc.onconnectionstatechange=e=>{this.pc&&this.writePeerConnectionTimelineLog("onconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState})},this.pc.ondatachannel=e=>{this.onDataChannel(e)}}async setRemoteDescription(e){if(!this.pc)return;const t=new RTCSessionDescription({type:"offer",sdp:e.sdp});await this.pc.setRemoteDescription(t),this.writePeerConnectionTimelineLog("set-remote-description",t)}async createAnswer(e){if(!this.pc)return;for(const e of Object.values(this.mids)){const t=this.pc.getTransceivers().find((t=>t.mid===e));t&&"recvonly"===t.direction&&(t.direction="sendrecv")}if(this.options.simulcast&&("sendrecv"===this.role||"sendonly"===this.role)){const t=this.pc.getTransceivers().find((e=>{if(null!==e.mid&&null!==e.sender.track&&(null===e.currentDirection||"sendonly"===e.currentDirection))return""!==this.mids.video&&this.mids.video===e.mid||0<=e.mid.indexOf("video")?e:void 0}));if(t){await this.setSenderParameters(t,this.encodings),await this.setRemoteDescription(e),this.trace("TRANSCEIVER SENDER GET_PARAMETERS",t.sender.getParameters()),await this.setSenderParameters(t,this.encodings);const n=await this.pc.createAnswer();return await this.pc.setLocalDescription(n),void this.trace("TRANSCEIVER SENDER GET_PARAMETERS",t.sender.getParameters())}}const t=await this.pc.createAnswer();this.writePeerConnectionTimelineLog("create-answer",t),await this.pc.setLocalDescription(t),this.writePeerConnectionTimelineLog("set-local-description",t)}sendAnswer(){if(this.pc&&this.ws&&this.pc.localDescription){this.trace("ANSWER SDP",this.pc.localDescription.sdp);const e={type:"answer",sdp:this.pc.localDescription.sdp};this.ws.send(JSON.stringify(e)),this.writeWebSocketSignalingLog("send-answer",e)}}onIceCandidate(){return new Promise(((e,t)=>{this.pc&&(this.pc.oniceconnectionstatechange=t=>{this.pc&&(this.writePeerConnectionTimelineLog("oniceconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),this.trace("ONICECONNECTIONSTATECHANGE ICECONNECTIONSTATE",this.pc.iceConnectionState),"connected"===this.pc.iceConnectionState&&e())},this.pc.onicecandidate=t=>{if(this.writePeerConnectionTimelineLog("onicecandidate",t.candidate),this.pc&&this.trace("ONICECANDIDATE ICEGATHERINGSTATE",this.pc.iceGatheringState),null===t.candidate)e();else{const e=t.candidate.toJSON(),n=Object.assign(e,{type:"candidate"});this.trace("ONICECANDIDATE CANDIDATE MESSAGE",n),this.sendSignalingMessage(n)}})}))}waitChangeConnectionStateConnected(){return new Promise(((e,t)=>{if(this.pc&&void 0===this.pc.connectionState)return void e();const n=setInterval((()=>{if(this.pc)this.pc&&"connected"===this.pc.connectionState&&(clearInterval(n),e());else{const e=new Error;e.message="PeerConnection connectionState did not change to 'connected'",clearInterval(n),t(e)}}),10)}))}monitorSignalingWebSocketEvent(){return new Promise(((e,t)=>{this.monitorSignalingWebSocketEventTimerId=setInterval((()=>{this.ws&&(this.clearMonitorSignalingWebSocketEvent(),this.ws.onclose=async e=>{const n=new z(`Signaling failed. CloseEventCode:${e.code} CloseEventReason:'${e.reason}'`);n.code=e.code,n.reason=e.reason,this.writeWebSocketTimelineLog("onclose",n),await this.signalingTerminate(),t(n)},this.ws.onerror=async e=>{const n=new z("Signaling failed. WebSocket onerror was called");this.writeWebSocketSignalingLog("onerror",n),await this.signalingTerminate(),t(n)})}),100)}))}monitorWebSocketEvent(){this.ws&&(this.ws.onclose=async e=>{this.writeWebSocketTimelineLog("onclose",{code:e.code,reason:e.reason}),await this.abend("WEBSOCKET-ONCLOSE",{code:e.code,reason:e.reason})},this.ws.onerror=async e=>{this.writeWebSocketSignalingLog("onerror"),await this.abend("WEBSOCKET-ONERROR")})}monitorPeerConnectionState(){this.pc&&(this.pc.oniceconnectionstatechange=async e=>{this.pc&&void 0===this.pc.connectionState&&(this.writePeerConnectionTimelineLog("oniceconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),this.trace("ONICECONNECTIONSTATECHANGE ICECONNECTIONSTATE",this.pc.iceConnectionState),clearTimeout(this.monitorIceConnectionStateChangeTimerId),"failed"===this.pc.iceConnectionState?await this.abendPeerConnectionState("ICE-CONNECTION-STATE-FAILED"):"disconnected"===this.pc.iceConnectionState&&(this.monitorIceConnectionStateChangeTimerId=setTimeout((async()=>{this.pc&&"disconnected"===this.pc.iceConnectionState&&await this.abendPeerConnectionState("ICE-CONNECTION-STATE-DISCONNECTED-TIMEOUT")}),1e4)))},this.pc.onconnectionstatechange=async e=>{this.pc&&(this.writePeerConnectionTimelineLog("onconnectionstatechange",{connectionState:this.pc.connectionState,iceConnectionState:this.pc.iceConnectionState,iceGatheringState:this.pc.iceGatheringState}),"failed"===this.pc.connectionState&&await this.abendPeerConnectionState("CONNECTION-STATE-FAILED"))})}setConnectionTimeout(){return new Promise(((e,t)=>{0{if(!this.pc||this.pc&&void 0!==this.pc.connectionState&&"connected"!==this.pc.connectionState){const e=new Error;e.message="Signaling connection timeout",this.callbacks.timeout(),this.trace("DISCONNECT","Signaling connection timeout"),this.writePeerConnectionTimelineLog("signaling-connection-timeout",{connectionTimeout:this.connectionTimeout}),await this.signalingTerminate(),t(e)}}),this.connectionTimeout))}))}clearConnectionTimeout(){clearTimeout(this.connectionTimeoutTimerId)}clearMonitorSignalingWebSocketEvent(){clearInterval(this.monitorSignalingWebSocketEventTimerId)}clearMonitorIceConnectionStateChange(){clearInterval(this.monitorIceConnectionStateChangeTimerId)}trace(e,t){this.callbacks.log(e,t),this.debug&&function(e,t,n){const i=e=>{if(e&&"object"==typeof e){let t=null;try{t=Object.keys(JSON.parse(JSON.stringify(e)))}catch(e){}t&&Array.isArray(t)?t.forEach((t=>{console.group(t),i(e[t]),console.groupEnd()})):console.info(e)}else console.info(e)};let s="";window.performance&&(s="["+(window.performance.now()/1e3).toFixed(3)+"]"),e&&(s=s+"["+e+"]"),void 0!==console.info&&void 0!==console.group?(console.group(s+" "+t),i(n),console.groupEnd()):console.log(s+" "+t+"\n",n)}(this.clientId,e,t)}writeWebSocketSignalingLog(e,t){this.callbacks.signaling(_(e,t,"websocket")),this.writeWebSocketTimelineLog(e,t)}writeDataChannelSignalingLog(e,t,n){this.callbacks.signaling(_(e,n,"datachannel")),this.writeDataChannelTimelineLog(e,t,n)}writeWebSocketTimelineLog(e,t){const n=q(e,t,"websocket");this.callbacks.timeline(n)}writeDataChannelTimelineLog(e,t,n){const i=q(e,n,"datachannel",t.id,t.label);this.callbacks.timeline(i)}writePeerConnectionTimelineLog(e,t){const n=q(e,t,"peerconnection");this.callbacks.timeline(n)}writeSoraTimelineLog(e,t){const n=q(e,t,"sora");this.callbacks.timeline(n)}async createOffer(){const e=new window.RTCPeerConnection({iceServers:[]});if(Q()){e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"});const t=await e.createOffer();return e.close(),this.writePeerConnectionTimelineLog("create-offer",t),t}const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});return e.close(),this.writePeerConnectionTimelineLog("create-offer",t),t}signalingOnMessageE2EE(e){if(this.e2ee){const t=new Uint8Array(e),n=this.e2ee.receiveMessage(t);this.e2ee.postRemoteSecretKeyMaterials(n),n.messages.forEach((e=>{this.sendE2EEMessage(e.buffer)}))}}signalingOnMessageTypeOffer(e){if(this.clientId=e.client_id,this.connectionId=e.connection_id,void 0!==e.metadata&&(this.authMetadata=e.metadata),Array.isArray(e.encodings)&&(this.encodings=e.encodings),void 0!==e.mid&&void 0!==e.mid.audio&&(this.mids.audio=e.mid.audio),void 0!==e.mid&&void 0!==e.mid.video&&(this.mids.video=e.mid.video),e.data_channels)for(const t of e.data_channels)this.signalingOfferMessageDataChannels[t.label]=t;this.trace("SIGNALING OFFER MESSAGE",e),this.trace("OFFER SDP",e.sdp)}sendUpdateAnswer(){this.pc&&this.ws&&this.pc.localDescription&&(this.trace("ANSWER SDP",this.pc.localDescription.sdp),this.sendSignalingMessage({type:"update",sdp:this.pc.localDescription.sdp}))}sendReAnswer(){this.pc&&this.pc.localDescription&&(this.trace("RE ANSWER SDP",this.pc.localDescription.sdp),this.sendSignalingMessage({type:"re-answer",sdp:this.pc.localDescription.sdp}))}async signalingOnMessageTypeUpdate(e){this.trace("SIGNALING UPDATE MESSGE",e),this.trace("UPDATE SDP",e.sdp),await this.setRemoteDescription(e),await this.createAnswer(e),this.sendUpdateAnswer()}async signalingOnMessageTypeReOffer(e){this.trace("SIGNALING RE OFFER MESSGE",e),this.trace("RE OFFER SDP",e.sdp),await this.setRemoteDescription(e),await this.createAnswer(e),this.sendReAnswer()}async signalingOnMessageTypePing(e){const t={type:"pong"};if(e.stats){const e=await this.getStats();t.stats=e}this.ws&&this.ws.send(JSON.stringify(t))}signalingOnMessageTypeNotify(e,t){if("connection.created"===e.event_type){const t=e.connection_id;if(this.connectionId!==t){const n=P(x(e));if(n&&this.e2ee&&t){const e=this.e2ee.startSession(t,n);this.e2ee.postRemoteSecretKeyMaterials(e),e.messages.forEach((e=>{this.sendE2EEMessage(e.buffer)})),this.e2ee.postSelfSecretKeyMaterial(e.selfConnectionId,e.selfKeyId,e.selfSecretKeyMaterial)}}const n=function(e){return e.data&&Array.isArray(e.data)?e.data:e.metadata_list&&Array.isArray(e.metadata_list)?e.metadata_list:[]}(e);n.forEach((e=>{const t=P(x(e)),n=e.connection_id;n&&this.e2ee&&t&&this.e2ee.addPreKeyBundle(n,t)}))}else if("connection.destroyed"===e.event_type){const t=P(x(e)),n=e.connection_id;if(t&&this.e2ee&&n){const e=this.e2ee.stopSession(n);this.e2ee.postSelfSecretKeyMaterial(e.selfConnectionId,e.selfKeyId,e.selfSecretKeyMaterial,5e3),e.messages.forEach((e=>{this.sendE2EEMessage(e.buffer)})),this.e2ee.postRemoveRemoteDeriveKey(n)}}this.callbacks.notify(e,t)}signalingOnMessageTypeSwitched(e){if(this.signalingSwitched=!0,this.ws){e.ignore_disconnect_websocket&&(this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.writeWebSocketSignalingLog("close"));for(const e of this.datachannels)this.callbacks.datachannel($(e))}}async signalingOnMessageTypeRedirect(e){this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null);const t=await this.getSignalingWebSocket(e.location);return await this.signaling(t,!0)}async setSenderParameters(e,t){const n=e.sender.getParameters();n.encodings=t,await e.sender.setParameters(n),this.trace("TRANSCEIVER SENDER SET_PARAMETERS",n),this.writePeerConnectionTimelineLog("transceiver-sender-set-parameters",n)}async getStats(){const e=[];if(!this.pc)return e;return(await this.pc.getStats()).forEach((t=>{e.push(t)})),e}onDataChannel(e){const t=e.channel;var n;this.writeDataChannelTimelineLog("ondatachannel",t,{binaryType:(n=t).binaryType,bufferedAmount:n.bufferedAmount,bufferedAmountLowThreshold:n.bufferedAmountLowThreshold,id:n.id,label:n.label,maxPacketLifeTime:n.maxPacketLifeTime,maxRetransmits:n.maxRetransmits,negotiated:n.negotiated,ordered:n.ordered,protocol:n.protocol,readyState:n.readyState,reliable:n.reliable}),e.channel.onbufferedamountlow=e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onbufferedamountlow",t)},e.channel.onopen=e=>{const t=e.currentTarget;t.bufferedAmountLowThreshold=65536,t.binaryType="arraybuffer",this.soraDataChannels[t.label]=t,this.trace("OPEN DATA CHANNEL",t.label),"signaling"===t.label&&this.ws?this.writeDataChannelSignalingLog("onopen",t):this.writeDataChannelTimelineLog("onopen",t)},e.channel.onclose=async e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onclose",t),this.trace("CLOSE DATA CHANNEL",t.label),await this.disconnect()},e.channel.onerror=async e=>{const t=e.currentTarget;this.writeDataChannelTimelineLog("onerror",t),this.trace("ERROR DATA CHANNEL",t.label),await this.abend("DATA-CHANNEL-ONERROR",{params:{label:t.label}})},"signaling"===e.channel.label?e.channel.onmessage=async e=>{const t=e.currentTarget;let n=e.data;if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const t=U(new Uint8Array(e.data));n=(new TextDecoder).decode(t)}const i=JSON.parse(n);this.writeDataChannelSignalingLog(`onmessage-${i.type}`,t,i),"re-offer"===i.type&&await this.signalingOnMessageTypeReOffer(i)}:"notify"===e.channel.label?e.channel.onmessage=e=>{const t=e.currentTarget;let n=e.data;if(this.signalingOfferMessageDataChannels.notify&&!0===this.signalingOfferMessageDataChannels.notify.compress){const t=U(new Uint8Array(e.data));n=(new TextDecoder).decode(t)}const i=JSON.parse(n);"connection.created"===i.event_type?this.writeDataChannelTimelineLog("notify-connection.created",t,i):"connection.destroyed"===i.event_type&&this.writeDataChannelTimelineLog("notify-connection.destroyed",t,i),this.signalingOnMessageTypeNotify(i,"datachannel")}:"push"===e.channel.label?e.channel.onmessage=e=>{let t=e.data;if(this.signalingOfferMessageDataChannels.push&&!0===this.signalingOfferMessageDataChannels.push.compress){const n=U(new Uint8Array(e.data));t=(new TextDecoder).decode(n)}const n=JSON.parse(t);this.callbacks.push(n,"datachannel")}:"e2ee"===e.channel.label?e.channel.onmessage=e=>{const t=e.currentTarget,n=e.data;this.signalingOnMessageE2EE(n),this.writeDataChannelSignalingLog("onmessage-e2ee",t,n)}:"stats"===e.channel.label?e.channel.onmessage=async e=>{let t=e.data;if(this.signalingOfferMessageDataChannels.stats&&!0===this.signalingOfferMessageDataChannels.stats.compress){const n=U(new Uint8Array(e.data));t=(new TextDecoder).decode(n)}if("req-stats"===JSON.parse(t).type){const e=await this.getStats();this.sendStatsMessage(e)}}:/^#.*/.exec(e.channel.label)&&(e.channel.onmessage=e=>{if(null===e.target)return;const t=e.target;let n=e.data;const i=this.signalingOfferMessageDataChannels[t.label];void 0!==i&&!0===i.compress&&(n=U(new Uint8Array(e.data)).buffer),this.callbacks.message(function(e,t){const n=new Event("message");return n.label=e,n.data=t,n}(t.label,n))})}sendSignalingMessage(e){if(this.soraDataChannels.signaling){if(this.signalingOfferMessageDataChannels.signaling&&!0===this.signalingOfferMessageDataChannels.signaling.compress){const t=F((new TextEncoder).encode(JSON.stringify(e)),{});this.soraDataChannels.signaling.send(t)}else this.soraDataChannels.signaling.send(JSON.stringify(e));this.writeDataChannelSignalingLog(`send-${e.type}`,this.soraDataChannels.signaling,e)}else null!==this.ws&&(this.ws.send(JSON.stringify(e)),this.writeWebSocketSignalingLog(`send-${e.type}`,e))}sendE2EEMessage(e){this.soraDataChannels.e2ee?(this.soraDataChannels.e2ee.send(e),this.writeDataChannelSignalingLog("send-e2ee",this.soraDataChannels.e2ee,e)):null!==this.ws&&(this.ws.send(e),this.writeWebSocketSignalingLog("send-e2ee",e))}sendStatsMessage(e){if(this.soraDataChannels.stats){const t={type:"stats",reports:e};if(this.signalingOfferMessageDataChannels.stats&&!0===this.signalingOfferMessageDataChannels.stats.compress){const e=F((new TextEncoder).encode(JSON.stringify(t)),{});this.soraDataChannels.stats.send(e)}else this.soraDataChannels.stats.send(JSON.stringify(t))}}getAudioTransceiver(){if(this.pc&&this.mids.audio){return this.pc.getTransceivers().find((e=>e.mid===this.mids.audio))||null}return null}getVideoTransceiver(){if(this.pc&&this.mids.video){return this.pc.getTransceivers().find((e=>e.mid===this.mids.video))||null}return null}soraCloseEvent(e,t,n){const i=class extends Event{constructor(e,t,n){super(e),n&&(n.code&&(this.code=n.code),n.reason&&(this.reason=n.reason),n.params&&(this.params=n.params)),this.title=t}};return new i(e,t,n)}sendMessage(e,t){const n=this.soraDataChannels[e];if(null===this.pc)return;if(void 0===n)throw new Error("Could not find DataChannel");const i=this.signalingOfferMessageDataChannels[e];if(void 0!==i&&!0===i.compress){const e=F(t,{});n.send(e)}else n.send(t)}get e2eeSelfFingerprint(){if(this.options.e2ee&&this.e2ee)return this.e2ee.selfFingerprint()}get e2eeRemoteFingerprints(){if(this.options.e2ee&&this.e2ee)return this.e2ee.remoteFingerprints()}get audio(){return null!==this.getAudioTransceiver()}get video(){return null!==this.getVideoTransceiver()}get signalingUrl(){return this.signalingUrlCandidates}get connectedSignalingUrl(){return this.ws?this.ws.url:""}get datachannels(){if(!this.signalingSwitched)return[];const e=Object.keys(this.signalingOfferMessageDataChannels).filter((e=>/^#.*/.exec(e))),t=[];for(const n of e){const e=this.soraDataChannels[n];if(!e)continue;const i=this.signalingOfferMessageDataChannels[n];if(!i)continue;const s={label:e.label,ordered:e.ordered,protocol:e.protocol,compress:i.compress,direction:i.direction};"number"==typeof e.maxPacketLifeTime&&(s.maxPacketLifeTime=e.maxPacketLifeTime),"number"==typeof e.maxRetransmits&&(s.maxRetransmits=e.maxRetransmits),t.push(s)}return t}}class te extends ee{async connect(e){return this.options.multistream?await Promise.race([this.multiStream(e).finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]):await Promise.race([this.singleStream(e).finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]),this.monitorWebSocketEvent(),this.monitorPeerConnectionState(),e}async singleStream(e){await this.disconnect(),this.setupE2EE();const t=await this.getSignalingWebSocket(this.signalingUrlCandidates),n=await this.signaling(t);return this.startE2EE(),await this.connectPeerConnection(n),await this.setRemoteDescription(n),e.getTracks().forEach((t=>{this.pc&&this.pc.addTrack(t,e)})),this.stream=e,await this.createAnswer(n),this.sendAnswer(),this.pc&&this.e2ee&&this.pc.getSenders().forEach((e=>{this.e2ee&&this.e2ee.setupSenderTransform(e)})),await this.onIceCandidate(),await this.waitChangeConnectionStateConnected(),e}async multiStream(e){await this.disconnect(),this.setupE2EE();const t=await this.getSignalingWebSocket(this.signalingUrlCandidates),n=await this.signaling(t);return this.startE2EE(),await this.connectPeerConnection(n),this.pc&&(this.pc.ontrack=e=>{const t=e.streams[0];if(!t)return;const n={"stream.id":t.id,id:e.track.id,label:e.track.label,enabled:e.track.enabled,kind:e.track.kind,muted:e.track.muted,readyState:e.track.readyState};this.writePeerConnectionTimelineLog("ontrack",n),"default"!==t.id&&t.id!==this.connectionId&&(this.e2ee&&this.e2ee.setupReceiverTransform(e.receiver),this.callbacks.track(e),t.onremovetrack=e=>{if(this.callbacks.removetrack(e),e.target){const t=this.remoteConnectionIds.indexOf(e.target.id);-1{this.pc&&this.pc.addTrack(t,e)})),this.stream=e,await this.createAnswer(n),this.sendAnswer(),this.pc&&this.e2ee&&this.pc.getSenders().forEach((e=>{this.e2ee&&this.e2ee.setupSenderTransform(e)})),await this.onIceCandidate(),await this.waitChangeConnectionStateConnected(),e}}class ne extends ee{async connect(){if(this.options.multistream)return await Promise.race([this.multiStream().finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]),this.monitorWebSocketEvent(),void this.monitorPeerConnectionState();{const e=await Promise.race([this.singleStream().finally((()=>{this.clearConnectionTimeout(),this.clearMonitorSignalingWebSocketEvent()})),this.setConnectionTimeout(),this.monitorSignalingWebSocketEvent()]);return this.monitorWebSocketEvent(),this.monitorPeerConnectionState(),e}}async singleStream(){await this.disconnect(),this.setupE2EE();const e=await this.getSignalingWebSocket(this.signalingUrlCandidates),t=await this.signaling(e);return this.startE2EE(),await this.connectPeerConnection(t),this.pc&&(this.pc.ontrack=e=>{this.stream=e.streams[0];const t=this.stream.id;if("default"===t)return;const n={"stream.id":t,id:e.track.id,label:e.track.label,enabled:e.track.enabled,kind:e.track.kind,muted:e.track.muted,readyState:e.track.readyState};this.writePeerConnectionTimelineLog("ontrack",n),this.e2ee&&this.e2ee.setupReceiverTransform(e.receiver),this.callbacks.track(e),this.stream.onremovetrack=e=>{if(this.callbacks.removetrack(e),e.target){const t=this.remoteConnectionIds.indexOf(e.target.id);-1{const t=e.streams[0];if("default"===t.id)return;if(t.id===this.connectionId)return;const n={"stream.id":t.id,id:e.track.id,label:e.track.label,enabled:e.track.enabled,kind:e.track.kind,muted:e.track.muted,readyState:e.track.readyState};this.writePeerConnectionTimelineLog("ontrack",n),this.e2ee&&this.e2ee.setupReceiverTransform(e.receiver),this.callbacks.track(e),t.onremovetrack=e=>{if(this.callbacks.removetrack(e),e.target){const t=this.remoteConnectionIds.indexOf(e.target.id);-1