@formant/data-sdk 0.0.103 → 0.0.105
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
CHANGED
|
@@ -18368,6 +18368,24 @@ class App {
|
|
|
18368
18368
|
const moduleName2 = urlParams2.get("module");
|
|
18369
18369
|
return moduleName2;
|
|
18370
18370
|
}
|
|
18371
|
+
static async getCurrentModuleConfiguration() {
|
|
18372
|
+
let urlParams2 = new URLSearchParams("");
|
|
18373
|
+
if (typeof window !== "undefined") {
|
|
18374
|
+
urlParams2 = new URLSearchParams(window.location.search);
|
|
18375
|
+
}
|
|
18376
|
+
const configurationId = urlParams2.get("configuration");
|
|
18377
|
+
if (configurationId === null || configurationId.trim() === "") {
|
|
18378
|
+
return void 0;
|
|
18379
|
+
}
|
|
18380
|
+
const response = await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/` + configurationId, {
|
|
18381
|
+
headers: {
|
|
18382
|
+
"Content-Type": "application/json",
|
|
18383
|
+
Authorization: "Bearer " + Authentication.token
|
|
18384
|
+
}
|
|
18385
|
+
});
|
|
18386
|
+
const moduleConfiguration = await response.json();
|
|
18387
|
+
return moduleConfiguration.configuration;
|
|
18388
|
+
}
|
|
18371
18389
|
static isModule() {
|
|
18372
18390
|
return this.getCurrentModuleContext() !== null;
|
|
18373
18391
|
}
|
|
@@ -18981,7 +18999,7 @@ class Device {
|
|
|
18981
18999
|
const result = await fetch(`${FORMANT_API_URL}/v1/admin/files/query`, {
|
|
18982
19000
|
method: "POST",
|
|
18983
19001
|
body: JSON.stringify({
|
|
18984
|
-
|
|
19002
|
+
fileIds: [fileId]
|
|
18985
19003
|
}),
|
|
18986
19004
|
headers: {
|
|
18987
19005
|
"Content-Type": "application/json",
|
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,r){function n(l){return(n=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})(l)}function o(l,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(l,c.key,c)}}e.exports=function(){function l(c){if(function(u,b){if(!(u instanceof b))throw new TypeError("Cannot call a class as a function")}(this,l),!c)throw new Error("Logger is required for profiling.");this.logger=c,this.start=Date.now()}var s,i;return s=l,(i=[{key:"done",value:function(){for(var c=arguments.length,u=new Array(c),b=0;b<c;b++)u[b]=arguments[b];typeof u[u.length-1]=="function"&&(console.warn("Callback function no longer supported as of winston@3.0.0"),u.pop());var A=n(u[u.length-1])==="object"?u.pop():{};return A.level=A.level||"info",A.durationMs=Date.now()-this.start,this.logger.write(A)}}])&&o(s.prototype,i),l}()},function(e,t,r){(function(n){const o=r(208),{MESSAGE:l}=r(3),s=r(30);function i(c,u){return u instanceof n?u.toString("base64"):typeof u=="bigint"?u.toString():u}e.exports=o((c,u={})=>(c[l]=(u.stable?s.stableStringify:s)(c,u.replacer||i,u.space),c))}).call(this,r(4).Buffer)},function(e,t,r){class n extends Error{constructor(l){super(`Format functions must be synchronous taking a two arguments: (info, opts)
|
|
42
42
|
Found: ${l.toString().split(`
|
|
43
43
|
`)[0]}
|
|
44
|
-
`),Error.captureStackTrace(this,n)}}e.exports=o=>{if(o.length>2)throw new n(o);function l(i={}){this.options=i}function s(i){return new l(i)}return l.prototype.transform=o,s.Format=l,s}},function(e,t,r){function n(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 u=i[c];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}var l=r(85);e.exports=function(){function s(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};n(this,s),this.loggers=new Map,this.options=u}var i,c;return i=s,(c=[{key:"add",value:function(u,b){var A=this;if(!this.loggers.has(u)){var _=(b=Object.assign({},b||this.options)).transports||this.options.transports;b.transports=_?_.slice():[];var v=l(b);v.on("close",function(){return A._delete(u)}),this.loggers.set(u,v)}return this.loggers.get(u)}},{key:"get",value:function(u,b){return this.add(u,b)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var b=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(A,_){return b._removeLogger(_)})}},{key:"_removeLogger",value:function(u){this.loggers.has(u)&&(this.loggers.get(u).close(),this._delete(u))}},{key:"_delete",value:function(u){this.loggers.delete(u)}}])&&o(i.prototype,c),s}()},function(e,t,r){(function(n){const o=r(49),l=/^([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){let u,b,A=!1,_=!1;function v(w,P){let N=`"${i}" ${P}`;throw w&&(N=`${N}, but is set to "${w}"`),b&&(N=`${N}. An example of a valid value would be: ${b}`),new o(N)}function f(w){return function(){let P=s[i];if(P===void 0)if(u===void 0&&_)v(void 0,"is a required variable, but it was not set");else{if(u===void 0)return;P=u}_&&P.trim().length===0&&v(void 0,"is a required variable, but its value was empty"),A&&(P.match(l)||v(P,"should be a valid base64 string if using convertFromBase64"),P=n.from(P,"base64").toString());const N=[P].concat(Array.prototype.slice.call(arguments));try{return w.apply(w,N)}catch(T){v(P,T.message)}}}const S={asArray:f(r(211)),asBoolStrict:f(r(212)),asBool:f(r(213)),asPortNumber:f(r(214)),asEnum:f(r(215)),asFloatNegative:f(r(216)),asFloatPositive:f(r(217)),asFloat:f(r(51)),asIntNegative:f(r(218)),asIntPositive:f(r(91)),asInt:f(r(50)),asJsonArray:f(r(219)),asJsonObject:f(r(220)),asJson:f(r(52)),asString:f(r(34)),asUrlObject:f(r(92)),asUrlString:f(r(221)),convertFromBase64:function(){return A=!0,S},default:function(w){if(typeof w=="number")u=w.toString();else if(Array.isArray(w)||typeof w=="object"&&w!==null)u=JSON.stringify(w);else{if(typeof w!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");u=w}return S},required:function(w){return _=w===void 0||w,S},example:function(w){return b=w,S}};return Object.entries(c).forEach(([w,P])=>{S[w]=f(P)}),S}}).call(this,r(4).Buffer)},function(e,t,r){const n=r(34);e.exports=function(o,l){return l=l||",",o.length?n(o).split(l).filter(Boolean):[]}},function(e,t,r){e.exports=function(n){const o=n.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,r){e.exports=function(n){const o=n.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,r){const n=r(91);e.exports=function(o){var l=n(o);if(l>65535)throw new Error("cannot assign a port number greater than 65535");return l}},function(e,t,r){const n=r(34);e.exports=function(o,l){const s=n(o);if(l.indexOf(s)<0)throw new Error(`should be one of [${l.join(", ")}]`);return s}},function(e,t,r){const n=r(51);e.exports=function(o){const l=n(o);if(l>0)throw new Error("should be a negative float");return l}},function(e,t,r){const n=r(51);e.exports=function(o){const l=n(o);if(l<0)throw new Error("should be a positive float");return l}},function(e,t,r){const n=r(50);e.exports=function(o){const l=n(o);if(l>0)throw new Error("should be a negative integer");return l}},function(e,t,r){const n=r(52);e.exports=function(o){var l=n(o);if(!Array.isArray(l))throw new Error("should be a parseable JSON Array");return l}},function(e,t,r){const n=r(52);e.exports=function(o){var l=n(o);if(Array.isArray(l))throw new Error("should be a parseable JSON Object");return l}},function(e,t,r){const n=r(92);e.exports=function(o){return n(o).toString()}},function(e,t,r){(function(n){(function(){var o,l,s,i,c,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:n!=null&&n.hrtime?(e.exports=function(){return(o()-c)/1e6},l=n.hrtime,i=(o=function(){var b;return 1e9*(b=l())[0]+b[1]})(),u=1e9*n.uptime(),c=i-u):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,r(2))},function(e,t,r){var n,o,l=r(96),s=r(97),i=0,c=0;e.exports=function(u,b,A){var _=b&&A||0,v=b||[],f=(u=u||{}).node||n,S=u.clockseq!==void 0?u.clockseq:o;if(f==null||S==null){var w=l();f==null&&(f=n=[1|w[0],w[1],w[2],w[3],w[4],w[5]]),S==null&&(S=o=16383&(w[6]<<8|w[7]))}var P=u.msecs!==void 0?u.msecs:new Date().getTime(),N=u.nsecs!==void 0?u.nsecs:c+1,T=P-i+(N-c)/1e4;if(T<0&&u.clockseq===void 0&&(S=S+1&16383),(T<0||P>i)&&u.nsecs===void 0&&(N=0),N>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");i=P,c=N,o=S;var R=(1e4*(268435455&(P+=122192928e5))+N)%4294967296;v[_++]=R>>>24&255,v[_++]=R>>>16&255,v[_++]=R>>>8&255,v[_++]=255&R;var d=P/4294967296*1e4&268435455;v[_++]=d>>>8&255,v[_++]=255&d,v[_++]=d>>>24&15|16,v[_++]=d>>>16&255,v[_++]=S>>>8|128,v[_++]=255&S;for(var I=0;I<6;++I)v[_+I]=f[I];return b||s(v)}},function(e,t,r){var n=r(96),o=r(97);e.exports=function(l,s,i){var c=s&&i||0;typeof l=="string"&&(s=l==="binary"?new Array(16):null,l=null);var u=(l=l||{}).random||(l.rng||n)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,s)for(var b=0;b<16;++b)s[c+b]=u[b];return s||o(u)}},function(e,t,r){(function(n){(function(o){function l(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(l.prototype,"encoding",{value:"utf-8"}),l.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 u=i.length,b=0,A=Math.max(32,u+(u>>1)+7),_=new Uint8Array(A>>3<<3);c<u;){var v=i.charCodeAt(c++);if(55296<=v&&56319>=v){if(c<u){var f=i.charCodeAt(c);(64512&f)==56320&&(++c,v=((1023&v)<<10)+(1023&f)+65536)}if(55296<=v&&56319>=v)continue}if(b+4>_.length&&(A+=8,A=(A*=1+c/i.length*2)>>3<<3,(f=new Uint8Array(A)).set(_),_=f),(4294967168&v)==0)_[b++]=v;else{if((4294965248&v)==0)_[b++]=v>>6&31|192;else if((4294901760&v)==0)_[b++]=v>>12&15|224,_[b++]=v>>6&63|128;else{if((4292870144&v)!=0)continue;_[b++]=v>>18&7|240,_[b++]=v>>12&63|128,_[b++]=v>>6&63|128}_[b++]=63&v|128}}return _.slice(0,b)},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 u=(i=new Uint8Array(i)).length,b=[];c<u;){var A=i[c++];if(A===0)break;if((128&A)==0)b.push(A);else if((224&A)==192){var _=63&i[c++];b.push((31&A)<<6|_)}else if((240&A)==224){_=63&i[c++];var v=63&i[c++];b.push((31&A)<<12|_<<6|v)}else(248&A)==240&&(65535<(A=(7&A)<<18|(_=63&i[c++])<<12|(v=63&i[c++])<<6|63&i[c++])&&(A-=65536,b.push(A>>>10&1023|55296),A=56320|1023&A),b.push(A))}return String.fromCharCode.apply(null,b)},o.TextEncoder=l,o.TextDecoder=s})(typeof window!="undefined"?window:n!==void 0?n:this)}).call(this,r(5))},function(e,t,r){r.r(t),r.d(t,"AuthClient",function(){return l}),r.d(t,"RtcSignalingClient",function(){return i}),r.d(t,"Credentials",function(){return P}),r.d(t,"SignalingPromiseClient",function(){return N.SignalingPromiseClient}),r.d(t,"IRtcClientConfiguration",function(){}),r.d(t,"IRtcConnectConfiguration",function(){}),r.d(t,"IRtcConnectionStatsInfo",function(){}),r.d(t,"IRtcSendConfiguration",function(){}),r.d(t,"IRtcSessionMetricsMessageCounts",function(){}),r.d(t,"IRtcStreamMessage",function(){}),r.d(t,"IStreamControl",function(){}),r.d(t,"RtcClient",function(){return Ee}),r.d(t,"createRtcStreamMessage",function(){return X}),r.d(t,"IRtcStream",function(){}),r.d(t,"IRtcStreamPayload",function(){});var n=r(25),o=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class l extends n.a{adminSignup(q,$){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:$,method:"POST",body:JSON.stringify(q)})})}login(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(q),allowUnsafeRetries:!0})})}loginWithGoogleToken(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(q),allowUnsafeRetries:!0})})}refresh(q,$){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:q,tokenExpirationSeconds:$}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(q)})})}forgotPassword(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:q})})})}confirmForgotPassword(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(q)})})}resendInvitation(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:q})})})}changePassword({token:q,refreshToken:$,currentPassword:te,newPassword:ue}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:q,method:"POST",body:JSON.stringify({refreshToken:$,currentPassword:te,newPassword:ue})})})}getDeviceCredentials(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:q,method:"POST",allowUnsafeRetries:!0})})}impersonate(q,$){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:q,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:$})})})}createServiceAccount(q,$,te,ue){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:q,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:$,roleId:te,tags:ue})})})}getFeatures(q){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:q})).features})}}var s=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class i extends n.a{createPeer(q,$){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:q,method:"POST",body:JSON.stringify($)})})}getPeers(q){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:q})).items})}refreshPeer(q,$){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${$}/refresh`,{token:q,method:"POST",allowUnsafeRetries:!0})})}createSession(q,$){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:q,method:"POST",body:JSON.stringify($)})})}refreshSession(q,$){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${$}/refresh`,{token:q,method:"POST",allowUnsafeRetries:!0})})}deleteSession(q,$){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${$}`,{token:q,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(q){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:q})).items})}getIceServers(q){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:q})).items})}addSignals(q,$,te){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${$}/add-signals`,{token:q,method:"POST",body:JSON.stringify(te)})})}takeSignals(q,$){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${$}/take-signals`,{token:q,method:"POST"})).items})}}var c=r(1),u=r(11),b=r(35),A=r.n(b),_=r(102),v=r.n(_),f=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class S extends class{constructor(q){this.cache=new v.a(Object.assign(Object.assign({},q.dispose||q.disposeAfter?{ttlAutopurge:!0}:{}),q)),this.stringify=q.fastStringify?JSON.stringify:A.a}set(q,$,te){const ue=this.stringify(q);if(!this.cache.set(ue,$,{ttl:te})){const ae=this.cache.sizeCalculation?this.cache.sizeCalculation($,ue):"unknown";throw Error(`Value too large (${ae} > ${this.cache.max})`)}}get(q){return this.cache.get(this.stringify(q))}delete(q){this.cache.delete(this.stringify(q))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(q){return this.cache.forEach(q)}}{constructor(q){if(super(q),this.expireRejectedPromiseValues=q.expireRejectedPromiseValues===void 0||q.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=q.rejectedPromiseValueTtl!==void 0?q.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(q,$,te){const ue=this.stringify(q);this.cache.set(ue,$,{ttl:te}),this.expireRejectedPromiseValues&&Promise.resolve($).catch(()=>f(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(ue)===$&&this.cache.delete(ue)}))}}var w=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class P{constructor(q,$,te){this.authClient=q,this.email=$,this.password=te,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new S({max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return w(this,void 0,void 0,function*(){let q=this.tokenCache.get(this.email);return q||(q=(()=>w(this,void 0,void 0,function*(){const{authentication:$}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!$)throw new Error("User account not verified.");return $.accessToken}))(),this.tokenCache.set(this.email,q)),q})}}var N=r(93),T=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};function R(ye){return T(this,void 0,void 0,function*(){return(yield Promise.all(ye.map(q=>q.catch($=>$)))).filter(q=>q instanceof Error)})}function d(ye){if(ye!==void 0)return ye;throw new Error("Value is undefined")}var I=r(0),Q=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};function Z({func:ye,delay:q,immediate:$}){let te=!1,ue=setTimeout(function de(){return Q(this,void 0,void 0,function*(){if(te)return;const me=new Date().getTime();try{ae=ye(),yield ae}finally{if(!te){const pe=new Date().getTime();ue=setTimeout(de,Math.max(q-(pe-me),0))}}})},$?0:q),ae=Promise.resolve();return{stop(){return Q(this,void 0,void 0,function*(){te=!0,clearTimeout(ue),yield ae})}}}function h(ye,q){return Object.keys(ye).reduce(($,te)=>Object.assign(Object.assign({},$),{[te]:q(ye[te])}),{})}var p=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class j{constructor(q){this.message=q}send(q){return p(this,void 0,void 0,function*(){I.a.info(this.message,h(q,$=>{const{sum:te,count:ue}=$,ae=te/ue;return Object.assign(Object.assign({},$),{average:ae})}))})}}var m=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};const x=r(222);var F=r(6);const D=!!F.c,O=new class{constructor(ye=60){this.buffer={},this.metrics={},this.reporters=[],this.flushInterval=Z({func:()=>this.flushStats(),delay:ye*c.a.second})}shutdown(){return m(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(ye,q){if(this.buffer[ye]){const{min:$,max:te,sum:ue,count:ae}=this.buffer[ye];this.buffer[ye]={min:Math.min($,q),max:Math.max(te,q),sum:ue+q,count:ae+1}}else this.buffer[ye]={min:q,max:q,sum:q,count:1}}increment(ye){this.aggregate(ye,1)}timer(ye,q){return m(this,void 0,void 0,function*(){const $=x(),te=yield q(),ue=x();return this.aggregate(ye,ue-$),te})}metric(ye,q){this.metrics[ye]=q}registerStatsReporter(ye){this.reporters.push(ye)}write(ye){return m(this,void 0,void 0,function*(){if(Object.values(ye).length===0)return;const q=yield R(this.reporters.map($=>$.send(ye)));for(const $ of q)I.a.warn("Failed to write stats",{error:$})})}flushStats(){return m(this,void 0,void 0,function*(){const ye=Object.assign(Object.assign({},this.buffer),h(this.metrics,q=>{const $=q();return{min:$,max:$,sum:$,count:1}}));Object.keys(ye).length>0&&(yield this.write(ye),this.buffer={})})}};D||["local","on-prem"].includes(F.i)||O.registerStatsReporter(new j("stats"));var L=r(8),k=r(21),E=r(103),g=r(36),U=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class B extends g.a{constructor(q){super(q)}postLanRtcOffer(q){return U(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(q)})})}}var G=r(55);const Y={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},K={ordered:!0},H={ordered:!0},V={ordered:!1,maxRetransmits:0},y={ordered:!1,maxRetransmits:0};function C({entityId:ye,streamName:q,streamType:$}){return`${ye}.${q}.${$}`}var W=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class ee{constructor(q,$){this.sessionId=q,this.connection=$,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=q,this.connection=$}updateRemoteMessagesCounts(q){if(q.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const $ of q.payload.streamsInfo.items)this.counts.remoteSent.set($.streamId,$.sentCount),this.counts.remoteReceived.set($.streamId,$.receivedCount)}}getLocalStreamsInfo(q){const{localSent:$,localReceived:te}=this.counts;return{items:[...new Set([...$.keys(),...te.keys()])].map(ue=>{var ae,de;return{streamId:ue,sentCount:(ae=$.get(ue))!==null&&ae!==void 0?ae:0,receivedCount:(de=te.get(ue))!==null&&de!==void 0?de:0}}),timestamp:q}}incrementLocalSent(q){const{localSent:$}=this.counts,te=C(q.header.stream);$.set(te,($.get(te)||0)+1)}incrementLocalReceived(q){const{localReceived:$}=this.counts,te=C(q.header.stream),ue=$.get(te)||0;if(ue===0){const{streamName:ae,streamType:de}=q.header.stream;I.a.debug("RTC client received first message for stream",{streamName:ae,streamType:de})}$.set(te,ue+1)}uploadMetrics(){return W(this,void 0,void 0,function*(){const{sessionId:q}=this,$=yield this.connection.peerConnection.getStats(),te={};$.forEach(ge=>te[ge.id]=ge),I.a.debug("rtc-stats",Object.assign(Object.assign({},te),{sessionId:q}));const{localSent:ue,localReceived:ae,remoteSent:de,remoteReceived:me}=this.counts,pe=[...new Set([...ue.keys(),...ae.keys()])].reduce((ge,ce)=>{const Te=ue.get(ce),Ae=ae.get(ce),Pe=de.get(ce),Le=me.get(ce);return Object.assign(Object.assign({},ge),{[`local-${ce}-sent`]:Te,[`local-${ce}-received`]:Ae,[`remote-${ce}-sent`]:Pe,[`remote-${ce}-received`]:Le})},{sessionId:q});I.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function X(ye,q){return{header:{stream:ye,created:Date.now(),frameId:""},payload:q}}function ne(ye){return new Set(["disconnected","failed","closed"]).has(ye.iceConnectionState)}var ie=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class he{constructor(q,$,te){this.peerConnection=q,this.config=$,this.dataChannelNotifier=te,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=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;const{isOffer:ue}=$.baseConfig;ue?this.initializeChannels(q):q.ondatachannel=ae=>{switch(ae.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ae.channel;break;case"stream.reliable":this.reliableStreamChannel=ae.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ae.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ae.channel;break;case"heartbeat":return void(this.heartbeatChannel=ae.channel);default:return void this.dataChannelNotifier(ae.channel)}this.setupChannel(ae.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"ping"})},this.pingUpdateTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ae=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((de,me,pe)=>{ae>me+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(de)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ae}=this;ae&&ae.readyState==="open"&&ae.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(q){return ie(this,void 0,void 0,function*(){const{peerConnection:$}=this,{track:te}=this.config.baseConfig,ue=(()=>{try{return JSON.parse(q.getPayload())}catch{return}})();if(!ue)return void I.a.error("Received unparseable signal.");I.a.debug("Handling signal",{description:ue});const{sdp:ae,type:de}=ue;if(!ae||!de)return void I.a.warn("Received non-SDP signal");const{signalingState:me,connectionState:pe}=$;if(me!=="stable"||pe!=="connected")if($.remoteDescription)I.a.warn(`Received SDP after remote description was set: ${ae}`);else{if(de==="offer"){if(me!=="stable")return void I.a.warn("Received offer SDP when signaling is ongoing.");yield $.setRemoteDescription(ue);const ge=yield $.createAnswer();yield $.setLocalDescription(ge);const ce=q.clone();return te==null||te("Answer Received",ce),ce.setPayload(JSON.stringify(ge)),ce.setReceiverId(q.getSenderId()),ce.setSenderId(q.getReceiverId()),ce}if(de==="answer"){if(me==="stable")return void I.a.warn("Received answer SDP when signaling hasn't started.");yield $.setRemoteDescription(ue)}}else I.a.warn(`Received SDP when already connected: ${ae}`)})}send(q,$){const te=this.getChannelFromLabel($.channelLabel);te?this.sendOnChannel(te,q):I.a.warn("Send called with unexpected channel label",{channelLabel:$.channelLabel})}controlRemoteStream(q){this.sendSystemMessage(d(this.reliableStreamChannel),{type:"stream-control",streamControl:q})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:q,latestTtlStreamChannel:$,latestTryOnceStreamChannel:te,latestReliableStreamChannel:ue}=this;return(q==null?void 0:q.readyState)==="open"&&($==null?void 0:$.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(ue==null?void 0:ue.readyState)==="open"}close(){return ie(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.reassemblyTableCleanupTimeout&&clearInterval(this.reassemblyTableCleanupTimeout),this.streamsInfoUpdateTimeout&&clearInterval(this.streamsInfoUpdateTimeout),this.heartbeatTimeout&&clearInterval(this.heartbeatTimeout);const{peerConnection:q,reliableStreamChannel:$,latestTtlStreamChannel:te,latestTryOnceStreamChannel:ue,latestReliableStreamChannel:ae}=this;q.close(),$==null||$.close(),te==null||te.close(),ue==null||ue.close(),ae==null||ae.close()})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var q;return(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionCreatedTimestamp}setSessionCreatedTimestamp(q){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=q)}getSessionId(){var q;return(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionId}setSessionId(q){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=q,this.sessionMetrics=new ee(q,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var q;return(q=this.config.baseConfig)===null||q===void 0?void 0:q.remoteDeviceId}setRemoteDeviceId(q){this.config.baseConfig.remoteDeviceId=q}getSessionMetricsMessageCounts(){var q;return(q=this.sessionMetrics)===null||q===void 0?void 0:q.counts}getConnectionStatsInfo(){return ie(this,void 0,void 0,function*(){const{peerConnection:q}=this;if(!q)return;const $=yield q.getStats(null),te=[];$.forEach(pe=>{te.push(pe)});const ue=te.find(pe=>pe.type==="transport");if(!ue)return;const ae=te.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===ue.selectedCandidatePairId);if(!ae)return;const de=te.find(pe=>pe.id===ae.localCandidateId),me=te.find(pe=>pe.id===ae.remoteCandidateId);return de&&me&&(de.address=de.address||de.ip,me.address=me.address||me.ip,de.address!==void 0&&me.address!==void 0)?{transport:ue,localCandidate:de,remoteCandidate:me}:void 0})}initializeChannels(q){this.heartbeatChannel=q.createDataChannel("heartbeat",y),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=q.createDataChannel("stream.latest-ttl",Y),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=q.createDataChannel("stream.reliable",K),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=q.createDataChannel("stream.latest-reliable",H),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=q.createDataChannel("stream.latest-try-once",V),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var q,$,te;return ie(this,void 0,void 0,function*(){const{gotOffer:ue}=this,{peerConnection:ae,config:de}=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=(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionId;if(ue)return void I.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,ne(this.peerConnection))return void I.a.debug("Failed to generate offer because the peer connection was inactive.");const pe=de.baseConfig.track;ae.onicecandidate=()=>{this.hasIceCandidate=!0},ae.oniceconnectionstatechange=()=>ie(this,void 0,void 0,function*(){const Pe=ae.iceConnectionState;if(Pe==="connected"||Pe==="completed"){const Le=yield this.getConnectionStatsInfo(),Fe=Le?function(ze){const De=ze.localCandidate.candidateType,We=ze.remoteCandidate.candidateType;return De==="host"&&We==="host"?"local":De==="relay"||We==="relay"?"TURN":"STUN"}(Le):void 0;I.a.info(`ICE connection state changed to ${Pe}`,{sessionId:me,connectionStatsInfo:Le,iceMode:Fe}),pe==null||pe("ICE connection state change",{iceConnectionState:Pe,sessionId:me,connectionStatsInfo:Le,iceMode:Fe})}}),yield ae.setLocalDescription(yield ae.createOffer());const ge=new Date().getTime();for(;;){const Pe=new Date().getTime()-ge;if(Pe>this.connectTimeoutMs)return void I.a.debug("Failed to generate offer because ICE gathering timed out.");if(Pe>this.iceGatheringTimeoutMs&&this.hasIceCandidate){I.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe}),pe==null||pe("ICE gathering partially completed",{sessionId:me,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe});break}if(ae.iceGatheringState==="complete"){I.a.debug("ICE gathering complete",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe}),pe==null||pe("ICE gathering completed",{sessionId:me,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe});break}yield Object(u.a)(.1*c.a.second)}const ce=($=this.peerConnection.getConfiguration().iceServers)!==null&&$!==void 0?$:[];for(const Pe of ce)Pe.credentialType=void 0;const Te=JSON.stringify(ce),Ae=new L.Signal;return Ae.setPayload(JSON.stringify(ae.localDescription)),Ae.setSenderId(this.config.baseConfig.localPeerId),Ae.setReceiverId(this.config.baseConfig.remotePeerId),Ae.setIceServers(Te),Ae.setIceTransportPolicy((te=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&te!==void 0?te:"all"),this.config.baseConfig.sessionType!==void 0?Ae.setSessionType(this.config.baseConfig.sessionType):Ae.setSessionType(L.SessionType.TELEOP),I.a.debug("Sending offer signal with description",{description:Ae.getPayload()}),Ae})}getLanOffer(){return ie(this,void 0,void 0,function*(){const{peerConnection:q,gotOffer:$}=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($)return void I.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,ne(this.peerConnection))return void I.a.debug("Failed to generate offer because the peer connection was inactive.");yield q.setLocalDescription(yield q.createOffer());const te=new Date().getTime();for(;;){if(new Date().getTime()-te>this.iceGatheringTimeoutMs)return void I.a.debug("Failed to generate offer because ICE gathering timed out.");if(q.iceGatheringState==="complete")break;yield Object(u.a)(.1*c.a.second)}const ue=q.localDescription;if(ue)return I.a.debug("Sending LAN offer signal with description",{description:ue}),ue;I.a.error("Failed to generate LAN offer description")})}handleLanAnswer(q){return ie(this,void 0,void 0,function*(){const{peerConnection:$}=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 $.setRemoteDescription(q)})}getChannelFromLabel(q){switch(q){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(q,$){let te;try{te=Object(G.encode)(JSON.stringify($))}catch(ue){return void I.a.warn("Failed to encode RTC message",{error:ue})}try{q.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent($)}catch(ue){I.a.warn("Failed to send message to channel",{error:ue,channel:q.label})}}channelNotRecognized(q){return q!==this.latestTtlStreamChannel&&q!==this.latestReliableStreamChannel&&q!==this.latestTryOnceStreamChannel&&q!==this.reliableStreamChannel}setupChannel(q){q.onmessage=$=>{if(this.channelNotRecognized(q))return void I.a.warn("Received message on unrecognized data channel.");let te;try{te=JSON.parse(Object(G.decode)($.data))}catch(ue){return void I.a.warn("Received unparseable message on RTC stream data channel",{error:ue,channel:q.label})}te.communicationType==="message-chunk"?this.receiveChannelMessageChunk(q,te):this.receiveChannelMessage(q,te)},q.onerror=$=>{I.a.warn(`Channel error: ${$.error}`,{error:$.error,sessionId:this.getSessionId(),channelLabel:q.label})},q.onopen=()=>{I.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:q.label})},q.onclose=()=>{const $={bufferedAmount:q.bufferedAmount,sessionId:this.getSessionId(),channelLabel:q.label};this.closeCalled===!1?I.a.debug("Unexpected channel closed",$):I.a.debug("Channel closed",$)}}receiveChannelMessage(q,$){const{config:te}=this,{remotePeerId:ue}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),$=function(ae){switch(ae.header.stream.streamType){case"twist":{const{twist:de}=ae.payload;if(!de)throw Error("twist not in payload of RTC message with type twist");return{header:ae.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},de.linear),angular:Object.assign({x:0,y:0,z:0},de.angular)}}}}case"pose":{const{pose:de}=ae.payload;if(!de)throw Error("pose not in payload of RTC message with type pose");return{header:ae.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},de.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},de.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:de}=ae.payload;if(!de)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const me=new Array(36).fill(0);return de.covariance.forEach((pe,ge)=>{if(ge>=36)throw Error("covariance contains more than 36 elements");me[ge]=pe}),{header:ae.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},de.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},de.pose.rotation)},covariance:me}}}}case"point":{const{point:de}=ae.payload;if(!de)throw Error("point not in payload of RTC message with type point");return{header:ae.header,payload:{point:Object.assign({x:0,y:0,z:0},de)}}}default:return ae}}($),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived($),this.handleSystemMessage(q,$)||(q===this.latestTryOnceStreamChannel||q===this.latestTtlStreamChannel||q===this.latestReliableStreamChannel)&&!this.isLatestMessage($)||te.baseConfig.receive(ue,$)}receiveChannelMessageChunk(q,$){const te=this.reassemblyTable.get($.id)||[];if(te.push($),te.length===$.total){const ue=function(ae){const de=ae.sort((me,pe)=>me.seq<pe.seq?-1:1).map(me=>me.part).reduce((me,pe)=>me+pe);try{return JSON.parse(de)}catch{return void I.a.warn("Could not reassemble RTC message chunks")}}(te);return ue&&this.receiveChannelMessage(q,ue),void this.reassemblyTable.delete($.id)}this.reassemblyTable.set($.id,te),this.reassemblyTableLastTimestamp.set($.id,new Date().getTime())}handleSystemMessage(q,$){var te,ue;const{config:ae}=this,{baseConfig:de}=ae,{remotePeerId:me}=de;switch($.header.stream.streamType){case"ping":return this.sendSystemMessage(q,{type:"pong",timestamp:d($.payload.ping)}),!0;case"pong":{const pe=new Date().getTime()-d($.payload.pong);return this.pingTimeMs=pe,O.aggregate("rtc-ping-time",pe),!0}case"streams-info":{const{sessionMetrics:pe}=this,ge=(te=$.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ge&&(pe==null||pe.updateRemoteMessagesCounts($),(ue=de.onStreamsInfoUpdate)===null||ue===void 0||ue.call(de,me,ge),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(q,$){var te;const{localUserId:ue,localPeerId:ae}=this.config.baseConfig;if(q.readyState!=="open")return;const de={entityId:ue!=null?ue:ae,streamName:`$.${$.type}`,streamType:$.type};let me;switch($.type){case"ping":me={ping:new Date().getTime()};break;case"pong":me={pong:$.timestamp};break;case"stream-control":me={streamControl:$.streamControl};break;case"streams-info":me={streamsInfo:(te=this.sessionMetrics)===null||te===void 0?void 0:te.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(q,X(de,me))}isLatestMessage(q){const $=C(q.header.stream),te=(this.streamLatestTimestamp.get($)||0)<=q.header.created;return te&&this.streamLatestTimestamp.set($,q.header.created),te}}function Se(ye){var q,$;return{userId:(q=ye.getUserId())===null||q===void 0?void 0:q.getValue(),deviceId:($=ye.getDeviceId())===null||$===void 0?void 0:$.getValue(),organizationId:ye.getOrganizationId(),id:ye.getPeerId(),capabilities:[],capabilitySet:{}}}var we=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class Ee{constructor(q){this.config=q,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:$}=this;this.refreshInterval=Z({func:()=>we(this,void 0,void 0,function*(){try{yield this.update()}catch(te){I.a.warn("RTC refresh failed",{error:te})}}),delay:$,immediate:!0})}send(q,$,te){const ue=this.getActiveConnection(q);ue?ue.isReady()?ue.send($,te):I.a.warn("Send called with unready connection."):I.a.warn("Send called with no connection.")}controlRemoteStream(q,$){const te=this.getActiveConnection(q);te?te.isReady()?te.controlRemoteStream($):I.a.warn("controlRemoteStream called with unready connection."):I.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return we(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Se(this.localPeer)})}connect(q,$){var te,ue,ae;return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:de,signalingClient:me}=this.config,{localPeer:pe,receiveSignalStream:ge,iceServers:ce}=this;if(!pe||!ge||!ce)return void I.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(q))return void I.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(q))return void I.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(q,!0);const Te=new he(yield this.createRTCPeerConnection(ce,$),{baseConfig:{isOffer:!0,isLan:!1,receive:(De,We)=>this.config.receive(De,We),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(De,We)=>{var Be,ke;return(ke=(Be=this.config).onStreamsInfoUpdate)===null||ke===void 0?void 0:ke.call(Be,De,We)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=pe.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:pe.getPeerId(),remotePeerId:q,sessionType:$==null?void 0:$.sessionType},remoteConfig:{}},De=>this.onCustomDataChannel(q,De)),Ae=yield Te.getOffer();if(!Ae)return I.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(q);I.a.debug("Sending offer."),de==null||de("Sending offer",Ae);const Pe=new L.SendSignalRequest;Pe.setSignal(Ae);const Le=yield(()=>we(this,void 0,void 0,function*(){try{return yield me.sendSignal(Pe,yield this.getMetadata({}))}catch(De){I.a.warn("Error when sending signal",{error:De})}}))();if(!this.isOutgoingConnection.get(q))return void I.a.debug("No offer set after receiving offer signal response.");I.a.debug("Offer sent.");const Fe=(ue=Le==null?void 0:Le.getSessionId())===null||ue===void 0?void 0:ue.getValue(),ze=(ae=Le==null?void 0:Le.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Fe&&ze?(Te.setSessionId(Fe),Te.setSessionCreatedTimestamp(ze),this.isOutgoingConnection.delete(q),this.connections.push(Te),this.isConnectionInitiator.set(Te,!0),this.setupHandlers(Te),Fe):(I.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(q))})}connectLan(q){var $,te;return we(this,void 0,void 0,function*(){const ue=new B(q),ae=new he(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ge,ce)=>this.config.receive(ge,ce),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ge,ce)=>{var Te,Ae;return(Ae=(Te=this.config).onStreamsInfoUpdate)===null||Ae===void 0?void 0:Ae.call(Te,ge,ce)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=($=this.localPeer)===null||$===void 0?void 0:$.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:"lan_client",remotePeerId:q}},ge=>this.onCustomDataChannel(q,ge)),de=yield ae.getLanOffer();if(!de)return I.a.warn("Could not generate LAN offer"),!1;const me=yield ue.postLanRtcOffer({offer:JSON.stringify(de)}),pe=new RTCSessionDescription(JSON.parse(me.answer));return yield ae.handleLanAnswer(pe),this.localConnections.push(ae),this.isConnectionInitiator.set(ae,!0),Object(E.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(q,$,te,ue,ae){const de=this.getActiveConnection(q);if(de&&this.isConnectionInitiator.has(de)){const pe=de.peerConnection.createDataChannel("custom."+$,te);return ue&&(pe.binaryType="arraybuffer"),ae(q,pe),()=>{}}const me=(pe,ge)=>{q===pe&&ge.label==="custom."+$&&ae(q,ge)};return this.peerDataChannelListeners.push(me),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==me)}}onCustomDataChannel(q,$){this.peerDataChannelListeners.forEach(te=>te(q,$))}getConnectionStatus(q){if(this.isOutgoingConnection.get(q))return"connecting";const $=this.getActiveConnection(q);return $?$.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(q){return we(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);if($)return yield $.getConnectionStatsInfo()})}disconnect(q){return we(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);$&&(yield $.close())})}getPeers(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:q}=this.config,$=yield(()=>we(this,void 0,void 0,function*(){try{return yield q.getPeers(new L.GetPeersRequest,yield this.getMetadata({}))}catch(ae){I.a.warn("Error when getting peers",{error:ae})}}))();if(!$)return[];const te=$.getPeersList();if(!te)return[];const ue=ae=>{var de,me;return(me=(de=ae.getPeerCreatedTimestamp())===null||de===void 0?void 0:de.getValue())!==null&&me!==void 0?me:0};return te.sort((ae,de)=>ue(de)-ue(ae)).map(ae=>Se(ae))})}getSessions(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:q}=this.config,$=yield(()=>we(this,void 0,void 0,function*(){try{return yield q.getPeers(new L.GetPeersRequest,yield this.getMetadata({}))}catch(ae){I.a.warn("Error when getting peers",{error:ae})}}))();if(!$)return{};const te=$.getPeersList(),ue={};for(const ae of te)ue[ae.getPeerId()]=ae.getSessionIdsList();return ue})}getPing(q){const $=this.getActiveConnection(q);if($)return $.getPing();I.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(q){const $=this.getActiveConnection(q);if($)return $.getLastMessageTimestamp();I.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(q){const $=this.getActiveConnection(q);if($)return $.getSessionMetricsMessageCounts();I.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:q,receiveSignalStream:$,iceServers:te}=this;return!!(q&&$&&te)}shutdown(){return we(this,void 0,void 0,function*(){I.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const q=this.connections;this.connections=[],yield this.closeConnections(q);const{localPeer:$}=this;if(!$||this.config.lanOnlyMode)return;const{signalingClient:te}=this.config;yield(()=>we(this,void 0,void 0,function*(){try{const ue=new L.DeletePeerRequest;ue.setPeerId($.getPeerId()),yield te.deletePeer(ue,yield this.getMetadata({}))}catch(ue){return void I.a.warn("Error deleting local peer",{error:ue})}}))()})}createPeer(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:q}=this.config,$=yield(()=>we(this,void 0,void 0,function*(){try{return yield q.createPeer(new L.CreatePeerRequest,yield this.getMetadata({}))}catch(ue){throw new Error(`Was not able to create peer: ${JSON.stringify(ue)}`)}}))(),te=$==null?void 0:$.getPeer();if(!te)throw new Error("Response did not provide peer.");return this.localPeer=te})}createReceiveSignalStream(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:q}=this.config,{localPeer:$,iceServers:te}=this;if(!$||!te)return;const{receiveSignalStream:ue}=this;ue&&ue.cancel();const ae=new L.ReceiveSignalStreamRequest;ae.setPeerId($.getPeerId());const de=yield(()=>we(this,void 0,void 0,function*(){try{return q.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(me){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(me)}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",me=>we(this,void 0,void 0,function*(){var pe,ge,ce,Te;const Ae=me.getSignal(),Pe=(pe=Ae==null?void 0:Ae.getSessionId())===null||pe===void 0?void 0:pe.getValue(),Le=Ae==null?void 0:Ae.getSenderId(),Fe=Ae==null?void 0:Ae.getReceiverId(),ze=(ge=Ae==null?void 0:Ae.getSessionCreatedTimestamp())===null||ge===void 0?void 0:ge.getValue();if(!(Ae&&Pe&&Le&&Fe&&ze))return void I.a.warn("Received signal with missing information.");const De=this.getActiveConnection(Le);if(De)if(De.getSessionId()!==Pe){if(I.a.debug("Received signal: different session for a peer we're already connected to."),(De.getSessionCreatedTimestamp()||0)>ze)return;const We=new he(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,ke)=>this.config.receive(Be,ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,ke)=>{var qe,Ge;return(Ge=(qe=this.config).onStreamsInfoUpdate)===null||Ge===void 0?void 0:Ge.call(qe,Be,ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(Te=$.getUserId())===null||Te===void 0?void 0:Te.getValue(),remotePeerId:Le},remoteConfig:{sessionId:Pe,sessionCreatedTimestamp:ze}},Be=>this.onCustomDataChannel(Le,Be));yield We.handleSignal(Ae),this.connections.push(We)}else I.a.debug("Received signal: for an existing connection."),yield De.handleSignal(Ae);else{I.a.debug("Received signal: new connection.");const We=new he(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,ke)=>this.config.receive(Be,ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,ke)=>{var qe,Ge;return(Ge=(qe=this.config).onStreamsInfoUpdate)===null||Ge===void 0?void 0:Ge.call(qe,Be,ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(ce=$.getUserId())===null||ce===void 0?void 0:ce.getValue(),remotePeerId:Le},remoteConfig:{sessionId:Pe,sessionCreatedTimestamp:ze}},Be=>this.onCustomDataChannel(Le,Be));yield We.handleSignal(Ae),this.connections.push(We)}})),de.on("end",()=>{de.cancel(),this.receiveSignalStream=void 0}),de.on("error",me=>{switch(me.code){case k.StatusCode.CANCELLED:case k.StatusCode.UNAVAILABLE:case k.StatusCode.UNKNOWN:I.a.debug("Receive signal stream error",{error:me});break;case k.StatusCode.UNAUTHENTICATED:I.a.warn("Receive signal stream error",{error:me});break;default:I.a.error("Receive signal stream error",{error:me})}de.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=de})}createRTCPeerConnection(q,$){var te;return we(this,void 0,void 0,function*(){const ue=$==null?void 0:$.rtcIceTransportPolicies,ae=$!=null&&$.rtcIceServerProtocol?[$==null?void 0:$.rtcIceServerProtocol]:void 0,de=q.map(pe=>Object.assign(Object.assign({},pe),{urls:typeof pe.urls=="string"?[pe.urls]:pe.urls})).map(pe=>Object.assign(Object.assign({},pe),{urls:pe.urls.filter(ge=>{const ce=(ue===void 0||ue.some(Te=>((Ae,Pe)=>{switch(Pe){case"stun":return/^stuns?:/.test(Ae);case"turn":return/^turns?:/.test(Ae)}})(ge,Te)))&&(ae===void 0||ae.some(Te=>((Ae,Pe)=>Ae.endsWith(`transport=${Pe}`))(ge,Te)));return ce||I.a.debug(`Ignoring ICE server: ${ge}`),ce})})).filter(({urls:pe})=>pe.filter(ge=>ge).length>0),me=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!me)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new me(Object.assign({iceServers:de,iceTransportPolicy:(ue==null?void 0:ue.length)===1&&ue[0]==="turn"?"relay":"all"},$))})}closeConnections(q){return we(this,void 0,void 0,function*(){const $=yield R(q.map(te=>we(this,void 0,void 0,function*(){yield te.close()})));for(const te of $)I.a.warn("Request to close session failed",{error:te})})}getActiveConnection(q){return this.getConnections().find($=>$.getRemotePeerId()===q&&$.isActive())}update(){var q;return we(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:$}=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:te}=this,ue=this.connections.filter(me=>me.getSessionId).map(me=>d(me.getSessionId()));te.setSessionIdsList(ue);const ae=new L.RefreshPeerRequest;ae.setPeer(te);try{yield $.refreshPeer(ae,yield this.getMetadata({}))}catch(me){me.code===k.StatusCode.NOT_FOUND?(I.a.warn("Peer expired, creating new peer",{peerId:te.getPeerId()}),yield this.reset()):I.a.warn("Error calling RefreshPeer",{error:me})}const de=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((q=de.find(pe=>pe.id===me.getRemotePeerId()))===null||q===void 0?void 0:q.deviceId)})}reset(){return we(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 we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:q,iceServersTtl:$}=this,te=new Date().getTime();if(!q||te-q>$)try{const ue=(yield this.config.signalingClient.getIceServers(new L.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(ue),this.iceServersLastUpdate=te}catch(ue){I.a.warn("Error in updateIceServers",{error:ue})}})}setupHandlers(q){const{peerConnection:$}=q,te=q.getSessionCreatedTimestamp();$.onconnectionstatechange=()=>we(this,void 0,void 0,function*(){const ue=$.connectionState;if(te)switch(ue){case"connected":O.aggregate("rtc-connect-time",new Date().getTime()-te);break;case"failed":O.increment("rtc-connect-failed")}})}getMetadata(q){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:$}=this.config,{grpcCallDeadline:te}=this,{hasDeadline:ue}=q,ae=ue===!1?void 0:new Date().getTime()+te;return{authorization:yield $(),deadline:ae}})}}},,function(e,t,r){r.r(t),r.d(t,"LogClient",function(){return l});var n=r(25),o=function(s,i,c,u){return new(c||(c=Promise))(function(b,A){function _(S){try{f(u.next(S))}catch(w){A(w)}}function v(S){try{f(u.throw(S))}catch(w){A(w)}}function f(S){var w;S.done?b(S.value):(w=S.value,w instanceof c?w:new c(function(P){P(w)})).then(_,v)}f((u=u.apply(s,i||[])).next())})};class l extends n.a{log(i){return o(this,void 0,void 0,function*(){yield this.fetch("logs",{method:"POST",body:JSON.stringify({logs:i}),allowUnsafeRetries:!0})})}}}])})})(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$1=new URLSearchParams("");typeof window!="undefined"&&(urlParams$1=new URLSearchParams(window.location.search));const envDev=urlParams$1.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$1.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");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 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,r){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:n,before:t,after:r||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,r){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:n,channel:t,data:r})}static setupModuleMenus(t){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:r,menus:t})}static addMenuListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_menu_item_clicked"&&t(n.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="auth_token"&&t(n.token)})}static addModuleDataListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_data"&&t({streams:n.streams,time:n.time,queryRange:n.queryRange})})}static addChannelDataListener(t,r){window.addEventListener("message",n=>{const o=n.data;o.type==="channel_data"&&o.channel===t&&r({source:o.source,data:o.data})})}}const Ce=class{static async login(t,r){try{const n=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:r}),headers:{"Content-Type":"application/json"}}),o=await n.json();if(n.status!==200)throw new Error(o.message);return await Ce.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(n){return Ce.waitingForAuth.forEach(o=>o(!1)),Ce.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let o;if(Ce.isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(Ce.currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(Ce.currentOrganization=n["custom:organization_id"]),Ce.isShareToken||(o=n.sub),n["formant:claims"]&&n["formant:claims"].userId&&(o=n["formant:claims"].userId),o){const l=await fetch(`${FORMANT_API_URL}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await l.json();if(l.status!==200)throw new Error(s.message);Ce.currentUser=s}Ce.token=t,Ce.waitingForAuth.forEach(l=>l(!0))}catch(o){console.error(o),Ce.waitingForAuth.forEach(l=>l(!1))}Ce.waitingForAuth=[],r&&(Ce.refreshToken=r,setInterval(async()=>{if(Ce.refreshToken){const l=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Ce.refreshToken})})).json();Ce.token=l.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Ce.token!==void 0}static getCurrentUser(){return Ce.currentUser}static async waitTilAuthenticated(){return Ce.token!==void 0?!0:new Promise(t=>{Ce.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Ce;Re(Authentication,"token"),Re(Authentication,"refreshToken"),Re(Authentication,"currentUser"),Re(Authentication,"currentOrganization"),Re(Authentication,"isShareToken",!1),Re(Authentication,"defaultDeviceId"),Re(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Re(this,"ready",!1);Re(this,"listeners",[]);Re(this,"openListeners",[]);Re(this,"closeListeners",[]);Re(this,"errorListeners",[]);Re(this,"binaryListeners",[]);Re(this,"error");Re(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(r=>r())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(r=>r())},this.dataChannel.onerror=r=>{console.error(r),this.error="An error occurred in DataChannel",this.errorListeners.forEach(n=>n(r))},this.dataChannel.onmessage=r=>{this.listeners.forEach(n=>{const o=new Uint8Array(r.data),l=this.decoder.decode(o);n(l)}),this.binaryListeners.forEach(n=>{n(new Uint8Array(r.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(r=>r!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(r=>r!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(r=>r!==t)}async waitTilReady(){return this.ready?!0:new Promise((r,n)=>{let o=window.setInterval(()=>{this.ready&&(window.clearInterval(o),r(!0)),this.error&&n(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 r=this.listeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(r,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const r=this.binaryListeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(r,1)}}class CaptureStream{constructor(t){Re(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=n.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,r){Re(this,"currentListeners",[]);Re(this,"onRealtimeMessage",(t,r)=>{r.payload.jointState&&this.currentListeners.forEach(n=>{r.payload.jointState&&n(r.payload.jointState)})});this.device=t,this.config=r}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,r,n){Re(this,"channel");Re(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}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);Re(this,"RESPONSE_SUCCESS_BYTE",0);Re(this,"decoder",new TextDecoder)}generateBinaryId(){const r=new Uint8Array(16);for(let n=0;n<r.length;n++)r[n]=Math.floor(Math.random()*256);return r}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(r=>{const o=r.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const l=r.slice(16);if(l.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,l)})}async request(r){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:o,timeout:l}=this;await n.waitTilReady();const s=this.generateBinaryId(),i=s.toString();o.set(i,!0),n.sendBinary(new Uint8Array([...s,...r]));const c=new Date().getTime();for(;new Date().getTime()<c+l;)if(await delay(50),o.has(i)){const u=o.get(i);if(u!==!0){o.delete(i);const b=u[0]===this.RESPONSE_SUCCESS_BYTE,A=u.slice(1);if(b)return A;throw console.error({name:"AdapterError",message:this.decoder.decode(A)}),new Error("Binary request datachannel adapter error")}}throw o.delete(i),console.error({name:"TimeoutError",message:`Request timed out after ${l/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 r=JSON.parse(t),{id:n,data:o,error:l}=r;if(!n)throw new Error("Invalid response");if(!o&&!l)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,r)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:n,timeout:o}=this;await r.waitTilReady();const l=this.generateTextId();n.set(l,!0),r.send(JSON.stringify({id:l,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+o;)if(await delay(50),n.has(l)){const i=n.get(l);if(i!==!0){n.delete(l);const{data:c,error:u}=i;if(c)return c;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw n.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}const SessionType={Teleop:1,Observe:3};class Device{constructor(t,r,n){Re(this,"rtcClient");Re(this,"remoteDevicePeerId");Re(this,"realtimeListeners",[]);Re(this,"handleMessage",(t,r)=>{this.realtimeListeners.forEach(n=>n(t,r))});this.id=t,this.name=r,this.organizationId=n}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 r=await t.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const n=r.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${n}`,{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({fileId:[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}`);{const r=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});for(;!r.isReady();)await delay(100);const o=(await r.getPeers()).find(l=>l.deviceId===this.id);if(!o)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=o.id,await r.connect(this.remoteDevicePeerId,t||{sessionType:SessionType.Teleop});r.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=r}}async sendRealtimeMessage(t,r={channelLabel:"stream.reliable"}){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();n.send(defined(o).id,t,r)}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const r=this.realtimeListeners.indexOf(t);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeAudioStreams(){var n,o,l,s,i,c;const t=await this.getConfiguration(),r=[];for(const u of(o=(n=t.teleop)==null?void 0:n.hardwareStreams)!=null?o:[])u.rtcStreamType==="audio-chunk"&&r.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="audio_common_msgs/AudioData"&&r.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="audio-chunk"&&r.push({name:u.name});return r}async getRealtimeVideoStreams(){var n,o,l,s,i,c;const t=await this.getConfiguration(),r=[];for(const u of(o=(n=t.teleop)==null?void 0:n.hardwareStreams)!=null?o:[])u.rtcStreamType==="h264-video-frame"&&r.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="formant/H264VideoFrame"&&r.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="h264-video-frame"&&r.push({name:u.name});return r}async getRealtimeManipulators(){var n;const t=await this.getConfiguration(),r=[];for(const o of(n=t.teleop.rosStreams)!=null?n:[])o.topicType=="sensor_msgs/JointState"&&r.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 r}async startListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(t,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();n.controlRemoteStream(defined(o).id,{streamName:t,setAudioFormat:r})}async disableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const r=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(n=>n.deviceId===this.id);return defined(r,"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(),r=await Fleet.getRealtimeSessions(),n=t.find(o=>o.deviceId===this.id);return n?r[n.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(n=>({name:n.name,id:n.id,command:n.command,description:n.description,parameterEnabled:n.parameterEnabled,parameterValue:n.parameterValue,parameterMeta:n.parameterMeta,enabled:n.enabled}))}async sendCommand(t,r,n,o){var u;const s=(await this.getAvailableCommands()).find(b=>b.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let i;if(r===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=r;let c={value:i,scrubberTime:(n||new Date).toISOString(),meta:st(st({},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:(u=Authentication.currentUser)==null?void 0:u.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{n.createCustomDataChannel(defined(o).id,t,st({ordered:!0},r),!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,r=3e3){return new TextRequestDataChannel(this,t,r)}createCustomBinaryRequestDataChannel(t,r=3e3){return new BinaryRequestDataChannel(this,t,r)}async createCaptureStream(t){const n=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(n)}async getTelemetry(t,r,n,o){return await Fleet.getTelemetry(this.id,t,r,n,o)}async getTelemetryStreams(){var i,c;const t=await this.getConfiguration(),r=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}}),n=[],o=[];return(c=(i=t.telemetry)==null?void 0:i.streams)==null||c.forEach(u=>{u.disabled!==!0&&n.push(u.name),u.onDemand===!0&&o.push(u.name)}),console.log(o),(await r.json()).items.filter(u=>!n.includes(u)).map(u=>({name:u,onDemand:o.includes(u)}))}async createInterventionRequest(t,r,n,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:r,time:new Date().toISOString(),deviceId:this.id,tags:o,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,r,n){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:r,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Re(this,"rtcClient");Re(this,"remoteDevicePeerId");Re(this,"realtimeListeners",[]);Re(this,"id");Re(this,"handleMessage",(t,r)=>{this.realtimeListeners.forEach(n=>n(t,r))});this.peerUrl=t}async getLatestTelemetry(){const r=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(r).map(([o,l])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:l,currentValueTime:l.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 r=new dist.exports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage});for(await r.connectLan(this.peerUrl);r.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=r}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const r=this.realtimeListeners.indexOf(t);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeVideoStreams(){var n,o,l;const t=await this.getConfiguration(),r=[];for(const s of(n=t.teleop.hardwareStreams)!=null?n:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});for(const s of(o=t.teleop.rosStreams)!=null?o:[])s.topicType=="formant/H264VideoFrame"&&r.push({name:s.topicName});for(const s of(l=t.teleop.customStreams)!=null?l:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});return r}async getRealtimeManipulators(){var n;const t=await this.getConfiguration(),r=[];for(const o of(n=t.teleop.rosStreams)!=null?n:[])o.topicType=="sensor_msgs/JointState"&&r.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 r}async startListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).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,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{n.createCustomDataChannel(defined(o).id,t,st({ordered:!0},r),!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,r=3e3){return new TextRequestDataChannel(this,t,r)}createCustomBinaryRequestDataChannel(t,r=3e3){return new BinaryRequestDataChannel(this,t,r)}}const Me=class{static async setDefaultDevice(t){Me.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Me.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===Me.defaultDeviceId).name,l=new Device(Me.defaultDeviceId,o,defined(Authentication.currentOrganization));return Me.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const r=new PeerDevice(t);return r.id=await r.getDeviceId(),r}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=n.name,l=new Device(t,o,n.organizationId);return Me.knownContext.push(new WeakRef(l)),l}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=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 r.items,r.items.map(n=>new Device(n.id,n.name,n.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(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 Me.getDevices()).filter(l=>n.includes(l.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 n=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await Me.getDevices()).filter(l=>n.includes(l.id))}static async getLatestTelemetry(t){let r=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:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,r,n,o,l){let s=t;Array.isArray(t)||(s=[t]);let i=r;return Array.isArray(r)||(i=[r]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:n.toISOString(),tags:l}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const n=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(n.fileUrls.length===0)throw new Error("File not found");return n.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=Me;Re(Fleet,"defaultDeviceId"),Re(Fleet,"knownContext",[]);class KeyValue{static async set(t,r){try{const n=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),o=await n.json();if(n.status!==200)throw new Error(o.message)}catch(n){throw n}}static async get(t){try{const r=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await r.json();if(r.status!==200)throw new Error(n.message);return n.value}catch(r){throw r}}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}}),r=await t.json();if(t.status!==200)throw new Error(r.message);return r.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(r){throw r}}}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,r){Re(this,"muted",!1);Re(this,"hasReceivedData",!1);Re(this,"audioContext");Re(this,"chunks",[]);Re(this,"isPlaying",!1);Re(this,"startTime",0);Re(this,"lastChunkOffset",0);Re(this,"bufferSize",3);Re(this,"receive",async t=>{var s;const r=(s=t.payload.audioChunk)==null?void 0:s.chunk_data;if(!r)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:n,muted:o}=this;if(!n||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const l=stringToArrayBuffer(r);try{await n.decodeAudioData(l.buffer,this.scheduleChunk)}catch(i){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:i}),this.changeAudioWireFormat("wav")}});Re(this,"scheduleChunk",t=>{const{audioContext:r}=this;if(!r)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const n=this.createChunk(t);!n||!n.buffer||(this.isPlaying===!1&&(this.startTime=r.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),n.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=n.buffer.duration,this.chunks.push(n))});this.device=t,this.stream=r,this.device.startListeningToRealtimeDataStream(r),this.device.addRealtimeListener((o,l)=>{this.receive(l)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const n=window.AudioContext||window.webkitAudioContext;this.audioContext=new n}async play(){var t,r;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((r=this.audioContext)==null?void 0:r.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:r}=this;if(!r)return;const n=r.createBufferSource();return n.buffer=t,n.connect(r.destination),n.loop=!1,n.onended=o=>{this.chunks.splice(this.chunks.indexOf(n),1),this.chunks.length===0&&(this.isPlaying=!1)},n}changeAudioWireFormat(t){const{stream:r}=this;(async()=>await this.device.changeStreamAudioType(r.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.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.eventTypes=eventTypes,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.severities=severities,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
44
|
+
`),Error.captureStackTrace(this,n)}}e.exports=o=>{if(o.length>2)throw new n(o);function l(i={}){this.options=i}function s(i){return new l(i)}return l.prototype.transform=o,s.Format=l,s}},function(e,t,r){function n(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 u=i[c];u.enumerable=u.enumerable||!1,u.configurable=!0,"value"in u&&(u.writable=!0),Object.defineProperty(s,u.key,u)}}var l=r(85);e.exports=function(){function s(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};n(this,s),this.loggers=new Map,this.options=u}var i,c;return i=s,(c=[{key:"add",value:function(u,b){var A=this;if(!this.loggers.has(u)){var _=(b=Object.assign({},b||this.options)).transports||this.options.transports;b.transports=_?_.slice():[];var v=l(b);v.on("close",function(){return A._delete(u)}),this.loggers.set(u,v)}return this.loggers.get(u)}},{key:"get",value:function(u,b){return this.add(u,b)}},{key:"has",value:function(u){return!!this.loggers.has(u)}},{key:"close",value:function(u){var b=this;if(u)return this._removeLogger(u);this.loggers.forEach(function(A,_){return b._removeLogger(_)})}},{key:"_removeLogger",value:function(u){this.loggers.has(u)&&(this.loggers.get(u).close(),this._delete(u))}},{key:"_delete",value:function(u){this.loggers.delete(u)}}])&&o(i.prototype,c),s}()},function(e,t,r){(function(n){const o=r(49),l=/^([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){let u,b,A=!1,_=!1;function v(w,P){let N=`"${i}" ${P}`;throw w&&(N=`${N}, but is set to "${w}"`),b&&(N=`${N}. An example of a valid value would be: ${b}`),new o(N)}function f(w){return function(){let P=s[i];if(P===void 0)if(u===void 0&&_)v(void 0,"is a required variable, but it was not set");else{if(u===void 0)return;P=u}_&&P.trim().length===0&&v(void 0,"is a required variable, but its value was empty"),A&&(P.match(l)||v(P,"should be a valid base64 string if using convertFromBase64"),P=n.from(P,"base64").toString());const N=[P].concat(Array.prototype.slice.call(arguments));try{return w.apply(w,N)}catch(T){v(P,T.message)}}}const S={asArray:f(r(211)),asBoolStrict:f(r(212)),asBool:f(r(213)),asPortNumber:f(r(214)),asEnum:f(r(215)),asFloatNegative:f(r(216)),asFloatPositive:f(r(217)),asFloat:f(r(51)),asIntNegative:f(r(218)),asIntPositive:f(r(91)),asInt:f(r(50)),asJsonArray:f(r(219)),asJsonObject:f(r(220)),asJson:f(r(52)),asString:f(r(34)),asUrlObject:f(r(92)),asUrlString:f(r(221)),convertFromBase64:function(){return A=!0,S},default:function(w){if(typeof w=="number")u=w.toString();else if(Array.isArray(w)||typeof w=="object"&&w!==null)u=JSON.stringify(w);else{if(typeof w!="string")throw new o("values passed to default() must be of Number, String, Array, or Object type");u=w}return S},required:function(w){return _=w===void 0||w,S},example:function(w){return b=w,S}};return Object.entries(c).forEach(([w,P])=>{S[w]=f(P)}),S}}).call(this,r(4).Buffer)},function(e,t,r){const n=r(34);e.exports=function(o,l){return l=l||",",o.length?n(o).split(l).filter(Boolean):[]}},function(e,t,r){e.exports=function(n){const o=n.toLowerCase();if(o!=="false"&&o!=="true")throw new Error('should be either "true", "false", "TRUE", or "FALSE"');return o!=="false"}},function(e,t,r){e.exports=function(n){const o=n.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,r){const n=r(91);e.exports=function(o){var l=n(o);if(l>65535)throw new Error("cannot assign a port number greater than 65535");return l}},function(e,t,r){const n=r(34);e.exports=function(o,l){const s=n(o);if(l.indexOf(s)<0)throw new Error(`should be one of [${l.join(", ")}]`);return s}},function(e,t,r){const n=r(51);e.exports=function(o){const l=n(o);if(l>0)throw new Error("should be a negative float");return l}},function(e,t,r){const n=r(51);e.exports=function(o){const l=n(o);if(l<0)throw new Error("should be a positive float");return l}},function(e,t,r){const n=r(50);e.exports=function(o){const l=n(o);if(l>0)throw new Error("should be a negative integer");return l}},function(e,t,r){const n=r(52);e.exports=function(o){var l=n(o);if(!Array.isArray(l))throw new Error("should be a parseable JSON Array");return l}},function(e,t,r){const n=r(52);e.exports=function(o){var l=n(o);if(Array.isArray(l))throw new Error("should be a parseable JSON Object");return l}},function(e,t,r){const n=r(92);e.exports=function(o){return n(o).toString()}},function(e,t,r){(function(n){(function(){var o,l,s,i,c,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:n!=null&&n.hrtime?(e.exports=function(){return(o()-c)/1e6},l=n.hrtime,i=(o=function(){var b;return 1e9*(b=l())[0]+b[1]})(),u=1e9*n.uptime(),c=i-u):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,r(2))},function(e,t,r){var n,o,l=r(96),s=r(97),i=0,c=0;e.exports=function(u,b,A){var _=b&&A||0,v=b||[],f=(u=u||{}).node||n,S=u.clockseq!==void 0?u.clockseq:o;if(f==null||S==null){var w=l();f==null&&(f=n=[1|w[0],w[1],w[2],w[3],w[4],w[5]]),S==null&&(S=o=16383&(w[6]<<8|w[7]))}var P=u.msecs!==void 0?u.msecs:new Date().getTime(),N=u.nsecs!==void 0?u.nsecs:c+1,T=P-i+(N-c)/1e4;if(T<0&&u.clockseq===void 0&&(S=S+1&16383),(T<0||P>i)&&u.nsecs===void 0&&(N=0),N>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");i=P,c=N,o=S;var R=(1e4*(268435455&(P+=122192928e5))+N)%4294967296;v[_++]=R>>>24&255,v[_++]=R>>>16&255,v[_++]=R>>>8&255,v[_++]=255&R;var d=P/4294967296*1e4&268435455;v[_++]=d>>>8&255,v[_++]=255&d,v[_++]=d>>>24&15|16,v[_++]=d>>>16&255,v[_++]=S>>>8|128,v[_++]=255&S;for(var I=0;I<6;++I)v[_+I]=f[I];return b||s(v)}},function(e,t,r){var n=r(96),o=r(97);e.exports=function(l,s,i){var c=s&&i||0;typeof l=="string"&&(s=l==="binary"?new Array(16):null,l=null);var u=(l=l||{}).random||(l.rng||n)();if(u[6]=15&u[6]|64,u[8]=63&u[8]|128,s)for(var b=0;b<16;++b)s[c+b]=u[b];return s||o(u)}},function(e,t,r){(function(n){(function(o){function l(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(l.prototype,"encoding",{value:"utf-8"}),l.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 u=i.length,b=0,A=Math.max(32,u+(u>>1)+7),_=new Uint8Array(A>>3<<3);c<u;){var v=i.charCodeAt(c++);if(55296<=v&&56319>=v){if(c<u){var f=i.charCodeAt(c);(64512&f)==56320&&(++c,v=((1023&v)<<10)+(1023&f)+65536)}if(55296<=v&&56319>=v)continue}if(b+4>_.length&&(A+=8,A=(A*=1+c/i.length*2)>>3<<3,(f=new Uint8Array(A)).set(_),_=f),(4294967168&v)==0)_[b++]=v;else{if((4294965248&v)==0)_[b++]=v>>6&31|192;else if((4294901760&v)==0)_[b++]=v>>12&15|224,_[b++]=v>>6&63|128;else{if((4292870144&v)!=0)continue;_[b++]=v>>18&7|240,_[b++]=v>>12&63|128,_[b++]=v>>6&63|128}_[b++]=63&v|128}}return _.slice(0,b)},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 u=(i=new Uint8Array(i)).length,b=[];c<u;){var A=i[c++];if(A===0)break;if((128&A)==0)b.push(A);else if((224&A)==192){var _=63&i[c++];b.push((31&A)<<6|_)}else if((240&A)==224){_=63&i[c++];var v=63&i[c++];b.push((31&A)<<12|_<<6|v)}else(248&A)==240&&(65535<(A=(7&A)<<18|(_=63&i[c++])<<12|(v=63&i[c++])<<6|63&i[c++])&&(A-=65536,b.push(A>>>10&1023|55296),A=56320|1023&A),b.push(A))}return String.fromCharCode.apply(null,b)},o.TextEncoder=l,o.TextDecoder=s})(typeof window!="undefined"?window:n!==void 0?n:this)}).call(this,r(5))},function(e,t,r){r.r(t),r.d(t,"AuthClient",function(){return l}),r.d(t,"RtcSignalingClient",function(){return i}),r.d(t,"Credentials",function(){return P}),r.d(t,"SignalingPromiseClient",function(){return N.SignalingPromiseClient}),r.d(t,"IRtcClientConfiguration",function(){}),r.d(t,"IRtcConnectConfiguration",function(){}),r.d(t,"IRtcConnectionStatsInfo",function(){}),r.d(t,"IRtcSendConfiguration",function(){}),r.d(t,"IRtcSessionMetricsMessageCounts",function(){}),r.d(t,"IRtcStreamMessage",function(){}),r.d(t,"IStreamControl",function(){}),r.d(t,"RtcClient",function(){return Ee}),r.d(t,"createRtcStreamMessage",function(){return X}),r.d(t,"IRtcStream",function(){}),r.d(t,"IRtcStreamPayload",function(){});var n=r(25),o=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class l extends n.a{adminSignup(q,$){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/admin-signup",{token:$,method:"POST",body:JSON.stringify(q)})})}login(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login",{method:"POST",body:JSON.stringify(q),allowUnsafeRetries:!0})})}loginWithGoogleToken(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/login-google",{method:"POST",body:JSON.stringify(q),allowUnsafeRetries:!0})})}refresh(q,$){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:q,tokenExpirationSeconds:$}),allowUnsafeRetries:!0})})}respondToNewPasswordRequiredChallenge(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/respond-to-new-password-required-challenge",{method:"POST",body:JSON.stringify(q)})})}forgotPassword(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/forgot-password",{method:"POST",body:JSON.stringify({email:q})})})}confirmForgotPassword(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/confirm-forgot-password",{method:"POST",body:JSON.stringify(q)})})}resendInvitation(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/resend-invitation",{method:"POST",body:JSON.stringify({email:q})})})}changePassword({token:q,refreshToken:$,currentPassword:te,newPassword:ue}){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/change-password",{token:q,method:"POST",body:JSON.stringify({refreshToken:$,currentPassword:te,newPassword:ue})})})}getDeviceCredentials(q){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/device-credentials",{token:q,method:"POST",allowUnsafeRetries:!0})})}impersonate(q,$){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/impersonate",{token:q,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({userId:$})})})}createServiceAccount(q,$,te,ue){return o(this,void 0,void 0,function*(){return yield this.fetch("auth/service-account",{token:q,method:"POST",allowUnsafeRetries:!0,body:JSON.stringify({name:$,roleId:te,tags:ue})})})}getFeatures(q){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:q})).features})}}var s=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class i extends n.a{createPeer(q,$){return s(this,void 0,void 0,function*(){return yield this.fetch("peers",{token:q,method:"POST",body:JSON.stringify($)})})}getPeers(q){return s(this,void 0,void 0,function*(){return(yield this.fetch("peers",{token:q})).items})}refreshPeer(q,$){return s(this,void 0,void 0,function*(){yield this.fetch(`peers/${$}/refresh`,{token:q,method:"POST",allowUnsafeRetries:!0})})}createSession(q,$){return s(this,void 0,void 0,function*(){return yield this.fetch("sessions",{token:q,method:"POST",body:JSON.stringify($)})})}refreshSession(q,$){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${$}/refresh`,{token:q,method:"POST",allowUnsafeRetries:!0})})}deleteSession(q,$){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${$}`,{token:q,method:"DELETE",allowUnsafeRetries:!0})})}getSessions(q){return s(this,void 0,void 0,function*(){return(yield this.fetch("sessions",{token:q})).items})}getIceServers(q){return s(this,void 0,void 0,function*(){return(yield this.fetch("ice-servers",{token:q})).items})}addSignals(q,$,te){return s(this,void 0,void 0,function*(){yield this.fetch(`sessions/${$}/add-signals`,{token:q,method:"POST",body:JSON.stringify(te)})})}takeSignals(q,$){return s(this,void 0,void 0,function*(){return(yield this.fetch(`sessions/${$}/take-signals`,{token:q,method:"POST"})).items})}}var c=r(1),u=r(11),b=r(35),A=r.n(b),_=r(102),v=r.n(_),f=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class S extends class{constructor(q){this.cache=new v.a(Object.assign(Object.assign({},q.dispose||q.disposeAfter?{ttlAutopurge:!0}:{}),q)),this.stringify=q.fastStringify?JSON.stringify:A.a}set(q,$,te){const ue=this.stringify(q);if(!this.cache.set(ue,$,{ttl:te})){const ae=this.cache.sizeCalculation?this.cache.sizeCalculation($,ue):"unknown";throw Error(`Value too large (${ae} > ${this.cache.max})`)}}get(q){return this.cache.get(this.stringify(q))}delete(q){this.cache.delete(this.stringify(q))}size(){return this.cache.size}clear(){this.cache.clear()}forEach(q){return this.cache.forEach(q)}}{constructor(q){if(super(q),this.expireRejectedPromiseValues=q.expireRejectedPromiseValues===void 0||q.expireRejectedPromiseValues,this.rejectedPromiseValueTtl=q.rejectedPromiseValueTtl!==void 0?q.rejectedPromiseValueTtl:c.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(q,$,te){const ue=this.stringify(q);this.cache.set(ue,$,{ttl:te}),this.expireRejectedPromiseValues&&Promise.resolve($).catch(()=>f(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(ue)===$&&this.cache.delete(ue)}))}}var w=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class P{constructor(q,$,te){this.authClient=q,this.email=$,this.password=te,this.tokenTtlMs=1*c.a.hour,this.tokenCache=new S({max:100,ttl:this.tokenTtlMs-5*c.a.minute,fastStringify:!0})}getToken(){return w(this,void 0,void 0,function*(){let q=this.tokenCache.get(this.email);return q||(q=(()=>w(this,void 0,void 0,function*(){const{authentication:$}=yield this.authClient.login({email:this.email,password:this.password,tokenExpirationSeconds:this.tokenTtlMs/c.a.second});if(!$)throw new Error("User account not verified.");return $.accessToken}))(),this.tokenCache.set(this.email,q)),q})}}var N=r(93),T=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};function R(ye){return T(this,void 0,void 0,function*(){return(yield Promise.all(ye.map(q=>q.catch($=>$)))).filter(q=>q instanceof Error)})}function d(ye){if(ye!==void 0)return ye;throw new Error("Value is undefined")}var I=r(0),Q=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};function Z({func:ye,delay:q,immediate:$}){let te=!1,ue=setTimeout(function de(){return Q(this,void 0,void 0,function*(){if(te)return;const me=new Date().getTime();try{ae=ye(),yield ae}finally{if(!te){const pe=new Date().getTime();ue=setTimeout(de,Math.max(q-(pe-me),0))}}})},$?0:q),ae=Promise.resolve();return{stop(){return Q(this,void 0,void 0,function*(){te=!0,clearTimeout(ue),yield ae})}}}function h(ye,q){return Object.keys(ye).reduce(($,te)=>Object.assign(Object.assign({},$),{[te]:q(ye[te])}),{})}var p=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class j{constructor(q){this.message=q}send(q){return p(this,void 0,void 0,function*(){I.a.info(this.message,h(q,$=>{const{sum:te,count:ue}=$,ae=te/ue;return Object.assign(Object.assign({},$),{average:ae})}))})}}var m=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};const x=r(222);var F=r(6);const D=!!F.c,O=new class{constructor(ye=60){this.buffer={},this.metrics={},this.reporters=[],this.flushInterval=Z({func:()=>this.flushStats(),delay:ye*c.a.second})}shutdown(){return m(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*c.a.second)})}aggregate(ye,q){if(this.buffer[ye]){const{min:$,max:te,sum:ue,count:ae}=this.buffer[ye];this.buffer[ye]={min:Math.min($,q),max:Math.max(te,q),sum:ue+q,count:ae+1}}else this.buffer[ye]={min:q,max:q,sum:q,count:1}}increment(ye){this.aggregate(ye,1)}timer(ye,q){return m(this,void 0,void 0,function*(){const $=x(),te=yield q(),ue=x();return this.aggregate(ye,ue-$),te})}metric(ye,q){this.metrics[ye]=q}registerStatsReporter(ye){this.reporters.push(ye)}write(ye){return m(this,void 0,void 0,function*(){if(Object.values(ye).length===0)return;const q=yield R(this.reporters.map($=>$.send(ye)));for(const $ of q)I.a.warn("Failed to write stats",{error:$})})}flushStats(){return m(this,void 0,void 0,function*(){const ye=Object.assign(Object.assign({},this.buffer),h(this.metrics,q=>{const $=q();return{min:$,max:$,sum:$,count:1}}));Object.keys(ye).length>0&&(yield this.write(ye),this.buffer={})})}};D||["local","on-prem"].includes(F.i)||O.registerStatsReporter(new j("stats"));var L=r(8),k=r(21),E=r(103),g=r(36),U=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class B extends g.a{constructor(q){super(q)}postLanRtcOffer(q){return U(this,void 0,void 0,function*(){return yield this.fetch("v1/lan-rtc-offer",{method:"POST",body:JSON.stringify(q)})})}}var G=r(55);const Y={ordered:!1,maxPacketLifeTime:300*c.a.millisecond},K={ordered:!0},H={ordered:!0},V={ordered:!1,maxRetransmits:0},y={ordered:!1,maxRetransmits:0};function C({entityId:ye,streamName:q,streamType:$}){return`${ye}.${q}.${$}`}var W=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class ee{constructor(q,$){this.sessionId=q,this.connection=$,this.counts={localSent:new Map,localReceived:new Map,remoteSent:new Map,remoteReceived:new Map},this.sessionId=q,this.connection=$}updateRemoteMessagesCounts(q){if(q.payload.streamsInfo){this.counts.remoteSent=new Map,this.counts.remoteReceived=new Map;for(const $ of q.payload.streamsInfo.items)this.counts.remoteSent.set($.streamId,$.sentCount),this.counts.remoteReceived.set($.streamId,$.receivedCount)}}getLocalStreamsInfo(q){const{localSent:$,localReceived:te}=this.counts;return{items:[...new Set([...$.keys(),...te.keys()])].map(ue=>{var ae,de;return{streamId:ue,sentCount:(ae=$.get(ue))!==null&&ae!==void 0?ae:0,receivedCount:(de=te.get(ue))!==null&&de!==void 0?de:0}}),timestamp:q}}incrementLocalSent(q){const{localSent:$}=this.counts,te=C(q.header.stream);$.set(te,($.get(te)||0)+1)}incrementLocalReceived(q){const{localReceived:$}=this.counts,te=C(q.header.stream),ue=$.get(te)||0;if(ue===0){const{streamName:ae,streamType:de}=q.header.stream;I.a.debug("RTC client received first message for stream",{streamName:ae,streamType:de})}$.set(te,ue+1)}uploadMetrics(){return W(this,void 0,void 0,function*(){const{sessionId:q}=this,$=yield this.connection.peerConnection.getStats(),te={};$.forEach(ge=>te[ge.id]=ge),I.a.debug("rtc-stats",Object.assign(Object.assign({},te),{sessionId:q}));const{localSent:ue,localReceived:ae,remoteSent:de,remoteReceived:me}=this.counts,pe=[...new Set([...ue.keys(),...ae.keys()])].reduce((ge,ce)=>{const Te=ue.get(ce),Ae=ae.get(ce),Pe=de.get(ce),Le=me.get(ce);return Object.assign(Object.assign({},ge),{[`local-${ce}-sent`]:Te,[`local-${ce}-received`]:Ae,[`remote-${ce}-sent`]:Pe,[`remote-${ce}-received`]:Le})},{sessionId:q});I.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},pe))})}}function X(ye,q){return{header:{stream:ye,created:Date.now(),frameId:""},payload:q}}function ne(ye){return new Set(["disconnected","failed","closed"]).has(ye.iceConnectionState)}var ie=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class he{constructor(q,$,te){this.peerConnection=q,this.config=$,this.dataChannelNotifier=te,this.connectTimeoutMs=20*c.a.second,this.iceGatheringTimeoutMs=15*c.a.second,this.pingUpdateTimeoutMs=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;const{isOffer:ue}=$.baseConfig;ue?this.initializeChannels(q):q.ondatachannel=ae=>{switch(ae.channel.label){case"stream.latest-ttl":this.latestTtlStreamChannel=ae.channel;break;case"stream.reliable":this.reliableStreamChannel=ae.channel;break;case"stream.latest-reliable":this.latestReliableStreamChannel=ae.channel;break;case"stream.latest-try-once":this.latestTryOnceStreamChannel=ae.channel;break;case"heartbeat":return void(this.heartbeatChannel=ae.channel);default:return void this.dataChannelNotifier(ae.channel)}this.setupChannel(ae.channel)},this.pingUpdateTimeout=setInterval(()=>{const{reliableStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"ping"})},this.pingUpdateTimeoutMs),this.streamsInfoUpdateTimeout=setInterval(()=>{const{latestTtlStreamChannel:ae}=this;ae&&this.sendSystemMessage(ae,{type:"streams-info"})},this.streamsInfoUpdateTimeoutMs),this.reassemblyTableCleanupTimeout=setInterval(()=>{const ae=new Date().getTime();this.reassemblyTableLastTimestamp.forEach((de,me,pe)=>{ae>me+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(de)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ae}=this;ae&&ae.readyState==="open"&&ae.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(q){return ie(this,void 0,void 0,function*(){const{peerConnection:$}=this,{track:te}=this.config.baseConfig,ue=(()=>{try{return JSON.parse(q.getPayload())}catch{return}})();if(!ue)return void I.a.error("Received unparseable signal.");I.a.debug("Handling signal",{description:ue});const{sdp:ae,type:de}=ue;if(!ae||!de)return void I.a.warn("Received non-SDP signal");const{signalingState:me,connectionState:pe}=$;if(me!=="stable"||pe!=="connected")if($.remoteDescription)I.a.warn(`Received SDP after remote description was set: ${ae}`);else{if(de==="offer"){if(me!=="stable")return void I.a.warn("Received offer SDP when signaling is ongoing.");yield $.setRemoteDescription(ue);const ge=yield $.createAnswer();yield $.setLocalDescription(ge);const ce=q.clone();return te==null||te("Answer Received",ce),ce.setPayload(JSON.stringify(ge)),ce.setReceiverId(q.getSenderId()),ce.setSenderId(q.getReceiverId()),ce}if(de==="answer"){if(me==="stable")return void I.a.warn("Received answer SDP when signaling hasn't started.");yield $.setRemoteDescription(ue)}}else I.a.warn(`Received SDP when already connected: ${ae}`)})}send(q,$){const te=this.getChannelFromLabel($.channelLabel);te?this.sendOnChannel(te,q):I.a.warn("Send called with unexpected channel label",{channelLabel:$.channelLabel})}controlRemoteStream(q){this.sendSystemMessage(d(this.reliableStreamChannel),{type:"stream-control",streamControl:q})}isActive(){return new Set(["new","checking","connected","completed"]).has(this.peerConnection.iceConnectionState)||this.isReady()}isReady(){const{reliableStreamChannel:q,latestTtlStreamChannel:$,latestTryOnceStreamChannel:te,latestReliableStreamChannel:ue}=this;return(q==null?void 0:q.readyState)==="open"&&($==null?void 0:$.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(ue==null?void 0:ue.readyState)==="open"}close(){return ie(this,void 0,void 0,function*(){if(this.closeCalled)return;this.closeCalled=!0,this.sessionMetrics&&(yield this.sessionMetrics.uploadMetrics()),this.pingUpdateTimeout&&clearInterval(this.pingUpdateTimeout),this.reassemblyTableCleanupTimeout&&clearInterval(this.reassemblyTableCleanupTimeout),this.streamsInfoUpdateTimeout&&clearInterval(this.streamsInfoUpdateTimeout),this.heartbeatTimeout&&clearInterval(this.heartbeatTimeout);const{peerConnection:q,reliableStreamChannel:$,latestTtlStreamChannel:te,latestTryOnceStreamChannel:ue,latestReliableStreamChannel:ae}=this;q.close(),$==null||$.close(),te==null||te.close(),ue==null||ue.close(),ae==null||ae.close()})}getPing(){return this.pingTimeMs}getLastMessageTimestamp(){return this.lastMessageTimestamp}getSessionCreatedTimestamp(){var q;return(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionCreatedTimestamp}setSessionCreatedTimestamp(q){this.config.remoteConfig&&(this.config.remoteConfig.sessionCreatedTimestamp=q)}getSessionId(){var q;return(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionId}setSessionId(q){this.config.remoteConfig&&(this.config.remoteConfig.sessionId=q,this.sessionMetrics=new ee(q,this))}getRemotePeerId(){return this.config.baseConfig.remotePeerId}getRemoteDeviceId(){var q;return(q=this.config.baseConfig)===null||q===void 0?void 0:q.remoteDeviceId}setRemoteDeviceId(q){this.config.baseConfig.remoteDeviceId=q}getSessionMetricsMessageCounts(){var q;return(q=this.sessionMetrics)===null||q===void 0?void 0:q.counts}getConnectionStatsInfo(){return ie(this,void 0,void 0,function*(){const{peerConnection:q}=this;if(!q)return;const $=yield q.getStats(null),te=[];$.forEach(pe=>{te.push(pe)});const ue=te.find(pe=>pe.type==="transport");if(!ue)return;const ae=te.find(pe=>(pe.type==="candidate-pair"||pe.type==="candidatepair")&&pe.id===ue.selectedCandidatePairId);if(!ae)return;const de=te.find(pe=>pe.id===ae.localCandidateId),me=te.find(pe=>pe.id===ae.remoteCandidateId);return de&&me&&(de.address=de.address||de.ip,me.address=me.address||me.ip,de.address!==void 0&&me.address!==void 0)?{transport:ue,localCandidate:de,remoteCandidate:me}:void 0})}initializeChannels(q){this.heartbeatChannel=q.createDataChannel("heartbeat",y),this.heartbeatChannel.binaryType="arraybuffer",this.latestTtlStreamChannel=q.createDataChannel("stream.latest-ttl",Y),this.latestTtlStreamChannel.binaryType="arraybuffer",this.reliableStreamChannel=q.createDataChannel("stream.reliable",K),this.reliableStreamChannel.binaryType="arraybuffer",this.latestReliableStreamChannel=q.createDataChannel("stream.latest-reliable",H),this.latestReliableStreamChannel.binaryType="arraybuffer",this.latestTryOnceStreamChannel=q.createDataChannel("stream.latest-try-once",V),this.latestTryOnceStreamChannel.binaryType="arraybuffer",this.setupChannel(this.latestTtlStreamChannel),this.setupChannel(this.reliableStreamChannel),this.setupChannel(this.latestReliableStreamChannel),this.setupChannel(this.latestTryOnceStreamChannel)}getOffer(){var q,$,te;return ie(this,void 0,void 0,function*(){const{gotOffer:ue}=this,{peerConnection:ae,config:de}=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=(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionId;if(ue)return void I.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,ne(this.peerConnection))return void I.a.debug("Failed to generate offer because the peer connection was inactive.");const pe=de.baseConfig.track;ae.onicecandidate=()=>{this.hasIceCandidate=!0},ae.oniceconnectionstatechange=()=>ie(this,void 0,void 0,function*(){const Pe=ae.iceConnectionState;if(Pe==="connected"||Pe==="completed"){const Le=yield this.getConnectionStatsInfo(),Fe=Le?function(ze){const De=ze.localCandidate.candidateType,We=ze.remoteCandidate.candidateType;return De==="host"&&We==="host"?"local":De==="relay"||We==="relay"?"TURN":"STUN"}(Le):void 0;I.a.info(`ICE connection state changed to ${Pe}`,{sessionId:me,connectionStatsInfo:Le,iceMode:Fe}),pe==null||pe("ICE connection state change",{iceConnectionState:Pe,sessionId:me,connectionStatsInfo:Le,iceMode:Fe})}}),yield ae.setLocalDescription(yield ae.createOffer());const ge=new Date().getTime();for(;;){const Pe=new Date().getTime()-ge;if(Pe>this.connectTimeoutMs)return void I.a.debug("Failed to generate offer because ICE gathering timed out.");if(Pe>this.iceGatheringTimeoutMs&&this.hasIceCandidate){I.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe}),pe==null||pe("ICE gathering partially completed",{sessionId:me,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe});break}if(ae.iceGatheringState==="complete"){I.a.debug("ICE gathering complete",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe}),pe==null||pe("ICE gathering completed",{sessionId:me,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Pe});break}yield Object(u.a)(.1*c.a.second)}const ce=($=this.peerConnection.getConfiguration().iceServers)!==null&&$!==void 0?$:[];for(const Pe of ce)Pe.credentialType=void 0;const Te=JSON.stringify(ce),Ae=new L.Signal;return Ae.setPayload(JSON.stringify(ae.localDescription)),Ae.setSenderId(this.config.baseConfig.localPeerId),Ae.setReceiverId(this.config.baseConfig.remotePeerId),Ae.setIceServers(Te),Ae.setIceTransportPolicy((te=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&te!==void 0?te:"all"),this.config.baseConfig.sessionType!==void 0?Ae.setSessionType(this.config.baseConfig.sessionType):Ae.setSessionType(L.SessionType.TELEOP),I.a.debug("Sending offer signal with description",{description:Ae.getPayload()}),Ae})}getLanOffer(){return ie(this,void 0,void 0,function*(){const{peerConnection:q,gotOffer:$}=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($)return void I.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,ne(this.peerConnection))return void I.a.debug("Failed to generate offer because the peer connection was inactive.");yield q.setLocalDescription(yield q.createOffer());const te=new Date().getTime();for(;;){if(new Date().getTime()-te>this.iceGatheringTimeoutMs)return void I.a.debug("Failed to generate offer because ICE gathering timed out.");if(q.iceGatheringState==="complete")break;yield Object(u.a)(.1*c.a.second)}const ue=q.localDescription;if(ue)return I.a.debug("Sending LAN offer signal with description",{description:ue}),ue;I.a.error("Failed to generate LAN offer description")})}handleLanAnswer(q){return ie(this,void 0,void 0,function*(){const{peerConnection:$}=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 $.setRemoteDescription(q)})}getChannelFromLabel(q){switch(q){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(q,$){let te;try{te=Object(G.encode)(JSON.stringify($))}catch(ue){return void I.a.warn("Failed to encode RTC message",{error:ue})}try{q.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent($)}catch(ue){I.a.warn("Failed to send message to channel",{error:ue,channel:q.label})}}channelNotRecognized(q){return q!==this.latestTtlStreamChannel&&q!==this.latestReliableStreamChannel&&q!==this.latestTryOnceStreamChannel&&q!==this.reliableStreamChannel}setupChannel(q){q.onmessage=$=>{if(this.channelNotRecognized(q))return void I.a.warn("Received message on unrecognized data channel.");let te;try{te=JSON.parse(Object(G.decode)($.data))}catch(ue){return void I.a.warn("Received unparseable message on RTC stream data channel",{error:ue,channel:q.label})}te.communicationType==="message-chunk"?this.receiveChannelMessageChunk(q,te):this.receiveChannelMessage(q,te)},q.onerror=$=>{I.a.warn(`Channel error: ${$.error}`,{error:$.error,sessionId:this.getSessionId(),channelLabel:q.label})},q.onopen=()=>{I.a.debug("Channel opened",{sessionId:this.getSessionId(),channelLabel:q.label})},q.onclose=()=>{const $={bufferedAmount:q.bufferedAmount,sessionId:this.getSessionId(),channelLabel:q.label};this.closeCalled===!1?I.a.debug("Unexpected channel closed",$):I.a.debug("Channel closed",$)}}receiveChannelMessage(q,$){const{config:te}=this,{remotePeerId:ue}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),$=function(ae){switch(ae.header.stream.streamType){case"twist":{const{twist:de}=ae.payload;if(!de)throw Error("twist not in payload of RTC message with type twist");return{header:ae.header,payload:{twist:{linear:Object.assign({x:0,y:0,z:0},de.linear),angular:Object.assign({x:0,y:0,z:0},de.angular)}}}}case"pose":{const{pose:de}=ae.payload;if(!de)throw Error("pose not in payload of RTC message with type pose");return{header:ae.header,payload:{pose:{translation:Object.assign({x:0,y:0,z:0},de.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},de.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:de}=ae.payload;if(!de)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const me=new Array(36).fill(0);return de.covariance.forEach((pe,ge)=>{if(ge>=36)throw Error("covariance contains more than 36 elements");me[ge]=pe}),{header:ae.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},de.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},de.pose.rotation)},covariance:me}}}}case"point":{const{point:de}=ae.payload;if(!de)throw Error("point not in payload of RTC message with type point");return{header:ae.header,payload:{point:Object.assign({x:0,y:0,z:0},de)}}}default:return ae}}($),this.sessionMetrics&&this.sessionMetrics.incrementLocalReceived($),this.handleSystemMessage(q,$)||(q===this.latestTryOnceStreamChannel||q===this.latestTtlStreamChannel||q===this.latestReliableStreamChannel)&&!this.isLatestMessage($)||te.baseConfig.receive(ue,$)}receiveChannelMessageChunk(q,$){const te=this.reassemblyTable.get($.id)||[];if(te.push($),te.length===$.total){const ue=function(ae){const de=ae.sort((me,pe)=>me.seq<pe.seq?-1:1).map(me=>me.part).reduce((me,pe)=>me+pe);try{return JSON.parse(de)}catch{return void I.a.warn("Could not reassemble RTC message chunks")}}(te);return ue&&this.receiveChannelMessage(q,ue),void this.reassemblyTable.delete($.id)}this.reassemblyTable.set($.id,te),this.reassemblyTableLastTimestamp.set($.id,new Date().getTime())}handleSystemMessage(q,$){var te,ue;const{config:ae}=this,{baseConfig:de}=ae,{remotePeerId:me}=de;switch($.header.stream.streamType){case"ping":return this.sendSystemMessage(q,{type:"pong",timestamp:d($.payload.ping)}),!0;case"pong":{const pe=new Date().getTime()-d($.payload.pong);return this.pingTimeMs=pe,O.aggregate("rtc-ping-time",pe),!0}case"streams-info":{const{sessionMetrics:pe}=this,ge=(te=$.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ge&&(pe==null||pe.updateRemoteMessagesCounts($),(ue=de.onStreamsInfoUpdate)===null||ue===void 0||ue.call(de,me,ge),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(q,$){var te;const{localUserId:ue,localPeerId:ae}=this.config.baseConfig;if(q.readyState!=="open")return;const de={entityId:ue!=null?ue:ae,streamName:`$.${$.type}`,streamType:$.type};let me;switch($.type){case"ping":me={ping:new Date().getTime()};break;case"pong":me={pong:$.timestamp};break;case"stream-control":me={streamControl:$.streamControl};break;case"streams-info":me={streamsInfo:(te=this.sessionMetrics)===null||te===void 0?void 0:te.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(q,X(de,me))}isLatestMessage(q){const $=C(q.header.stream),te=(this.streamLatestTimestamp.get($)||0)<=q.header.created;return te&&this.streamLatestTimestamp.set($,q.header.created),te}}function Se(ye){var q,$;return{userId:(q=ye.getUserId())===null||q===void 0?void 0:q.getValue(),deviceId:($=ye.getDeviceId())===null||$===void 0?void 0:$.getValue(),organizationId:ye.getOrganizationId(),id:ye.getPeerId(),capabilities:[],capabilitySet:{}}}var we=function(ye,q,$,te){return new($||($=Promise))(function(ue,ae){function de(ge){try{pe(te.next(ge))}catch(ce){ae(ce)}}function me(ge){try{pe(te.throw(ge))}catch(ce){ae(ce)}}function pe(ge){var ce;ge.done?ue(ge.value):(ce=ge.value,ce instanceof $?ce:new $(function(Te){Te(ce)})).then(de,me)}pe((te=te.apply(ye,q||[])).next())})};class Ee{constructor(q){this.config=q,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:$}=this;this.refreshInterval=Z({func:()=>we(this,void 0,void 0,function*(){try{yield this.update()}catch(te){I.a.warn("RTC refresh failed",{error:te})}}),delay:$,immediate:!0})}send(q,$,te){const ue=this.getActiveConnection(q);ue?ue.isReady()?ue.send($,te):I.a.warn("Send called with unready connection."):I.a.warn("Send called with no connection.")}controlRemoteStream(q,$){const te=this.getActiveConnection(q);te?te.isReady()?te.controlRemoteStream($):I.a.warn("controlRemoteStream called with unready connection."):I.a.warn("controlRemoteStream called with no connection.")}getLocalPeer(){return we(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*c.a.second);return Se(this.localPeer)})}connect(q,$){var te,ue,ae;return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:de,signalingClient:me}=this.config,{localPeer:pe,receiveSignalStream:ge,iceServers:ce}=this;if(!pe||!ge||!ce)return void I.a.warn("Connect called prior to local peer, receiveSignalStream, and ICE servers ready");if(this.getActiveConnection(q))return void I.a.warn("Connect called for peer with existing connection.");if(this.isOutgoingConnection.get(q))return void I.a.warn("Connect called for peer with an existing outgoing connection offer.");this.isOutgoingConnection.set(q,!0);const Te=new he(yield this.createRTCPeerConnection(ce,$),{baseConfig:{isOffer:!0,isLan:!1,receive:(De,We)=>this.config.receive(De,We),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(De,We)=>{var Be,ke;return(ke=(Be=this.config).onStreamsInfoUpdate)===null||ke===void 0?void 0:ke.call(Be,De,We)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=pe.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:pe.getPeerId(),remotePeerId:q,sessionType:$==null?void 0:$.sessionType},remoteConfig:{}},De=>this.onCustomDataChannel(q,De)),Ae=yield Te.getOffer();if(!Ae)return I.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(q);I.a.debug("Sending offer."),de==null||de("Sending offer",Ae);const Pe=new L.SendSignalRequest;Pe.setSignal(Ae);const Le=yield(()=>we(this,void 0,void 0,function*(){try{return yield me.sendSignal(Pe,yield this.getMetadata({}))}catch(De){I.a.warn("Error when sending signal",{error:De})}}))();if(!this.isOutgoingConnection.get(q))return void I.a.debug("No offer set after receiving offer signal response.");I.a.debug("Offer sent.");const Fe=(ue=Le==null?void 0:Le.getSessionId())===null||ue===void 0?void 0:ue.getValue(),ze=(ae=Le==null?void 0:Le.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Fe&&ze?(Te.setSessionId(Fe),Te.setSessionCreatedTimestamp(ze),this.isOutgoingConnection.delete(q),this.connections.push(Te),this.isConnectionInitiator.set(Te,!0),this.setupHandlers(Te),Fe):(I.a.warn("No session ID or no session created timestamp on send signal response."),void this.isOutgoingConnection.delete(q))})}connectLan(q){var $,te;return we(this,void 0,void 0,function*(){const ue=new B(q),ae=new he(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ge,ce)=>this.config.receive(ge,ce),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ge,ce)=>{var Te,Ae;return(Ae=(Te=this.config).onStreamsInfoUpdate)===null||Ae===void 0?void 0:Ae.call(Te,ge,ce)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=($=this.localPeer)===null||$===void 0?void 0:$.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:"lan_client",remotePeerId:q}},ge=>this.onCustomDataChannel(q,ge)),de=yield ae.getLanOffer();if(!de)return I.a.warn("Could not generate LAN offer"),!1;const me=yield ue.postLanRtcOffer({offer:JSON.stringify(de)}),pe=new RTCSessionDescription(JSON.parse(me.answer));return yield ae.handleLanAnswer(pe),this.localConnections.push(ae),this.isConnectionInitiator.set(ae,!0),Object(E.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(q,$,te,ue,ae){const de=this.getActiveConnection(q);if(de&&this.isConnectionInitiator.has(de)){const pe=de.peerConnection.createDataChannel("custom."+$,te);return ue&&(pe.binaryType="arraybuffer"),ae(q,pe),()=>{}}const me=(pe,ge)=>{q===pe&&ge.label==="custom."+$&&ae(q,ge)};return this.peerDataChannelListeners.push(me),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(pe=>pe!==me)}}onCustomDataChannel(q,$){this.peerDataChannelListeners.forEach(te=>te(q,$))}getConnectionStatus(q){if(this.isOutgoingConnection.get(q))return"connecting";const $=this.getActiveConnection(q);return $?$.isReady()?"connected":"connecting":"disconnected"}getConnectionStatsInfo(q){return we(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);if($)return yield $.getConnectionStatsInfo()})}disconnect(q){return we(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);$&&(yield $.close())})}getPeers(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:q}=this.config,$=yield(()=>we(this,void 0,void 0,function*(){try{return yield q.getPeers(new L.GetPeersRequest,yield this.getMetadata({}))}catch(ae){I.a.warn("Error when getting peers",{error:ae})}}))();if(!$)return[];const te=$.getPeersList();if(!te)return[];const ue=ae=>{var de,me;return(me=(de=ae.getPeerCreatedTimestamp())===null||de===void 0?void 0:de.getValue())!==null&&me!==void 0?me:0};return te.sort((ae,de)=>ue(de)-ue(ae)).map(ae=>Se(ae))})}getSessions(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getPeers method cannot be used in local-only mode.");const{signalingClient:q}=this.config,$=yield(()=>we(this,void 0,void 0,function*(){try{return yield q.getPeers(new L.GetPeersRequest,yield this.getMetadata({}))}catch(ae){I.a.warn("Error when getting peers",{error:ae})}}))();if(!$)return{};const te=$.getPeersList(),ue={};for(const ae of te)ue[ae.getPeerId()]=ae.getSessionIdsList();return ue})}getPing(q){const $=this.getActiveConnection(q);if($)return $.getPing();I.a.warn("Attempted to get ping time from inactive peer.")}getLastMessageTimestamp(q){const $=this.getActiveConnection(q);if($)return $.getLastMessageTimestamp();I.a.warn("Attempted to get last message time from inactive peer.")}getSessionMetricsMessageCounts(q){const $=this.getActiveConnection(q);if($)return $.getSessionMetricsMessageCounts();I.a.warn("Attempted to get session metrics counts from inactive peer.")}isReady(){if(this.config.lanOnlyMode)return!0;const{localPeer:q,receiveSignalStream:$,iceServers:te}=this;return!!(q&&$&&te)}shutdown(){return we(this,void 0,void 0,function*(){I.a.info("Shutdown called on RTC client"),yield this.refreshInterval.stop(),this.receiveSignalStream&&this.receiveSignalStream.cancel();const q=this.connections;this.connections=[],yield this.closeConnections(q);const{localPeer:$}=this;if(!$||this.config.lanOnlyMode)return;const{signalingClient:te}=this.config;yield(()=>we(this,void 0,void 0,function*(){try{const ue=new L.DeletePeerRequest;ue.setPeerId($.getPeerId()),yield te.deletePeer(ue,yield this.getMetadata({}))}catch(ue){return void I.a.warn("Error deleting local peer",{error:ue})}}))()})}createPeer(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createPeer method cannot be used in local-only mode.");const{signalingClient:q}=this.config,$=yield(()=>we(this,void 0,void 0,function*(){try{return yield q.createPeer(new L.CreatePeerRequest,yield this.getMetadata({}))}catch(ue){throw new Error(`Was not able to create peer: ${JSON.stringify(ue)}`)}}))(),te=$==null?void 0:$.getPeer();if(!te)throw new Error("Response did not provide peer.");return this.localPeer=te})}createReceiveSignalStream(){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("createReceiveSignalStream method cannot be used in local-only mode.");const{signalingClient:q}=this.config,{localPeer:$,iceServers:te}=this;if(!$||!te)return;const{receiveSignalStream:ue}=this;ue&&ue.cancel();const ae=new L.ReceiveSignalStreamRequest;ae.setPeerId($.getPeerId());const de=yield(()=>we(this,void 0,void 0,function*(){try{return q.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(me){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(me)}`)}}))();if(!de)throw new Error("Response did not provide stream.");return de.on("data",me=>we(this,void 0,void 0,function*(){var pe,ge,ce,Te;const Ae=me.getSignal(),Pe=(pe=Ae==null?void 0:Ae.getSessionId())===null||pe===void 0?void 0:pe.getValue(),Le=Ae==null?void 0:Ae.getSenderId(),Fe=Ae==null?void 0:Ae.getReceiverId(),ze=(ge=Ae==null?void 0:Ae.getSessionCreatedTimestamp())===null||ge===void 0?void 0:ge.getValue();if(!(Ae&&Pe&&Le&&Fe&&ze))return void I.a.warn("Received signal with missing information.");const De=this.getActiveConnection(Le);if(De)if(De.getSessionId()!==Pe){if(I.a.debug("Received signal: different session for a peer we're already connected to."),(De.getSessionCreatedTimestamp()||0)>ze)return;const We=new he(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,ke)=>this.config.receive(Be,ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,ke)=>{var qe,Ge;return(Ge=(qe=this.config).onStreamsInfoUpdate)===null||Ge===void 0?void 0:Ge.call(qe,Be,ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(Te=$.getUserId())===null||Te===void 0?void 0:Te.getValue(),remotePeerId:Le},remoteConfig:{sessionId:Pe,sessionCreatedTimestamp:ze}},Be=>this.onCustomDataChannel(Le,Be));yield We.handleSignal(Ae),this.connections.push(We)}else I.a.debug("Received signal: for an existing connection."),yield De.handleSignal(Ae);else{I.a.debug("Received signal: new connection.");const We=new he(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(Be,ke)=>this.config.receive(Be,ke),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(Be,ke)=>{var qe,Ge;return(Ge=(qe=this.config).onStreamsInfoUpdate)===null||Ge===void 0?void 0:Ge.call(qe,Be,ke)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(ce=$.getUserId())===null||ce===void 0?void 0:ce.getValue(),remotePeerId:Le},remoteConfig:{sessionId:Pe,sessionCreatedTimestamp:ze}},Be=>this.onCustomDataChannel(Le,Be));yield We.handleSignal(Ae),this.connections.push(We)}})),de.on("end",()=>{de.cancel(),this.receiveSignalStream=void 0}),de.on("error",me=>{switch(me.code){case k.StatusCode.CANCELLED:case k.StatusCode.UNAVAILABLE:case k.StatusCode.UNKNOWN:I.a.debug("Receive signal stream error",{error:me});break;case k.StatusCode.UNAUTHENTICATED:I.a.warn("Receive signal stream error",{error:me});break;default:I.a.error("Receive signal stream error",{error:me})}de.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=de})}createRTCPeerConnection(q,$){var te;return we(this,void 0,void 0,function*(){const ue=$==null?void 0:$.rtcIceTransportPolicies,ae=$!=null&&$.rtcIceServerProtocol?[$==null?void 0:$.rtcIceServerProtocol]:void 0,de=q.map(pe=>Object.assign(Object.assign({},pe),{urls:typeof pe.urls=="string"?[pe.urls]:pe.urls})).map(pe=>Object.assign(Object.assign({},pe),{urls:pe.urls.filter(ge=>{const ce=(ue===void 0||ue.some(Te=>((Ae,Pe)=>{switch(Pe){case"stun":return/^stuns?:/.test(Ae);case"turn":return/^turns?:/.test(Ae)}})(ge,Te)))&&(ae===void 0||ae.some(Te=>((Ae,Pe)=>Ae.endsWith(`transport=${Pe}`))(ge,Te)));return ce||I.a.debug(`Ignoring ICE server: ${ge}`),ce})})).filter(({urls:pe})=>pe.filter(ge=>ge).length>0),me=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!me)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new me(Object.assign({iceServers:de,iceTransportPolicy:(ue==null?void 0:ue.length)===1&&ue[0]==="turn"?"relay":"all"},$))})}closeConnections(q){return we(this,void 0,void 0,function*(){const $=yield R(q.map(te=>we(this,void 0,void 0,function*(){yield te.close()})));for(const te of $)I.a.warn("Request to close session failed",{error:te})})}getActiveConnection(q){return this.getConnections().find($=>$.getRemotePeerId()===q&&$.isActive())}update(){var q;return we(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(me=>me.isActive()),this.config.lanOnlyMode)return;const{signalingClient:$}=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:te}=this,ue=this.connections.filter(me=>me.getSessionId).map(me=>d(me.getSessionId()));te.setSessionIdsList(ue);const ae=new L.RefreshPeerRequest;ae.setPeer(te);try{yield $.refreshPeer(ae,yield this.getMetadata({}))}catch(me){me.code===k.StatusCode.NOT_FOUND?(I.a.warn("Peer expired, creating new peer",{peerId:te.getPeerId()}),yield this.reset()):I.a.warn("Error calling RefreshPeer",{error:me})}const de=yield this.getPeers();for(const me of this.connections)me.setRemoteDeviceId((q=de.find(pe=>pe.id===me.getRemotePeerId()))===null||q===void 0?void 0:q.deviceId)})}reset(){return we(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 we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)return;const{iceServersLastUpdate:q,iceServersTtl:$}=this,te=new Date().getTime();if(!q||te-q>$)try{const ue=(yield this.config.signalingClient.getIceServers(new L.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(ue),this.iceServersLastUpdate=te}catch(ue){I.a.warn("Error in updateIceServers",{error:ue})}})}setupHandlers(q){const{peerConnection:$}=q,te=q.getSessionCreatedTimestamp();$.onconnectionstatechange=()=>we(this,void 0,void 0,function*(){const ue=$.connectionState;if(te)switch(ue){case"connected":O.aggregate("rtc-connect-time",new Date().getTime()-te);break;case"failed":O.increment("rtc-connect-failed")}})}getMetadata(q){return we(this,void 0,void 0,function*(){if(this.config.lanOnlyMode)throw new Error("getMetadata method cannot be called in local-only mode");const{getToken:$}=this.config,{grpcCallDeadline:te}=this,{hasDeadline:ue}=q,ae=ue===!1?void 0:new Date().getTime()+te;return{authorization:yield $(),deadline:ae}})}}},,function(e,t,r){r.r(t),r.d(t,"LogClient",function(){return l});var n=r(25),o=function(s,i,c,u){return new(c||(c=Promise))(function(b,A){function _(S){try{f(u.next(S))}catch(w){A(w)}}function v(S){try{f(u.throw(S))}catch(w){A(w)}}function f(S){var w;S.done?b(S.value):(w=S.value,w instanceof c?w:new c(function(P){P(w)})).then(_,v)}f((u=u.apply(s,i||[])).next())})};class l extends n.a{log(i){return o(this,void 0,void 0,function*(){yield this.fetch("logs",{method:"POST",body:JSON.stringify({logs:i}),allowUnsafeRetries:!0})})}}}])})})(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$1=new URLSearchParams("");typeof window!="undefined"&&(urlParams$1=new URLSearchParams(window.location.search));const envDev=urlParams$1.get("formant_dev");envDev&&(FORMANT_API_URL="https://api-dev.formant.io");const envStage=urlParams$1.get("formant_stage");envStage&&(FORMANT_API_URL="https://api-stage.formant.io");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 r=t.get("configuration");return r===null||r.trim()===""?void 0:(await(await fetch(`${FORMANT_API_URL}/v1/admin/module-configurations/`+r,{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,r){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"set_module_data_time_range",module:n,before:t,after:r||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,r){const n=this.getCurrentModuleContext();if(!n)throw new Error("No module context");this.sendAppMessage({type:"send_channel_data",source:n,channel:t,data:r})}static setupModuleMenus(t){const r=this.getCurrentModuleContext();if(!r)throw new Error("No module context");this.sendAppMessage({type:"setup_module_menus",module:r,menus:t})}static addMenuListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_menu_item_clicked"&&t(n.menu)})}static addAccessTokenRefreshListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="auth_token"&&t(n.token)})}static addModuleDataListener(t){window.addEventListener("message",r=>{const n=r.data;n.type==="module_data"&&t({streams:n.streams,time:n.time,queryRange:n.queryRange})})}static addChannelDataListener(t,r){window.addEventListener("message",n=>{const o=n.data;o.type==="channel_data"&&o.channel===t&&r({source:o.source,data:o.data})})}}const Ce=class{static async login(t,r){try{const n=await fetch(`${FORMANT_API_URL}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:t,password:r}),headers:{"Content-Type":"application/json"}}),o=await n.json();if(n.status!==200)throw new Error(o.message);return await Ce.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(n){return Ce.waitingForAuth.forEach(o=>o(!1)),Ce.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let o;if(Ce.isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(Ce.currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(Ce.currentOrganization=n["custom:organization_id"]),Ce.isShareToken||(o=n.sub),n["formant:claims"]&&n["formant:claims"].userId&&(o=n["formant:claims"].userId),o){const l=await fetch(`${FORMANT_API_URL}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+t}}),s=await l.json();if(l.status!==200)throw new Error(s.message);Ce.currentUser=s}Ce.token=t,Ce.waitingForAuth.forEach(l=>l(!0))}catch(o){console.error(o),Ce.waitingForAuth.forEach(l=>l(!1))}Ce.waitingForAuth=[],r&&(Ce.refreshToken=r,setInterval(async()=>{if(Ce.refreshToken){const l=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Ce.refreshToken})})).json();Ce.token=l.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Ce.token!==void 0}static getCurrentUser(){return Ce.currentUser}static async waitTilAuthenticated(){return Ce.token!==void 0?!0:new Promise(t=>{Ce.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Ce;Re(Authentication,"token"),Re(Authentication,"refreshToken"),Re(Authentication,"currentUser"),Re(Authentication,"currentOrganization"),Re(Authentication,"isShareToken",!1),Re(Authentication,"defaultDeviceId"),Re(Authentication,"waitingForAuth",[]);function delay(e){return new Promise(t=>setTimeout(t,e))}class DataChannel{constructor(t){Re(this,"ready",!1);Re(this,"listeners",[]);Re(this,"openListeners",[]);Re(this,"closeListeners",[]);Re(this,"errorListeners",[]);Re(this,"binaryListeners",[]);Re(this,"error");Re(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0,this.openListeners.forEach(r=>r())},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(r=>r())},this.dataChannel.onerror=r=>{console.error(r),this.error="An error occurred in DataChannel",this.errorListeners.forEach(n=>n(r))},this.dataChannel.onmessage=r=>{this.listeners.forEach(n=>{const o=new Uint8Array(r.data),l=this.decoder.decode(o);n(l)}),this.binaryListeners.forEach(n=>{n(new Uint8Array(r.data))})}}addOpenListener(t){this.openListeners.push(t)}removeOpenListener(t){this.openListeners=this.openListeners.filter(r=>r!==t)}addCloseListener(t){this.closeListeners.push(t)}removeCloseListener(t){this.closeListeners=this.closeListeners.filter(r=>r!==t)}addErrorListener(t){this.errorListeners.push(t)}removeErrorListener(t){this.errorListeners=this.errorListeners.filter(r=>r!==t)}async waitTilReady(){return this.ready?!0:new Promise((r,n)=>{let o=window.setInterval(()=>{this.ready&&(window.clearInterval(o),r(!0)),this.error&&n(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 r=this.listeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(r,1)}addBinaryListener(t){this.binaryListeners.push(t)}removeBinaryListener(t){const r=this.binaryListeners.indexOf(t);if(r===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(r,1)}}class CaptureStream{constructor(t){Re(this,"token");this.captureSession=t}async ingestJSON(t){if(!this.token){const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=n.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,r){Re(this,"currentListeners",[]);Re(this,"onRealtimeMessage",(t,r)=>{r.payload.jointState&&this.currentListeners.forEach(n=>{r.payload.jointState&&n(r.payload.jointState)})});this.device=t,this.config=r}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,r,n){Re(this,"channel");Re(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}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);Re(this,"RESPONSE_SUCCESS_BYTE",0);Re(this,"decoder",new TextDecoder)}generateBinaryId(){const r=new Uint8Array(16);for(let n=0;n<r.length;n++)r[n]=Math.floor(Math.random()*256);return r}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(r=>{const o=r.slice(0,16).toString();if(o.length===0)throw new Error("Invalid response");const l=r.slice(16);if(l.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(o)&&this.requestIdToResponseMap.set(o,l)})}async request(r){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:o,timeout:l}=this;await n.waitTilReady();const s=this.generateBinaryId(),i=s.toString();o.set(i,!0),n.sendBinary(new Uint8Array([...s,...r]));const c=new Date().getTime();for(;new Date().getTime()<c+l;)if(await delay(50),o.has(i)){const u=o.get(i);if(u!==!0){o.delete(i);const b=u[0]===this.RESPONSE_SUCCESS_BYTE,A=u.slice(1);if(b)return A;throw console.error({name:"AdapterError",message:this.decoder.decode(A)}),new Error("Binary request datachannel adapter error")}}throw o.delete(i),console.error({name:"TimeoutError",message:`Request timed out after ${l/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 r=JSON.parse(t),{id:n,data:o,error:l}=r;if(!n)throw new Error("Invalid response");if(!o&&!l)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,r)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:r,requestIdToResponseMap:n,timeout:o}=this;await r.waitTilReady();const l=this.generateTextId();n.set(l,!0),r.send(JSON.stringify({id:l,data:t}));const s=new Date().getTime();for(;new Date().getTime()<s+o;)if(await delay(50),n.has(l)){const i=n.get(l);if(i!==!0){n.delete(l);const{data:c,error:u}=i;if(c)return c;if(u)throw console.error({name:"AdapterError",message:u}),new Error("Text request datachannel adapter error")}}throw n.delete(l),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Text request datachannel request timed out")}}const SessionType={Teleop:1,Observe:3};class Device{constructor(t,r,n){Re(this,"rtcClient");Re(this,"remoteDevicePeerId");Re(this,"realtimeListeners",[]);Re(this,"handleMessage",(t,r)=>{this.realtimeListeners.forEach(n=>n(t,r))});this.id=t,this.name=r,this.organizationId=n}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 r=await t.json();if(!r.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const n=r.state.reportedConfiguration.version;return t=await fetch(`${FORMANT_API_URL}/v1/admin/devices/${this.id}/configurations/${n}`,{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}`);{const r=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});for(;!r.isReady();)await delay(100);const o=(await r.getPeers()).find(l=>l.deviceId===this.id);if(!o)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=o.id,await r.connect(this.remoteDevicePeerId,t||{sessionType:SessionType.Teleop});r.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=r}}async sendRealtimeMessage(t,r={channelLabel:"stream.reliable"}){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();n.send(defined(o).id,t,r)}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const r=this.realtimeListeners.indexOf(t);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeAudioStreams(){var n,o,l,s,i,c;const t=await this.getConfiguration(),r=[];for(const u of(o=(n=t.teleop)==null?void 0:n.hardwareStreams)!=null?o:[])u.rtcStreamType==="audio-chunk"&&r.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="audio_common_msgs/AudioData"&&r.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="audio-chunk"&&r.push({name:u.name});return r}async getRealtimeVideoStreams(){var n,o,l,s,i,c;const t=await this.getConfiguration(),r=[];for(const u of(o=(n=t.teleop)==null?void 0:n.hardwareStreams)!=null?o:[])u.rtcStreamType==="h264-video-frame"&&r.push({name:u.name});for(const u of(s=(l=t.teleop)==null?void 0:l.rosStreams)!=null?s:[])u.topicType=="formant/H264VideoFrame"&&r.push({name:u.topicName});for(const u of(c=(i=t.teleop)==null?void 0:i.customStreams)!=null?c:[])u.rtcStreamType==="h264-video-frame"&&r.push({name:u.name});return r}async getRealtimeManipulators(){var n;const t=await this.getConfiguration(),r=[];for(const o of(n=t.teleop.rosStreams)!=null?n:[])o.topicType=="sensor_msgs/JointState"&&r.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 r}async startListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async changeStreamAudioType(t,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();n.controlRemoteStream(defined(o).id,{streamName:t,setAudioFormat:r})}async disableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async getRemotePeer(){const r=(await defined(this.rtcClient,"Realtime connection has not been started").getPeers()).find(n=>n.deviceId===this.id);return defined(r,"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(),r=await Fleet.getRealtimeSessions(),n=t.find(o=>o.deviceId===this.id);return n?r[n.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(n=>({name:n.name,id:n.id,command:n.command,description:n.description,parameterEnabled:n.parameterEnabled,parameterValue:n.parameterValue,parameterMeta:n.parameterMeta,enabled:n.enabled}))}async sendCommand(t,r,n,o){var u;const s=(await this.getAvailableCommands()).find(b=>b.name===t);if(!s)throw new Error(`Could not find command with name "${t}"`);let i;if(r===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=r;let c={value:i,scrubberTime:(n||new Date).toISOString(),meta:st(st({},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:(u=Authentication.currentUser)==null?void 0:u.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})}async createCustomDataChannel(t,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{n.createCustomDataChannel(defined(o).id,t,st({ordered:!0},r),!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,r=3e3){return new TextRequestDataChannel(this,t,r)}createCustomBinaryRequestDataChannel(t,r=3e3){return new BinaryRequestDataChannel(this,t,r)}async createCaptureStream(t){const n=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(n)}async getTelemetry(t,r,n,o){return await Fleet.getTelemetry(this.id,t,r,n,o)}async getTelemetryStreams(){var i,c;const t=await this.getConfiguration(),r=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}}),n=[],o=[];return(c=(i=t.telemetry)==null?void 0:i.streams)==null||c.forEach(u=>{u.disabled!==!0&&n.push(u.name),u.onDemand===!0&&o.push(u.name)}),console.log(o),(await r.json()).items.filter(u=>!n.includes(u)).map(u=>({name:u,onDemand:o.includes(u)}))}async createInterventionRequest(t,r,n,o){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:t,interventionType:r,time:new Date().toISOString(),deviceId:this.id,tags:o,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}async addInterventionResponse(t,r,n){return await(await fetch(`${FORMANT_API_URL}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:t,interventionType:r,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()}}class PeerDevice{constructor(t){Re(this,"rtcClient");Re(this,"remoteDevicePeerId");Re(this,"realtimeListeners",[]);Re(this,"id");Re(this,"handleMessage",(t,r)=>{this.realtimeListeners.forEach(n=>n(t,r))});this.peerUrl=t}async getLatestTelemetry(){const r=await(await fetch(`${this.peerUrl}/telemetry`)).json();return Object.entries(r).map(([o,l])=>({deviceId:this.id,streamName:o,streamType:"json",currentValue:l,currentValueTime:l.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 r=new dist.exports.RtcClient({lanOnlyMode:!0,receive:this.handleMessage});for(await r.connectLan(this.peerUrl);r.getConnectionStatus(this.peerUrl)!=="connected";)await delay(100);this.rtcClient=r}}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const r=this.realtimeListeners.indexOf(t);if(r===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(r,1)}async getRealtimeVideoStreams(){var n,o,l;const t=await this.getConfiguration(),r=[];for(const s of(n=t.teleop.hardwareStreams)!=null?n:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});for(const s of(o=t.teleop.rosStreams)!=null?o:[])s.topicType=="formant/H264VideoFrame"&&r.push({name:s.topicName});for(const s of(l=t.teleop.customStreams)!=null?l:[])s.rtcStreamType==="h264-video-frame"&&r.push({name:s.name});return r}async getRealtimeManipulators(){var n;const t=await this.getConfiguration(),r=[];for(const o of(n=t.teleop.rosStreams)!=null?n:[])o.topicType=="sensor_msgs/JointState"&&r.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 r}async startListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const r=defined(this.rtcClient,"Realtime connection has not been started"),n=await this.getRemotePeer();r.controlRemoteStream(defined(n).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,r){const n=defined(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),l=await new Promise(s=>{n.createCustomDataChannel(defined(o).id,t,st({ordered:!0},r),!1,(i,c)=>{const u=new DataChannel(c);s(u)})});return await l.waitTilReady(),l}createCustomRequestDataChannel(t,r=3e3){return new TextRequestDataChannel(this,t,r)}createCustomBinaryRequestDataChannel(t,r=3e3){return new BinaryRequestDataChannel(this,t,r)}}const Me=class{static async setDefaultDevice(t){Me.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Me.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===Me.defaultDeviceId).name,l=new Device(Me.defaultDeviceId,o,defined(Authentication.currentOrganization));return Me.knownContext.push(new WeakRef(l)),l}static async getPeerDevice(t){const r=new PeerDevice(t);return r.id=await r.getDeviceId(),r}static async getDevice(t){if(!Authentication.token)throw new Error("Not authenticated");const n=await(await fetch(`${FORMANT_API_URL}/v1/admin/devices/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json(),o=n.name,l=new Device(t,o,n.organizationId);return Me.knownContext.push(new WeakRef(l)),l}static async getDevices(){if(!Authentication.token)throw new Error("Not authenticated");const r=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 r.items,r.items.map(n=>new Device(n.id,n.name,n.organizationId))}static async getOnlineDevices(){if(!Authentication.token)throw new Error("Not authenticated");const n=(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 Me.getDevices()).filter(l=>n.includes(l.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 n=(await(await fetch(`${FORMANT_API_URL}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items.map(l=>l.deviceId);return(await Me.getDevices()).filter(l=>n.includes(l.id))}static async getLatestTelemetry(t){let r=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:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getTelemetry(t,r,n,o,l){let s=t;Array.isArray(t)||(s=[t]);let i=r;return Array.isArray(r)||(i=[r]),(await(await fetch(`${FORMANT_API_URL}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:s,end:o.toISOString(),names:i,start:n.toISOString(),tags:l}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).items}static async getFileUrl(t){const n=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(n.fileUrls.length===0)throw new Error("File not found");return n.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=Me;Re(Fleet,"defaultDeviceId"),Re(Fleet,"knownContext",[]);class KeyValue{static async set(t,r){try{const n=await fetch(FORMANT_API_URL+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId,key:t,value:r}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),o=await n.json();if(n.status!==200)throw new Error(o.message)}catch(n){throw n}}static async get(t){try{const r=await fetch(FORMANT_API_URL+`/v1/admin/key-value/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}}),n=await r.json();if(r.status!==200)throw new Error(n.message);return n.value}catch(r){throw r}}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}}),r=await t.json();if(t.status!==200)throw new Error(r.message);return r.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(r){throw r}}}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,r){Re(this,"muted",!1);Re(this,"hasReceivedData",!1);Re(this,"audioContext");Re(this,"chunks",[]);Re(this,"isPlaying",!1);Re(this,"startTime",0);Re(this,"lastChunkOffset",0);Re(this,"bufferSize",3);Re(this,"receive",async t=>{var s;const r=(s=t.payload.audioChunk)==null?void 0:s.chunk_data;if(!r)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:n,muted:o}=this;if(!n||t.header.stream.streamType!==rtcAudioChunkStreamType||o!==!1)return;const l=stringToArrayBuffer(r);try{await n.decodeAudioData(l.buffer,this.scheduleChunk)}catch(i){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:i}),this.changeAudioWireFormat("wav")}});Re(this,"scheduleChunk",t=>{const{audioContext:r}=this;if(!r)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(o=>{o.stop()}),this.isPlaying=!1,this.chunks=[]);const n=this.createChunk(t);!n||!n.buffer||(this.isPlaying===!1&&(this.startTime=r.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),n.start(this.startTime+this.lastChunkOffset,0,t.duration),this.lastChunkOffset+=n.buffer.duration,this.chunks.push(n))});this.device=t,this.stream=r,this.device.startListeningToRealtimeDataStream(r),this.device.addRealtimeListener((o,l)=>{this.receive(l)}),browser()==="Safari"||browser()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const n=window.AudioContext||window.webkitAudioContext;this.audioContext=new n}async play(){var t,r;((t=this.audioContext)==null?void 0:t.state)==="suspended"&&await((r=this.audioContext)==null?void 0:r.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(t){const{audioContext:r}=this;if(!r)return;const n=r.createBufferSource();return n.buffer=t,n.connect(r.destination),n.loop=!1,n.onended=o=>{this.chunks.splice(this.chunks.indexOf(n),1),this.chunks.length===0&&(this.isPlaying=!1)},n}changeAudioWireFormat(t){const{stream:r}=this;(async()=>await this.device.changeStreamAudioType(r.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.aggregateLevels=aggregateLevels,exports.annotationTypes=annotationTypes,exports.eventTypes=eventTypes,exports.healthStatuses=healthStatuses,exports.interventionTypes=interventionTypes,exports.operator=operator,exports.severities=severities,exports.videoMimeTypes=videoMimeTypes,exports.viewer=viewer,Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
@@ -83,6 +83,7 @@ export declare type DataPoint = [number, any];
|
|
|
83
83
|
export declare class App {
|
|
84
84
|
private static sendAppMessage;
|
|
85
85
|
static getCurrentModuleContext(): string | null;
|
|
86
|
+
static getCurrentModuleConfiguration(): Promise<string | undefined>;
|
|
86
87
|
static isModule(): boolean;
|
|
87
88
|
static goToTime(date: Date): void;
|
|
88
89
|
static goToDevice(deviceId: string): void;
|