@formant/data-sdk 0.0.109 → 0.0.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-sdk.es.js +1 -1
- package/dist/data-sdk.umd.js +1 -1
- package/package.json +4 -4
package/dist/data-sdk.es.js
CHANGED
|
@@ -19921,7 +19921,7 @@ class Device {
|
|
|
19921
19921
|
let rtcClient;
|
|
19922
19922
|
if (rtcClientVersion === "1") {
|
|
19923
19923
|
rtcClient = new dist.exports.RtcClientV1({
|
|
19924
|
-
signalingClient: new dist.exports.RtcSignalingClient(FORMANT_API_URL + "/v1/signaling
|
|
19924
|
+
signalingClient: new dist.exports.RtcSignalingClient(FORMANT_API_URL + "/v1/signaling"),
|
|
19925
19925
|
getToken: async () => defined(Authentication.token, "Realtime when user isn't authorized"),
|
|
19926
19926
|
receive: this.handleMessage
|
|
19927
19927
|
});
|
package/dist/data-sdk.umd.js
CHANGED
|
@@ -41,4 +41,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
41
41
|
`))},s.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)}},function(e,t,n){function r(u){return(r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s})(u)}function o(u,s){for(var i=0;i<s.length;i++){var c=s[i];c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(u,c.key,c)}}e.exports=function(){function u(c){if(function(l,m){if(!(l instanceof m))throw new TypeError("Cannot call a class as a function")}(this,u),!c)throw new Error("Logger is required for profiling.");this.logger=c,this.start=Date.now()}var s,i;return s=u,(i=[{key:"done",value:function(){for(var c=arguments.length,l=new Array(c),m=0;m<c;m++)l[m]=arguments[m];typeof l[l.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),l.pop());var R=r(l[l.length-1])==="object"?l.pop():{};return R.level=R.level||"info",R.durationMs=Date.now()-this.start,this.logger.write(R)}}])&&o(s.prototype,i),u}()},function(e,t,n){(function(r){const o=n(209),{MESSAGE:u}=n(3),s=n(35);function i(c,l){return l instanceof r?l.toString("base64"):typeof l=="bigint"?l.toString():l}e.exports=o((c,l={})=>(c[u]=(l.stable?s.stableStringify:s)(c,l.replacer||i,l.space),c))}).call(this,n(5).Buffer)},function(e,t,n){class r extends Error{constructor(u){super(`Format functions must be synchronous taking a two arguments: (info, opts)
|
|
42
42
|
Found: ${u.toString().split(`
|
|
43
43
|
`)[0]}
|
|
44
|
-
`),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function u(i={}){this.options=i}function s(i){return new u(i)}return u.prototype.transform=o,s.Format=u,s}},function(e,t,n){function r(s,i){if(!(s instanceof i))throw new TypeError("Cannot call a class as a function")}function o(s,i){for(var c=0;c<i.length;c++){var l=i[c];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(s,l.key,l)}}var u=n(88);e.exports=function(){function s(){var l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,s),this.loggers=new Map,this.options=l}var i,c;return i=s,(c=[{key:"add",value:function(l,m){var R=this;if(!this.loggers.has(l)){var E=(m=Object.assign({},m||this.options)).transports||this.options.transports;m.transports=E?E.slice():[];var y=u(m);y.on("close",function(){return R._delete(l)}),this.loggers.set(l,y)}return this.loggers.get(l)}},{key:"get",value:function(l,m){return this.add(l,m)}},{key:"has",value:function(l){return!!this.loggers.has(l)}},{key:"close",value:function(l){var m=this;if(l)return this._removeLogger(l);this.loggers.forEach(function(R,E){return m._removeLogger(E)})}},{key:"_removeLogger",value:function(l){this.loggers.has(l)&&(this.loggers.get(l).close(),this._delete(l))}},{key:"_delete",value:function(l){this.loggers.delete(l)}}])&&o(i.prototype,c),s}()},function(e,t,n){(function(r){const o=n(52),u=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(s,i,c,l){let m,R,E=!1,y=!1;const g=n(94);function _(V){l(i,V)}function T(V,M){let A=`"${i}" ${M}`;throw V&&(A=`${A}`),R&&(A=`${A}. An example of a valid value would be: ${R}`),new o(A)}const L={convertFromBase64:function(){return _("marking for base64 conversion"),E=!0,L},default:function(V){if(typeof V=="number")m=V.toString();else if(Array.isArray(V)||typeof V=="object"&&V!==null)m=JSON.stringify(V);else{if(typeof V!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");m=V}return _(`setting default value to "${m}"`),L},required:function(V){return V===void 0?(_("marked as required"),y=!0):(_(`setting required flag to ${V}`),y=V),L},example:function(V){return R=V,L}};return Object.entries(ht(ht({},g),c)).forEach(([V,M])=>{L[V]=function(A){return function(){let f=s[i];if(_(`will be read from the environment using "${A.name}" accessor`),f===void 0)if(m===void 0&&y)_("was not found in the environment, but is required to be set"),T(void 0,"is a required variable, but it was not set");else{if(m===void 0)return void _("was not found in the environment, but is not required. returning undefined");_(`was not found in the environment, parsing default value "${m}" instead`),f=m}y&&(_("verifying variable value is not an empty string"),f.trim().length===0&&T(void 0,"is a required variable, but its value was empty")),E&&(_("verifying variable is a valid base64 string"),f.match(u)||T(f,"should be a valid base64 string if using convertFromBase64"),_("converting from base64 to utf8 string"),f=r.from(f,"base64").toString());const O=[f].concat(Array.prototype.slice.call(arguments));try{_(`passing value "${f}" to "${A.name}" accessor`);const Y=A.apply(A,O);return _(`parsed successfully, returning ${Y}`),Y}catch(Y){T(f,Y.message)}}}(M)}),L}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(33);e.exports=function(o,u){return u=u||",",o.length?r(o).split(u).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(95);e.exports=function(o){var u=r(o);if(u>65535)throw new Error("cannot assign a port number greater than 65535");return u}},function(e,t,n){const r=n(33);e.exports=function(o,u){const s=r(o);if(u.indexOf(s)<0)throw new Error(`should be one of [${u.join(", ")}]`);return s}},function(e,t,n){const r=n(54);e.exports=function(o){const u=r(o);if(u>0)throw new Error("should be a negative float");return u}},function(e,t,n){const r=n(54);e.exports=function(o){const u=r(o);if(u<0)throw new Error("should be a positive float");return u}},function(e,t,n){const r=n(53);e.exports=function(o){const u=r(o);if(u>0)throw new Error("should be a negative integer");return u}},function(e,t,n){const r=n(55);e.exports=function(o){var u=r(o);if(!Array.isArray(u))throw new Error("should be a parseable JSON Array");return u}},function(e,t,n){const r=n(55);e.exports=function(o){var u=r(o);if(Array.isArray(u))throw new Error("should be a parseable JSON Object");return u}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(33),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(u){const s=r(u);if(!o.test(s))throw new Error("should be a valid email address");return s}},function(e,t,n){e.exports=function(r,o){return function(u,s){o&&o.match(/prod|production/)||r(`env-var (${u}): ${s}`)}}},function(e,t,n){(function(r){(function(){var o,u,s,i,c,l;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-c)/1e6},u=r.hrtime,i=(o=function(){var m;return 1e9*(m=u())[0]+m[1]})(),l=1e9*r.uptime(),c=i-l):Date.now?(e.exports=function(){return Date.now()-s},s=Date.now()):(e.exports=function(){return new Date().getTime()-s},s=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function u(i){if((i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+i+"') is invalid.")}function s(i,c){if(c=c===void 0?{fatal:!1}:c,(i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+i+"') is invalid.");if(c.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(u.prototype,"encoding",{value:"utf-8"}),u.prototype.encode=function(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");c=0;for(var l=i.length,m=0,R=Math.max(32,l+(l>>1)+7),E=new Uint8Array(R>>3<<3);c<l;){var y=i.charCodeAt(c++);if(55296<=y&&56319>=y){if(c<l){var g=i.charCodeAt(c);(64512&g)==56320&&(++c,y=((1023&y)<<10)+(1023&g)+65536)}if(55296<=y&&56319>=y)continue}if(m+4>E.length&&(R+=8,R=(R*=1+c/i.length*2)>>3<<3,(g=new Uint8Array(R)).set(E),E=g),(4294967168&y)==0)E[m++]=y;else{if((4294965248&y)==0)E[m++]=y>>6&31|192;else if((4294901760&y)==0)E[m++]=y>>12&15|224,E[m++]=y>>6&63|128;else{if((4292870144&y)!=0)continue;E[m++]=y>>18&7|240,E[m++]=y>>12&63|128,E[m++]=y>>6&63|128}E[m++]=63&y|128}}return E.slice(0,m)},Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(s.prototype,"fatal",{value:!1}),Object.defineProperty(s.prototype,"ignoreBOM",{value:!1}),s.prototype.decode=function(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");c=0;for(var l=(i=new Uint8Array(i)).length,m=[];c<l;){var R=i[c++];if(R===0)break;if((128&R)==0)m.push(R);else if((224&R)==192){var E=63&i[c++];m.push((31&R)<<6|E)}else if((240&R)==224){E=63&i[c++];var y=63&i[c++];m.push((31&R)<<12|E<<6|y)}else(248&R)==240&&(65535<(R=(7&R)<<18|(E=63&i[c++])<<12|(y=63&i[c++])<<6|63&i[c++])&&(R-=65536,m.push(R>>>10&1023|55296),R=56320|1023&R),m.push(R))}return String.fromCharCode.apply(null,m)},o.TextEncoder=u,o.TextDecoder=s})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return u}),n.d(t,"RtcSignalingClient",function(){return i}),n.d(t,"Credentials",function(){return P}),n.d(t,"IRtcStream",function(){}),n.d(t,"SignalingPromiseClient",function(){return F.SignalingPromiseClient}),n.d(t,"IRtcClientConfigurationV1",function(){}),n.d(t,"IRtcClientConfiguration",function(){}),n.d(t,"IRtcConnectionStatsInfo",function(){}),n.d(t,"IRtcSendConfiguration",function(){}),n.d(t,"IRtcSessionMetricsMessageCounts",function(){}),n.d(t,"IRtcStreamMessage",function(){}),n.d(t,"IRtcStreamPayload",function(){}),n.d(t,"IStreamControl",function(){}),n.d(t,"RtcClient",function(){return _t}),n.d(t,"RtcClientV1",function(){return jt}),n.d(t,"createRtcStreamMessage",function(){return Ee});var r=n(28),o=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class u extends r.a{adminSignup(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:W,method:"POST",body:JSON.stringify(x)})})}login(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}loginWithGoogleToken(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}refresh(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:x,tokenExpirationSeconds:W}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(x)})})}forgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:x})})})}confirmForgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(x)})})}resendInvitation(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:x})})})}changePassword({token:x,refreshToken:W,currentPassword:K,newPassword:re}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:x,method:"POST",body:JSON.stringify({refreshToken:W,currentPassword:K,newPassword:re})})})}getDeviceCredentials(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:x,method:"POST",allowUnsafeRetries:!0})})}impersonate(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:W})})})}createServiceAccount(x,W,K,re){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:W,roleId:K,tags:re})})})}getFeatures(x){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:x})).features})}}var s=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class i extends r.a{createPeer(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:x,method:"POST",body:JSON.stringify(W)})})}getPeers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:x})).items})}refreshPeer(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}createSession(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:x,method:"POST",body:JSON.stringify(W)})})}refreshSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}deleteSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}`,{token:x,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:x})).items})}getIceServers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:x})).items})}addSignals(x,W,K){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/add-signals`,{token:x,method:"POST",body:JSON.stringify(K)})})}takeSignals(x,W){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${W}/take-signals`,{token:x,method:"POST"})).items})}}var c=n(1),l=n(8),m=n(14),R=n.n(m),E=n(104),y=n.n(E),g=n(0),_=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class T{constructor(x){this.name="LogReporter",this.type="simple",this.message=x}send(x){return _(this,void 0,void 0,function*(){var W,K;g.a.info(this.message,(W=x.reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe.name]:oe.stat}),{}),K=re=>{const{sum:oe,count:he}=re,me=oe/he;return Object.assign(Object.assign({},re),{average:me})},Object.keys(W).reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe]:K(W[oe])}),{})))})}}var L=n(4),V=n(39);function M(ye){return!!ye.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function f({func:ye,delay:x,immediate:W}){let K=!1,re=setTimeout(function he(){return A(this,void 0,void 0,function*(){if(K)return;const me=new Date().getTime();try{oe=ye(),yield oe}finally{if(!K){const pe=new Date().getTime();re=setTimeout(he,Math.max(x-(pe-me),0))}}})},W?0:x),oe=Promise.resolve();return{stop(){return A(this,void 0,void 0,function*(){K=!0,clearTimeout(re),yield oe})}}}var O=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};const Y=n(226),Z=!!L.c,d=new class{constructor(ye){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=f({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((ye==null?void 0:ye.tags)||{app:L.a,version:L.j,namespace:L.i,instanceId:V.a})}shutdown(){return O(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(l.a)(2*c.a.second)})}aggregate(ye,x,W){this.addToBuffer(this.buffer,this.encodeKey({metric:ye,tags:this.filterTags(W||{})}),typeof x=="number"?{min:x,max:x,sum:x,count:1}:x)}increment(ye,x){this.aggregate(ye,1,x)}timer(ye,x,W){return O(this,void 0,void 0,function*(){const K=Y(),re=yield x(),oe=Y();return this.aggregate(ye,oe-K,W),re})}registerStatsReporter(ye){this.reporters.push(ye)}setTag(ye,x){const W=this.filterTags({[ye]:x});this.tags=Object.assign(Object.assign({},this.tags),W)}addToBuffer(ye,x,W){if(ye[x]){const{min:K,max:re,sum:oe,count:he}=ye[x];ye[x]={min:Math.min(K,W.min),max:Math.max(re,W.max),sum:oe+W.sum,count:he+W.count}}else ye[x]=W}write(ye){return O(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(x=>O(this,void 0,void 0,function*(){let W;const K={};switch(x.type){case"simple":for(const[oe,he]of Object.entries(ye)){const{metric:me}=this.decodeKey(oe);this.addToBuffer(K,this.encodeKey({metric:me}),he)}W=K;break;case"tagged":W=ye;break;default:(function(oe){throw new Error(`Unreachable type encountered (${oe})`)})(x.type)}const re=Object.entries(W);if(re.length>0)return x.send(re.map(([oe,he])=>{const{metric:me,tags:pe}=this.decodeKey(oe);return{name:me,tags:Object.assign(Object.assign({},pe),this.tags),stat:he}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${x.name}`,{error:oe})})})))})}flushStats(){return O(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(ye){return R()(Object.assign(Object.assign({},ye),Object.keys(ye.tags||{}).length>0?{tags:ye.tags}:{}))}decodeKey(ye){return JSON.parse(ye)}filterTags(ye){return Object.entries(ye||{}).reduce((x,[W,K])=>(M(W)&&M(K)&&(x[W]=K),x),{})}};Z||["local","on-prem"].includes(L.i)||d.registerStatsReporter(new T("stats"));var p=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class C extends class{constructor(x){this.options=x,this.cache=new y.a(Object.assign(Object.assign(Object.assign({},x.dispose||x.disposeAfter?{ttlAutopurge:!0}:{}),x),{dispose:(...W)=>{var K;W[2]==="evict"&&d.increment("lru-eviction",{name:x.name}),(K=x.dispose)===null||K===void 0||K.call(x,...W)},disposeAfter:(...W)=>{var K;this.updateStats(),(K=x.disposeAfter)===null||K===void 0||K.call(x,...W)}})),this.stringify=x.fastStringify?JSON.stringify:R.a}set(x,W,K){const re=this.stringify(x);if(!this.cache.set(re,W,{ttl:K})){const oe=this.cache.sizeCalculation?this.cache.sizeCalculation(W,re):"unknown";throw Error(`Value too large (${oe} > ${this.cache.max})`)}this.updateStats()}get(x){const{name:W}=this.options,K=this.stringify(x),re=this.cache.getRemainingTTL(K);return re<=0?d.increment("cache-miss",{name:W}):re!==1/0&&d.aggregate("cache-item-ttl",re,{name:W}),this.cache.get(K)}delete(x){this.cache.delete(this.stringify(x))}peek(x){return this.cache.peek(this.stringify(x))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(x){this.cache.forEach(x)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:x}=this.options;d.aggregate("cache-item-count",this.cache.size,{name:x}),this.cache.calculatedSize!==void 0&&d.aggregate("cache-length",this.cache.calculatedSize,{name:x})}}{constructor(x){if(super(x),this.expireRejectedPromiseValues=x.expireRejectedPromiseValues===void 0||x.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=x.rejectedPromiseValueTtl!==void 0?x.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(x,W,K){super.set(x,W,K),this.expireRejectedPromiseValues&&W.catch(()=>p(this,void 0,void 0,function*(){yield Object(l.a)(this.rejectedPromiseValueTtl),this.peek(x)===W&&this.delete(x)}))}}var b=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class P{constructor(x,W,K){this.authClient=x,this.email=W,this.password=K,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new C({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return b(this,void 0,void 0,function*(){let x=this.tokenCache.get(this.email);return x||(x=(()=>b(this,void 0,void 0,function*(){const{authentication:W}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!W)throw new Error("User account not verified.");return W.accessToken}))(),this.tokenCache.set(this.email,x)),x})}}var F=n(97),D=n(40),I=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class N extends D.a{constructor(x){super(x)}postLanRtcOffer(x){return I(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(x)})})}}var k=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function w(ye){return k(this,void 0,void 0,function*(){return(yield Promise.all(ye.map(x=>x.catch(W=>W)))).filter(x=>x instanceof Error)})}function h(ye){if(ye!==void 0)return ye;throw new Error("Value is undefined")}function B(ye,x){const W=ye.reduce((K,re)=>[...K,...re.urls],[]).filter(K=>z(K,x)).sort(K=>X(K,"udp")?-1:0).shift();if(W)return Object.assign(Object.assign({},h(ye.find(K=>K.urls.includes(W)))),{urls:[W]})}function z(ye,x){switch(x){case"stun":return/^stuns?:/.test(ye);case"turn":return/^turns?:/.test(ye)}}function X(ye,x){return ye.endsWith(`transport=${x}`)}var Q=n(9),te=n(24),q=n(229),H=n(29);const v={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},S={ordered:!0},U={ordered:!0},J={ordered:!1,maxRetransmits:0},$={ordered:!1,maxRetransmits:0},ne=ye=>"received"in ye&&ye.received!==void 0,se=ye=>!("received"in ye)||ye.received===void 0,ge=2*c.a.second;function ve(ye,x={}){const W=Array.from(ye.values()),K=W.filter(ne),re=K.length>0,oe=Math.max(...K.map(ue=>ue.received));let he;if(re){const ue=W.length,le=K.length,Re=K.map(je=>je.received-je.sent),{standardDeviation:Ie,mean:ke,jitter:He}=function(je){const Fe=je.length;if(Fe===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const $e=je.reduce((Je,ot)=>Je+ot,0)/Fe,Ze=Math.sqrt(je.map(Je=>Math.pow(Je-$e,2)).reduce((Je,ot)=>Je+ot)/Fe);let Ke=0;for(let Je=1;Je<Fe;++Je)Ke+=Math.abs(je[Je]-je[Je-1]);return{mean:$e,standardDeviation:Ze,jitter:Ke/(Fe-1)}}(Re),Xe=W.filter(je=>je.sent<oe-ge),Ye=Xe.filter(se),Ge=Ye.length===0?0:Ye.length/Xe.length;he={pingsSent:ue,pongsReceived:le,average:ke,standardDeviation:Ie,jitter:He,max:Math.max(...Re),min:Math.min(...Re),loss:Ge}}else he=null;const{temporalNow:me=Date.now()}=x,pe=(re?oe:me)-4*ge;return Array.from(ye.entries()).forEach(ue=>{const[le,Re]=ue;Re.sent<pe&&ye.delete(le)}),he}function Ae({entityId:ye,streamName:x,streamType:W}){return`${ye}.${x}.${W}`}var Se=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ce{constructor(x,W){this.sessionId=x,this.connection=W,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=x,this.connection=W}updateRemoteMessagesCounts(x){if(x.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const W of x.payload.streamsInfo.items)this.counts.remoteSent.set(W.streamId,W.sentCount),this.counts.remoteReceived.set(W.streamId,W.receivedCount)}}getLocalStreamsInfo(x){const{localSent:W,localReceived:K}=this.counts;return{items:[...new Set([...W.keys(),...K.keys()])].map(re=>{var oe,he;return{streamId:re,sentCount:(oe=W.get(re))!==null&&oe!==void 0?oe:0,receivedCount:(he=K.get(re))!==null&&he!==void 0?he:0}}),timestamp:x}}incrementLocalSent(x){const{localSent:W}=this.counts,K=Ae(x.header.stream);W.set(K,(W.get(K)||0)+1)}incrementLocalReceived(x){const{localReceived:W}=this.counts,K=Ae(x.header.stream),re=W.get(K)||0;if(re===0){const{streamName:oe,streamType:he}=x.header.stream;g.a.debug("RTC client received first message for stream",{streamName:oe,streamType:he})}W.set(K,re+1)}uploadMetrics(){return Se(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(ue=>K[ue.id]=ue),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const{localSent:re,localReceived:oe,remoteSent:he,remoteReceived:me}=this.counts,pe=[...new Set([...re.keys(),...oe.keys()])].reduce((ue,le)=>{const Re=re.get(le),Ie=oe.get(le),ke=he.get(le),He=me.get(le);return Object.assign(Object.assign({},ue),{[`local-${le}-sent`]:Re,[`local-${le}-received`]:Ie,[`remote-${le}-sent`]:ke,[`remote-${le}-received`]:He})},{sessionId:x});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function Ee(ye,x,W){return{header:{stream:ye,created:Date.now(),frameId:W||""},payload:x}}function Te(ye){return new Set(["disconnected","failed","closed"]).has(ye.iceConnectionState)}function Ue(ye){switch(ye.header.stream.streamType){case"twist":{const{twist:x}=ye.payload;if(!x)throw Error("twist not in payload of RTC message with type twist");return{header:ye.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},x.linear),angular:Object.assign({x:0,y:0,z:0},x.angular)}}}}case"pose":{const{pose:x}=ye.payload;if(!x)throw Error("pose not in payload of RTC message with type pose");return{header:ye.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},x.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:x}=ye.payload;if(!x)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const W=new Array(36).fill(0);return x.covariance.forEach((K,re)=>{if(re>=36)throw Error("covariance contains more than 36 elements");W[re]=K}),{header:ye.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},x.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.pose.rotation)},covariance:W}}}}case"point":{const{point:x}=ye.payload;if(!x)throw Error("point not in payload of RTC message with type point");return{header:ye.header,payload:{point:Object.assign({x:0,y:0,z:0},x)}}}default:return ye}}var qe=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Qe{constructor(x,W,K){this.peerConnection=x,this.config=W,this.dataChannelNotifier=K,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=1*c.a.second,this.pingV2UpdateTimeoutMs=250*c.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*c.a.second,this.streamsInfoUpdateTimeoutMs=2*c.a.second,this.reassemblyTimeoutMs=500*c.a.millisecond,this.reassemblyTableCleanupMs=1*c.a.second,this.heartbeatTimeoutMs=20*c.a.millisecond,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:oe}=this;if(!oe)return;const he=new Date().getTime(),me=Object(q.a)();this.sendSystemMessage(oe,{type:"ping-v2",payload:{timestamp:he,id:me}}),this.pingV2Map.set(me,{sent:he})},this.gatherPingV2Metrics=()=>{const oe=ve(this.pingV2Map);oe&&(this.pingInfo=oe,d.aggregate("rtc-ping-average",oe.average),d.aggregate("rtc-ping-loss",oe.loss),d.aggregate("rtc-jitter",oe.jitter))};const{isOffer:re}=W.baseConfig;re?this.initializeChannels(x):x.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel;break;case"heartbeat":return void(this.heartbeatChannel=oe.channel);default:return void this.dataChannelNotifier(oe.channel)}this.setupChannel(oe.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const oe=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,me,pe)=>{oe>me+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:oe}=this;oe&&oe.readyState==="open"&&oe.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=this,{track:K}=this.config.baseConfig,re=(()=>{try{return JSON.parse(x.getPayload())}catch{return}})();if(!re)return void g.a.error("Received unparseable signal.");g.a.debug("Handling signal",{description:re});const{sdp:oe,type:he}=re;if(!oe||!he)return void g.a.warn("Received non-SDP signal");const{signalingState:me,connectionState:pe}=W;if(me!=="stable"||pe!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP after remote description was set: ${oe}`);else{if(he==="offer"){if(me!=="stable")return void g.a.warn("Received offer SDP when signaling is ongoing.");yield W.setRemoteDescription(re);const ue=yield W.createAnswer();yield W.setLocalDescription(ue);const le=x.clone();return K==null||K("Answer Received",le),le.setPayload(JSON.stringify(ue)),le.setReceiverId(x.getSenderId()),le.setSenderId(x.getReceiverId()),le}if(he==="answer"){if(me==="stable")return void g.a.warn("Received answer SDP when signaling hasn't started.");yield W.setRemoteDescription(re)}}else g.a.warn(`Received SDP when already connected: ${oe}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:x,latestTtlStreamChannel:W,latestTryOnceStreamChannel:K,latestReliableStreamChannel:re}=this;return(x==null?void 0:x.readyState)==="open"&&(W==null?void 0:W.readyState)==="open"&&(K==null?void 0:K.readyState)==="open"&&(re==null?void 0:re.readyState)==="open"}close(){return qe(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),tt(this.pingUpdateTimeout),tt(this.pingV2UpdateTimeout),tt(this.pingV2MetricsGatherTimeout),tt(this.reassemblyTableCleanupTimeout),tt(this.streamsInfoUpdateTimeout),tt(this.heartbeatTimeout);const{peerConnection:x,reliableStreamChannel:W,latestTtlStreamChannel:K,latestTryOnceStreamChannel:re,latestReliableStreamChannel:oe}=this;x.close(),W==null||W.close(),K==null||K.close(),re==null||re.close(),oe==null||oe.close()})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionCreatedTimestamp}setSessionCreatedTimestamp(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=x)}getSessionId(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId}setSessionId(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=x,this.sessionMetrics=new Ce(x,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var x;return(x=this.config.baseConfig)===null||x===void 0?void 0:x.remoteDeviceId}setRemoteDeviceId(x){this.config.baseConfig.remoteDeviceId=x}getSessionMetricsMessageCounts(){var x;return(x=this.sessionMetrics)===null||x===void 0?void 0:x.counts}getConnectionStatsInfo(){return qe(this,void 0,void 0,function*(){const{peerConnection:x}=this;if(!x)return;const W=yield x.getStats(null),K=[];W.forEach(pe=>{K.push(pe)});const re=K.find(pe=>pe.type==="transport");if(!re)return;const oe=K.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===re.selectedCandidatePairId);if(!oe)return;const he=K.find(pe=>pe.id===oe.localCandidateId),me=K.find(pe=>pe.id===oe.remoteCandidateId);return he&&me&&(he.address=he.address||he.ip,me.address=me.address||me.ip,he.address!==void 0&&me.address!==void 0)?{transport:re,localCandidate:he,remoteCandidate:me}:void 0})}initializeChannels(x){this.heartbeatChannel=x.createDataChannel("heartbeat",$),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var x,W,K;return qe(this,void 0,void 0,function*(){const{gotOffer:re}=this,{peerConnection:oe,config:he}=this;if(this.config.baseConfig.isLan)throw new Error('"getOffer" method can only be called with internet connections. LAN connections should call the "getLanOffer" method.');const me=(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId;if(re)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const pe=he.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>qe(this,void 0,void 0,function*(){const ke=oe.iceConnectionState;if(ke==="connected"||ke==="completed"){const He=yield this.getConnectionStatsInfo(),Xe=He?function(Ye){const Ge=Ye.localCandidate.candidateType,je=Ye.remoteCandidate.candidateType;return Ge==="host"&&je==="host"?"local":Ge==="relay"||je==="relay"?"TURN":"STUN"}(He):void 0;g.a.info(`ICE connection state changed to ${ke}`,{sessionId:me,connectionStatsInfo:He,iceMode:Xe}),pe==null||pe("ICE connection state change",{iceConnectionState:ke,sessionId:me,connectionStatsInfo:He,iceMode:Xe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ue=new Date().getTime();for(;;){const ke=new Date().getTime()-ue;if(ke>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(ke>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering partially completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}yield Object(l.a)(.1*c.a.second)}const le=(W=this.peerConnection.getConfiguration().iceServers)!==null&&W!==void 0?W:[];for(const ke of le)ke.credentialType=void 0;const Re=JSON.stringify(le),Ie=new Q.Signal;return Ie.setPayload(JSON.stringify(oe.localDescription)),Ie.setSenderId(this.config.baseConfig.localPeerId),Ie.setReceiverId(this.config.baseConfig.remotePeerId),Ie.setIceServers(Re),Ie.setIceTransportPolicy((K=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&K!==void 0?K:"all"),this.config.baseConfig.sessionType!==void 0?Ie.setSessionType(this.config.baseConfig.sessionType):Ie.setSessionType(Q.SessionType.TELEOP),g.a.debug("Sending offer signal with description",{description:Ie.getPayload()}),Ie})}getLanOffer(){return qe(this,void 0,void 0,function*(){const{peerConnection:x,gotOffer:W}=this;if(!this.config.baseConfig.isLan)throw new Error('"getLanOffer" method can only be used with LAN connections. Internet connections should call the "getOffer" method.');if(W)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");yield x.setLocalDescription(yield x.createOffer());const K=new Date().getTime();for(;;){if(new Date().getTime()-K>this.iceGatheringTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(x.iceGatheringState==="complete")break;yield Object(l.a)(.1*c.a.second)}const re=x.localDescription;if(re)return g.a.debug("Sending LAN offer signal with description",{description:re}),re;g.a.error("Failed to generate LAN offer description")})}handleLanAnswer(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=this;if(!this.config.baseConfig.isLan)throw new Error('"handleLanAnswer" method can only be used with LAN connections. Internet connections should call the "handleSignal" method.');yield W.setRemoteDescription(x)})}getChannelFromLabel(x){switch(x){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable message on RTC stream data channel",{error:re,channel:x.label})}K.communicationType==="message-chunk"?this.receiveChannelMessageChunk(x,K):this.receiveChannelMessage(x,K)},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}receiveChannelMessage(x,W){const{config:K}=this,{remotePeerId:re}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),W=Ue(W),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(W),this.handleSystemMessage(x,W)||(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(W)||K.baseConfig.receive(re,W)}receiveChannelMessageChunk(x,W){const K=this.reassemblyTable.get(W.id)||[];if(K.push(W),K.length===W.total){const re=function(oe){const he=oe.sort((me,pe)=>me.seq<pe.seq?-1:1).map(me=>me.part).reduce((me,pe)=>me+pe);try{return JSON.parse(he)}catch{return void g.a.warn("Could not reassemble RTC message chunks")}}(K);return re&&this.receiveChannelMessage(x,re),void this.reassemblyTable.delete(W.id)}this.reassemblyTable.set(W.id,K),this.reassemblyTableLastTimestamp.set(W.id,new Date().getTime())}handleSystemMessage(x,W){var K,re;const{config:oe}=this,{baseConfig:he}=oe,{remotePeerId:me}=he;switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const pe=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=pe,d.aggregate("rtc-ping-time",pe),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const pe=h(W.payload.pongV2),ue=this.pingV2Map.get(pe.id);return(ue==null?void 0:ue.sent)!==pe.timestamp?(g.a.warn("Pong timestamp doesn't match stored value",{currentEntry:ue,pong:pe}),!0):(this.pingV2Map.set(pe.id,{sent:pe.timestamp,received:new Date().getTime()}),!0)}case"streams-info":{const{sessionMetrics:pe}=this,ue=(K=W.payload.streamsInfo)===null||K===void 0?void 0:K.timestamp;return!!ue&&(pe==null||pe.updateRemoteMessagesCounts(W),(re=he.onStreamsInfoUpdate)===null||re===void 0||re.call(he,me,ue),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){var K;const{localUserId:re,localPeerId:oe}=this.config.baseConfig;if(x.readyState!=="open")return;const he={entityId:re!=null?re:oe,streamName:`$.${W.type}`,streamType:W.type};let me;switch(W.type){case"ping":me={ping:new Date().getTime()};break;case"pong":me={pong:W.timestamp};break;case"ping-v2":me={pingV2:W.payload};break;case"pong-v2":me={pongV2:W.payload};break;case"stream-control":me={streamControl:W.streamControl};break;case"streams-info":me={streamsInfo:(K=this.sessionMetrics)===null||K===void 0?void 0:K.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(x,Ee(he,me))}isLatestMessage(x){const W=Ae(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}function tt(ye){ye&&clearInterval(ye)}function Rt(ye){var x,W;return{userId:(x=ye.getUserId())===null||x===void 0?void 0:x.getValue(),deviceId:(W=ye.getDeviceId())===null||W===void 0?void 0:W.getValue(),organizationId:ye.getOrganizationId(),id:ye.getPeerId(),capabilities:[],capabilitySet:{}}}var xe=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class _t{constructor(x){this.config=x,this.grpcCallDeadline=5*c.a.second,this.refreshIntervalDelayMs=2*c.a.second,this.iceServersTtl=30*c.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:W}=this;this.refreshInterval=f({func:()=>xe(this,void 0,void 0,function*(){try{yield this.update()}catch(K){g.a.warn("RTC refresh failed",{error:K})}}),delay:W,immediate:!0})}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Send called with unready connection."):g.a.warn("Send called with no connection.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("controlRemoteStream called with unready connection."):g.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return xe(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(l.a)(.1*c.a.second);return Rt(this.localPeer)})}connect(x,W){var K,re,oe;return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:he,signalingClient:me}=this.config,{localPeer:pe,receiveSignalStream:ue,iceServers:le}=this;if(!pe||!ue||!le)return void g.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(x))return void g.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(x))return void g.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(x,!0);const Re=function(je,Fe,$e){const{rtcIceTransportPolicies:Ze,rtcIceServerProtocol:Ke,useAllServers:Je}=Fe||{},ot=je.map(it=>Object.assign(Object.assign({},it),{urls:it.urls.filter(dt=>{const St=(Ze===void 0||Ze.some(wt=>z(dt,wt)))&&(Ke===void 0||X(dt,Ke));return St||g.a.debug(`Ignoring ICE server: ${dt}`,{organizationId:$e}),St})})).filter(({urls:it})=>it.filter(dt=>dt).length>0);return Je?ot:[B(ot,"stun"),B(ot,"turn")].filter(it=>it!==void 0).map(it=>h(it))}(le,W);g.a.debug("Received ICE servers:",le),g.a.debug("Using ICE servers:",Re);const Ie=new Qe(yield this.createRTCPeerConnection(Re),{baseConfig:{isOffer:!0,isLan:!1,receive:(je,Fe)=>this.config.receive(je,Fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(je,Fe)=>{var $e,Ze;return(Ze=($e=this.config).onStreamsInfoUpdate)===null||Ze===void 0?void 0:Ze.call($e,je,Fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=pe.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:pe.getPeerId(),remotePeerId:x,sessionType:this.config.sessionType},remoteConfig:{}},je=>this.onCustomDataChannel(x,je)),ke=yield Ie.getOffer();if(!ke)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(x);g.a.debug("Sending offer."),he==null||he("Sending offer",ke);const He=new Q.SendSignalRequest;He.setSignal(ke);const Xe=yield(()=>xe(this,void 0,void 0,function*(){try{return yield me.sendSignal(He,yield this.getMetadata({}))}catch(je){g.a.warn("Error when sending signal",{error:je})}}))();if(!this.isOutgoingConnection.get(x))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const Ye=(re=Xe==null?void 0:Xe.getSessionId())===null||re===void 0?void 0:re.getValue(),Ge=(oe=Xe==null?void 0:Xe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return Ye&&Ge?(Ie.setSessionId(Ye),Ie.setSessionCreatedTimestamp(Ge),this.isOutgoingConnection.delete(x),this.connections.push(Ie),this.isConnectionInitiator.set(Ie,!0),this.setupHandlers(Ie),Ye):(g.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(x))})}connectLan(x){var W,K;return xe(this,void 0,void 0,function*(){const re=new N(x),oe=new Qe(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ue,le)=>this.config.receive(ue,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ue,le)=>{var Re,Ie;return(Ie=(Re=this.config).onStreamsInfoUpdate)===null||Ie===void 0?void 0:Ie.call(Re,ue,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=(W=this.localPeer)===null||W===void 0?void 0:W.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:"lan_client",remotePeerId:x}},ue=>this.onCustomDataChannel(x,ue)),he=yield oe.getLanOffer();if(!he)return g.a.warn("Could not generate LAN offer"),!1;const me=yield re.postLanRtcOffer({offer:JSON.stringify(he)}),pe=new RTCSessionDescription(JSON.parse(me.answer));return yield oe.handleLanAnswer(pe),this.localConnections.push(oe),this.isConnectionInitiator.set(oe,!0),Object(q.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(x,W,K,re,oe){const he=this.getActiveConnection(x);if(he&&this.isConnectionInitiator.has(he)){const pe=he.peerConnection.createDataChannel("custom."+W,K);return re&&(pe.binaryType="arraybuffer"),oe(x,pe),()=>{}}const me=(pe,ue)=>{x===pe&&ue.label==="custom."+W&&oe(x,ue)};return this.peerDataChannelListeners.push(me),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==me)}}onCustomDataChannel(x,W){this.peerDataChannelListeners.forEach(K=>K(x,W))}getConnectionStatus(x){if(this.isOutgoingConnection.get(x))return"connecting";const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(x){return xe(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);if(W)return yield W.getConnectionStatsInfo()})}disconnect(x){return xe(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield W.close())})}getPeers(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>xe(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return[];const K=W.getPeersList();if(!K)return[];const re=oe=>{var he,me;return(me=(he=oe.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&me!==void 0?me:0};return K.sort((oe,he)=>re(he)-re(oe)).map(oe=>Rt(oe))})}getSessions(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>xe(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return{};const K=W.getPeersList(),re={};for(const oe of K)re[oe.getPeerId()]=oe.getSessionIdsList();return re})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(x){const W=this.getActiveConnection(x);if(W)return W.getPingInfo();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(x){const W=this.getActiveConnection(x);if(W)return W.getSessionMetricsMessageCounts();g.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:x,receiveSignalStream:W,iceServers:K}=this;return!!(x&&W&&K)}shutdown(){return xe(this,void 0,void 0,function*(){g.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const x=this.connections;this.connections=[],yield this.closeConnections(x);const{localPeer:W}=this;if(!W||this.config.lanOnlyMode)return;const{signalingClient:K}=this.config;yield(()=>xe(this,void 0,void 0,function*(){try{const re=new Q.DeletePeerRequest;re.setPeerId(W.getPeerId()),yield K.deletePeer(re,yield this.getMetadata({}))}catch(re){return void g.a.warn("Error deleting local peer",{error:re})}}))()})}createPeer(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>xe(this,void 0,void 0,function*(){try{return yield x.createPeer(new Q.CreatePeerRequest,yield this.getMetadata({}))}catch(re){throw new Error(`Was not able to create peer: ${JSON.stringify(re)}`)}}))(),K=W==null?void 0:W.getPeer();if(!K)throw new Error("Response did not provide peer.");return this.localPeer=K})}createReceiveSignalStream(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:x}=this.config,{localPeer:W,iceServers:K}=this;if(!W||!K)return;const{receiveSignalStream:re}=this;re&&re.cancel();const oe=new Q.ReceiveSignalStreamRequest;oe.setPeerId(W.getPeerId());const he=yield(()=>xe(this,void 0,void 0,function*(){try{return x.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(me){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(me)}`)}}))();if(!he)throw new Error("Response did not provide stream.");return he.on("data",me=>xe(this,void 0,void 0,function*(){var pe,ue,le,Re;const Ie=me.getSignal(),ke=(pe=Ie==null?void 0:Ie.getSessionId())===null||pe===void 0?void 0:pe.getValue(),He=Ie==null?void 0:Ie.getSenderId(),Xe=Ie==null?void 0:Ie.getReceiverId(),Ye=(ue=Ie==null?void 0:Ie.getSessionCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue();if(!(Ie&&ke&&He&&Xe&&Ye))return void g.a.warn("Received signal with missing information.");const Ge=this.getActiveConnection(He);if(Ge)if(Ge.getSessionId()!==ke){if(g.a.debug("Received signal: different session for a peer we're already connected to."),(Ge.getSessionCreatedTimestamp()||0)>Ye)return;const je=new Qe(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,$e)=>this.config.receive(Fe,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Fe,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(Re=W.getUserId())===null||Re===void 0?void 0:Re.getValue(),remotePeerId:He},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Fe=>this.onCustomDataChannel(He,Fe));yield je.handleSignal(Ie),this.connections.push(je)}else g.a.debug("Received signal: for an existing connection."),yield Ge.handleSignal(Ie);else{g.a.debug("Received signal: new connection.");const je=new Qe(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,$e)=>this.config.receive(Fe,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Fe,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(le=W.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:He},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Fe=>this.onCustomDataChannel(He,Fe));yield je.handleSignal(Ie),this.connections.push(je)}})),he.on("end",()=>{he.cancel(),this.receiveSignalStream=void 0}),he.on("error",me=>{switch(me.code){case te.StatusCode.CANCELLED:case te.StatusCode.UNAVAILABLE:case te.StatusCode.UNKNOWN:g.a.debug("Receive signal stream error",{error:me});break;case te.StatusCode.UNAUTHENTICATED:g.a.warn("Receive signal stream error",{error:me});break;default:g.a.error("Receive signal stream error",{error:me})}he.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=he})}createRTCPeerConnection(x){var W;return xe(this,void 0,void 0,function*(){const K=(W=this.config.alternateRTCPeerConnection)!==null&&W!==void 0?W:window.RTCPeerConnection;if(!K)throw function(){const{userAgent:re}=navigator;return re.includes("Firefox/")?"Firefox":re.includes("Edg/")?"Edge":re.includes("Chrome/")?"Chrome":re.includes("Safari/")?"Safari":re.includes("MSIE/")||re.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");return new K({iceServers:x})})}closeConnections(x){return xe(this,void 0,void 0,function*(){const W=yield w(x.map(K=>xe(this,void 0,void 0,function*(){yield K.close()})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}getActiveConnection(x){return this.getConnections().find(W=>W.getRemotePeerId()===x&&W.isActive())}update(){var x;return xe(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:W}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers)return this.localPeer||(yield this.createPeer()),this.iceServers||(yield this.updateIceServers()),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()));yield this.closeConnections(this.connections.filter(me=>!me.isActive())),this.connections=this.connections.filter(me=>me.isActive());const{localPeer:K}=this,re=this.connections.filter(me=>me.getSessionId).map(me=>h(me.getSessionId()));K.setSessionIdsList(re);const oe=new Q.RefreshPeerRequest;oe.setPeer(K);try{yield W.refreshPeer(oe,yield this.getMetadata({}))}catch(me){me.code===te.StatusCode.NOT_FOUND?(g.a.warn("Peer expired, creating new peer",{peerId:K.getPeerId()}),yield this.reset()):g.a.warn("Error calling RefreshPeer",{error:me})}const he=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((x=he.find(pe=>pe.id===me.getRemotePeerId()))===null||x===void 0?void 0:x.deviceId)})}reset(){return xe(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection=new Map,yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:x,iceServersTtl:W}=this,K=new Date().getTime();if(!x||K-x>W)try{const re=(yield this.config.signalingClient.getIceServers(new Q.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(re),this.iceServersLastUpdate=K}catch(re){g.a.warn("Error in updateIceServers",{error:re})}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionCreatedTimestamp();W.onconnectionstatechange=()=>xe(this,void 0,void 0,function*(){const re=W.connectionState;if(K)switch(re){case"connected":d.aggregate("rtc-connect-time",new Date().getTime()-K);break;case"failed":d.increment("rtc-connect-failed")}})}getMetadata(x){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:W}=this.config,{grpcCallDeadline:K}=this,{hasDeadline:re}=x,oe=re===!1?void 0:new Date().getTime()+K;return{authorization:yield W(),deadline:oe}})}}var gt=n(10),lt=n(11),Ot=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ct{constructor(x,W){this.sessionId=x,this.connection=W,this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=x,this.connection=W}incrementMessageSent(x){const W=Ae(x.header.stream);this.sentMessagesCounts.set(W,(this.sentMessagesCounts.get(W)||0)+1)}incrementMessageReceived(x){const W=Ae(x.header.stream);this.receivedMessagesCounts.set(W,(this.receivedMessagesCounts.get(W)||0)+1)}uploadMetrics(){return Ot(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(oe=>K[oe.id]=oe),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const re=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((oe,he)=>{const me=this.sentMessagesCounts.get(he),pe=this.receivedMessagesCounts.get(he);return Object.assign(Object.assign({},oe),{[`${he}-sent`]:me,[`${he}-received`]:pe})},{sessionId:x});g.a.debug("rtc-message-report",re)})}}function ut(ye,x){return Ae(ye)===Ae(x)}var et=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class It{constructor(x,W){this.peerConnection=x,this.config=W,this.connectTimeoutMs=10*c.a.second,this.gatherIceTimeoutMs=5*c.a.second,this.pingUpdateTimeoutMs=2*c.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:K}=W;K?this.initializeChannels(x):x.ondatachannel=re=>{switch(re.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=re.channel;break;case"stream.reliable":this.reliableStreamChannel=re.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=re.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=re.channel}this.setupChannel(re.channel)},this.sessionMetrics=new Ct(this.getSessionId(),this)}connect(){return et(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:re}=this;re&&this.sendSystemMessage(re,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>et(this,void 0,void 0,function*(){this.isReady()||(g.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:x,config:{isOffer:W,sessionId:K}}=this;if(W){const re=yield x.createOffer();yield x.setLocalDescription(re)}W&&(this.gatherIceTimeout=setTimeout(()=>et(this,void 0,void 0,function*(){this.sentOffer||(g.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(g.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),x.onicecandidate=re=>et(this,void 0,void 0,function*(){re.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),x.onicegatheringstatechange=()=>et(this,void 0,void 0,function*(){x.iceGatheringState==="complete"&&(yield this.sendOffer())}),x.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:K})})})}handleSignal(x){return et(this,void 0,void 0,function*(){const{peerConnection:W,config:{sessionId:K,sendSignal:re}}=this,{description:oe}=JSON.parse(x.payload);if(g.a.debug("Handling signal",{sessionId:K,description:JSON.stringify(oe)}),oe)if(W.signalingState!=="stable"||W.connectionState!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(x)}`);else if(oe.type==="offer"){yield W.setRemoteDescription(oe);const he=yield W.createAnswer();yield W.setLocalDescription(he),yield re({payload:JSON.stringify({description:he})})}else oe.type==="answer"&&(yield W.setRemoteDescription(oe));else g.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(x)}`);else g.a.warn(`Received non-SDP signal: ${JSON.stringify(x)}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;return!!(K&&W&&re)&&x.connectionState==="connected"&&K.readyState==="open"&&W.readyState==="open"&&re.readyState==="open"}isClosed(){const{peerConnection:x,reliableStreamChannel:W,latestTryOnceStreamChannel:K,latestTtlStreamChannel:re}=this;return!(x.connectionState!=="closed"||W!==void 0&&W.readyState!=="closed"||K!==void 0&&K.readyState!=="closed"||re!==void 0&&re.readyState!=="closed")}needsClosing(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;if(this.isClosed())return!1;const oe=new Set(["closing","closed"]),he=me=>me&&oe.has(me.readyState);return Te(x)||he(W)||he(K)||he(re)}close(){return et(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(x){this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return et(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Te(this.peerConnection)))return;const{peerConnection:x,config:{sendSignal:W}}=this,K=yield x.createOffer();yield x.setLocalDescription(K);const re={payload:JSON.stringify({description:K})};yield W(re)})}getChannelFromLabel(x){switch(x){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics.incrementMessageSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable RTC message",{error:re,channel:x.label})}if(this.lastMessageTimestamp=new Date().getTime(),K=Ue(K),this.sessionMetrics.incrementMessageReceived(K),!this.handleSystemMessage(x,K)){if(!this.hasCapabilities(K))return void g.a.warn("Received RTC message that was not within the capability scope of the connection.");(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(K)||this.config.receive(this.config.remotePeer.id,K)}},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}handleSystemMessage(x,W){switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const K=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=K,d.aggregate("rtc-ping-time",K),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){if(x.readyState!=="open")return;const K={entityId:h(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${W.type}`,streamType:W.type};let re;switch(W.type){case"ping":re={ping:new Date().getTime()};break;case"pong":re={pong:W.timestamp};break;case"stream-control":re={streamControl:W.streamControl}}this.sendOnChannel(x,Ee(K,re))}hasCapabilities(x){var W,K;const{localPeer:re,remotePeer:oe}=this.config,he=(W=re.capabilitySet.streaming)===null||W===void 0?void 0:W.streams,me=he&&he.some(le=>le.receive&&ut(le.stream,x.header.stream)),pe=(K=oe.capabilitySet.streaming)===null||K===void 0?void 0:K.streams,ue=pe&&pe.some(le=>le.send&&ut(le.stream,x.header.stream));return me||ue}isLatestMessage(x){const W=Ae(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}var Be=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class jt{constructor(x){this.config=x,this.connections=[],this.connectingSessions=new Map,this.updateInterval=f({func:()=>Be(this,void 0,void 0,function*(){try{yield this.update()}catch(W){g.a.warn("RTC update failed",{error:W})}}),delay:250*c.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(x){return Be(this,void 0,void 0,function*(){const W=yield this.getLocalPeer();if(this.getActiveConnection(x))return void g.a.warn("Attempted to connect to peer with an already active connection.");let K;try{K=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:W.id,answerPeerId:x})}catch(re){Object(gt.a)(re,lt.a,oe=>oe.statusCode===404),g.a.warn("Attempted to connect to peer that does not exist.")}if(K)for(this.connectingSessions.set(K.id,new Date().getTime()),yield this.connectToSession(K);;)switch(yield Object(l.a)(.1),this.getConnectionStatus(x)){case"connecting":continue;case"connected":return K.id;case"disconnected":return}})}getConnectionStatus(x){const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getIceMode(x){const W=this.getActiveConnection(x);if(W)return W.iceMode}disconnect(x){return Be(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield this.closeConnection(W))})}getLocalPeer(){return Be(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Be(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Be(this,void 0,void 0,function*(){yield this.updateInterval.stop();const x=this.connections;this.connections=[],yield this.closeConnections(x)})}closeConnection(x){return Be(this,void 0,void 0,function*(){this.connectingSessions.delete(x.getSessionId()),yield x.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),x.getSessionId())}catch(W){Object(gt.a)(W,lt.a,K=>K.statusCode===404)}})}getSessions(){return Be(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(W=>W.offer.peer.id===x.id||W.answer.peer.id===x.id)})}createPeer(){return Be(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(x={}){return Be(this,void 0,void 0,function*(){return new(this.config.alternateRTCPeerConnection||RTCPeerConnection)(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},x))})}closeConnections(x){return Be(this,void 0,void 0,function*(){const W=yield w(x.map(K=>Be(this,void 0,void 0,function*(){yield this.closeConnection(K)})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}reset(){return Be(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.connectingSessions=new Map,this.localPeer=this.createPeer(),yield this.localPeer})}getActiveConnection(x){return this.connections.find(W=>W.getRemotePeer().id===x&&W.isActive())}update(){return Be(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),x.id)}catch(W){Object(gt.a)(W,lt.a,K=>K.statusCode===404),g.a.warn("Peer expired, creating new peer",{peerId:x.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(x){return Be(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(x);const W=x.map(K=>({session:K,connection:this.connections.find(re=>re.getSessionId()===K.id)}));yield Promise.all(W.map(({session:K,connection:re})=>Be(this,void 0,void 0,function*(){return yield this.maintainConnection(K,re)})))})}syncConnectionsAndSessions(x){return Be(this,void 0,void 0,function*(){const W=new Set(x.map(oe=>oe.id)),K=oe=>W.has(oe.getSessionId())||this.connectingSessions.has(oe.getSessionId());this.connections=this.connections.filter(oe=>K(oe));const re=this.connections.filter(oe=>!K(oe)||oe.needsClosing());yield Promise.all(re.map(oe=>Be(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(x,W){return Be(this,void 0,void 0,function*(){const K=yield this.getLocalPeer(),re=x.offer.peer.id===K.id;if(W){if(W.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),x.id)}catch(oe){Object(gt.a)(oe,lt.a,he=>he.statusCode===404),g.a.debug("Refresh session not found",{sessionId:x.id})}else if(W.isActive())try{yield this.consumeSignals(W)}catch(oe){g.a.warn("Failed to ingest signals, closing connection",{error:oe}),yield this.closeConnection(W)}}else{if(re)return;yield this.connectToSession(x)}})}connectToSession(x){return Be(this,void 0,void 0,function*(){const W=yield this.getLocalPeer(),K=x.offer.peer.id===W.id,re=yield this.createRTCPeerConnection(),oe=new It(re,{localPeer:K?x.offer.peer:x.answer.peer,remotePeer:K?x.answer.peer:x.offer.peer,sessionId:x.id,isOffer:K,sendSignal:he=>this.sendSignal(x.id,he),receive:(he,me)=>this.config.receive(he,me)});if(this.connections.find(he=>he.getSessionId()===x.id))return g.a.warn("connectToSession called on a session that already has a connection.",{sessionId:x.id}),void(yield oe.close());this.setupHandlers(oe),this.connections.push(oe);try{yield oe.connect()}catch(he){g.a.warn("Failed to handle negotiation, closing connection",{error:he}),yield this.closeConnection(oe)}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionId();W.onconnectionstatechange=()=>Be(this,void 0,void 0,function*(){const re=this.connectingSessions.get(K);if(re===void 0)return;const oe=W.connectionState;switch(Te(W)&&this.connectingSessions.delete(K),oe){case"connected":{this.connectingSessions.delete(K);const he=new Date().getTime()-re;d.aggregate("rtc-connect-time",he);break}case"failed":d.increment("rtc-connect-failed"),yield this.closeConnection(x)}})}consumeSignals(x){return Be(this,void 0,void 0,function*(){let W=[];try{W=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),x.getSessionId())}catch(K){Object(gt.a)(K,lt.a,re=>re.statusCode===404)}for(const K of W)yield x.handleSignal(K)})}sendSignal(x,W){return Be(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),x,{signals:[W]})}catch(K){Object(gt.a)(K,lt.a,re=>re.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const u=new Uint8Array(16);function s(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(u)}const i=[];for(let l=0;l<256;++l)i.push((l+256).toString(16).slice(1));function c(l,m=0){return(i[l[m+0]]+i[l[m+1]]+i[l[m+2]]+i[l[m+3]]+"-"+i[l[m+4]]+i[l[m+5]]+"-"+i[l[m+6]]+i[l[m+7]]+"-"+i[l[m+8]]+i[l[m+9]]+"-"+i[l[m+10]]+i[l[m+11]]+i[l[m+12]]+i[l[m+13]]+i[l[m+14]]+i[l[m+15]]).toLowerCase()}t.a=function(l,m,R){if(r.randomUUID&&!m&&!l)return r.randomUUID();const E=(l=l||{}).random||(l.rng||s)();if(E[6]=15&E[6]|64,E[8]=63&E[8]|128,m){R=R||0;for(let y=0;y<16;++y)m[R+y]=E[y];return m}return c(E)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return i});var r=n(28),o=n(10),u=n(11),s=function(c,l,m,R){return new(m||(m=Promise))(function(E,y){function g(L){try{T(R.next(L))}catch(V){y(V)}}function _(L){try{T(R.throw(L))}catch(V){y(V)}}function T(L){var V;L.done?E(L.value):(V=L.value,V instanceof m?V:new m(function(M){M(V)})).then(g,_)}T((R=R.apply(c,l||[])).next())})};class i extends r.a{log(l){return s(this,void 0,void 0,function*(){const m=i.token;try{yield this.fetch("logs",{token:m,method:"POST",body:JSON.stringify({logs:l}),allowUnsafeRetries:!0})}catch(R){Object(o.a)(R,u.a,E=>E.statusCode===401&&m!==void 0),i.token===m&&delete i.token,yield this.log(l)}})}}}])})})(dist);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}let FORMANT_API_URL="https://api.formant.io";typeof window!="undefined"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$2=new URLSearchParams("");typeof window!="undefined"&&(urlParams$2=new URLSearchParams(window.location.search));const envDev=urlParams$2.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$2.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");const envLocal=urlParams$2.get("formant_local");envLocal&&(FORMANT_API_URL="https://api.formant.local");class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window!="undefined"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");return n===null||n.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}static goToDevice(t){this.sendAppMessage({type:"go_to_device",deviceId:t})}static showMessage(t){this.sendAppMessage({type:"show_message",message:t})}static requestModuleData(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"request_module_data",module:t})}static setModuleDateTimeRange(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:r,before:t,after:n||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static sendChannelData(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:r,channel:t,data:n})}static setupModuleMenus(t){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:n,menus:t})}static addMenuListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_menu_item_clicked"&&t(r.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="auth_token"&&t(r.token)})}static addModuleDataListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_data"&&t({streams:r.streams,time:r.time,queryRange:r.queryRange})})}static addChannelDataListener(t,n){window.addEventListener("message",r=>{const o=r.data;o.type==="channel_data"&&o.channel===t&&n({source:o.source,data:o.data})})}}const Me=class{static async login(t,n){try{const r=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),o=await r.json();if(r.status!==200)throw new Error(o.message);return await Me.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(r){return Me.waitingForAuth.forEach(o=>o(!1)),Me.waitingForAuth=[],Promise.reject(r)}}static async loginWithToken(t,n){const r=JSON.parse(atob(t.split(".")[1]));try{let o;if(Me.isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(Me.currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(Me.currentOrganization=r["custom:organization_id"]),Me.isShareToken||(o=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(o=r["formant:claims"].userId),o){const u=await fetch(`${FORMANT_API_URL}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await u.json();if(u.status!==200)throw new Error(s.message);Me.currentUser=s}Me.token=t,Me.waitingForAuth.forEach(u=>u(!0))}catch(o){console.error(o),Me.waitingForAuth.forEach(u=>u(!1))}Me.waitingForAuth=[],n&&(Me.refreshToken=n,setInterval(async()=>{if(Me.refreshToken){const u=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Me.refreshToken})})).json();Me.token=u.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Me.token!==void 0}static getCurrentUser(){return Me.currentUser}static async waitTilAuthenticated(){return Me.token!==void 0?!0:new Promise(t=>{Me.waitingForAuth.push(function(n){t(n)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Me;Oe(Authentication,"token"),Oe(Authentication,"refreshToken"),Oe(Authentication,"currentUser"),Oe(Authentication,"currentOrganization"),Oe(Authentication,"isShareToken",!1),Oe(Authentication,"defaultDeviceId"),Oe(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Oe(this,"ready",!1);Oe(this,"listeners",[]);Oe(this,"openListeners",[]);Oe(this,"closeListeners",[]);Oe(this,"errorListeners",[]);Oe(this,"binaryListeners",[]);Oe(this,"error");Oe(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(n=>n())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const o=new Uint8Array(n.data),u=this.decoder.decode(o);r(u)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let o=window.setInterval(()=>{this.ready&&(window.clearInterval(o),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}class CaptureStream{constructor(t){Oe(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class Manipulator{constructor(t,n){Oe(this,"currentListeners",[]);Oe(this,"onRealtimeMessage",(t,n)=>{n.payload.jointState&&this.currentListeners.forEach(r=>{n.payload.jointState&&r(n.payload.jointState)})});this.device=t,this.config=n}async synchronize(){this.device.addRealtimeListener(this.onRealtimeMessage),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}async desynchronize(){this.device.removeRealtimeListener(this.onRealtimeMessage),this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream)}async addCurrentJointStateListener(t){this.currentListeners.push(t)}}class RequestDataChannel{constructor(t,n,r){Oe(this,"channel");Oe(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Oe(this,"RESPONSE_SUCCESS_BYTE",0);Oe(this,"decoder",new TextDecoder)}generateBinaryId(){const t=new Uint8Array(16);for(let n=0;n<t.length;n++)t[n]=Math.floor(Math.random()*256);return t}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(t=>{const r=t.slice(0,16).toString();if(r.length===0)throw new Error("Invalid response");const o=t.slice(16);if(o.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,o)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const u=this.generateBinaryId(),s=u.toString();r.set(s,!0),n.sendBinary(new Uint8Array([...u,...t]));const i=new Date().getTime();for(;new Date().getTime()<i+o;)if(await delay(50),r.has(s)){const c=r.get(s);if(c!==!0){r.delete(s);const l=c[0]===this.RESPONSE_SUCCESS_BYTE,m=c.slice(1);if(l)return m;throw console.error({name:"AdapterError",message:this.decoder.decode(m)}),new Error("Binary request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:u}=n;if(!r)throw new Error("Invalid response");if(!o&&!u)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const u=this.generateTextId();r.set(u,!0),n.send(JSON.stringify({id:u,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+o;)if(await delay(50),r.has(u)){const i=r.get(u);if(i!==!0){r.delete(u);const{data:c,error:l}=i;if(c)return c;if(l)throw console.error({name:"AdapterError",message:l}),new Error("Text request datachannel adapter error")}}throw r.delete(u),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device{constructor(t,n,r){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.id=t,this.name=n,this.organizationId=r}async getLatestTelemetry(){return(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(){let t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const r=n.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await t.json()).document}async getFileUrl(t){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let n;if(rtcClientVersion==="1"?n=new dist.exports.RtcClientV1({signalingClient:new dist.exports.RtcSignalingClient(FORMANT_API_URL+"/v1/signaling/"),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage}):n=new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage,sessionType:t}),n.isReady)for(;!n.isReady();)await delay(100);const o=(await n.getPeers()).find(u=>u.deviceId===this.id);if(!o)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=o.id,await n.connect(this.remoteDevicePeerId);n.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=n}}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.send(defined(o).id,t,n)}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeAudioStreams(){var r,o,u,s,i,c;const t=await this.getConfiguration(),n=[];for(const l of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});for(const l of(s=(u=t.teleop)==null?void 0:u.rosStreams)!=null?s:[])l.topicType=="audio_common_msgs/AudioData"&&n.push({name:l.topicName});for(const l of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});return n}async getRealtimeVideoStreams(){var r,o,u,s,i,c;const t=await this.getConfiguration(),n=[];for(const l of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.name});for(const l of(s=(u=t.teleop)==null?void 0:u.rosStreams)!=null?s:[])l.topicType=="formant/H264VideoFrame"&&n.push({name:l.topicName});for(const l of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:t,setAudioFormat:n})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){let t=await Fleet.getPeers(),n=await Fleet.getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled}))}async sendCommand(t,n,r,o){var l;const s=(await this.getAvailableCommands()).find(m=>m.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let i;if(n===void 0)if(s.parameterEnabled&&s.parameterValue)i=s.parameterValue;else throw new Error("Command has no default parameter value, you must provide one");else i=n;let c={value:i,scrubberTime:(r||new Date).toISOString(),meta:ht(ht({},s.parameterMeta),o)};await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:s.id,organizationId:this.organizationId,deviceId:this.id,command:s.command,parameter:c,userId:(l=Authentication.currentUser)==null?void 0:l.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,n){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),u=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,ht({ordered:!0},n),!1,(i,c)=>{const l=new DataChannel(c);s(l)})});return await u.waitTilReady(),u}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}async createCaptureStream(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o){return await Fleet.getTelemetry(this.id,t,n,r,o)}async getTelemetryStreams(){var i,c;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(c=(i=t.telemetry)==null?void 0:i.streams)==null||c.forEach(l=>{l.disabled!==!0&&r.push(l.name),l.onDemand===!0&&o.push(l.name)}),console.log(o),(await n.json()).items.filter(l=>!r.includes(l)).map(l=>({name:l,onDemand:o.includes(l)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"id");Oe(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.peerUrl=t}async getLatestTelemetry(){const n=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(n).map(([o,u])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:u,currentValueTime:u.timestamp,tags:{}}))}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.document}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const n=new dist.exports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=n}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeVideoStreams(){var r,o,u;const t=await this.getConfiguration(),n=[];for(const s of(r=t.teleop.hardwareStreams)!=null?r:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});for(const s of(o=t.teleop.rosStreams)!=null?o:[])s.topicType=="formant/H264VideoFrame"&&n.push({name:s.topicName});for(const s of(u=t.teleop.customStreams)!=null?u:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async createCustomDataChannel(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),u=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,ht({ordered:!0},n),!1,(i,c)=>{const l=new DataChannel(c);s(l)})});return await u.waitTilReady(),u}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}}const Le=class{static async setDefaultDevice(t){Le.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Le.defaultDeviceId)throw new Error("No known default device");const o=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(s=>s.id===Le.defaultDeviceId).name,u=new Device(Le.defaultDeviceId,o,defined(Authentication.currentOrganization));return Le.knownContext.push(new WeakRef(u)),u}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=r.name,u=new Device(t,o,r.organizationId);return Le.knownContext.push(new WeakRef(u)),u}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await Le.getDevices()).filter(u=>r.includes(u.id))}static async getPeers(){if(!Authentication.token)throw new Error("Not authenticated");return await new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getPeers()}static async getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");return await new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getSessions()}static async getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(u=>u.deviceId);return(await Le.getDevices()).filter(u=>r.includes(u.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,o,u){let s=t;Array.isArray(t)||(s=[t]);let i=n;return Array.isArray(n)||(i=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:r.toISOString(),tags:u}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}};let Fleet=Le;Oe(Fleet,"defaultDeviceId"),Oe(Fleet,"knownContext",[]);class KeyValue{static async set(t,n){try{const r=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),o=await r.json();if(r.status!==200)throw new Error(o.message)}catch(r){throw r}}static async get(t){try{const n=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}}function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount};function getZeroINumericSet(){return{min:Number.MAX_SAFE_INTEGER,max:0,sum:0,count:0,sumOfSquares:0}}function reduceNumericStreamAggregates(e){return e.aggregates.reduce((t,n)=>{const r=n[1];return combineNumericAggregates(r,t)},getZeroINumericSet())}function reduceNumericSetStreamAggregates(e,t){var n;return(n=e.aggregates.reduce((r,o)=>{const u=o[1];return combineNumericSetAggregates(u,r)},{})[t])==null?void 0:n.value}function combineNumericAggregates(e,t){return{min:Math.min(e.min,t.min),max:Math.max(e.max,t.max),sum:e.sum+t.sum,count:e.count+t.count,sumOfSquares:e.sumOfSquares+t.sumOfSquares}}function combineNumericSetAggregates(e,t){return Object.keys(e).reduce((n,r)=>{var o,u;return Qt(ht({},n),{[r]:{value:combineNumericAggregates(e[r].value,(u=(o=t[r])==null?void 0:o.value)!=null?u:getZeroINumericSet()),unit:e[r].unit}})},{})}function stringToArrayBuffer(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function fork(e){}function browser(){const{userAgent:e}=navigator;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){Oe(this,"muted",!1);Oe(this,"hasReceivedData",!1);Oe(this,"audioContext");Oe(this,"chunks",[]);Oe(this,"isPlaying",!1);Oe(this,"startTime",0);Oe(this,"lastChunkOffset",0);Oe(this,"bufferSize",3);Oe(this,"receive",async t=>{var s;const n=(s=t.payload.audioChunk)==null?void 0:s.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:o}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const u=stringToArrayBuffer(n);try{await r.decodeAudioData(u.buffer,this.scheduleChunk)}catch(i){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:i}),this.changeAudioWireFormat("wav")}});Oe(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);!r||!r.buffer||(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((o,u)=>{this.receive(u)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=o=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;fork((async()=>{await this.device.changeStreamAudioType(n.name,t)})())}}const accessLevels=["viewer","operator","administrator"],viewer="viewer",operator="operator",administrator="administrator",aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"];let urlParams=new URLSearchParams("");typeof window!="undefined"&&(urlParams=new URLSearchParams(window.location.search));const urlDevice=urlParams.get("device");urlDevice&&Fleet.setDefaultDevice(urlDevice);const urlAuth=urlParams.get("auth");urlAuth&&Authentication.loginWithToken(urlAuth);const moduleName=urlParams.get("module");moduleName&&Authentication.listenForRefresh(),exports.App=App,exports.AudioPlayer=AudioPlayer,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.IRtcSendConfiguration=dist.exports.IRtcSendConfiguration,exports.IRtcStreamMessage=dist.exports.IRtcStreamMessage,exports.IRtcStreamPayload=dist.exports.IRtcStreamPayload,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.PeerDevice=PeerDevice,exports.SessionType=SessionType,exports.TextRequestDataChannel=TextRequestDataChannel,exports.accessLevels=accessLevels,exports.administrator=administrator,exports.aggregateFunctionMap=aggregateFunctionMap,exports.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.combineNumericAggregates=combineNumericAggregates,exports.combineNumericSetAggregates=combineNumericSetAggregates,exports.eventTypes=eventTypes,exports.getAverage=getAverage,exports.getCount=getCount,exports.getMax=getMax,exports.getMin=getMin,exports.getStandardDeviation=getStandardDeviation,exports.getSum=getSum,exports.getVariance=getVariance,exports.getZeroINumericSet=getZeroINumericSet,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.reduceNumericSetStreamAggregates=reduceNumericSetStreamAggregates,exports.reduceNumericStreamAggregates=reduceNumericStreamAggregates,exports.severities=severities,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperty(exports,"__esModule",{value:!0}),exports[Symbol.toStringTag]="Module"});
|
|
44
|
+
`),Error.captureStackTrace(this,r)}}e.exports=o=>{if(o.length>2)throw new r(o);function u(i={}){this.options=i}function s(i){return new u(i)}return u.prototype.transform=o,s.Format=u,s}},function(e,t,n){function r(s,i){if(!(s instanceof i))throw new TypeError("Cannot call a class as a function")}function o(s,i){for(var c=0;c<i.length;c++){var l=i[c];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(s,l.key,l)}}var u=n(88);e.exports=function(){function s(){var l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r(this,s),this.loggers=new Map,this.options=l}var i,c;return i=s,(c=[{key:"add",value:function(l,m){var R=this;if(!this.loggers.has(l)){var E=(m=Object.assign({},m||this.options)).transports||this.options.transports;m.transports=E?E.slice():[];var y=u(m);y.on("close",function(){return R._delete(l)}),this.loggers.set(l,y)}return this.loggers.get(l)}},{key:"get",value:function(l,m){return this.add(l,m)}},{key:"has",value:function(l){return!!this.loggers.has(l)}},{key:"close",value:function(l){var m=this;if(l)return this._removeLogger(l);this.loggers.forEach(function(R,E){return m._removeLogger(E)})}},{key:"_removeLogger",value:function(l){this.loggers.has(l)&&(this.loggers.get(l).close(),this._delete(l))}},{key:"_delete",value:function(l){this.loggers.delete(l)}}])&&o(i.prototype,c),s}()},function(e,t,n){(function(r){const o=n(52),u=/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;e.exports=function(s,i,c,l){let m,R,E=!1,y=!1;const g=n(94);function _(V){l(i,V)}function T(V,M){let A=`"${i}" ${M}`;throw V&&(A=`${A}`),R&&(A=`${A}. An example of a valid value would be: ${R}`),new o(A)}const L={convertFromBase64:function(){return _("marking for base64 conversion"),E=!0,L},default:function(V){if(typeof V=="number")m=V.toString();else if(Array.isArray(V)||typeof V=="object"&&V!==null)m=JSON.stringify(V);else{if(typeof V!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");m=V}return _(`setting default value to "${m}"`),L},required:function(V){return V===void 0?(_("marked as required"),y=!0):(_(`setting required flag to ${V}`),y=V),L},example:function(V){return R=V,L}};return Object.entries(ht(ht({},g),c)).forEach(([V,M])=>{L[V]=function(A){return function(){let f=s[i];if(_(`will be read from the environment using "${A.name}" accessor`),f===void 0)if(m===void 0&&y)_("was not found in the environment, but is required to be set"),T(void 0,"is a required variable, but it was not set");else{if(m===void 0)return void _("was not found in the environment, but is not required. returning undefined");_(`was not found in the environment, parsing default value "${m}" instead`),f=m}y&&(_("verifying variable value is not an empty string"),f.trim().length===0&&T(void 0,"is a required variable, but its value was empty")),E&&(_("verifying variable is a valid base64 string"),f.match(u)||T(f,"should be a valid base64 string if using convertFromBase64"),_("converting from base64 to utf8 string"),f=r.from(f,"base64").toString());const O=[f].concat(Array.prototype.slice.call(arguments));try{_(`passing value "${f}" to "${A.name}" accessor`);const Y=A.apply(A,O);return _(`parsed successfully, returning ${Y}`),Y}catch(Y){T(f,Y.message)}}}(M)}),L}}).call(this,n(5).Buffer)},function(e,t,n){const r=n(33);e.exports=function(o,u){return u=u||",",o.length?r(o).split(u).filter(Boolean):[]}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,n){e.exports=function(r){const o=r.toLowerCase();if(["false","0","true","1"].indexOf(o)===-1)throw new Error('should be either "true", "false", "TRUE", "FALSE", 1, or 0');return!(o==="0"||o==="false")}},function(e,t,n){const r=n(95);e.exports=function(o){var u=r(o);if(u>65535)throw new Error("cannot assign a port number greater than 65535");return u}},function(e,t,n){const r=n(33);e.exports=function(o,u){const s=r(o);if(u.indexOf(s)<0)throw new Error(`should be one of [${u.join(", ")}]`);return s}},function(e,t,n){const r=n(54);e.exports=function(o){const u=r(o);if(u>0)throw new Error("should be a negative float");return u}},function(e,t,n){const r=n(54);e.exports=function(o){const u=r(o);if(u<0)throw new Error("should be a positive float");return u}},function(e,t,n){const r=n(53);e.exports=function(o){const u=r(o);if(u>0)throw new Error("should be a negative integer");return u}},function(e,t,n){const r=n(55);e.exports=function(o){var u=r(o);if(!Array.isArray(u))throw new Error("should be a parseable JSON Array");return u}},function(e,t,n){const r=n(55);e.exports=function(o){var u=r(o);if(Array.isArray(u))throw new Error("should be a parseable JSON Object");return u}},function(e,t,n){e.exports=function(r,o){try{RegExp(void 0,o)}catch{throw new Error("invalid regexp flags")}try{return new RegExp(r,o)}catch{throw new Error("should be a valid regexp")}}},function(e,t,n){const r=n(96);e.exports=function(o){return r(o).toString()}},function(e,t,n){const r=n(33),o=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/;e.exports=function(u){const s=r(u);if(!o.test(s))throw new Error("should be a valid email address");return s}},function(e,t,n){e.exports=function(r,o){return function(u,s){o&&o.match(/prod|production/)||r(`env-var (${u}): ${s}`)}}},function(e,t,n){(function(r){(function(){var o,u,s,i,c,l;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:r!=null&&r.hrtime?(e.exports=function(){return(o()-c)/1e6},u=r.hrtime,i=(o=function(){var m;return 1e9*(m=u())[0]+m[1]})(),l=1e9*r.uptime(),c=i-l):Date.now?(e.exports=function(){return Date.now()-s},s=Date.now()):(e.exports=function(){return new Date().getTime()-s},s=new Date().getTime())}).call(this)}).call(this,n(2))},function(e,t,n){(function(r){(function(o){function u(i){if((i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextEncoder': The encoding label provided ('"+i+"') is invalid.")}function s(i,c){if(c=c===void 0?{fatal:!1}:c,(i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+i+"') is invalid.");if(c.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}if(o.TextEncoder&&o.TextDecoder)return!1;Object.defineProperty(u.prototype,"encoding",{value:"utf-8"}),u.prototype.encode=function(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");c=0;for(var l=i.length,m=0,R=Math.max(32,l+(l>>1)+7),E=new Uint8Array(R>>3<<3);c<l;){var y=i.charCodeAt(c++);if(55296<=y&&56319>=y){if(c<l){var g=i.charCodeAt(c);(64512&g)==56320&&(++c,y=((1023&y)<<10)+(1023&g)+65536)}if(55296<=y&&56319>=y)continue}if(m+4>E.length&&(R+=8,R=(R*=1+c/i.length*2)>>3<<3,(g=new Uint8Array(R)).set(E),E=g),(4294967168&y)==0)E[m++]=y;else{if((4294965248&y)==0)E[m++]=y>>6&31|192;else if((4294901760&y)==0)E[m++]=y>>12&15|224,E[m++]=y>>6&63|128;else{if((4292870144&y)!=0)continue;E[m++]=y>>18&7|240,E[m++]=y>>12&63|128,E[m++]=y>>6&63|128}E[m++]=63&y|128}}return E.slice(0,m)},Object.defineProperty(s.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(s.prototype,"fatal",{value:!1}),Object.defineProperty(s.prototype,"ignoreBOM",{value:!1}),s.prototype.decode=function(i,c){if((c=c===void 0?{stream:!1}:c).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");c=0;for(var l=(i=new Uint8Array(i)).length,m=[];c<l;){var R=i[c++];if(R===0)break;if((128&R)==0)m.push(R);else if((224&R)==192){var E=63&i[c++];m.push((31&R)<<6|E)}else if((240&R)==224){E=63&i[c++];var y=63&i[c++];m.push((31&R)<<12|E<<6|y)}else(248&R)==240&&(65535<(R=(7&R)<<18|(E=63&i[c++])<<12|(y=63&i[c++])<<6|63&i[c++])&&(R-=65536,m.push(R>>>10&1023|55296),R=56320|1023&R),m.push(R))}return String.fromCharCode.apply(null,m)},o.TextEncoder=u,o.TextDecoder=s})(typeof window!="undefined"?window:r!==void 0?r:this)}).call(this,n(6))},function(e,t,n){n.r(t),n.d(t,"AuthClient",function(){return u}),n.d(t,"RtcSignalingClient",function(){return i}),n.d(t,"Credentials",function(){return P}),n.d(t,"IRtcStream",function(){}),n.d(t,"SignalingPromiseClient",function(){return F.SignalingPromiseClient}),n.d(t,"IRtcClientConfigurationV1",function(){}),n.d(t,"IRtcClientConfiguration",function(){}),n.d(t,"IRtcConnectionStatsInfo",function(){}),n.d(t,"IRtcSendConfiguration",function(){}),n.d(t,"IRtcSessionMetricsMessageCounts",function(){}),n.d(t,"IRtcStreamMessage",function(){}),n.d(t,"IRtcStreamPayload",function(){}),n.d(t,"IStreamControl",function(){}),n.d(t,"RtcClient",function(){return _t}),n.d(t,"RtcClientV1",function(){return jt}),n.d(t,"createRtcStreamMessage",function(){return Ee});var r=n(28),o=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class u extends r.a{adminSignup(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:W,method:"POST",body:JSON.stringify(x)})})}login(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}loginWithGoogleToken(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(x),allowUnsafeRetries:!0})})}refresh(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:x,tokenExpirationSeconds:W}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(x)})})}forgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:x})})})}confirmForgotPassword(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(x)})})}resendInvitation(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:x})})})}changePassword({token:x,refreshToken:W,currentPassword:K,newPassword:re}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:x,method:"POST",body:JSON.stringify({refreshToken:W,currentPassword:K,newPassword:re})})})}getDeviceCredentials(x){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:x,method:"POST",allowUnsafeRetries:!0})})}impersonate(x,W){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:W})})})}createServiceAccount(x,W,K,re){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:x,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:W,roleId:K,tags:re})})})}getFeatures(x){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:x})).features})}}var s=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class i extends r.a{createPeer(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:x,method:"POST",body:JSON.stringify(W)})})}getPeers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:x})).items})}refreshPeer(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}createSession(x,W){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:x,method:"POST",body:JSON.stringify(W)})})}refreshSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/refresh`,{token:x,method:"POST",allowUnsafeRetries:!0})})}deleteSession(x,W){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}`,{token:x,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:x})).items})}getIceServers(x){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:x})).items})}addSignals(x,W,K){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${W}/add-signals`,{token:x,method:"POST",body:JSON.stringify(K)})})}takeSignals(x,W){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${W}/take-signals`,{token:x,method:"POST"})).items})}}var c=n(1),l=n(8),m=n(14),R=n.n(m),E=n(104),y=n.n(E),g=n(0),_=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class T{constructor(x){this.name="LogReporter",this.type="simple",this.message=x}send(x){return _(this,void 0,void 0,function*(){var W,K;g.a.info(this.message,(W=x.reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe.name]:oe.stat}),{}),K=re=>{const{sum:oe,count:he}=re,me=oe/he;return Object.assign(Object.assign({},re),{average:me})},Object.keys(W).reduce((re,oe)=>Object.assign(Object.assign({},re),{[oe]:K(W[oe])}),{})))})}}var L=n(4),V=n(39);function M(ye){return!!ye.match(/^[a-zA-Z0-9-_.,:?'"()@\/\\#$+ ]{1,255}$/)}var A=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function f({func:ye,delay:x,immediate:W}){let K=!1,re=setTimeout(function he(){return A(this,void 0,void 0,function*(){if(K)return;const me=new Date().getTime();try{oe=ye(),yield oe}finally{if(!K){const pe=new Date().getTime();re=setTimeout(he,Math.max(x-(pe-me),0))}}})},W?0:x),oe=Promise.resolve();return{stop(){return A(this,void 0,void 0,function*(){K=!0,clearTimeout(re),yield oe})}}}var O=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};const Y=n(226),Z=!!L.c,d=new class{constructor(ye){this.samplePeriodSeconds=60,this.buffer={},this.reporters=[],this.flushInterval=f({func:()=>this.flushStats(),delay:this.samplePeriodSeconds*c.a.second}),this.tags=this.filterTags((ye==null?void 0:ye.tags)||{app:L.a,version:L.j,namespace:L.i,instanceId:V.a})}shutdown(){return O(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(l.a)(2*c.a.second)})}aggregate(ye,x,W){this.addToBuffer(this.buffer,this.encodeKey({metric:ye,tags:this.filterTags(W||{})}),typeof x=="number"?{min:x,max:x,sum:x,count:1}:x)}increment(ye,x){this.aggregate(ye,1,x)}timer(ye,x,W){return O(this,void 0,void 0,function*(){const K=Y(),re=yield x(),oe=Y();return this.aggregate(ye,oe-K,W),re})}registerStatsReporter(ye){this.reporters.push(ye)}setTag(ye,x){const W=this.filterTags({[ye]:x});this.tags=Object.assign(Object.assign({},this.tags),W)}addToBuffer(ye,x,W){if(ye[x]){const{min:K,max:re,sum:oe,count:he}=ye[x];ye[x]={min:Math.min(K,W.min),max:Math.max(re,W.max),sum:oe+W.sum,count:he+W.count}}else ye[x]=W}write(ye){return O(this,void 0,void 0,function*(){yield Promise.all(this.reporters.map(x=>O(this,void 0,void 0,function*(){let W;const K={};switch(x.type){case"simple":for(const[oe,he]of Object.entries(ye)){const{metric:me}=this.decodeKey(oe);this.addToBuffer(K,this.encodeKey({metric:me}),he)}W=K;break;case"tagged":W=ye;break;default:(function(oe){throw new Error(`Unreachable type encountered (${oe})`)})(x.type)}const re=Object.entries(W);if(re.length>0)return x.send(re.map(([oe,he])=>{const{metric:me,tags:pe}=this.decodeKey(oe);return{name:me,tags:Object.assign(Object.assign({},pe),this.tags),stat:he}}),this.samplePeriodSeconds).catch(oe=>{g.a.debug(`Failed to write stats to ${x.name}`,{error:oe})})})))})}flushStats(){return O(this,void 0,void 0,function*(){yield this.write(this.buffer),this.buffer={}})}encodeKey(ye){return R()(Object.assign(Object.assign({},ye),Object.keys(ye.tags||{}).length>0?{tags:ye.tags}:{}))}decodeKey(ye){return JSON.parse(ye)}filterTags(ye){return Object.entries(ye||{}).reduce((x,[W,K])=>(M(W)&&M(K)&&(x[W]=K),x),{})}};Z||["local","on-prem"].includes(L.i)||d.registerStatsReporter(new T("stats"));var p=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class C extends class{constructor(x){this.options=x,this.cache=new y.a(Object.assign(Object.assign(Object.assign({},x.dispose||x.disposeAfter?{ttlAutopurge:!0}:{}),x),{dispose:(...W)=>{var K;W[2]==="evict"&&d.increment("lru-eviction",{name:x.name}),(K=x.dispose)===null||K===void 0||K.call(x,...W)},disposeAfter:(...W)=>{var K;this.updateStats(),(K=x.disposeAfter)===null||K===void 0||K.call(x,...W)}})),this.stringify=x.fastStringify?JSON.stringify:R.a}set(x,W,K){const re=this.stringify(x);if(!this.cache.set(re,W,{ttl:K})){const oe=this.cache.sizeCalculation?this.cache.sizeCalculation(W,re):"unknown";throw Error(`Value too large (${oe} > ${this.cache.max})`)}this.updateStats()}get(x){const{name:W}=this.options,K=this.stringify(x),re=this.cache.getRemainingTTL(K);return re<=0?d.increment("cache-miss",{name:W}):re!==1/0&&d.aggregate("cache-item-ttl",re,{name:W}),this.cache.get(K)}delete(x){this.cache.delete(this.stringify(x))}peek(x){return this.cache.peek(this.stringify(x))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(x){this.cache.forEach(x)}purgeStale(){return this.cache.purgeStale()}updateStats(){const{name:x}=this.options;d.aggregate("cache-item-count",this.cache.size,{name:x}),this.cache.calculatedSize!==void 0&&d.aggregate("cache-length",this.cache.calculatedSize,{name:x})}}{constructor(x){if(super(x),this.expireRejectedPromiseValues=x.expireRejectedPromiseValues===void 0||x.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=x.rejectedPromiseValueTtl!==void 0?x.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(x,W,K){super.set(x,W,K),this.expireRejectedPromiseValues&&W.catch(()=>p(this,void 0,void 0,function*(){yield Object(l.a)(this.rejectedPromiseValueTtl),this.peek(x)===W&&this.delete(x)}))}}var b=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class P{constructor(x,W,K){this.authClient=x,this.email=W,this.password=K,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new C({name:"Credentials-tokenCache",max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return b(this,void 0,void 0,function*(){let x=this.tokenCache.get(this.email);return x||(x=(()=>b(this,void 0,void 0,function*(){const{authentication:W}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!W)throw new Error("User account not verified.");return W.accessToken}))(),this.tokenCache.set(this.email,x)),x})}}var F=n(97),D=n(40),I=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class N extends D.a{constructor(x){super(x)}postLanRtcOffer(x){return I(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(x)})})}}var k=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};function w(ye){return k(this,void 0,void 0,function*(){return(yield Promise.all(ye.map(x=>x.catch(W=>W)))).filter(x=>x instanceof Error)})}function h(ye){if(ye!==void 0)return ye;throw new Error("Value is undefined")}function B(ye,x){const W=ye.reduce((K,re)=>[...K,...re.urls],[]).filter(K=>z(K,x)).sort(K=>X(K,"udp")?-1:0).shift();if(W)return Object.assign(Object.assign({},h(ye.find(K=>K.urls.includes(W)))),{urls:[W]})}function z(ye,x){switch(x){case"stun":return/^stuns?:/.test(ye);case"turn":return/^turns?:/.test(ye)}}function X(ye,x){return ye.endsWith(`transport=${x}`)}var Q=n(9),te=n(24),q=n(229),H=n(29);const v={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},S={ordered:!0},U={ordered:!0},J={ordered:!1,maxRetransmits:0},$={ordered:!1,maxRetransmits:0},ne=ye=>"received"in ye&&ye.received!==void 0,se=ye=>!("received"in ye)||ye.received===void 0,ge=2*c.a.second;function ve(ye,x={}){const W=Array.from(ye.values()),K=W.filter(ne),re=K.length>0,oe=Math.max(...K.map(ue=>ue.received));let he;if(re){const ue=W.length,le=K.length,Re=K.map(je=>je.received-je.sent),{standardDeviation:Ie,mean:ke,jitter:He}=function(je){const Fe=je.length;if(Fe===0)return{mean:NaN,standardDeviation:-1,jitter:NaN};const $e=je.reduce((Je,ot)=>Je+ot,0)/Fe,Ze=Math.sqrt(je.map(Je=>Math.pow(Je-$e,2)).reduce((Je,ot)=>Je+ot)/Fe);let Ke=0;for(let Je=1;Je<Fe;++Je)Ke+=Math.abs(je[Je]-je[Je-1]);return{mean:$e,standardDeviation:Ze,jitter:Ke/(Fe-1)}}(Re),Xe=W.filter(je=>je.sent<oe-ge),Ye=Xe.filter(se),Ge=Ye.length===0?0:Ye.length/Xe.length;he={pingsSent:ue,pongsReceived:le,average:ke,standardDeviation:Ie,jitter:He,max:Math.max(...Re),min:Math.min(...Re),loss:Ge}}else he=null;const{temporalNow:me=Date.now()}=x,pe=(re?oe:me)-4*ge;return Array.from(ye.entries()).forEach(ue=>{const[le,Re]=ue;Re.sent<pe&&ye.delete(le)}),he}function Ae({entityId:ye,streamName:x,streamType:W}){return`${ye}.${x}.${W}`}var Se=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ce{constructor(x,W){this.sessionId=x,this.connection=W,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=x,this.connection=W}updateRemoteMessagesCounts(x){if(x.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const W of x.payload.streamsInfo.items)this.counts.remoteSent.set(W.streamId,W.sentCount),this.counts.remoteReceived.set(W.streamId,W.receivedCount)}}getLocalStreamsInfo(x){const{localSent:W,localReceived:K}=this.counts;return{items:[...new Set([...W.keys(),...K.keys()])].map(re=>{var oe,he;return{streamId:re,sentCount:(oe=W.get(re))!==null&&oe!==void 0?oe:0,receivedCount:(he=K.get(re))!==null&&he!==void 0?he:0}}),timestamp:x}}incrementLocalSent(x){const{localSent:W}=this.counts,K=Ae(x.header.stream);W.set(K,(W.get(K)||0)+1)}incrementLocalReceived(x){const{localReceived:W}=this.counts,K=Ae(x.header.stream),re=W.get(K)||0;if(re===0){const{streamName:oe,streamType:he}=x.header.stream;g.a.debug("RTC client received first message for stream",{streamName:oe,streamType:he})}W.set(K,re+1)}uploadMetrics(){return Se(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(ue=>K[ue.id]=ue),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const{localSent:re,localReceived:oe,remoteSent:he,remoteReceived:me}=this.counts,pe=[...new Set([...re.keys(),...oe.keys()])].reduce((ue,le)=>{const Re=re.get(le),Ie=oe.get(le),ke=he.get(le),He=me.get(le);return Object.assign(Object.assign({},ue),{[`local-${le}-sent`]:Re,[`local-${le}-received`]:Ie,[`remote-${le}-sent`]:ke,[`remote-${le}-received`]:He})},{sessionId:x});g.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function Ee(ye,x,W){return{header:{stream:ye,created:Date.now(),frameId:W||""},payload:x}}function Te(ye){return new Set(["disconnected","failed","closed"]).has(ye.iceConnectionState)}function Ue(ye){switch(ye.header.stream.streamType){case"twist":{const{twist:x}=ye.payload;if(!x)throw Error("twist not in payload of RTC message with type twist");return{header:ye.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},x.linear),angular:Object.assign({x:0,y:0,z:0},x.angular)}}}}case"pose":{const{pose:x}=ye.payload;if(!x)throw Error("pose not in payload of RTC message with type pose");return{header:ye.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},x.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:x}=ye.payload;if(!x)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const W=new Array(36).fill(0);return x.covariance.forEach((K,re)=>{if(re>=36)throw Error("covariance contains more than 36 elements");W[re]=K}),{header:ye.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},x.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},x.pose.rotation)},covariance:W}}}}case"point":{const{point:x}=ye.payload;if(!x)throw Error("point not in payload of RTC message with type point");return{header:ye.header,payload:{point:Object.assign({x:0,y:0,z:0},x)}}}default:return ye}}var qe=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Qe{constructor(x,W,K){this.peerConnection=x,this.config=W,this.dataChannelNotifier=K,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=1*c.a.second,this.pingV2UpdateTimeoutMs=250*c.a.millisecond,this.pingV2MetricsGatherTimeoutMs=1*c.a.second,this.streamsInfoUpdateTimeoutMs=2*c.a.second,this.reassemblyTimeoutMs=500*c.a.millisecond,this.reassemblyTableCleanupMs=1*c.a.second,this.heartbeatTimeoutMs=20*c.a.millisecond,this.streamLatestTimestamp=new Map,this.reassemblyTable=new Map,this.reassemblyTableLastTimestamp=new Map,this.closeCalled=!1,this.gotOffer=!1,this.hasIceCandidate=!1,this.pingV2Map=new Map,this.sendPingV2=()=>{const{latestTryOnceStreamChannel:oe}=this;if(!oe)return;const he=new Date().getTime(),me=Object(q.a)();this.sendSystemMessage(oe,{type:"ping-v2",payload:{timestamp:he,id:me}}),this.pingV2Map.set(me,{sent:he})},this.gatherPingV2Metrics=()=>{const oe=ve(this.pingV2Map);oe&&(this.pingInfo=oe,d.aggregate("rtc-ping-average",oe.average),d.aggregate("rtc-ping-loss",oe.loss),d.aggregate("rtc-jitter",oe.jitter))};const{isOffer:re}=W.baseConfig;re?this.initializeChannels(x):x.ondatachannel=oe=>{switch(oe.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=oe.channel;break;case"stream.reliable":this.reliableStreamChannel=oe.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=oe.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=oe.channel;break;case"heartbeat":return void(this.heartbeatChannel=oe.channel);default:return void this.dataChannelNotifier(oe.channel)}this.setupChannel(oe.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"ping"})},this.pingUpdateTimeoutMs),this.pingV2UpdateTimeout=setInterval(this.sendPingV2,this.pingV2UpdateTimeoutMs),this.pingV2MetricsGatherTimeout=setInterval(this.gatherPingV2Metrics,this.pingV2MetricsGatherTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:oe}=this;oe&&this.sendSystemMessage(oe,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const oe=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((he,me,pe)=>{oe>me+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(he)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:oe}=this;oe&&oe.readyState==="open"&&oe.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=this,{track:K}=this.config.baseConfig,re=(()=>{try{return JSON.parse(x.getPayload())}catch{return}})();if(!re)return void g.a.error("Received unparseable signal.");g.a.debug("Handling signal",{description:re});const{sdp:oe,type:he}=re;if(!oe||!he)return void g.a.warn("Received non-SDP signal");const{signalingState:me,connectionState:pe}=W;if(me!=="stable"||pe!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP after remote description was set: ${oe}`);else{if(he==="offer"){if(me!=="stable")return void g.a.warn("Received offer SDP when signaling is ongoing.");yield W.setRemoteDescription(re);const ue=yield W.createAnswer();yield W.setLocalDescription(ue);const le=x.clone();return K==null||K("Answer Received",le),le.setPayload(JSON.stringify(ue)),le.setReceiverId(x.getSenderId()),le.setSenderId(x.getReceiverId()),le}if(he==="answer"){if(me==="stable")return void g.a.warn("Received answer SDP when signaling hasn't started.");yield W.setRemoteDescription(re)}}else g.a.warn(`Received SDP when already connected: ${oe}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:x,latestTtlStreamChannel:W,latestTryOnceStreamChannel:K,latestReliableStreamChannel:re}=this;return(x==null?void 0:x.readyState)==="open"&&(W==null?void 0:W.readyState)==="open"&&(K==null?void 0:K.readyState)==="open"&&(re==null?void 0:re.readyState)==="open"}close(){return qe(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),tt(this.pingUpdateTimeout),tt(this.pingV2UpdateTimeout),tt(this.pingV2MetricsGatherTimeout),tt(this.reassemblyTableCleanupTimeout),tt(this.streamsInfoUpdateTimeout),tt(this.heartbeatTimeout);const{peerConnection:x,reliableStreamChannel:W,latestTtlStreamChannel:K,latestTryOnceStreamChannel:re,latestReliableStreamChannel:oe}=this;x.close(),W==null||W.close(),K==null||K.close(),re==null||re.close(),oe==null||oe.close()})}getPing(){return this.pingTimeMs}getPingInfo(){return this.pingInfo}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionCreatedTimestamp}setSessionCreatedTimestamp(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=x)}getSessionId(){var x;return(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId}setSessionId(x){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=x,this.sessionMetrics=new Ce(x,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var x;return(x=this.config.baseConfig)===null||x===void 0?void 0:x.remoteDeviceId}setRemoteDeviceId(x){this.config.baseConfig.remoteDeviceId=x}getSessionMetricsMessageCounts(){var x;return(x=this.sessionMetrics)===null||x===void 0?void 0:x.counts}getConnectionStatsInfo(){return qe(this,void 0,void 0,function*(){const{peerConnection:x}=this;if(!x)return;const W=yield x.getStats(null),K=[];W.forEach(pe=>{K.push(pe)});const re=K.find(pe=>pe.type==="transport");if(!re)return;const oe=K.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===re.selectedCandidatePairId);if(!oe)return;const he=K.find(pe=>pe.id===oe.localCandidateId),me=K.find(pe=>pe.id===oe.remoteCandidateId);return he&&me&&(he.address=he.address||he.ip,me.address=me.address||me.ip,he.address!==void 0&&me.address!==void 0)?{transport:re,localCandidate:he,remoteCandidate:me}:void 0})}initializeChannels(x){this.heartbeatChannel=x.createDataChannel("heartbeat",$),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var x,W,K;return qe(this,void 0,void 0,function*(){const{gotOffer:re}=this,{peerConnection:oe,config:he}=this;if(this.config.baseConfig.isLan)throw new Error('"getOffer" method can only be called with internet connections. LAN connections should call the "getLanOffer" method.');const me=(x=this.config.remoteConfig)===null||x===void 0?void 0:x.sessionId;if(re)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");const pe=he.baseConfig.track;oe.onicecandidate=()=>{this.hasIceCandidate=!0},oe.oniceconnectionstatechange=()=>qe(this,void 0,void 0,function*(){const ke=oe.iceConnectionState;if(ke==="connected"||ke==="completed"){const He=yield this.getConnectionStatsInfo(),Xe=He?function(Ye){const Ge=Ye.localCandidate.candidateType,je=Ye.remoteCandidate.candidateType;return Ge==="host"&&je==="host"?"local":Ge==="relay"||je==="relay"?"TURN":"STUN"}(He):void 0;g.a.info(`ICE connection state changed to ${ke}`,{sessionId:me,connectionStatsInfo:He,iceMode:Xe}),pe==null||pe("ICE connection state change",{iceConnectionState:ke,sessionId:me,connectionStatsInfo:He,iceMode:Xe})}}),yield oe.setLocalDescription(yield oe.createOffer());const ue=new Date().getTime();for(;;){const ke=new Date().getTime()-ue;if(ke>this.connectTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(ke>this.iceGatheringTimeoutMs&&this.hasIceCandidate){g.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering partially completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}if(oe.iceGatheringState==="complete"){g.a.debug("ICE gathering complete",{iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke}),pe==null||pe("ICE gathering completed",{sessionId:me,iceTransportPolicy:oe.getConfiguration().iceTransportPolicy,waitTime:ke});break}yield Object(l.a)(.1*c.a.second)}const le=(W=this.peerConnection.getConfiguration().iceServers)!==null&&W!==void 0?W:[];for(const ke of le)ke.credentialType=void 0;const Re=JSON.stringify(le),Ie=new Q.Signal;return Ie.setPayload(JSON.stringify(oe.localDescription)),Ie.setSenderId(this.config.baseConfig.localPeerId),Ie.setReceiverId(this.config.baseConfig.remotePeerId),Ie.setIceServers(Re),Ie.setIceTransportPolicy((K=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&K!==void 0?K:"all"),this.config.baseConfig.sessionType!==void 0?Ie.setSessionType(this.config.baseConfig.sessionType):Ie.setSessionType(Q.SessionType.TELEOP),g.a.debug("Sending offer signal with description",{description:Ie.getPayload()}),Ie})}getLanOffer(){return qe(this,void 0,void 0,function*(){const{peerConnection:x,gotOffer:W}=this;if(!this.config.baseConfig.isLan)throw new Error('"getLanOffer" method can only be used with LAN connections. Internet connections should call the "getOffer" method.');if(W)return void g.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,Te(this.peerConnection))return void g.a.debug("Failed to generate offer because the peer connection was inactive.");yield x.setLocalDescription(yield x.createOffer());const K=new Date().getTime();for(;;){if(new Date().getTime()-K>this.iceGatheringTimeoutMs)return void g.a.debug("Failed to generate offer because ICE gathering timed out.");if(x.iceGatheringState==="complete")break;yield Object(l.a)(.1*c.a.second)}const re=x.localDescription;if(re)return g.a.debug("Sending LAN offer signal with description",{description:re}),re;g.a.error("Failed to generate LAN offer description")})}handleLanAnswer(x){return qe(this,void 0,void 0,function*(){const{peerConnection:W}=this;if(!this.config.baseConfig.isLan)throw new Error('"handleLanAnswer" method can only be used with LAN connections. Internet connections should call the "handleSignal" method.');yield W.setRemoteDescription(x)})}getChannelFromLabel(x){switch(x){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable message on RTC stream data channel",{error:re,channel:x.label})}K.communicationType==="message-chunk"?this.receiveChannelMessageChunk(x,K):this.receiveChannelMessage(x,K)},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}receiveChannelMessage(x,W){const{config:K}=this,{remotePeerId:re}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),W=Ue(W),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived(W),this.handleSystemMessage(x,W)||(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(W)||K.baseConfig.receive(re,W)}receiveChannelMessageChunk(x,W){const K=this.reassemblyTable.get(W.id)||[];if(K.push(W),K.length===W.total){const re=function(oe){const he=oe.sort((me,pe)=>me.seq<pe.seq?-1:1).map(me=>me.part).reduce((me,pe)=>me+pe);try{return JSON.parse(he)}catch{return void g.a.warn("Could not reassemble RTC message chunks")}}(K);return re&&this.receiveChannelMessage(x,re),void this.reassemblyTable.delete(W.id)}this.reassemblyTable.set(W.id,K),this.reassemblyTableLastTimestamp.set(W.id,new Date().getTime())}handleSystemMessage(x,W){var K,re;const{config:oe}=this,{baseConfig:he}=oe,{remotePeerId:me}=he;switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const pe=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=pe,d.aggregate("rtc-ping-time",pe),!0}case"ping-v2":return this.sendPingV2(),!0;case"pong-v2":{const pe=h(W.payload.pongV2),ue=this.pingV2Map.get(pe.id);return(ue==null?void 0:ue.sent)!==pe.timestamp?(g.a.warn("Pong timestamp doesn't match stored value",{currentEntry:ue,pong:pe}),!0):(this.pingV2Map.set(pe.id,{sent:pe.timestamp,received:new Date().getTime()}),!0)}case"streams-info":{const{sessionMetrics:pe}=this,ue=(K=W.payload.streamsInfo)===null||K===void 0?void 0:K.timestamp;return!!ue&&(pe==null||pe.updateRemoteMessagesCounts(W),(re=he.onStreamsInfoUpdate)===null||re===void 0||re.call(he,me,ue),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){var K;const{localUserId:re,localPeerId:oe}=this.config.baseConfig;if(x.readyState!=="open")return;const he={entityId:re!=null?re:oe,streamName:`$.${W.type}`,streamType:W.type};let me;switch(W.type){case"ping":me={ping:new Date().getTime()};break;case"pong":me={pong:W.timestamp};break;case"ping-v2":me={pingV2:W.payload};break;case"pong-v2":me={pongV2:W.payload};break;case"stream-control":me={streamControl:W.streamControl};break;case"streams-info":me={streamsInfo:(K=this.sessionMetrics)===null||K===void 0?void 0:K.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(x,Ee(he,me))}isLatestMessage(x){const W=Ae(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}function tt(ye){ye&&clearInterval(ye)}function Rt(ye){var x,W;return{userId:(x=ye.getUserId())===null||x===void 0?void 0:x.getValue(),deviceId:(W=ye.getDeviceId())===null||W===void 0?void 0:W.getValue(),organizationId:ye.getOrganizationId(),id:ye.getPeerId(),capabilities:[],capabilitySet:{}}}var xe=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class _t{constructor(x){this.config=x,this.grpcCallDeadline=5*c.a.second,this.refreshIntervalDelayMs=2*c.a.second,this.iceServersTtl=30*c.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:W}=this;this.refreshInterval=f({func:()=>xe(this,void 0,void 0,function*(){try{yield this.update()}catch(K){g.a.warn("RTC refresh failed",{error:K})}}),delay:W,immediate:!0})}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Send called with unready connection."):g.a.warn("Send called with no connection.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("controlRemoteStream called with unready connection."):g.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return xe(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(l.a)(.1*c.a.second);return Rt(this.localPeer)})}connect(x,W){var K,re,oe;return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:he,signalingClient:me}=this.config,{localPeer:pe,receiveSignalStream:ue,iceServers:le}=this;if(!pe||!ue||!le)return void g.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(x))return void g.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(x))return void g.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(x,!0);const Re=function(je,Fe,$e){const{rtcIceTransportPolicies:Ze,rtcIceServerProtocol:Ke,useAllServers:Je}=Fe||{},ot=je.map(it=>Object.assign(Object.assign({},it),{urls:it.urls.filter(dt=>{const St=(Ze===void 0||Ze.some(wt=>z(dt,wt)))&&(Ke===void 0||X(dt,Ke));return St||g.a.debug(`Ignoring ICE server: ${dt}`,{organizationId:$e}),St})})).filter(({urls:it})=>it.filter(dt=>dt).length>0);return Je?ot:[B(ot,"stun"),B(ot,"turn")].filter(it=>it!==void 0).map(it=>h(it))}(le,W);g.a.debug("Received ICE servers:",le),g.a.debug("Using ICE servers:",Re);const Ie=new Qe(yield this.createRTCPeerConnection(Re),{baseConfig:{isOffer:!0,isLan:!1,receive:(je,Fe)=>this.config.receive(je,Fe),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(je,Fe)=>{var $e,Ze;return(Ze=($e=this.config).onStreamsInfoUpdate)===null||Ze===void 0?void 0:Ze.call($e,je,Fe)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=pe.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:pe.getPeerId(),remotePeerId:x,sessionType:this.config.sessionType},remoteConfig:{}},je=>this.onCustomDataChannel(x,je)),ke=yield Ie.getOffer();if(!ke)return g.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(x);g.a.debug("Sending offer."),he==null||he("Sending offer",ke);const He=new Q.SendSignalRequest;He.setSignal(ke);const Xe=yield(()=>xe(this,void 0,void 0,function*(){try{return yield me.sendSignal(He,yield this.getMetadata({}))}catch(je){g.a.warn("Error when sending signal",{error:je})}}))();if(!this.isOutgoingConnection.get(x))return void g.a.debug("No offer set after receiving offer signal response.");g.a.debug("Offer sent.");const Ye=(re=Xe==null?void 0:Xe.getSessionId())===null||re===void 0?void 0:re.getValue(),Ge=(oe=Xe==null?void 0:Xe.getSessionCreatedTimestamp())===null||oe===void 0?void 0:oe.getValue();return Ye&&Ge?(Ie.setSessionId(Ye),Ie.setSessionCreatedTimestamp(Ge),this.isOutgoingConnection.delete(x),this.connections.push(Ie),this.isConnectionInitiator.set(Ie,!0),this.setupHandlers(Ie),Ye):(g.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(x))})}connectLan(x){var W,K;return xe(this,void 0,void 0,function*(){const re=new N(x),oe=new Qe(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ue,le)=>this.config.receive(ue,le),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ue,le)=>{var Re,Ie;return(Ie=(Re=this.config).onStreamsInfoUpdate)===null||Ie===void 0?void 0:Ie.call(Re,ue,le)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(K=(W=this.localPeer)===null||W===void 0?void 0:W.getUserId())===null||K===void 0?void 0:K.getValue(),localPeerId:"lan_client",remotePeerId:x}},ue=>this.onCustomDataChannel(x,ue)),he=yield oe.getLanOffer();if(!he)return g.a.warn("Could not generate LAN offer"),!1;const me=yield re.postLanRtcOffer({offer:JSON.stringify(he)}),pe=new RTCSessionDescription(JSON.parse(me.answer));return yield oe.handleLanAnswer(pe),this.localConnections.push(oe),this.isConnectionInitiator.set(oe,!0),Object(q.a)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(x,W,K,re,oe){const he=this.getActiveConnection(x);if(he&&this.isConnectionInitiator.has(he)){const pe=he.peerConnection.createDataChannel("custom."+W,K);return re&&(pe.binaryType="arraybuffer"),oe(x,pe),()=>{}}const me=(pe,ue)=>{x===pe&&ue.label==="custom."+W&&oe(x,ue)};return this.peerDataChannelListeners.push(me),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==me)}}onCustomDataChannel(x,W){this.peerDataChannelListeners.forEach(K=>K(x,W))}getConnectionStatus(x){if(this.isOutgoingConnection.get(x))return"connecting";const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(x){return xe(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);if(W)return yield W.getConnectionStatsInfo()})}disconnect(x){return xe(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield W.close())})}getPeers(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>xe(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return[];const K=W.getPeersList();if(!K)return[];const re=oe=>{var he,me;return(me=(he=oe.getPeerCreatedTimestamp())===null||he===void 0?void 0:he.getValue())!==null&&me!==void 0?me:0};return K.sort((oe,he)=>re(he)-re(oe)).map(oe=>Rt(oe))})}getSessions(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>xe(this,void 0,void 0,function*(){try{return yield x.getPeers(new Q.GetPeersRequest,yield this.getMetadata({}))}catch(oe){g.a.warn("Error when getting peers",{error:oe})}}))();if(!W)return{};const K=W.getPeersList(),re={};for(const oe of K)re[oe.getPeerId()]=oe.getSessionIdsList();return re})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getPingInfo(x){const W=this.getActiveConnection(x);if(W)return W.getPingInfo();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(x){const W=this.getActiveConnection(x);if(W)return W.getSessionMetricsMessageCounts();g.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:x,receiveSignalStream:W,iceServers:K}=this;return!!(x&&W&&K)}shutdown(){return xe(this,void 0,void 0,function*(){g.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const x=this.connections;this.connections=[],yield this.closeConnections(x);const{localPeer:W}=this;if(!W||this.config.lanOnlyMode)return;const{signalingClient:K}=this.config;yield(()=>xe(this,void 0,void 0,function*(){try{const re=new Q.DeletePeerRequest;re.setPeerId(W.getPeerId()),yield K.deletePeer(re,yield this.getMetadata({}))}catch(re){return void g.a.warn("Error deleting local peer",{error:re})}}))()})}createPeer(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:x}=this.config,W=yield(()=>xe(this,void 0,void 0,function*(){try{return yield x.createPeer(new Q.CreatePeerRequest,yield this.getMetadata({}))}catch(re){throw new Error(`Was not able to create peer: ${JSON.stringify(re)}`)}}))(),K=W==null?void 0:W.getPeer();if(!K)throw new Error("Response did not provide peer.");return this.localPeer=K})}createReceiveSignalStream(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:x}=this.config,{localPeer:W,iceServers:K}=this;if(!W||!K)return;const{receiveSignalStream:re}=this;re&&re.cancel();const oe=new Q.ReceiveSignalStreamRequest;oe.setPeerId(W.getPeerId());const he=yield(()=>xe(this,void 0,void 0,function*(){try{return x.receiveSignalStream(oe,yield this.getMetadata({hasDeadline:!1}))}catch(me){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(me)}`)}}))();if(!he)throw new Error("Response did not provide stream.");return he.on("data",me=>xe(this,void 0,void 0,function*(){var pe,ue,le,Re;const Ie=me.getSignal(),ke=(pe=Ie==null?void 0:Ie.getSessionId())===null||pe===void 0?void 0:pe.getValue(),He=Ie==null?void 0:Ie.getSenderId(),Xe=Ie==null?void 0:Ie.getReceiverId(),Ye=(ue=Ie==null?void 0:Ie.getSessionCreatedTimestamp())===null||ue===void 0?void 0:ue.getValue();if(!(Ie&&ke&&He&&Xe&&Ye))return void g.a.warn("Received signal with missing information.");const Ge=this.getActiveConnection(He);if(Ge)if(Ge.getSessionId()!==ke){if(g.a.debug("Received signal: different session for a peer we're already connected to."),(Ge.getSessionCreatedTimestamp()||0)>Ye)return;const je=new Qe(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,$e)=>this.config.receive(Fe,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Fe,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(Re=W.getUserId())===null||Re===void 0?void 0:Re.getValue(),remotePeerId:He},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Fe=>this.onCustomDataChannel(He,Fe));yield je.handleSignal(Ie),this.connections.push(je)}else g.a.debug("Received signal: for an existing connection."),yield Ge.handleSignal(Ie);else{g.a.debug("Received signal: new connection.");const je=new Qe(yield this.createRTCPeerConnection(K),{baseConfig:{isOffer:!1,isLan:!1,receive:(Fe,$e)=>this.config.receive(Fe,$e),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Fe,$e)=>{var Ze,Ke;return(Ke=(Ze=this.config).onStreamsInfoUpdate)===null||Ke===void 0?void 0:Ke.call(Ze,Fe,$e)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:W.getPeerId(),localUserId:(le=W.getUserId())===null||le===void 0?void 0:le.getValue(),remotePeerId:He},remoteConfig:{sessionId:ke,sessionCreatedTimestamp:Ye}},Fe=>this.onCustomDataChannel(He,Fe));yield je.handleSignal(Ie),this.connections.push(je)}})),he.on("end",()=>{he.cancel(),this.receiveSignalStream=void 0}),he.on("error",me=>{switch(me.code){case te.StatusCode.CANCELLED:case te.StatusCode.UNAVAILABLE:case te.StatusCode.UNKNOWN:g.a.debug("Receive signal stream error",{error:me});break;case te.StatusCode.UNAUTHENTICATED:g.a.warn("Receive signal stream error",{error:me});break;default:g.a.error("Receive signal stream error",{error:me})}he.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=he})}createRTCPeerConnection(x){var W;return xe(this,void 0,void 0,function*(){const K=(W=this.config.alternateRTCPeerConnection)!==null&&W!==void 0?W:window.RTCPeerConnection;if(!K)throw function(){const{userAgent:re}=navigator;return re.includes("Firefox/")?"Firefox":re.includes("Edg/")?"Edge":re.includes("Chrome/")?"Chrome":re.includes("Safari/")?"Safari":re.includes("MSIE/")||re.includes("Trident/")?"IE":"Other"}()!=="Chrome"?new Error("WebRTC is not enabled. Please try again with the latest version of Google Chrome."):new Error("WebRTC is not enabled. Please ensure WebRTC is not disabled by ad blocking software.");return new K({iceServers:x})})}closeConnections(x){return xe(this,void 0,void 0,function*(){const W=yield w(x.map(K=>xe(this,void 0,void 0,function*(){yield K.close()})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}getActiveConnection(x){return this.getConnections().find(W=>W.getRemotePeerId()===x&&W.isActive())}update(){var x;return xe(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:W}=this.config;if(!this.localPeer||!this.receiveSignalStream||!this.iceServers)return this.localPeer||(yield this.createPeer()),this.iceServers||(yield this.updateIceServers()),void(this.receiveSignalStream||(yield this.createReceiveSignalStream()));yield this.closeConnections(this.connections.filter(me=>!me.isActive())),this.connections=this.connections.filter(me=>me.isActive());const{localPeer:K}=this,re=this.connections.filter(me=>me.getSessionId).map(me=>h(me.getSessionId()));K.setSessionIdsList(re);const oe=new Q.RefreshPeerRequest;oe.setPeer(K);try{yield W.refreshPeer(oe,yield this.getMetadata({}))}catch(me){me.code===te.StatusCode.NOT_FOUND?(g.a.warn("Peer expired, creating new peer",{peerId:K.getPeerId()}),yield this.reset()):g.a.warn("Error calling RefreshPeer",{error:me})}const he=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((x=he.find(pe=>pe.id===me.getRemotePeerId()))===null||x===void 0?void 0:x.deviceId)})}reset(){return xe(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.isOutgoingConnection=new Map,yield this.createPeer(),yield this.createReceiveSignalStream()})}updateIceServers(){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:x,iceServersTtl:W}=this,K=new Date().getTime();if(!x||K-x>W)try{const re=(yield this.config.signalingClient.getIceServers(new Q.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(re),this.iceServersLastUpdate=K}catch(re){g.a.warn("Error in updateIceServers",{error:re})}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionCreatedTimestamp();W.onconnectionstatechange=()=>xe(this,void 0,void 0,function*(){const re=W.connectionState;if(K)switch(re){case"connected":d.aggregate("rtc-connect-time",new Date().getTime()-K);break;case"failed":d.increment("rtc-connect-failed")}})}getMetadata(x){return xe(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:W}=this.config,{grpcCallDeadline:K}=this,{hasDeadline:re}=x,oe=re===!1?void 0:new Date().getTime()+K;return{authorization:yield W(),deadline:oe}})}}var gt=n(10),lt=n(11),Ot=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class Ct{constructor(x,W){this.sessionId=x,this.connection=W,this.sentMessagesCounts=new Map,this.receivedMessagesCounts=new Map,this.sessionId=x,this.connection=W}incrementMessageSent(x){const W=Ae(x.header.stream);this.sentMessagesCounts.set(W,(this.sentMessagesCounts.get(W)||0)+1)}incrementMessageReceived(x){const W=Ae(x.header.stream);this.receivedMessagesCounts.set(W,(this.receivedMessagesCounts.get(W)||0)+1)}uploadMetrics(){return Ot(this,void 0,void 0,function*(){const{sessionId:x}=this,W=yield this.connection.peerConnection.getStats(),K={};W.forEach(oe=>K[oe.id]=oe),g.a.debug("rtc-stats",Object.assign(Object.assign({},K),{sessionId:x}));const re=[...new Set(Array.from(this.sentMessagesCounts.keys()).concat(Array.from(this.receivedMessagesCounts.keys())))].reduce((oe,he)=>{const me=this.sentMessagesCounts.get(he),pe=this.receivedMessagesCounts.get(he);return Object.assign(Object.assign({},oe),{[`${he}-sent`]:me,[`${he}-received`]:pe})},{sessionId:x});g.a.debug("rtc-message-report",re)})}}function ut(ye,x){return Ae(ye)===Ae(x)}var et=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class It{constructor(x,W){this.peerConnection=x,this.config=W,this.connectTimeoutMs=10*c.a.second,this.gatherIceTimeoutMs=5*c.a.second,this.pingUpdateTimeoutMs=2*c.a.second,this.streamLatestTimestamp=new Map,this.closeCalled=!1,this.connectCalled=!1,this.sentOffer=!1,this.receivedIceCandidate=!1;const{isOffer:K}=W;K?this.initializeChannels(x):x.ondatachannel=re=>{switch(re.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=re.channel;break;case"stream.reliable":this.reliableStreamChannel=re.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=re.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=re.channel}this.setupChannel(re.channel)},this.sessionMetrics=new Ct(this.getSessionId(),this)}connect(){return et(this,void 0,void 0,function*(){if(this.connectCalled)return;this.connectCalled=!0,this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:re}=this;re&&this.sendSystemMessage(re,{type:"ping"})},this.pingUpdateTimeoutMs),this.connectTimeout=setTimeout(()=>et(this,void 0,void 0,function*(){this.isReady()||(g.a.warn("RTC connect timed out, closing connection"),yield this.close())}),this.connectTimeoutMs);const{peerConnection:x,config:{isOffer:W,sessionId:K}}=this;if(W){const re=yield x.createOffer();yield x.setLocalDescription(re)}W&&(this.gatherIceTimeout=setTimeout(()=>et(this,void 0,void 0,function*(){this.sentOffer||(g.a.warn("ICE gathering timed out"),this.receivedIceCandidate?(g.a.warn("Attempting to connect with partial ICE candidate pool"),yield this.sendOffer()):yield this.close())}),this.gatherIceTimeoutMs),x.onicecandidate=re=>et(this,void 0,void 0,function*(){re.candidate?this.receivedIceCandidate=!0:yield this.sendOffer()}),x.onicegatheringstatechange=()=>et(this,void 0,void 0,function*(){x.iceGatheringState==="complete"&&(yield this.sendOffer())}),x.onnegotiationneeded=()=>{g.a.debug("Negotiation needed",{sessionId:K})})})}handleSignal(x){return et(this,void 0,void 0,function*(){const{peerConnection:W,config:{sessionId:K,sendSignal:re}}=this,{description:oe}=JSON.parse(x.payload);if(g.a.debug("Handling signal",{sessionId:K,description:JSON.stringify(oe)}),oe)if(W.signalingState!=="stable"||W.connectionState!=="connected")if(W.remoteDescription)g.a.warn(`Received SDP signal during negotiation when remote description is already set: ${JSON.stringify(x)}`);else if(oe.type==="offer"){yield W.setRemoteDescription(oe);const he=yield W.createAnswer();yield W.setLocalDescription(he),yield re({payload:JSON.stringify({description:he})})}else oe.type==="answer"&&(yield W.setRemoteDescription(oe));else g.a.warn(`Received SDP signal when signaling is stable and connected: ${JSON.stringify(x)}`);else g.a.warn(`Received non-SDP signal: ${JSON.stringify(x)}`)})}send(x,W){const K=this.getChannelFromLabel(W.channelLabel);K?this.sendOnChannel(K,x):g.a.warn("Send called with unexpected channel label",{channelLabel:W.channelLabel})}controlRemoteStream(x){this.sendSystemMessage(h(this.reliableStreamChannel),{type:"stream-control",streamControl:x})}isActive(){return new Set(["new","connecting","connected"]).has(this.peerConnection.connectionState)}isReady(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;return!!(K&&W&&re)&&x.connectionState==="connected"&&K.readyState==="open"&&W.readyState==="open"&&re.readyState==="open"}isClosed(){const{peerConnection:x,reliableStreamChannel:W,latestTryOnceStreamChannel:K,latestTtlStreamChannel:re}=this;return!(x.connectionState!=="closed"||W!==void 0&&W.readyState!=="closed"||K!==void 0&&K.readyState!=="closed"||re!==void 0&&re.readyState!=="closed")}needsClosing(){const{peerConnection:x,latestTtlStreamChannel:W,reliableStreamChannel:K,latestTryOnceStreamChannel:re}=this;if(this.isClosed())return!1;const oe=new Set(["closing","closed"]),he=me=>me&&oe.has(me.readyState);return Te(x)||he(W)||he(K)||he(re)}close(){return et(this,void 0,void 0,function*(){this.closeCalled||(this.closeCalled=!0,yield this.sessionMetrics.uploadMetrics(),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.connectTimeout&&clearTimeout(this.connectTimeout),this.gatherIceTimeout&&clearTimeout(this.gatherIceTimeout),this.peerConnection.close())})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionId(){return this.config.sessionId}getRemotePeer(){return this.config.remotePeer}initializeChannels(x){this.latestTtlStreamChannel=x.createDataChannel("stream.latest-ttl",v),this.reliableStreamChannel=x.createDataChannel("stream.reliable",S),this.latestReliableStreamChannel=x.createDataChannel("stream.latest-reliable",U),this.latestTryOnceStreamChannel=x.createDataChannel("stream.latest-try-once",J),this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}sendOffer(){return et(this,void 0,void 0,function*(){if(this.sentOffer||(this.sentOffer=!0,Te(this.peerConnection)))return;const{peerConnection:x,config:{sendSignal:W}}=this,K=yield x.createOffer();yield x.setLocalDescription(K);const re={payload:JSON.stringify({description:K})};yield W(re)})}getChannelFromLabel(x){switch(x){case"stream.latest-ttl":return this.latestTtlStreamChannel;case"stream.reliable":return this.reliableStreamChannel;case"stream.latest-reliable":return this.latestReliableStreamChannel;case"stream.latest-try-once":return this.latestTryOnceStreamChannel}}sendOnChannel(x,W){let K;try{K=Object(H.encode)(JSON.stringify(W))}catch(re){return void g.a.warn("Failed to encode RTC message",{error:re})}try{x.send(K),this.sessionMetrics.incrementMessageSent(W)}catch(re){g.a.warn("Failed to send message to channel",{error:re,channel:x.label})}}channelNotRecognized(x){return x!==this.latestTtlStreamChannel&&x!==this.latestReliableStreamChannel&&x!==this.latestTryOnceStreamChannel&&x!==this.reliableStreamChannel}setupChannel(x){x.onmessage=W=>{if(this.channelNotRecognized(x))return void g.a.warn("Received message on unrecognized data channel.");let K;try{K=JSON.parse(Object(H.decode)(W.data))}catch(re){return void g.a.warn("Received unparseable RTC message",{error:re,channel:x.label})}if(this.lastMessageTimestamp=new Date().getTime(),K=Ue(K),this.sessionMetrics.incrementMessageReceived(K),!this.handleSystemMessage(x,K)){if(!this.hasCapabilities(K))return void g.a.warn("Received RTC message that was not within the capability scope of the connection.");(x===this.latestTryOnceStreamChannel||x===this.latestTtlStreamChannel||x===this.latestReliableStreamChannel)&&!this.isLatestMessage(K)||this.config.receive(this.config.remotePeer.id,K)}},x.onerror=W=>{g.a.warn(`Channel error: ${W.error}`,{error:W.error,sessionId:this.getSessionId(),channelLabel:x.label})},x.onopen=()=>{g.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:x.label})},x.onclose=()=>{const W={bufferedAmount:x.bufferedAmount,sessionId:this.getSessionId(),channelLabel:x.label};this.closeCalled===!1?g.a.debug("Unexpected channel closed",W):g.a.debug("Channel closed",W)}}handleSystemMessage(x,W){switch(W.header.stream.streamType){case"ping":return this.sendSystemMessage(x,{type:"pong",timestamp:h(W.payload.ping)}),!0;case"pong":{const K=new Date().getTime()-h(W.payload.pong);return this.pingTimeMs=K,d.aggregate("rtc-ping-time",K),!0}case"stream-control":return!0;default:return!1}}sendSystemMessage(x,W){if(x.readyState!=="open")return;const K={entityId:h(this.config.localPeer.deviceId||this.config.localPeer.userId),streamName:`$.${W.type}`,streamType:W.type};let re;switch(W.type){case"ping":re={ping:new Date().getTime()};break;case"pong":re={pong:W.timestamp};break;case"stream-control":re={streamControl:W.streamControl}}this.sendOnChannel(x,Ee(K,re))}hasCapabilities(x){var W,K;const{localPeer:re,remotePeer:oe}=this.config,he=(W=re.capabilitySet.streaming)===null||W===void 0?void 0:W.streams,me=he&&he.some(le=>le.receive&&ut(le.stream,x.header.stream)),pe=(K=oe.capabilitySet.streaming)===null||K===void 0?void 0:K.streams,ue=pe&&pe.some(le=>le.send&&ut(le.stream,x.header.stream));return me||ue}isLatestMessage(x){const W=Ae(x.header.stream),K=(this.streamLatestTimestamp.get(W)||0)<=x.header.created;return K&&this.streamLatestTimestamp.set(W,x.header.created),K}}var Be=function(ye,x,W,K){return new(W||(W=Promise))(function(re,oe){function he(ue){try{pe(K.next(ue))}catch(le){oe(le)}}function me(ue){try{pe(K.throw(ue))}catch(le){oe(le)}}function pe(ue){var le;ue.done?re(ue.value):(le=ue.value,le instanceof W?le:new W(function(Re){Re(le)})).then(he,me)}pe((K=K.apply(ye,x||[])).next())})};class jt{constructor(x){this.config=x,this.connections=[],this.connectingSessions=new Map,this.updateInterval=f({func:()=>Be(this,void 0,void 0,function*(){try{yield this.update()}catch(W){g.a.warn("RTC update failed",{error:W})}}),delay:250*c.a.millisecond,immediate:!0}),this.localPeer=this.createPeer()}send(x,W,K){const re=this.getActiveConnection(x);re?re.isReady()?re.send(W,K):g.a.warn("Attempted to send with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to send with no active connection to that peer.")}controlRemoteStream(x,W){const K=this.getActiveConnection(x);K?K.isReady()?K.controlRemoteStream(W):g.a.warn("Attempted to control remote stream with an active connection to that peer which was not yet ready."):g.a.warn("Attempted to control remote stream with no active connection to that peer.")}connect(x){return Be(this,void 0,void 0,function*(){const W=yield this.getLocalPeer();if(this.getActiveConnection(x))return void g.a.warn("Attempted to connect to peer with an already active connection.");let K;try{K=yield this.config.signalingClient.createSession(yield this.config.getToken(),{offerPeerId:W.id,answerPeerId:x})}catch(re){Object(gt.a)(re,lt.a,oe=>oe.statusCode===404),g.a.warn("Attempted to connect to peer that does not exist.")}if(K)for(this.connectingSessions.set(K.id,new Date().getTime()),yield this.connectToSession(K);;)switch(yield Object(l.a)(.1),this.getConnectionStatus(x)){case"connecting":continue;case"connected":return K.id;case"disconnected":return}})}getConnectionStatus(x){const W=this.getActiveConnection(x);return W?W.isReady()?"connected":"connecting":"disconnected"}getIceMode(x){const W=this.getActiveConnection(x);if(W)return W.iceMode}disconnect(x){return Be(this,void 0,void 0,function*(){const W=this.getActiveConnection(x);W&&(yield this.closeConnection(W))})}getLocalPeer(){return Be(this,void 0,void 0,function*(){return yield this.localPeer})}getPeers(){return Be(this,void 0,void 0,function*(){return yield this.config.signalingClient.getPeers(yield this.config.getToken())})}getPing(x){const W=this.getActiveConnection(x);if(W)return W.getPing();g.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(x){const W=this.getActiveConnection(x);if(W)return W.getLastMessageTimestamp();g.a.warn("Attempted to get ping time from inactive peer.")}shutdown(){return Be(this,void 0,void 0,function*(){yield this.updateInterval.stop();const x=this.connections;this.connections=[],yield this.closeConnections(x)})}closeConnection(x){return Be(this,void 0,void 0,function*(){this.connectingSessions.delete(x.getSessionId()),yield x.close();try{yield this.config.signalingClient.deleteSession(yield this.config.getToken(),x.getSessionId())}catch(W){Object(gt.a)(W,lt.a,K=>K.statusCode===404)}})}getSessions(){return Be(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();return(yield this.config.signalingClient.getSessions(yield this.config.getToken())).filter(W=>W.offer.peer.id===x.id||W.answer.peer.id===x.id)})}createPeer(){return Be(this,void 0,void 0,function*(){return yield this.config.signalingClient.createPeer(yield this.config.getToken(),{capabilitySet:this.config.capabilitySet||{}})})}createRTCPeerConnection(x={}){return Be(this,void 0,void 0,function*(){return new(this.config.alternateRTCPeerConnection||RTCPeerConnection)(Object.assign({iceServers:yield this.config.signalingClient.getIceServers(yield this.config.getToken())},x))})}closeConnections(x){return Be(this,void 0,void 0,function*(){const W=yield w(x.map(K=>Be(this,void 0,void 0,function*(){yield this.closeConnection(K)})));for(const K of W)g.a.warn("Request to close session failed",{error:K})})}reset(){return Be(this,void 0,void 0,function*(){yield this.closeConnections(this.connections),this.connections=[],this.connectingSessions=new Map,this.localPeer=this.createPeer(),yield this.localPeer})}getActiveConnection(x){return this.connections.find(W=>W.getRemotePeer().id===x&&W.isActive())}update(){return Be(this,void 0,void 0,function*(){const x=yield this.getLocalPeer();try{yield this.config.signalingClient.refreshPeer(yield this.config.getToken(),x.id)}catch(W){Object(gt.a)(W,lt.a,K=>K.statusCode===404),g.a.warn("Peer expired, creating new peer",{peerId:x.id}),yield this.reset()}yield this.handleSessions(yield this.getSessions())})}handleSessions(x){return Be(this,void 0,void 0,function*(){yield this.syncConnectionsAndSessions(x);const W=x.map(K=>({session:K,connection:this.connections.find(re=>re.getSessionId()===K.id)}));yield Promise.all(W.map(({session:K,connection:re})=>Be(this,void 0,void 0,function*(){return yield this.maintainConnection(K,re)})))})}syncConnectionsAndSessions(x){return Be(this,void 0,void 0,function*(){const W=new Set(x.map(oe=>oe.id)),K=oe=>W.has(oe.getSessionId())||this.connectingSessions.has(oe.getSessionId());this.connections=this.connections.filter(oe=>K(oe));const re=this.connections.filter(oe=>!K(oe)||oe.needsClosing());yield Promise.all(re.map(oe=>Be(this,void 0,void 0,function*(){yield this.closeConnection(oe)})))})}maintainConnection(x,W){return Be(this,void 0,void 0,function*(){const K=yield this.getLocalPeer(),re=x.offer.peer.id===K.id;if(W){if(W.isReady())try{yield this.config.signalingClient.refreshSession(yield this.config.getToken(),x.id)}catch(oe){Object(gt.a)(oe,lt.a,he=>he.statusCode===404),g.a.debug("Refresh session not found",{sessionId:x.id})}else if(W.isActive())try{yield this.consumeSignals(W)}catch(oe){g.a.warn("Failed to ingest signals, closing connection",{error:oe}),yield this.closeConnection(W)}}else{if(re)return;yield this.connectToSession(x)}})}connectToSession(x){return Be(this,void 0,void 0,function*(){const W=yield this.getLocalPeer(),K=x.offer.peer.id===W.id,re=yield this.createRTCPeerConnection(),oe=new It(re,{localPeer:K?x.offer.peer:x.answer.peer,remotePeer:K?x.answer.peer:x.offer.peer,sessionId:x.id,isOffer:K,sendSignal:he=>this.sendSignal(x.id,he),receive:(he,me)=>this.config.receive(he,me)});if(this.connections.find(he=>he.getSessionId()===x.id))return g.a.warn("connectToSession called on a session that already has a connection.",{sessionId:x.id}),void(yield oe.close());this.setupHandlers(oe),this.connections.push(oe);try{yield oe.connect()}catch(he){g.a.warn("Failed to handle negotiation, closing connection",{error:he}),yield this.closeConnection(oe)}})}setupHandlers(x){const{peerConnection:W}=x,K=x.getSessionId();W.onconnectionstatechange=()=>Be(this,void 0,void 0,function*(){const re=this.connectingSessions.get(K);if(re===void 0)return;const oe=W.connectionState;switch(Te(W)&&this.connectingSessions.delete(K),oe){case"connected":{this.connectingSessions.delete(K);const he=new Date().getTime()-re;d.aggregate("rtc-connect-time",he);break}case"failed":d.increment("rtc-connect-failed"),yield this.closeConnection(x)}})}consumeSignals(x){return Be(this,void 0,void 0,function*(){let W=[];try{W=yield this.config.signalingClient.takeSignals(yield this.config.getToken(),x.getSessionId())}catch(K){Object(gt.a)(K,lt.a,re=>re.statusCode===404)}for(const K of W)yield x.handleSignal(K)})}sendSignal(x,W){return Be(this,void 0,void 0,function*(){try{yield this.config.signalingClient.addSignals(yield this.config.getToken(),x,{signals:[W]})}catch(K){Object(gt.a)(K,lt.a,re=>re.statusCode===404)}})}}},function(e,t,n){var r={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let o;const u=new Uint8Array(16);function s(){if(!o&&(o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(u)}const i=[];for(let l=0;l<256;++l)i.push((l+256).toString(16).slice(1));function c(l,m=0){return(i[l[m+0]]+i[l[m+1]]+i[l[m+2]]+i[l[m+3]]+"-"+i[l[m+4]]+i[l[m+5]]+"-"+i[l[m+6]]+i[l[m+7]]+"-"+i[l[m+8]]+i[l[m+9]]+"-"+i[l[m+10]]+i[l[m+11]]+i[l[m+12]]+i[l[m+13]]+i[l[m+14]]+i[l[m+15]]).toLowerCase()}t.a=function(l,m,R){if(r.randomUUID&&!m&&!l)return r.randomUUID();const E=(l=l||{}).random||(l.rng||s)();if(E[6]=15&E[6]|64,E[8]=63&E[8]|128,m){R=R||0;for(let y=0;y<16;++y)m[R+y]=E[y];return m}return c(E)}},,function(e,t,n){n.r(t),n.d(t,"LogClient",function(){return i});var r=n(28),o=n(10),u=n(11),s=function(c,l,m,R){return new(m||(m=Promise))(function(E,y){function g(L){try{T(R.next(L))}catch(V){y(V)}}function _(L){try{T(R.throw(L))}catch(V){y(V)}}function T(L){var V;L.done?E(L.value):(V=L.value,V instanceof m?V:new m(function(M){M(V)})).then(g,_)}T((R=R.apply(c,l||[])).next())})};class i extends r.a{log(l){return s(this,void 0,void 0,function*(){const m=i.token;try{yield this.fetch("logs",{token:m,method:"POST",body:JSON.stringify({logs:l}),allowUnsafeRetries:!0})}catch(R){Object(o.a)(R,u.a,E=>E.statusCode===401&&m!==void 0),i.token===m&&delete i.token,yield this.log(l)}})}}}])})})(dist);function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}let FORMANT_API_URL="https://api.formant.io";typeof window!="undefined"&&(FORMANT_API_URL=window.FORMANT_API_URL||FORMANT_API_URL);let urlParams$2=new URLSearchParams("");typeof window!="undefined"&&(urlParams$2=new URLSearchParams(window.location.search));const envDev=urlParams$2.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$2.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");const envLocal=urlParams$2.get("formant_local");envLocal&&(FORMANT_API_URL="https://api.formant.local");class App{static sendAppMessage(t){window.parent.postMessage(t,"*")}static getCurrentModuleContext(){let t=new URLSearchParams("");return typeof window!="undefined"&&(t=new URLSearchParams(window.location.search)),t.get("module")}static async getCurrentModuleConfiguration(){let t=new URLSearchParams("");typeof window!="undefined"&&(t=new URLSearchParams(window.location.search));const n=t.get("configuration");return n===null||n.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+n,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).configuration}static isModule(){return this.getCurrentModuleContext()!==null}static goToTime(t){this.sendAppMessage({type:"go_to_time",time:t.getTime()})}static goToDevice(t){this.sendAppMessage({type:"go_to_device",deviceId:t})}static showMessage(t){this.sendAppMessage({type:"show_message",message:t})}static requestModuleData(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"request_module_data",module:t})}static setModuleDateTimeRange(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:r,before:t,after:n||0})}static refreshAuthToken(){const t=this.getCurrentModuleContext();if(!t)throw new Error("No module context");this.sendAppMessage({type:"refresh_auth_token",module:t})}static sendChannelData(t,n){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:r,channel:t,data:n})}static setupModuleMenus(t){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:n,menus:t})}static addMenuListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_menu_item_clicked"&&t(r.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="auth_token"&&t(r.token)})}static addModuleDataListener(t){window.addEventListener("message",n=>{const r=n.data;r.type==="module_data"&&t({streams:r.streams,time:r.time,queryRange:r.queryRange})})}static addChannelDataListener(t,n){window.addEventListener("message",r=>{const o=r.data;o.type==="channel_data"&&o.channel===t&&n({source:o.source,data:o.data})})}}const Me=class{static async login(t,n){try{const r=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:n}),headers:{"Content-Type":"application/json"}}),o=await r.json();if(r.status!==200)throw new Error(o.message);return await Me.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(r){return Me.waitingForAuth.forEach(o=>o(!1)),Me.waitingForAuth=[],Promise.reject(r)}}static async loginWithToken(t,n){const r=JSON.parse(atob(t.split(".")[1]));try{let o;if(Me.isShareToken=r["formant:claims"]&&r["formant:claims"].type=="share",r["formant:claims"]&&(Me.currentOrganization=r["formant:claims"].organizationId),r["custom:organization_id"]&&(Me.currentOrganization=r["custom:organization_id"]),Me.isShareToken||(o=r.sub),r["formant:claims"]&&r["formant:claims"].userId&&(o=r["formant:claims"].userId),o){const u=await fetch(`${FORMANT_API_URL}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await u.json();if(u.status!==200)throw new Error(s.message);Me.currentUser=s}Me.token=t,Me.waitingForAuth.forEach(u=>u(!0))}catch(o){console.error(o),Me.waitingForAuth.forEach(u=>u(!1))}Me.waitingForAuth=[],n&&(Me.refreshToken=n,setInterval(async()=>{if(Me.refreshToken){const u=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Me.refreshToken})})).json();Me.token=u.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Me.token!==void 0}static getCurrentUser(){return Me.currentUser}static async waitTilAuthenticated(){return Me.token!==void 0?!0:new Promise(t=>{Me.waitingForAuth.push(function(n){t(n)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Me;Oe(Authentication,"token"),Oe(Authentication,"refreshToken"),Oe(Authentication,"currentUser"),Oe(Authentication,"currentOrganization"),Oe(Authentication,"isShareToken",!1),Oe(Authentication,"defaultDeviceId"),Oe(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Oe(this,"ready",!1);Oe(this,"listeners",[]);Oe(this,"openListeners",[]);Oe(this,"closeListeners",[]);Oe(this,"errorListeners",[]);Oe(this,"binaryListeners",[]);Oe(this,"error");Oe(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(n=>n())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(n=>n())},this.dataChannel.onerror=n=>{console.error(n),this.error="An error occurred in DataChannel",this.errorListeners.forEach(r=>r(n))},this.dataChannel.onmessage=n=>{this.listeners.forEach(r=>{const o=new Uint8Array(n.data),u=this.decoder.decode(o);r(u)}),this.binaryListeners.forEach(r=>{r(new Uint8Array(n.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(n=>n!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(n=>n!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(n=>n!==t)}async waitTilReady(){return this.ready?!0:new Promise((n,r)=>{let o=window.setInterval(()=>{this.ready&&(window.clearInterval(o),n(!0)),this.error&&r(this.error)},10)})}send(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}sendBinary(t){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(t)}addListener(t){this.listeners.push(t)}removeListener(t){const n=this.listeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(n,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const n=this.binaryListeners.indexOf(t);if(n===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(n,1)}}class CaptureStream{constructor(t){Oe(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=r.token}await fetch(`${FORMANT_API_URL}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(t)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}class Manipulator{constructor(t,n){Oe(this,"currentListeners",[]);Oe(this,"onRealtimeMessage",(t,n)=>{n.payload.jointState&&this.currentListeners.forEach(r=>{n.payload.jointState&&r(n.payload.jointState)})});this.device=t,this.config=n}async synchronize(){this.device.addRealtimeListener(this.onRealtimeMessage),this.device.startListeningToRealtimeDataStream(this.config.currentJointStateStream)}async desynchronize(){this.device.removeRealtimeListener(this.onRealtimeMessage),this.device.stopListeningToRealtimeDataStream(this.config.currentJointStateStream)}async addCurrentJointStateListener(t){this.currentListeners.push(t)}}class RequestDataChannel{constructor(t,n,r){Oe(this,"channel");Oe(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=n,this.timeout=r}addOpenListener(t){defined(this.channel,"channel not initalized").addOpenListener(t)}removeOpenListener(t){defined(this.channel,"channel not initalized").removeOpenListener(t)}addCloseListener(t){defined(this.channel,"channel not initalized").addCloseListener(t)}removeCloseListener(t){defined(this.channel,"channel not initalized").removeCloseListener(t)}addErrorListener(t){defined(this.channel,"channel not initalized").addErrorListener(t)}removeErrorListener(t){defined(this.channel,"channel not initalized").removeErrorListener(t)}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);Oe(this,"RESPONSE_SUCCESS_BYTE",0);Oe(this,"decoder",new TextDecoder)}generateBinaryId(){const t=new Uint8Array(16);for(let n=0;n<t.length;n++)t[n]=Math.floor(Math.random()*256);return t}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(t=>{const r=t.slice(0,16).toString();if(r.length===0)throw new Error("Invalid response");const o=t.slice(16);if(o.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,o)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const u=this.generateBinaryId(),s=u.toString();r.set(s,!0),n.sendBinary(new Uint8Array([...u,...t]));const i=new Date().getTime();for(;new Date().getTime()<i+o;)if(await delay(50),r.has(s)){const c=r.get(s);if(c!==!0){r.delete(s);const l=c[0]===this.RESPONSE_SUCCESS_BYTE,m=c.slice(1);if(l)return m;throw console.error({name:"AdapterError",message:this.decoder.decode(m)}),new Error("Binary request datachannel adapter error")}}throw r.delete(s),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class TextRequestDataChannel extends RequestDataChannel{generateTextId(){return Math.random().toString(36).substring(2)+"-"+Math.random().toString(36).substring(2)}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addListener(t=>{const n=JSON.parse(t),{id:r,data:o,error:u}=n;if(!r)throw new Error("Invalid response");if(!o&&!u)throw new Error("Invalid response");this.requestIdToResponseMap.has(r)&&this.requestIdToResponseMap.set(r,n)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:r,timeout:o}=this;await n.waitTilReady();const u=this.generateTextId();r.set(u,!0),n.send(JSON.stringify({id:u,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+o;)if(await delay(50),r.has(u)){const i=r.get(u);if(i!==!0){r.delete(u);const{data:c,error:l}=i;if(c)return c;if(l)throw console.error({name:"AdapterError",message:l}),new Error("Text request datachannel adapter error")}}throw r.delete(u),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}const urlParams$1=new URLSearchParams(window.location.search),rtcClientVersion=urlParams$1.get("rtc_client"),SessionType={Teleop:1,Observe:3};class Device{constructor(t,n,r){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.id=t,this.name=n,this.organizationId=r}async getLatestTelemetry(){return(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}async getConfiguration(){let t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const r=n.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),(await t.json()).document}async getFileUrl(t){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{let n;if(rtcClientVersion==="1"?n=new dist.exports.RtcClientV1({signalingClient:new dist.exports.RtcSignalingClient(FORMANT_API_URL+"/v1/signaling"),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage}):n=new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:this.handleMessage,sessionType:t}),n.isReady)for(;!n.isReady();)await delay(100);const o=(await n.getPeers()).find(u=>u.deviceId===this.id);if(!o)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=o.id,await n.connect(this.remoteDevicePeerId);n.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=n}}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.send(defined(o).id,t,n)}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeAudioStreams(){var r,o,u,s,i,c;const t=await this.getConfiguration(),n=[];for(const l of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});for(const l of(s=(u=t.teleop)==null?void 0:u.rosStreams)!=null?s:[])l.topicType=="audio_common_msgs/AudioData"&&n.push({name:l.topicName});for(const l of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])l.rtcStreamType==="audio-chunk"&&n.push({name:l.name});return n}async getRealtimeVideoStreams(){var r,o,u,s,i,c;const t=await this.getConfiguration(),n=[];for(const l of(o=(r=t.teleop)==null?void 0:r.hardwareStreams)!=null?o:[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.name});for(const l of(s=(u=t.teleop)==null?void 0:u.rosStreams)!=null?s:[])l.topicType=="formant/H264VideoFrame"&&n.push({name:l.topicName});for(const l of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])l.rtcStreamType==="h264-video-frame"&&n.push({name:l.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();r.controlRemoteStream(defined(o).id,{streamName:t,setAudioFormat:n})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const n=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(r=>r.deviceId===this.id);return defined(n,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){let t=await Fleet.getPeers(),n=await Fleet.getRealtimeSessions(),r=t.find(o=>o.deviceId===this.id);return r?n[r.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${FORMANT_API_URL}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(r=>({name:r.name,id:r.id,command:r.command,description:r.description,parameterEnabled:r.parameterEnabled,parameterValue:r.parameterValue,parameterMeta:r.parameterMeta,enabled:r.enabled}))}async sendCommand(t,n,r,o){var l;const s=(await this.getAvailableCommands()).find(m=>m.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let i;if(n===void 0)if(s.parameterEnabled&&s.parameterValue)i=s.parameterValue;else throw new Error("Command has no default parameter value, you must provide one");else i=n;let c={value:i,scrubberTime:(r||new Date).toISOString(),meta:ht(ht({},s.parameterMeta),o)};await fetch(`${FORMANT_API_URL}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:s.id,organizationId:this.organizationId,deviceId:this.id,command:s.command,parameter:c,userId:(l=Authentication.currentUser)==null?void 0:l.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,n){if(rtcClientVersion==="1")throw new Error("createCustomDataChannel is not supported in rtcClientVersion 1");const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),u=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,ht({ordered:!0},n),!1,(i,c)=>{const l=new DataChannel(c);s(l)})});return await u.waitTilReady(),u}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}async createCaptureStream(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:t,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return new CaptureStream(r)}async getTelemetry(t,n,r,o){return await Fleet.getTelemetry(this.id,t,n,r,o)}async getTelemetryStreams(){var i,c;const t=await this.getConfiguration(),n=await fetch(`${FORMANT_API_URL}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=[],o=[];return(c=(i=t.telemetry)==null?void 0:i.streams)==null||c.forEach(l=>{l.disabled!==!0&&r.push(l.name),l.onDemand===!0&&o.push(l.name)}),console.log(o),(await n.json()).items.filter(l=>!r.includes(l)).map(l=>({name:l,onDemand:o.includes(l)}))}async createInterventionRequest(t,n,r,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:n,time:new Date().toISOString(),deviceId:this.id,tags:o,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,n,r){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:n,data:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Oe(this,"rtcClient");Oe(this,"remoteDevicePeerId");Oe(this,"realtimeListeners",[]);Oe(this,"id");Oe(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(r=>r(t,n))});this.peerUrl=t}async getLatestTelemetry(){const n=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(n).map(([o,u])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:u,currentValueTime:u.timestamp,tags:{}}))}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/configuration`)).json()).agent_config.document}getRealtimeStatus(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getConnectionStatus(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}getRealtimePing(){if(this.rtcClient&&this.remoteDevicePeerId)return this.rtcClient.getPing(this.remoteDevicePeerId);throw new Error("Realtime connection hasn't been started")}async startRealtimeConnection(t){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const n=new dist.exports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=n}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeVideoStreams(){var r,o,u;const t=await this.getConfiguration(),n=[];for(const s of(r=t.teleop.hardwareStreams)!=null?r:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});for(const s of(o=t.teleop.rosStreams)!=null?o:[])s.topicType=="formant/H264VideoFrame"&&n.push({name:s.topicName});for(const s of(u=t.teleop.customStreams)!=null?u:[])s.rtcStreamType==="h264-video-frame"&&n.push({name:s.name});return n}async getRealtimeManipulators(){var r;const t=await this.getConfiguration(),n=[];for(const o of(r=t.teleop.rosStreams)!=null?r:[])o.topicType=="sensor_msgs/JointState"&&n.push(new Manipulator(this,{currentJointStateStream:{name:o.topicName},plannedJointStateStream:o.plannedTopic?{name:o.plannedTopic}:void 0,planValidStream:o.planValidTopic?{name:o.planValidTopic}:void 0,endEffectorStream:o.endEffectorTopic?{name:o.endEffectorTopic}:void 0,endEffectorLinkName:o.endEffectorLinkName,baseReferenceFrame:o.baseReferenceFrame,localFrame:o.localFrame}));return n}async startListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=defined(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();n.controlRemoteStream(defined(r).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){if(this.rtcClient)await this.rtcClient.disconnect(this.id);else throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async createCustomDataChannel(t,n){const r=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),u=await new Promise(s=>{r.createCustomDataChannel(defined(o).id,t,ht({ordered:!0},n),!1,(i,c)=>{const l=new DataChannel(c);s(l)})});return await u.waitTilReady(),u}createCustomRequestDataChannel(t,n=3e3){return new TextRequestDataChannel(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new BinaryRequestDataChannel(this,t,n)}}const Le=class{static async setDefaultDevice(t){Le.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Le.defaultDeviceId)throw new Error("No known default device");const o=(await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.find(s=>s.id===Le.defaultDeviceId).name,u=new Device(Le.defaultDeviceId,o,defined(Authentication.currentOrganization));return Le.knownContext.push(new WeakRef(u)),u}static async getPeerDevice(t){const n=new PeerDevice(t);return n.id=await n.getDeviceId(),n}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=r.name,u=new Device(t,o,r.organizationId);return Le.knownContext.push(new WeakRef(u)),u}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();return n.items,n.items.map(r=>new Device(r.id,r.name,r.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items;return(await Le.getDevices()).filter(u=>r.includes(u.id))}static async getPeers(){if(!Authentication.token)throw new Error("Not authenticated");return await new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getPeers()}static async getRealtimeSessions(){if(!Authentication.token)throw new Error("Not authenticated");return await new dist.exports.RtcClient({signalingClient:new dist.exports.SignalingPromiseClient(FORMANT_API_URL,null,null),getToken:async()=>defined(Authentication.token,"Realtime when user isn't authorized"),receive:()=>{}}).getSessions()}static async getRealtimeDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(u=>u.deviceId);return(await Le.getDevices()).filter(u=>r.includes(u.id))}static async getLatestTelemetry(t){let n=t;return t&&!Array.isArray(t)&&(t=[t]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,n,r,o,u){let s=t;Array.isArray(t)||(s=[t]);let i=n;return Array.isArray(n)||(i=[n]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:r.toISOString(),tags:u}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const r=await(await fetch(`${FORMANT_API_URL}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[t]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json();if(r.fileUrls.length===0)throw new Error("File not found");return r.fileUrls[0]}static async queryTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async aggregateTelemetry(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).aggregates}static async queryEvents(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getEvent(t){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/events/query/id=${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getInterventions(){if(!Authentication.token)throw new Error("Not authenticated");return(await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}};let Fleet=Le;Oe(Fleet,"defaultDeviceId"),Oe(Fleet,"knownContext",[]);class KeyValue{static async set(t,n){try{const r=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),o=await r.json();if(r.status!==200)throw new Error(o.message)}catch(r){throw r}}static async get(t){try{const n=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),r=await n.json();if(n.status!==200)throw new Error(r.message);return r.value}catch(n){throw n}}static async list(){try{const t=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.items}catch(t){throw t}}static async delete(t){try{if(!(await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).ok)throw new Error("Unable to handle request");return}catch(n){throw n}}}function getVariance(e){return e.count<2?0:e.sumOfSquares/(e.count-1)}function getStandardDeviation(e){return Math.sqrt(getVariance(e))}function getMax(e){return e.max}function getMin(e){return e.min}function getAverage(e){return e.count===0?-1:e.sum/e.count}function getSum(e){return e.sum}function getCount(e){return e.count}const aggregateFunctionMap={min:getMin,max:getMax,"standard deviation":getStandardDeviation,average:getAverage,sum:getSum,count:getCount};function getZeroINumericSet(){return{min:Number.MAX_SAFE_INTEGER,max:0,sum:0,count:0,sumOfSquares:0}}function reduceNumericStreamAggregates(e){return e.aggregates.reduce((t,n)=>{const r=n[1];return combineNumericAggregates(r,t)},getZeroINumericSet())}function reduceNumericSetStreamAggregates(e,t){var n;return(n=e.aggregates.reduce((r,o)=>{const u=o[1];return combineNumericSetAggregates(u,r)},{})[t])==null?void 0:n.value}function combineNumericAggregates(e,t){return{min:Math.min(e.min,t.min),max:Math.max(e.max,t.max),sum:e.sum+t.sum,count:e.count+t.count,sumOfSquares:e.sumOfSquares+t.sumOfSquares}}function combineNumericSetAggregates(e,t){return Object.keys(e).reduce((n,r)=>{var o,u;return Qt(ht({},n),{[r]:{value:combineNumericAggregates(e[r].value,(u=(o=t[r])==null?void 0:o.value)!=null?u:getZeroINumericSet()),unit:e[r].unit}})},{})}function stringToArrayBuffer(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function fork(e){}function browser(){const{userAgent:e}=navigator;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")?"Safari":e.includes("MSIE/")||e.includes("Trident/")?"IE":"Other"}const rtcAudioChunkStreamType="audio-chunk";class AudioPlayer{constructor(t,n){Oe(this,"muted",!1);Oe(this,"hasReceivedData",!1);Oe(this,"audioContext");Oe(this,"chunks",[]);Oe(this,"isPlaying",!1);Oe(this,"startTime",0);Oe(this,"lastChunkOffset",0);Oe(this,"bufferSize",3);Oe(this,"receive",async t=>{var s;const n=(s=t.payload.audioChunk)==null?void 0:s.chunk_data;if(!n)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:r,muted:o}=this;if(!r||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const u=stringToArrayBuffer(n);try{await r.decodeAudioData(u.buffer,this.scheduleChunk)}catch(i){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:i}),this.changeAudioWireFormat("wav")}});Oe(this,"scheduleChunk",t=>{const{audioContext:n}=this;if(!n)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const r=this.createChunk(t);!r||!r.buffer||(this.isPlaying===!1&&(this.startTime=n.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),r.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=r.buffer.duration,this.chunks.push(r))});this.device=t,this.stream=n,this.device.startListeningToRealtimeDataStream(n),this.device.addRealtimeListener((o,u)=>{this.receive(u)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const r=window.AudioContext||window.webkitAudioContext;this.audioContext=new r}async play(){var t,n;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((n=this.audioContext)==null?void 0:n.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:n}=this;if(!n)return;const r=n.createBufferSource();return r.buffer=t,r.connect(n.destination),r.loop=!1,r.onended=o=>{this.chunks.splice(this.chunks.indexOf(r),1),this.chunks.length===0&&(this.isPlaying=!1)},r}changeAudioWireFormat(t){const{stream:n}=this;fork((async()=>{await this.device.changeStreamAudioType(n.name,t)})())}}const accessLevels=["viewer","operator","administrator"],viewer="viewer",operator="operator",administrator="administrator",aggregateLevels=["year","month","week","day","hour","minute"],annotationTypes=["tag","sheet","user"],eventTypes=["triggered-event","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],healthStatuses=["unknown","operational","offline","error"],interventionTypes=["selection","labeling","teleop"],severities=["info","warning","error","critical"],videoMimeTypes=["video/mp4"];let urlParams=new URLSearchParams("");typeof window!="undefined"&&(urlParams=new URLSearchParams(window.location.search));const urlDevice=urlParams.get("device");urlDevice&&Fleet.setDefaultDevice(urlDevice);const urlAuth=urlParams.get("auth");urlAuth&&Authentication.loginWithToken(urlAuth);const moduleName=urlParams.get("module");moduleName&&Authentication.listenForRefresh(),exports.App=App,exports.AudioPlayer=AudioPlayer,exports.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,exports.IRtcSendConfiguration=dist.exports.IRtcSendConfiguration,exports.IRtcStreamMessage=dist.exports.IRtcStreamMessage,exports.IRtcStreamPayload=dist.exports.IRtcStreamPayload,exports.KeyValue=KeyValue,exports.Manipulator=Manipulator,exports.PeerDevice=PeerDevice,exports.SessionType=SessionType,exports.TextRequestDataChannel=TextRequestDataChannel,exports.accessLevels=accessLevels,exports.administrator=administrator,exports.aggregateFunctionMap=aggregateFunctionMap,exports.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.combineNumericAggregates=combineNumericAggregates,exports.combineNumericSetAggregates=combineNumericSetAggregates,exports.eventTypes=eventTypes,exports.getAverage=getAverage,exports.getCount=getCount,exports.getMax=getMax,exports.getMin=getMin,exports.getStandardDeviation=getStandardDeviation,exports.getSum=getSum,exports.getVariance=getVariance,exports.getZeroINumericSet=getZeroINumericSet,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.reduceNumericSetStreamAggregates=reduceNumericSetStreamAggregates,exports.reduceNumericStreamAggregates=reduceNumericStreamAggregates,exports.severities=severities,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperty(exports,"__esModule",{value:!0}),exports[Symbol.toStringTag]="Module"});
|
package/package.json
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"require": "./dist/data-sdk.umd.js"
|
|
19
19
|
}
|
|
20
20
|
},
|
|
21
|
-
"version": "0.0.
|
|
21
|
+
"version": "0.0.111",
|
|
22
22
|
"scripts": {
|
|
23
23
|
"dev": "vite --port 9146",
|
|
24
24
|
"build": "tsc && vite build",
|
|
@@ -28,12 +28,12 @@
|
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"typescript": "^4.3.2",
|
|
31
|
-
"vite": "^2.5.4"
|
|
31
|
+
"vite": "^2.5.4",
|
|
32
|
+
"typedoc": "^0.22.13"
|
|
32
33
|
},
|
|
33
34
|
"types": "./dist/types/data-sdk/src/main.d.ts",
|
|
34
35
|
"dependencies": {
|
|
35
36
|
"@formant/realtime-sdk": "^0.0.18",
|
|
36
|
-
"@types/google-protobuf": "^3.15.5"
|
|
37
|
-
"typedoc": "^0.22.13"
|
|
37
|
+
"@types/google-protobuf": "^3.15.5"
|
|
38
38
|
}
|
|
39
39
|
}
|