@formant/data-sdk 0.0.86 → 0.0.89
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
|
@@ -17700,7 +17700,7 @@ Found: ${e2.toString().split("\n")[0]}
|
|
|
17700
17700
|
for (const e3 of c2)
|
|
17701
17701
|
e3.credentialType = void 0;
|
|
17702
17702
|
const f2 = JSON.stringify(c2), p2 = new N.Signal();
|
|
17703
|
-
return p2.setPayload(JSON.stringify(o2.localDescription)), p2.setSenderId(this.config.baseConfig.localPeerId), p2.setReceiverId(this.config.baseConfig.remotePeerId), p2.setIceServers(f2), p2.setIceTransportPolicy((r2 = this.peerConnection.getConfiguration().iceTransportPolicy) !== null && r2 !== void 0 ? r2 : "all"), p2.setSessionType(this.config.baseConfig.sessionType
|
|
17703
|
+
return p2.setPayload(JSON.stringify(o2.localDescription)), p2.setSenderId(this.config.baseConfig.localPeerId), p2.setReceiverId(this.config.baseConfig.remotePeerId), p2.setIceServers(f2), p2.setIceTransportPolicy((r2 = this.peerConnection.getConfiguration().iceTransportPolicy) !== null && r2 !== void 0 ? r2 : "all"), this.config.baseConfig.sessionType !== void 0 ? p2.setSessionType(this.config.baseConfig.sessionType) : p2.setSessionType(N.SessionType.TELEOP), w.a.debug("Sending offer signal with description", { description: p2.getPayload() }), p2;
|
|
17704
17704
|
});
|
|
17705
17705
|
}
|
|
17706
17706
|
getLanOffer() {
|
|
@@ -18954,7 +18954,7 @@ class Device {
|
|
|
18954
18954
|
throw new Error(`Realtime connection hasn't been started for ${this.id}`);
|
|
18955
18955
|
}
|
|
18956
18956
|
}
|
|
18957
|
-
async startRealtimeConnection() {
|
|
18957
|
+
async startRealtimeConnection(sessionType) {
|
|
18958
18958
|
if (!this.rtcClient) {
|
|
18959
18959
|
const rtcClient = new dist.exports.RtcClient({
|
|
18960
18960
|
signalingClient: new dist.exports.SignalingPromiseClient(FORMANT_API_URL, null, null),
|
|
@@ -18972,7 +18972,9 @@ class Device {
|
|
|
18972
18972
|
throw new Error("Cannot find peer, is the robot offline?");
|
|
18973
18973
|
}
|
|
18974
18974
|
this.remoteDevicePeerId = devicePeer.id;
|
|
18975
|
-
await rtcClient.connect(this.remoteDevicePeerId,
|
|
18975
|
+
await rtcClient.connect(this.remoteDevicePeerId, {
|
|
18976
|
+
sessionType: sessionType === void 0 ? 1 : sessionType
|
|
18977
|
+
});
|
|
18976
18978
|
while (rtcClient.getConnectionStatus(this.remoteDevicePeerId) !== "connected") {
|
|
18977
18979
|
await delay(100);
|
|
18978
18980
|
}
|
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 g=s[i];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(l,g.key,g)}}e.exports=function(){function l(g){if(function(u,b){if(!(u instanceof b))throw new TypeError("Cannot call a class as a function")}(this,l),!g)throw new Error("Logger is required for profiling.");this.logger=g,this.start=Date.now()}var s,i;return s=l,(i=[{key:"done",value:function(){for(var g=arguments.length,u=new Array(g),b=0;b<g;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(g,u){return u instanceof n?u.toString("base64"):typeof u=="bigint"?u.toString():u}e.exports=o((g,u={})=>(g[l]=(u.stable?s.stableStringify:s)(g,u.replacer||i,u.space),g))}).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 g=0;g<i.length;g++){var u=i[g];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,g;return i=s,(g=[{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,g),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,g){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(g).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,g,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:n!=null&&n.hrtime?(e.exports=function(){return(o()-g)/1e6},l=n.hrtime,i=(o=function(){var b;return 1e9*(b=l())[0]+b[1]})(),u=1e9*n.uptime(),g=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,g=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:g+1,T=P-i+(N-g)/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,g=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 g=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[g+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,g){if(g=g===void 0?{fatal:!1}:g,(i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+i+"') is invalid.");if(g.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,g){if((g=g===void 0?{stream:!1}:g).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");g=0;for(var u=i.length,b=0,A=Math.max(32,u+(u>>1)+7),_=new Uint8Array(A>>3<<3);g<u;){var v=i.charCodeAt(g++);if(55296<=v&&56319>=v){if(g<u){var f=i.charCodeAt(g);(64512&f)==56320&&(++g,v=((1023&v)<<10)+(1023&f)+65536)}if(55296<=v&&56319>=v)continue}if(b+4>_.length&&(A+=8,A=(A*=1+g/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,g){if((g=g===void 0?{stream:!1}:g).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");g=0;for(var u=(i=new Uint8Array(i)).length,b=[];g<u;){var A=i[g++];if(A===0)break;if((128&A)==0)b.push(A);else if((224&A)==192){var _=63&i[g++];b.push((31&A)<<6|_)}else if((240&A)==224){_=63&i[g++];var v=63&i[g++];b.push((31&A)<<12|_<<6|v)}else(248&A)==240&&(65535<(A=(7&A)<<18|(_=63&i[g++])<<12|(v=63&i[g++])<<6|63&i[g++])&&(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 Oe});var n=r(25),o=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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:le}){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:le})})})}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,le){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:le})})})}getFeatures(q){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:q})).features})}}var s=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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 g=r(1),u=r(11),b=r(35),A=r.n(b),_=r(102),v=r.n(_),f=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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 le=this.stringify(q);if(!this.cache.set(le,$,{ttl:te})){const ae=this.cache.sizeCalculation?this.cache.sizeCalculation($,le):"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:g.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(q,$,te){const le=this.stringify(q);this.cache.set(le,$,{ttl:te}),this.expireRejectedPromiseValues&&Promise.resolve($).catch(()=>f(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(le)===$&&this.cache.delete(le)}))}}var w=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class P{constructor(q,$,te){this.authClient=q,this.email=$,this.password=te,this.tokenTtlMs=1*g.a.hour,this.tokenCache=new S({max:100,ttl:this.tokenTtlMs-5*g.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/g.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(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};function R(pe){return T(this,void 0,void 0,function*(){return(yield Promise.all(pe.map(q=>q.catch($=>$)))).filter(q=>q instanceof Error)})}function d(pe){if(pe!==void 0)return pe;throw new Error("Value is undefined")}var I=r(0),Q=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};function Z({func:pe,delay:q,immediate:$}){let te=!1,le=setTimeout(function me(){return Q(this,void 0,void 0,function*(){if(te)return;const ye=new Date().getTime();try{ae=pe(),yield ae}finally{if(!te){const de=new Date().getTime();le=setTimeout(me,Math.max(q-(de-ye),0))}}})},$?0:q),ae=Promise.resolve();return{stop(){return Q(this,void 0,void 0,function*(){te=!0,clearTimeout(le),yield ae})}}}function h(pe,q){return Object.keys(pe).reduce(($,te)=>Object.assign(Object.assign({},$),{[te]:q(pe[te])}),{})}var p=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class C{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:le}=$,ae=te/le;return Object.assign(Object.assign({},$),{average:ae})}))})}}var m=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};const x=r(222);var F=r(6);const D=!!F.c,O=new class{constructor(pe=60){this.buffer={},this.metrics={},this.reporters=[],this.flushInterval=Z({func:()=>this.flushStats(),delay:pe*g.a.second})}shutdown(){return m(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*g.a.second)})}aggregate(pe,q){if(this.buffer[pe]){const{min:$,max:te,sum:le,count:ae}=this.buffer[pe];this.buffer[pe]={min:Math.min($,q),max:Math.max(te,q),sum:le+q,count:ae+1}}else this.buffer[pe]={min:q,max:q,sum:q,count:1}}increment(pe){this.aggregate(pe,1)}timer(pe,q){return m(this,void 0,void 0,function*(){const $=x(),te=yield q(),le=x();return this.aggregate(pe,le-$),te})}metric(pe,q){this.metrics[pe]=q}registerStatsReporter(pe){this.reporters.push(pe)}write(pe){return m(this,void 0,void 0,function*(){if(Object.values(pe).length===0)return;const q=yield R(this.reporters.map($=>$.send(pe)));for(const $ of q)I.a.warn("Failed to write stats",{error:$})})}flushStats(){return m(this,void 0,void 0,function*(){const pe=Object.assign(Object.assign({},this.buffer),h(this.metrics,q=>{const $=q();return{min:$,max:$,sum:$,count:1}}));Object.keys(pe).length>0&&(yield this.write(pe),this.buffer={})})}};D||["local","on-prem"].includes(F.i)||O.registerStatsReporter(new C("stats"));var L=r(8),k=r(21),E=r(103),c=r(36),U=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class B extends c.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*g.a.millisecond},K={ordered:!0},H={ordered:!0},V={ordered:!1,maxRetransmits:0},y={ordered:!1,maxRetransmits:0};function j({entityId:pe,streamName:q,streamType:$}){return`${pe}.${q}.${$}`}var W=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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(le=>{var ae,me;return{streamId:le,sentCount:(ae=$.get(le))!==null&&ae!==void 0?ae:0,receivedCount:(me=te.get(le))!==null&&me!==void 0?me:0}}),timestamp:q}}incrementLocalSent(q){const{localSent:$}=this.counts,te=j(q.header.stream);$.set(te,($.get(te)||0)+1)}incrementLocalReceived(q){const{localReceived:$}=this.counts,te=j(q.header.stream),le=$.get(te)||0;if(le===0){const{streamName:ae,streamType:me}=q.header.stream;I.a.debug("RTC client received first message for stream",{streamName:ae,streamType:me})}$.set(te,le+1)}uploadMetrics(){return W(this,void 0,void 0,function*(){const{sessionId:q}=this,$=yield this.connection.peerConnection.getStats(),te={};$.forEach(ce=>te[ce.id]=ce),I.a.debug("rtc-stats",Object.assign(Object.assign({},te),{sessionId:q}));const{localSent:le,localReceived:ae,remoteSent:me,remoteReceived:ye}=this.counts,de=[...new Set([...le.keys(),...ae.keys()])].reduce((ce,ge)=>{const we=le.get(ge),Ee=ae.get(ge),Me=me.get(ge),xe=ye.get(ge);return Object.assign(Object.assign({},ce),{[`local-${ge}-sent`]:we,[`local-${ge}-received`]:Ee,[`remote-${ge}-sent`]:Me,[`remote-${ge}-received`]:xe})},{sessionId:q});I.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},de))})}}function X(pe){return new Set(["disconnected","failed","closed"]).has(pe.iceConnectionState)}var re=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class ie{constructor(q,$,te){this.peerConnection=q,this.config=$,this.dataChannelNotifier=te,this.connectTimeoutMs=20*g.a.second,this.iceGatheringTimeoutMs=15*g.a.second,this.pingUpdateTimeoutMs=1*g.a.second,this.streamsInfoUpdateTimeoutMs=2*g.a.second,this.reassemblyTimeoutMs=500*g.a.millisecond,this.reassemblyTableCleanupMs=1*g.a.second,this.heartbeatTimeoutMs=20*g.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:le}=$.baseConfig;le?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((me,ye,de)=>{ae>ye+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(me)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ae}=this;ae&&ae.readyState==="open"&&ae.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(q){return re(this,void 0,void 0,function*(){const{peerConnection:$}=this,{track:te}=this.config.baseConfig,le=(()=>{try{return JSON.parse(q.getPayload())}catch{return}})();if(!le)return void I.a.error("Received unparseable signal.");I.a.debug("Handling signal",{description:le});const{sdp:ae,type:me}=le;if(!ae||!me)return void I.a.warn("Received non-SDP signal");const{signalingState:ye,connectionState:de}=$;if(ye!=="stable"||de!=="connected")if($.remoteDescription)I.a.warn(`Received SDP after remote description was set: ${ae}`);else{if(me==="offer"){if(ye!=="stable")return void I.a.warn("Received offer SDP when signaling is ongoing.");yield $.setRemoteDescription(le);const ce=yield $.createAnswer();yield $.setLocalDescription(ce);const ge=q.clone();return te==null||te("Answer Received",ge),ge.setPayload(JSON.stringify(ce)),ge.setReceiverId(q.getSenderId()),ge.setSenderId(q.getReceiverId()),ge}if(me==="answer"){if(ye==="stable")return void I.a.warn("Received answer SDP when signaling hasn't started.");yield $.setRemoteDescription(le)}}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:le}=this;return(q==null?void 0:q.readyState)==="open"&&($==null?void 0:$.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(le==null?void 0:le.readyState)==="open"}close(){return re(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:le,latestReliableStreamChannel:ae}=this;q.close(),$==null||$.close(),te==null||te.close(),le==null||le.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 re(this,void 0,void 0,function*(){const{peerConnection:q}=this;if(!q)return;const $=yield q.getStats(null),te=[];$.forEach(de=>{te.push(de)});const le=te.find(de=>de.type==="transport");if(!le)return;const ae=te.find(de=>(de.type==="candidate-pair"||de.type==="candidatepair")&&de.id===le.selectedCandidatePairId);if(!ae)return;const me=te.find(de=>de.id===ae.localCandidateId),ye=te.find(de=>de.id===ae.remoteCandidateId);return me&&ye&&(me.address=me.address||me.ip,ye.address=ye.address||ye.ip,me.address!==void 0&&ye.address!==void 0)?{transport:le,localCandidate:me,remoteCandidate:ye}: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 re(this,void 0,void 0,function*(){const{gotOffer:le}=this,{peerConnection:ae,config:me}=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 ye=(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionId;if(le)return void I.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,X(this.peerConnection))return void I.a.debug("Failed to generate offer because the peer connection was inactive.");const de=me.baseConfig.track;ae.onicecandidate=()=>{this.hasIceCandidate=!0},ae.oniceconnectionstatechange=()=>re(this,void 0,void 0,function*(){const Me=ae.iceConnectionState;if(Me==="connected"||Me==="completed"){const xe=yield this.getConnectionStatsInfo(),Fe=xe?function(Be){const De=Be.localCandidate.candidateType,Ue=Be.remoteCandidate.candidateType;return De==="host"&&Ue==="host"?"local":De==="relay"||Ue==="relay"?"TURN":"STUN"}(xe):void 0;I.a.info(`ICE connection state changed to ${Me}`,{sessionId:ye,connectionStatsInfo:xe,iceMode:Fe}),de==null||de("ICE connection state change",{iceConnectionState:Me,sessionId:ye,connectionStatsInfo:xe,iceMode:Fe})}}),yield ae.setLocalDescription(yield ae.createOffer());const ce=new Date().getTime();for(;;){const Me=new Date().getTime()-ce;if(Me>this.connectTimeoutMs)return void I.a.debug("Failed to generate offer because ICE gathering timed out.");if(Me>this.iceGatheringTimeoutMs&&this.hasIceCandidate){I.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me}),de==null||de("ICE gathering partially completed",{sessionId:ye,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me});break}if(ae.iceGatheringState==="complete"){I.a.debug("ICE gathering complete",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me}),de==null||de("ICE gathering completed",{sessionId:ye,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me});break}yield Object(u.a)(.1*g.a.second)}const ge=($=this.peerConnection.getConfiguration().iceServers)!==null&&$!==void 0?$:[];for(const Me of ge)Me.credentialType=void 0;const we=JSON.stringify(ge),Ee=new L.Signal;return Ee.setPayload(JSON.stringify(ae.localDescription)),Ee.setSenderId(this.config.baseConfig.localPeerId),Ee.setReceiverId(this.config.baseConfig.remotePeerId),Ee.setIceServers(we),Ee.setIceTransportPolicy((te=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&te!==void 0?te:"all"),Ee.setSessionType(this.config.baseConfig.sessionType||L.SessionType.TELEOP),I.a.debug("Sending offer signal with description",{description:Ee.getPayload()}),Ee})}getLanOffer(){return re(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,X(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*g.a.second)}const le=q.localDescription;if(le)return I.a.debug("Sending LAN offer signal with description",{description:le}),le;I.a.error("Failed to generate LAN offer description")})}handleLanAnswer(q){return re(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(le){return void I.a.warn("Failed to encode RTC message",{error:le})}try{q.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent($)}catch(le){I.a.warn("Failed to send message to channel",{error:le,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(le){return void I.a.warn("Received unparseable message on RTC stream data channel",{error:le,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:le}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),$=function(ae){switch(ae.header.stream.streamType){case"twist":{const{twist:me}=ae.payload;if(!me)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},me.linear),angular:Object.assign({x:0,y:0,z:0},me.angular)}}}}case"pose":{const{pose:me}=ae.payload;if(!me)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},me.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},me.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:me}=ae.payload;if(!me)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const ye=new Array(36).fill(0);return me.covariance.forEach((de,ce)=>{if(ce>=36)throw Error("covariance contains more than 36 elements");ye[ce]=de}),{header:ae.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},me.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},me.pose.rotation)},covariance:ye}}}}case"point":{const{point:me}=ae.payload;if(!me)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},me)}}}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(le,$)}receiveChannelMessageChunk(q,$){const te=this.reassemblyTable.get($.id)||[];if(te.push($),te.length===$.total){const le=function(ae){const me=ae.sort((ye,de)=>ye.seq<de.seq?-1:1).map(ye=>ye.part).reduce((ye,de)=>ye+de);try{return JSON.parse(me)}catch{return void I.a.warn("Could not reassemble RTC message chunks")}}(te);return le&&this.receiveChannelMessage(q,le),void this.reassemblyTable.delete($.id)}this.reassemblyTable.set($.id,te),this.reassemblyTableLastTimestamp.set($.id,new Date().getTime())}handleSystemMessage(q,$){var te,le;const{config:ae}=this,{baseConfig:me}=ae,{remotePeerId:ye}=me;switch($.header.stream.streamType){case"ping":return this.sendSystemMessage(q,{type:"pong",timestamp:d($.payload.ping)}),!0;case"pong":{const de=new Date().getTime()-d($.payload.pong);return this.pingTimeMs=de,O.aggregate("rtc-ping-time",de),!0}case"streams-info":{const{sessionMetrics:de}=this,ce=(te=$.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ce&&(de==null||de.updateRemoteMessagesCounts($),(le=me.onStreamsInfoUpdate)===null||le===void 0||le.call(me,ye,ce),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(q,$){var te;const{localUserId:le,localPeerId:ae}=this.config.baseConfig;if(q.readyState!=="open")return;const me={entityId:le!=null?le:ae,streamName:`$.${$.type}`,streamType:$.type};let ye;switch($.type){case"ping":ye={ping:new Date().getTime()};break;case"pong":ye={pong:$.timestamp};break;case"stream-control":ye={streamControl:$.streamControl};break;case"streams-info":ye={streamsInfo:(te=this.sessionMetrics)===null||te===void 0?void 0:te.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(q,function(de,ce){return{header:{stream:de,created:Date.now(),frameId:""},payload:ce}}(me,ye))}isLatestMessage(q){const $=j(q.header.stream),te=(this.streamLatestTimestamp.get($)||0)<=q.header.created;return te&&this.streamLatestTimestamp.set($,q.header.created),te}}function he(pe){var q,$;return{userId:(q=pe.getUserId())===null||q===void 0?void 0:q.getValue(),deviceId:($=pe.getDeviceId())===null||$===void 0?void 0:$.getValue(),organizationId:pe.getOrganizationId(),id:pe.getPeerId(),capabilities:[],capabilitySet:{}}}var be=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class Oe{constructor(q){this.config=q,this.grpcCallDeadline=5*g.a.second,this.refreshIntervalDelayMs=2*g.a.second,this.iceServersTtl=30*g.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:$}=this;this.refreshInterval=Z({func:()=>be(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 le=this.getActiveConnection(q);le?le.isReady()?le.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 be(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*g.a.second);return he(this.localPeer)})}connect(q,$){var te,le,ae;return be(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:me,signalingClient:ye}=this.config,{localPeer:de,receiveSignalStream:ce,iceServers:ge}=this;if(!de||!ce||!ge)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 we=new ie(yield this.createRTCPeerConnection(ge,$),{baseConfig:{isOffer:!0,isLan:!1,receive:(De,Ue)=>this.config.receive(De,Ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(De,Ue)=>{var ke,We;return(We=(ke=this.config).onStreamsInfoUpdate)===null||We===void 0?void 0:We.call(ke,De,Ue)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=de.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:de.getPeerId(),remotePeerId:q,sessionType:$==null?void 0:$.sessionType},remoteConfig:{}},De=>this.onCustomDataChannel(q,De)),Ee=yield we.getOffer();if(!Ee)return I.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(q);I.a.debug("Sending offer."),me==null||me("Sending offer",Ee);const Me=new L.SendSignalRequest;Me.setSignal(Ee);const xe=yield(()=>be(this,void 0,void 0,function*(){try{return yield ye.sendSignal(Me,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=(le=xe==null?void 0:xe.getSessionId())===null||le===void 0?void 0:le.getValue(),Be=(ae=xe==null?void 0:xe.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Fe&&Be?(we.setSessionId(Fe),we.setSessionCreatedTimestamp(Be),this.isOutgoingConnection.delete(q),this.connections.push(we),this.isConnectionInitiator.set(we,!0),this.setupHandlers(we),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 be(this,void 0,void 0,function*(){const le=new B(q),ae=new ie(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,ge)=>this.config.receive(ce,ge),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,ge)=>{var we,Ee;return(Ee=(we=this.config).onStreamsInfoUpdate)===null||Ee===void 0?void 0:Ee.call(we,ce,ge)}: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}},ce=>this.onCustomDataChannel(q,ce)),me=yield ae.getLanOffer();if(!me)return I.a.warn("Could not generate LAN offer"),!1;const ye=yield le.postLanRtcOffer({offer:JSON.stringify(me)}),de=new RTCSessionDescription(JSON.parse(ye.answer));return yield ae.handleLanAnswer(de),this.localConnections.push(ae),this.isConnectionInitiator.set(ae,!0),Object(E.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(q,$,te,le,ae){const me=this.getActiveConnection(q);if(me&&this.isConnectionInitiator.has(me)){const de=me.peerConnection.createDataChannel("custom."+$,te);return le&&(de.binaryType="arraybuffer"),ae(q,de),()=>{}}const ye=(de,ce)=>{q===de&&ce.label==="custom."+$&&ae(q,ce)};return this.peerDataChannelListeners.push(ye),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(de=>de!==ye)}}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 be(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);if($)return yield $.getConnectionStatsInfo()})}disconnect(q){return be(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);$&&(yield $.close())})}getPeers(){return be(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(()=>be(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 le=ae=>{var me,ye;return(ye=(me=ae.getPeerCreatedTimestamp())===null||me===void 0?void 0:me.getValue())!==null&&ye!==void 0?ye:0};return te.sort((ae,me)=>le(me)-le(ae)).map(ae=>he(ae))})}getSessions(){return be(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(()=>be(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(),le={};for(const ae of te)le[ae.getPeerId()]=ae.getSessionIdsList();return le})}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 be(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(()=>be(this,void 0,void 0,function*(){try{const le=new L.DeletePeerRequest;le.setPeerId($.getPeerId()),yield te.deletePeer(le,yield this.getMetadata({}))}catch(le){return void I.a.warn("Error deleting local peer",{error:le})}}))()})}createPeer(){return be(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(()=>be(this,void 0,void 0,function*(){try{return yield q.createPeer(new L.CreatePeerRequest,yield this.getMetadata({}))}catch(le){throw new Error(`Was not able to create peer: ${JSON.stringify(le)}`)}}))(),te=$==null?void 0:$.getPeer();if(!te)throw new Error("Response did not provide peer.");return this.localPeer=te})}createReceiveSignalStream(){return be(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:le}=this;le&&le.cancel();const ae=new L.ReceiveSignalStreamRequest;ae.setPeerId($.getPeerId());const me=yield(()=>be(this,void 0,void 0,function*(){try{return q.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(ye){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(ye)}`)}}))();if(!me)throw new Error("Response did not provide stream.");return me.on("data",ye=>be(this,void 0,void 0,function*(){var de,ce,ge,we;const Ee=ye.getSignal(),Me=(de=Ee==null?void 0:Ee.getSessionId())===null||de===void 0?void 0:de.getValue(),xe=Ee==null?void 0:Ee.getSenderId(),Fe=Ee==null?void 0:Ee.getReceiverId(),Be=(ce=Ee==null?void 0:Ee.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Ee&&Me&&xe&&Fe&&Be))return void I.a.warn("Received signal with missing information.");const De=this.getActiveConnection(xe);if(De)if(De.getSessionId()!==Me){if(I.a.debug("Received signal: different session for a peer we're already connected to."),(De.getSessionCreatedTimestamp()||0)>Be)return;const Ue=new ie(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,We)=>this.config.receive(ke,We),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,We)=>{var Ye,ze;return(ze=(Ye=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(Ye,ke,We)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(we=$.getUserId())===null||we===void 0?void 0:we.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Me,sessionCreatedTimestamp:Be}},ke=>this.onCustomDataChannel(xe,ke));yield Ue.handleSignal(Ee),this.connections.push(Ue)}else I.a.debug("Received signal: for an existing connection."),yield De.handleSignal(Ee);else{I.a.debug("Received signal: new connection.");const Ue=new ie(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,We)=>this.config.receive(ke,We),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,We)=>{var Ye,ze;return(ze=(Ye=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(Ye,ke,We)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(ge=$.getUserId())===null||ge===void 0?void 0:ge.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Me,sessionCreatedTimestamp:Be}},ke=>this.onCustomDataChannel(xe,ke));yield Ue.handleSignal(Ee),this.connections.push(Ue)}})),me.on("end",()=>{me.cancel(),this.receiveSignalStream=void 0}),me.on("error",ye=>{switch(ye.code){case k.StatusCode.CANCELLED:case k.StatusCode.UNAVAILABLE:case k.StatusCode.UNKNOWN:I.a.debug("Receive signal stream error",{error:ye});break;case k.StatusCode.UNAUTHENTICATED:I.a.warn("Receive signal stream error",{error:ye});break;default:I.a.error("Receive signal stream error",{error:ye})}me.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=me})}createRTCPeerConnection(q,$){var te;return be(this,void 0,void 0,function*(){const le=$==null?void 0:$.rtcIceTransportPolicies,ae=$!=null&&$.rtcIceServerProtocol?[$==null?void 0:$.rtcIceServerProtocol]:void 0,me=q.map(de=>Object.assign(Object.assign({},de),{urls:typeof de.urls=="string"?[de.urls]:de.urls})).map(de=>Object.assign(Object.assign({},de),{urls:de.urls.filter(ce=>{const ge=(le===void 0||le.some(we=>((Ee,Me)=>{switch(Me){case"stun":return/^stuns?:/.test(Ee);case"turn":return/^turns?:/.test(Ee)}})(ce,we)))&&(ae===void 0||ae.some(we=>((Ee,Me)=>Ee.endsWith(`transport=${Me}`))(ce,we)));return ge||I.a.debug(`Ignoring ICE server: ${ce}`),ge})})).filter(({urls:de})=>de.filter(ce=>ce).length>0),ye=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!ye)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new ye(Object.assign({iceServers:me,iceTransportPolicy:(le==null?void 0:le.length)===1&&le[0]==="turn"?"relay":"all"},$))})}closeConnections(q){return be(this,void 0,void 0,function*(){const $=yield R(q.map(te=>be(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 be(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(ye=>ye.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(ye=>!ye.isActive())),this.connections=this.connections.filter(ye=>ye.isActive());const{localPeer:te}=this,le=this.connections.filter(ye=>ye.getSessionId).map(ye=>d(ye.getSessionId()));te.setSessionIdsList(le);const ae=new L.RefreshPeerRequest;ae.setPeer(te);try{yield $.refreshPeer(ae,yield this.getMetadata({}))}catch(ye){ye.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:ye})}const me=yield this.getPeers();for(const ye of this.connections)ye.setRemoteDeviceId((q=me.find(de=>de.id===ye.getRemotePeerId()))===null||q===void 0?void 0:q.deviceId)})}reset(){return be(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 be(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 le=(yield this.config.signalingClient.getIceServers(new L.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(le),this.iceServersLastUpdate=te}catch(le){I.a.warn("Error in updateIceServers",{error:le})}})}setupHandlers(q){const{peerConnection:$}=q,te=q.getSessionCreatedTimestamp();$.onconnectionstatechange=()=>be(this,void 0,void 0,function*(){const le=$.connectionState;if(te)switch(le){case"connected":O.aggregate("rtc-connect-time",new Date().getTime()-te);break;case"failed":O.increment("rtc-connect-failed")}})}getMetadata(q){return be(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:le}=q,ae=le===!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,g,u){return new(g||(g=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 g?w:new g(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);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");function delay(e){return new Promise(t=>setTimeout(t,e))}function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}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 Re=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 Re.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(n){return Re.waitingForAuth.forEach(o=>o(!1)),Re.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let o;if(Re.isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(Re.currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(Re.currentOrganization=n["custom:organization_id"]),Re.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);Re.currentUser=s}Re.token=t,Re.waitingForAuth.forEach(l=>l(!0))}catch(o){console.error(o),Re.waitingForAuth.forEach(l=>l(!1))}Re.waitingForAuth=[],r&&(Re.refreshToken=r,setInterval(async()=>{if(Re.refreshToken){const l=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Re.refreshToken})})).json();Re.token=l.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Re.token!==void 0}static getCurrentUser(){return Re.currentUser}static async waitTilAuthenticated(){return Re.token!==void 0?!0:new Promise(t=>{Re.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Re;je(Authentication,"token"),je(Authentication,"refreshToken"),je(Authentication,"currentUser"),je(Authentication,"currentOrganization"),je(Authentication,"isShareToken",!1),je(Authentication,"defaultDeviceId"),je(Authentication,"waitingForAuth",[]);class DataChannel{constructor(t){je(this,"ready",!1);je(this,"listeners",[]);je(this,"binaryListeners",[]);je(this,"error");je(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0},this.dataChannel.onclose=()=>{this.ready=!1},this.dataChannel.onerror=r=>{console.error(r),this.error="An error occurred in DataChannel"},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))})}}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){je(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){je(this,"currentListeners",[]);je(this,"onRealtimeMessage",(t,r)=>{r.payload.jointState&&this.currentListeners.forEach(n=>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){je(this,"channel");je(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);je(this,"RESPONSE_SUCCESS_BYTE",0);je(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 g=new Date().getTime();for(;new Date().getTime()<g+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{name:"AdapterError",message:this.decoder.decode(A)}}}throw o.delete(i),{name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}}}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:g,error:u}=i;if(g)return g;if(u)throw{name:"AdapterError",message:u}}}throw n.delete(l),{name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}}}var SessionType=(e=>(e[e.Teleop=1]="Teleop",e[e.Observe=3]="Observe",e))(SessionType||{});class Device{constructor(t,r,n){je(this,"rtcClient");je(this,"remoteDevicePeerId");je(this,"realtimeListeners",[]);je(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(){if(this.rtcClient)throw new Error(`Already created realtime connection to device ${this.id}`);{const t=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(;!t.isReady();)await delay(100);const n=(await t.getPeers()).find(o=>o.deviceId===this.id);if(!n)throw new Error("Cannot find peer, is the robot offline?");for(this.remoteDevicePeerId=n.id,await t.connect(this.remoteDevicePeerId,void 0);t.getConnectionStatus(this.remoteDevicePeerId)!=="connected";)await delay(100);this.rtcClient=t}}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(){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}))}async sendCommand(t,r,n,o){var A;const s=(await this.getAvailableCommands()).find(_=>_.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 g={value:i,scrubberTime:(n||new Date).toISOString(),meta:it(it({},s.parameterMeta),o)};return(await(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:g,userId:(A=Authentication.currentUser)==null?void 0:A.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}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,it({ordered:!0},r),!1,(i,g)=>{const u=new DataChannel(g);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,g;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(g=(i=t.telemetry)==null?void 0:i.streams)==null||g.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){je(this,"rtcClient");je(this,"remoteDevicePeerId");je(this,"realtimeListeners",[]);je(this,"id");je(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,it({ordered:!0},r),!1,(i,g)=>{const u=new DataChannel(g);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 Ce=class{static async setDefaultDevice(t){Ce.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ce.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===Ce.defaultDeviceId).name,l=new Device(Ce.defaultDeviceId,o,defined(Authentication.currentOrganization));return Ce.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 Ce.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 Ce.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 Ce.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 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 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=Ce;je(Fleet,"defaultDeviceId"),je(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",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId}),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}}}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.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,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 g=0;g<i.length;g++){var u=i[g];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,g;return i=s,(g=[{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,g),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,g){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(g).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,g,u;typeof performance!="undefined"&&performance!==null&&performance.now?e.exports=function(){return performance.now()}:n!=null&&n.hrtime?(e.exports=function(){return(o()-g)/1e6},l=n.hrtime,i=(o=function(){var b;return 1e9*(b=l())[0]+b[1]})(),u=1e9*n.uptime(),g=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,g=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:g+1,T=P-i+(N-g)/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,g=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 g=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[g+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,g){if(g=g===void 0?{fatal:!1}:g,(i=i===void 0?"utf-8":i)!=="utf-8")throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+i+"') is invalid.");if(g.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,g){if((g=g===void 0?{stream:!1}:g).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");g=0;for(var u=i.length,b=0,A=Math.max(32,u+(u>>1)+7),_=new Uint8Array(A>>3<<3);g<u;){var v=i.charCodeAt(g++);if(55296<=v&&56319>=v){if(g<u){var f=i.charCodeAt(g);(64512&f)==56320&&(++g,v=((1023&v)<<10)+(1023&f)+65536)}if(55296<=v&&56319>=v)continue}if(b+4>_.length&&(A+=8,A=(A*=1+g/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,g){if((g=g===void 0?{stream:!1}:g).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");g=0;for(var u=(i=new Uint8Array(i)).length,b=[];g<u;){var A=i[g++];if(A===0)break;if((128&A)==0)b.push(A);else if((224&A)==192){var _=63&i[g++];b.push((31&A)<<6|_)}else if((240&A)==224){_=63&i[g++];var v=63&i[g++];b.push((31&A)<<12|_<<6|v)}else(248&A)==240&&(65535<(A=(7&A)<<18|(_=63&i[g++])<<12|(v=63&i[g++])<<6|63&i[g++])&&(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 Oe});var n=r(25),o=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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:le}){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:le})})})}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,le){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:le})})})}getFeatures(q){return o(this,void 0,void 0,function*(){return(yield this.fetch("auth/features",{token:q})).features})}}var s=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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 g=r(1),u=r(11),b=r(35),A=r.n(b),_=r(102),v=r.n(_),f=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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 le=this.stringify(q);if(!this.cache.set(le,$,{ttl:te})){const ae=this.cache.sizeCalculation?this.cache.sizeCalculation($,le):"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:g.a.second,this.rejectedPromiseValueTtl<0)throw new Error("rejectedPromiseValueTtl must not be negative")}set(q,$,te){const le=this.stringify(q);this.cache.set(le,$,{ttl:te}),this.expireRejectedPromiseValues&&Promise.resolve($).catch(()=>f(this,void 0,void 0,function*(){yield Object(u.a)(this.rejectedPromiseValueTtl),this.cache.peek(le)===$&&this.cache.delete(le)}))}}var w=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class P{constructor(q,$,te){this.authClient=q,this.email=$,this.password=te,this.tokenTtlMs=1*g.a.hour,this.tokenCache=new S({max:100,ttl:this.tokenTtlMs-5*g.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/g.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(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};function R(pe){return T(this,void 0,void 0,function*(){return(yield Promise.all(pe.map(q=>q.catch($=>$)))).filter(q=>q instanceof Error)})}function d(pe){if(pe!==void 0)return pe;throw new Error("Value is undefined")}var I=r(0),Q=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};function Z({func:pe,delay:q,immediate:$}){let te=!1,le=setTimeout(function me(){return Q(this,void 0,void 0,function*(){if(te)return;const ye=new Date().getTime();try{ae=pe(),yield ae}finally{if(!te){const de=new Date().getTime();le=setTimeout(me,Math.max(q-(de-ye),0))}}})},$?0:q),ae=Promise.resolve();return{stop(){return Q(this,void 0,void 0,function*(){te=!0,clearTimeout(le),yield ae})}}}function h(pe,q){return Object.keys(pe).reduce(($,te)=>Object.assign(Object.assign({},$),{[te]:q(pe[te])}),{})}var p=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class C{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:le}=$,ae=te/le;return Object.assign(Object.assign({},$),{average:ae})}))})}}var m=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};const x=r(222);var F=r(6);const D=!!F.c,O=new class{constructor(pe=60){this.buffer={},this.metrics={},this.reporters=[],this.flushInterval=Z({func:()=>this.flushStats(),delay:pe*g.a.second})}shutdown(){return m(this,void 0,void 0,function*(){yield this.flushInterval.stop(),yield this.flushStats(),yield Object(u.a)(2*g.a.second)})}aggregate(pe,q){if(this.buffer[pe]){const{min:$,max:te,sum:le,count:ae}=this.buffer[pe];this.buffer[pe]={min:Math.min($,q),max:Math.max(te,q),sum:le+q,count:ae+1}}else this.buffer[pe]={min:q,max:q,sum:q,count:1}}increment(pe){this.aggregate(pe,1)}timer(pe,q){return m(this,void 0,void 0,function*(){const $=x(),te=yield q(),le=x();return this.aggregate(pe,le-$),te})}metric(pe,q){this.metrics[pe]=q}registerStatsReporter(pe){this.reporters.push(pe)}write(pe){return m(this,void 0,void 0,function*(){if(Object.values(pe).length===0)return;const q=yield R(this.reporters.map($=>$.send(pe)));for(const $ of q)I.a.warn("Failed to write stats",{error:$})})}flushStats(){return m(this,void 0,void 0,function*(){const pe=Object.assign(Object.assign({},this.buffer),h(this.metrics,q=>{const $=q();return{min:$,max:$,sum:$,count:1}}));Object.keys(pe).length>0&&(yield this.write(pe),this.buffer={})})}};D||["local","on-prem"].includes(F.i)||O.registerStatsReporter(new C("stats"));var L=r(8),k=r(21),E=r(103),c=r(36),U=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class B extends c.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*g.a.millisecond},K={ordered:!0},H={ordered:!0},V={ordered:!1,maxRetransmits:0},y={ordered:!1,maxRetransmits:0};function j({entityId:pe,streamName:q,streamType:$}){return`${pe}.${q}.${$}`}var W=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,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(le=>{var ae,me;return{streamId:le,sentCount:(ae=$.get(le))!==null&&ae!==void 0?ae:0,receivedCount:(me=te.get(le))!==null&&me!==void 0?me:0}}),timestamp:q}}incrementLocalSent(q){const{localSent:$}=this.counts,te=j(q.header.stream);$.set(te,($.get(te)||0)+1)}incrementLocalReceived(q){const{localReceived:$}=this.counts,te=j(q.header.stream),le=$.get(te)||0;if(le===0){const{streamName:ae,streamType:me}=q.header.stream;I.a.debug("RTC client received first message for stream",{streamName:ae,streamType:me})}$.set(te,le+1)}uploadMetrics(){return W(this,void 0,void 0,function*(){const{sessionId:q}=this,$=yield this.connection.peerConnection.getStats(),te={};$.forEach(ce=>te[ce.id]=ce),I.a.debug("rtc-stats",Object.assign(Object.assign({},te),{sessionId:q}));const{localSent:le,localReceived:ae,remoteSent:me,remoteReceived:ye}=this.counts,de=[...new Set([...le.keys(),...ae.keys()])].reduce((ce,ge)=>{const we=le.get(ge),Ee=ae.get(ge),Me=me.get(ge),xe=ye.get(ge);return Object.assign(Object.assign({},ce),{[`local-${ge}-sent`]:we,[`local-${ge}-received`]:Ee,[`remote-${ge}-sent`]:Me,[`remote-${ge}-received`]:xe})},{sessionId:q});I.a.debug("rtc-message-report",Object.assign({deviceId:this.connection.getRemoteDeviceId()},de))})}}function X(pe){return new Set(["disconnected","failed","closed"]).has(pe.iceConnectionState)}var re=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class ie{constructor(q,$,te){this.peerConnection=q,this.config=$,this.dataChannelNotifier=te,this.connectTimeoutMs=20*g.a.second,this.iceGatheringTimeoutMs=15*g.a.second,this.pingUpdateTimeoutMs=1*g.a.second,this.streamsInfoUpdateTimeoutMs=2*g.a.second,this.reassemblyTimeoutMs=500*g.a.millisecond,this.reassemblyTableCleanupMs=1*g.a.second,this.heartbeatTimeoutMs=20*g.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:le}=$.baseConfig;le?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((me,ye,de)=>{ae>ye+this.reassemblyTimeoutMs&&this.reassemblyTable.delete(me)})},this.reassemblyTableCleanupMs),this.heartbeatTimeout=setInterval(()=>{const{heartbeatChannel:ae}=this;ae&&ae.readyState==="open"&&ae.send(new Uint8Array([1]))},this.heartbeatTimeoutMs)}handleSignal(q){return re(this,void 0,void 0,function*(){const{peerConnection:$}=this,{track:te}=this.config.baseConfig,le=(()=>{try{return JSON.parse(q.getPayload())}catch{return}})();if(!le)return void I.a.error("Received unparseable signal.");I.a.debug("Handling signal",{description:le});const{sdp:ae,type:me}=le;if(!ae||!me)return void I.a.warn("Received non-SDP signal");const{signalingState:ye,connectionState:de}=$;if(ye!=="stable"||de!=="connected")if($.remoteDescription)I.a.warn(`Received SDP after remote description was set: ${ae}`);else{if(me==="offer"){if(ye!=="stable")return void I.a.warn("Received offer SDP when signaling is ongoing.");yield $.setRemoteDescription(le);const ce=yield $.createAnswer();yield $.setLocalDescription(ce);const ge=q.clone();return te==null||te("Answer Received",ge),ge.setPayload(JSON.stringify(ce)),ge.setReceiverId(q.getSenderId()),ge.setSenderId(q.getReceiverId()),ge}if(me==="answer"){if(ye==="stable")return void I.a.warn("Received answer SDP when signaling hasn't started.");yield $.setRemoteDescription(le)}}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:le}=this;return(q==null?void 0:q.readyState)==="open"&&($==null?void 0:$.readyState)==="open"&&(te==null?void 0:te.readyState)==="open"&&(le==null?void 0:le.readyState)==="open"}close(){return re(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:le,latestReliableStreamChannel:ae}=this;q.close(),$==null||$.close(),te==null||te.close(),le==null||le.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 re(this,void 0,void 0,function*(){const{peerConnection:q}=this;if(!q)return;const $=yield q.getStats(null),te=[];$.forEach(de=>{te.push(de)});const le=te.find(de=>de.type==="transport");if(!le)return;const ae=te.find(de=>(de.type==="candidate-pair"||de.type==="candidatepair")&&de.id===le.selectedCandidatePairId);if(!ae)return;const me=te.find(de=>de.id===ae.localCandidateId),ye=te.find(de=>de.id===ae.remoteCandidateId);return me&&ye&&(me.address=me.address||me.ip,ye.address=ye.address||ye.ip,me.address!==void 0&&ye.address!==void 0)?{transport:le,localCandidate:me,remoteCandidate:ye}: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 re(this,void 0,void 0,function*(){const{gotOffer:le}=this,{peerConnection:ae,config:me}=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 ye=(q=this.config.remoteConfig)===null||q===void 0?void 0:q.sessionId;if(le)return void I.a.debug("Failed to generate offer because gotOffer was already called.");if(this.gotOffer=!0,X(this.peerConnection))return void I.a.debug("Failed to generate offer because the peer connection was inactive.");const de=me.baseConfig.track;ae.onicecandidate=()=>{this.hasIceCandidate=!0},ae.oniceconnectionstatechange=()=>re(this,void 0,void 0,function*(){const Me=ae.iceConnectionState;if(Me==="connected"||Me==="completed"){const xe=yield this.getConnectionStatsInfo(),Fe=xe?function(Be){const De=Be.localCandidate.candidateType,Ue=Be.remoteCandidate.candidateType;return De==="host"&&Ue==="host"?"local":De==="relay"||Ue==="relay"?"TURN":"STUN"}(xe):void 0;I.a.info(`ICE connection state changed to ${Me}`,{sessionId:ye,connectionStatsInfo:xe,iceMode:Fe}),de==null||de("ICE connection state change",{iceConnectionState:Me,sessionId:ye,connectionStatsInfo:xe,iceMode:Fe})}}),yield ae.setLocalDescription(yield ae.createOffer());const ce=new Date().getTime();for(;;){const Me=new Date().getTime()-ce;if(Me>this.connectTimeoutMs)return void I.a.debug("Failed to generate offer because ICE gathering timed out.");if(Me>this.iceGatheringTimeoutMs&&this.hasIceCandidate){I.a.debug("ICE gathering partially completed; proceeding",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me}),de==null||de("ICE gathering partially completed",{sessionId:ye,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me});break}if(ae.iceGatheringState==="complete"){I.a.debug("ICE gathering complete",{iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me}),de==null||de("ICE gathering completed",{sessionId:ye,iceTransportPolicy:ae.getConfiguration().iceTransportPolicy,waitTime:Me});break}yield Object(u.a)(.1*g.a.second)}const ge=($=this.peerConnection.getConfiguration().iceServers)!==null&&$!==void 0?$:[];for(const Me of ge)Me.credentialType=void 0;const we=JSON.stringify(ge),Ee=new L.Signal;return Ee.setPayload(JSON.stringify(ae.localDescription)),Ee.setSenderId(this.config.baseConfig.localPeerId),Ee.setReceiverId(this.config.baseConfig.remotePeerId),Ee.setIceServers(we),Ee.setIceTransportPolicy((te=this.peerConnection.getConfiguration().iceTransportPolicy)!==null&&te!==void 0?te:"all"),this.config.baseConfig.sessionType!==void 0?Ee.setSessionType(this.config.baseConfig.sessionType):Ee.setSessionType(L.SessionType.TELEOP),I.a.debug("Sending offer signal with description",{description:Ee.getPayload()}),Ee})}getLanOffer(){return re(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,X(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*g.a.second)}const le=q.localDescription;if(le)return I.a.debug("Sending LAN offer signal with description",{description:le}),le;I.a.error("Failed to generate LAN offer description")})}handleLanAnswer(q){return re(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(le){return void I.a.warn("Failed to encode RTC message",{error:le})}try{q.send(te),this.sessionMetrics&&this.sessionMetrics.incrementLocalSent($)}catch(le){I.a.warn("Failed to send message to channel",{error:le,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(le){return void I.a.warn("Received unparseable message on RTC stream data channel",{error:le,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:le}=this.config.baseConfig;this.lastMessageTimestamp=new Date().getTime(),$=function(ae){switch(ae.header.stream.streamType){case"twist":{const{twist:me}=ae.payload;if(!me)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},me.linear),angular:Object.assign({x:0,y:0,z:0},me.angular)}}}}case"pose":{const{pose:me}=ae.payload;if(!me)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},me.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},me.rotation)}}}}case"pose-with-covariance":{const{poseWithCovariance:me}=ae.payload;if(!me)throw Error("poseWithCovariance not in payload of RTC message with type pose-with-covariance");const ye=new Array(36).fill(0);return me.covariance.forEach((de,ce)=>{if(ce>=36)throw Error("covariance contains more than 36 elements");ye[ce]=de}),{header:ae.header,payload:{poseWithCovariance:{pose:{translation:Object.assign({x:0,y:0,z:0},me.pose.translation),rotation:Object.assign({x:0,y:0,z:0,w:0},me.pose.rotation)},covariance:ye}}}}case"point":{const{point:me}=ae.payload;if(!me)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},me)}}}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(le,$)}receiveChannelMessageChunk(q,$){const te=this.reassemblyTable.get($.id)||[];if(te.push($),te.length===$.total){const le=function(ae){const me=ae.sort((ye,de)=>ye.seq<de.seq?-1:1).map(ye=>ye.part).reduce((ye,de)=>ye+de);try{return JSON.parse(me)}catch{return void I.a.warn("Could not reassemble RTC message chunks")}}(te);return le&&this.receiveChannelMessage(q,le),void this.reassemblyTable.delete($.id)}this.reassemblyTable.set($.id,te),this.reassemblyTableLastTimestamp.set($.id,new Date().getTime())}handleSystemMessage(q,$){var te,le;const{config:ae}=this,{baseConfig:me}=ae,{remotePeerId:ye}=me;switch($.header.stream.streamType){case"ping":return this.sendSystemMessage(q,{type:"pong",timestamp:d($.payload.ping)}),!0;case"pong":{const de=new Date().getTime()-d($.payload.pong);return this.pingTimeMs=de,O.aggregate("rtc-ping-time",de),!0}case"streams-info":{const{sessionMetrics:de}=this,ce=(te=$.payload.streamsInfo)===null||te===void 0?void 0:te.timestamp;return!!ce&&(de==null||de.updateRemoteMessagesCounts($),(le=me.onStreamsInfoUpdate)===null||le===void 0||le.call(me,ye,ce),!0)}case"stream-control":return!0;default:return!1}}sendSystemMessage(q,$){var te;const{localUserId:le,localPeerId:ae}=this.config.baseConfig;if(q.readyState!=="open")return;const me={entityId:le!=null?le:ae,streamName:`$.${$.type}`,streamType:$.type};let ye;switch($.type){case"ping":ye={ping:new Date().getTime()};break;case"pong":ye={pong:$.timestamp};break;case"stream-control":ye={streamControl:$.streamControl};break;case"streams-info":ye={streamsInfo:(te=this.sessionMetrics)===null||te===void 0?void 0:te.getLocalStreamsInfo(new Date().getTime())}}this.sendOnChannel(q,function(de,ce){return{header:{stream:de,created:Date.now(),frameId:""},payload:ce}}(me,ye))}isLatestMessage(q){const $=j(q.header.stream),te=(this.streamLatestTimestamp.get($)||0)<=q.header.created;return te&&this.streamLatestTimestamp.set($,q.header.created),te}}function he(pe){var q,$;return{userId:(q=pe.getUserId())===null||q===void 0?void 0:q.getValue(),deviceId:($=pe.getDeviceId())===null||$===void 0?void 0:$.getValue(),organizationId:pe.getOrganizationId(),id:pe.getPeerId(),capabilities:[],capabilitySet:{}}}var be=function(pe,q,$,te){return new($||($=Promise))(function(le,ae){function me(ce){try{de(te.next(ce))}catch(ge){ae(ge)}}function ye(ce){try{de(te.throw(ce))}catch(ge){ae(ge)}}function de(ce){var ge;ce.done?le(ce.value):(ge=ce.value,ge instanceof $?ge:new $(function(we){we(ge)})).then(me,ye)}de((te=te.apply(pe,q||[])).next())})};class Oe{constructor(q){this.config=q,this.grpcCallDeadline=5*g.a.second,this.refreshIntervalDelayMs=2*g.a.second,this.iceServersTtl=30*g.a.minute,this.connections=[],this.localConnections=[],this.isConnectionInitiator=new Map,this.isOutgoingConnection=new Map,this.peerDataChannelListeners=[];const{refreshIntervalDelayMs:$}=this;this.refreshInterval=Z({func:()=>be(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 le=this.getActiveConnection(q);le?le.isReady()?le.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 be(this,void 0,void 0,function*(){for(;!this.localPeer;)yield Object(u.a)(.1*g.a.second);return he(this.localPeer)})}connect(q,$){var te,le,ae;return be(this,void 0,void 0,function*(){if(this.config.lanOnlyMode===!0)throw new Error("connect method called in local only mode.");const{track:me,signalingClient:ye}=this.config,{localPeer:de,receiveSignalStream:ce,iceServers:ge}=this;if(!de||!ce||!ge)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 we=new ie(yield this.createRTCPeerConnection(ge,$),{baseConfig:{isOffer:!0,isLan:!1,receive:(De,Ue)=>this.config.receive(De,Ue),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(De,Ue)=>{var ke,We;return(We=(ke=this.config).onStreamsInfoUpdate)===null||We===void 0?void 0:We.call(ke,De,Ue)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localUserId:(te=de.getUserId())===null||te===void 0?void 0:te.getValue(),localPeerId:de.getPeerId(),remotePeerId:q,sessionType:$==null?void 0:$.sessionType},remoteConfig:{}},De=>this.onCustomDataChannel(q,De)),Ee=yield we.getOffer();if(!Ee)return I.a.error("Failed to generate offer."),void this.isOutgoingConnection.delete(q);I.a.debug("Sending offer."),me==null||me("Sending offer",Ee);const Me=new L.SendSignalRequest;Me.setSignal(Ee);const xe=yield(()=>be(this,void 0,void 0,function*(){try{return yield ye.sendSignal(Me,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=(le=xe==null?void 0:xe.getSessionId())===null||le===void 0?void 0:le.getValue(),Be=(ae=xe==null?void 0:xe.getSessionCreatedTimestamp())===null||ae===void 0?void 0:ae.getValue();return Fe&&Be?(we.setSessionId(Fe),we.setSessionCreatedTimestamp(Be),this.isOutgoingConnection.delete(q),this.connections.push(we),this.isConnectionInitiator.set(we,!0),this.setupHandlers(we),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 be(this,void 0,void 0,function*(){const le=new B(q),ae=new ie(yield this.createRTCPeerConnection([]),{baseConfig:{isOffer:!0,isLan:!0,receive:(ce,ge)=>this.config.receive(ce,ge),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ce,ge)=>{var we,Ee;return(Ee=(we=this.config).onStreamsInfoUpdate)===null||Ee===void 0?void 0:Ee.call(we,ce,ge)}: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}},ce=>this.onCustomDataChannel(q,ce)),me=yield ae.getLanOffer();if(!me)return I.a.warn("Could not generate LAN offer"),!1;const ye=yield le.postLanRtcOffer({offer:JSON.stringify(me)}),de=new RTCSessionDescription(JSON.parse(ye.answer));return yield ae.handleLanAnswer(de),this.localConnections.push(ae),this.isConnectionInitiator.set(ae,!0),Object(E.v4)()})}getConnections(){return[...this.connections,...this.localConnections]}createCustomDataChannel(q,$,te,le,ae){const me=this.getActiveConnection(q);if(me&&this.isConnectionInitiator.has(me)){const de=me.peerConnection.createDataChannel("custom."+$,te);return le&&(de.binaryType="arraybuffer"),ae(q,de),()=>{}}const ye=(de,ce)=>{q===de&&ce.label==="custom."+$&&ae(q,ce)};return this.peerDataChannelListeners.push(ye),()=>{this.peerDataChannelListeners=this.peerDataChannelListeners.filter(de=>de!==ye)}}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 be(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);if($)return yield $.getConnectionStatsInfo()})}disconnect(q){return be(this,void 0,void 0,function*(){const $=this.getActiveConnection(q);$&&(yield $.close())})}getPeers(){return be(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(()=>be(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 le=ae=>{var me,ye;return(ye=(me=ae.getPeerCreatedTimestamp())===null||me===void 0?void 0:me.getValue())!==null&&ye!==void 0?ye:0};return te.sort((ae,me)=>le(me)-le(ae)).map(ae=>he(ae))})}getSessions(){return be(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(()=>be(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(),le={};for(const ae of te)le[ae.getPeerId()]=ae.getSessionIdsList();return le})}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 be(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(()=>be(this,void 0,void 0,function*(){try{const le=new L.DeletePeerRequest;le.setPeerId($.getPeerId()),yield te.deletePeer(le,yield this.getMetadata({}))}catch(le){return void I.a.warn("Error deleting local peer",{error:le})}}))()})}createPeer(){return be(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(()=>be(this,void 0,void 0,function*(){try{return yield q.createPeer(new L.CreatePeerRequest,yield this.getMetadata({}))}catch(le){throw new Error(`Was not able to create peer: ${JSON.stringify(le)}`)}}))(),te=$==null?void 0:$.getPeer();if(!te)throw new Error("Response did not provide peer.");return this.localPeer=te})}createReceiveSignalStream(){return be(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:le}=this;le&&le.cancel();const ae=new L.ReceiveSignalStreamRequest;ae.setPeerId($.getPeerId());const me=yield(()=>be(this,void 0,void 0,function*(){try{return q.receiveSignalStream(ae,yield this.getMetadata({hasDeadline:!1}))}catch(ye){throw new Error(`Unable to create receive signal stream: ${JSON.stringify(ye)}`)}}))();if(!me)throw new Error("Response did not provide stream.");return me.on("data",ye=>be(this,void 0,void 0,function*(){var de,ce,ge,we;const Ee=ye.getSignal(),Me=(de=Ee==null?void 0:Ee.getSessionId())===null||de===void 0?void 0:de.getValue(),xe=Ee==null?void 0:Ee.getSenderId(),Fe=Ee==null?void 0:Ee.getReceiverId(),Be=(ce=Ee==null?void 0:Ee.getSessionCreatedTimestamp())===null||ce===void 0?void 0:ce.getValue();if(!(Ee&&Me&&xe&&Fe&&Be))return void I.a.warn("Received signal with missing information.");const De=this.getActiveConnection(xe);if(De)if(De.getSessionId()!==Me){if(I.a.debug("Received signal: different session for a peer we're already connected to."),(De.getSessionCreatedTimestamp()||0)>Be)return;const Ue=new ie(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,We)=>this.config.receive(ke,We),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,We)=>{var Ye,ze;return(ze=(Ye=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(Ye,ke,We)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(we=$.getUserId())===null||we===void 0?void 0:we.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Me,sessionCreatedTimestamp:Be}},ke=>this.onCustomDataChannel(xe,ke));yield Ue.handleSignal(Ee),this.connections.push(Ue)}else I.a.debug("Received signal: for an existing connection."),yield De.handleSignal(Ee);else{I.a.debug("Received signal: new connection.");const Ue=new ie(yield this.createRTCPeerConnection(te),{baseConfig:{isOffer:!1,isLan:!1,receive:(ke,We)=>this.config.receive(ke,We),onStreamsInfoUpdate:this.config.onStreamsInfoUpdate?(ke,We)=>{var Ye,ze;return(ze=(Ye=this.config).onStreamsInfoUpdate)===null||ze===void 0?void 0:ze.call(Ye,ke,We)}:void 0,track:this.config.lanOnlyMode?void 0:this.config.track,localPeerId:$.getPeerId(),localUserId:(ge=$.getUserId())===null||ge===void 0?void 0:ge.getValue(),remotePeerId:xe},remoteConfig:{sessionId:Me,sessionCreatedTimestamp:Be}},ke=>this.onCustomDataChannel(xe,ke));yield Ue.handleSignal(Ee),this.connections.push(Ue)}})),me.on("end",()=>{me.cancel(),this.receiveSignalStream=void 0}),me.on("error",ye=>{switch(ye.code){case k.StatusCode.CANCELLED:case k.StatusCode.UNAVAILABLE:case k.StatusCode.UNKNOWN:I.a.debug("Receive signal stream error",{error:ye});break;case k.StatusCode.UNAUTHENTICATED:I.a.warn("Receive signal stream error",{error:ye});break;default:I.a.error("Receive signal stream error",{error:ye})}me.cancel(),this.receiveSignalStream=void 0}),this.receiveSignalStream=me})}createRTCPeerConnection(q,$){var te;return be(this,void 0,void 0,function*(){const le=$==null?void 0:$.rtcIceTransportPolicies,ae=$!=null&&$.rtcIceServerProtocol?[$==null?void 0:$.rtcIceServerProtocol]:void 0,me=q.map(de=>Object.assign(Object.assign({},de),{urls:typeof de.urls=="string"?[de.urls]:de.urls})).map(de=>Object.assign(Object.assign({},de),{urls:de.urls.filter(ce=>{const ge=(le===void 0||le.some(we=>((Ee,Me)=>{switch(Me){case"stun":return/^stuns?:/.test(Ee);case"turn":return/^turns?:/.test(Ee)}})(ce,we)))&&(ae===void 0||ae.some(we=>((Ee,Me)=>Ee.endsWith(`transport=${Me}`))(ce,we)));return ge||I.a.debug(`Ignoring ICE server: ${ce}`),ge})})).filter(({urls:de})=>de.filter(ce=>ce).length>0),ye=(te=this.config.alternateRTCPeerConnection)!==null&&te!==void 0?te:window.RTCPeerConnection;if(!ye)throw new Error("RTCPeerConnection class not found. WebRTC must be enabled.");return new ye(Object.assign({iceServers:me,iceTransportPolicy:(le==null?void 0:le.length)===1&&le[0]==="turn"?"relay":"all"},$))})}closeConnections(q){return be(this,void 0,void 0,function*(){const $=yield R(q.map(te=>be(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 be(this,void 0,void 0,function*(){if(this.localConnections=this.localConnections.filter(ye=>ye.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(ye=>!ye.isActive())),this.connections=this.connections.filter(ye=>ye.isActive());const{localPeer:te}=this,le=this.connections.filter(ye=>ye.getSessionId).map(ye=>d(ye.getSessionId()));te.setSessionIdsList(le);const ae=new L.RefreshPeerRequest;ae.setPeer(te);try{yield $.refreshPeer(ae,yield this.getMetadata({}))}catch(ye){ye.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:ye})}const me=yield this.getPeers();for(const ye of this.connections)ye.setRemoteDeviceId((q=me.find(de=>de.id===ye.getRemotePeerId()))===null||q===void 0?void 0:q.deviceId)})}reset(){return be(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 be(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 le=(yield this.config.signalingClient.getIceServers(new L.GetIceServersRequest,yield this.getMetadata({}))).getIceServers();this.iceServers=JSON.parse(le),this.iceServersLastUpdate=te}catch(le){I.a.warn("Error in updateIceServers",{error:le})}})}setupHandlers(q){const{peerConnection:$}=q,te=q.getSessionCreatedTimestamp();$.onconnectionstatechange=()=>be(this,void 0,void 0,function*(){const le=$.connectionState;if(te)switch(le){case"connected":O.aggregate("rtc-connect-time",new Date().getTime()-te);break;case"failed":O.increment("rtc-connect-failed")}})}getMetadata(q){return be(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:le}=q,ae=le===!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,g,u){return new(g||(g=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 g?w:new g(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);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");function delay(e){return new Promise(t=>setTimeout(t,e))}function defined(e,t){if(e!==void 0)return e;throw new Error(t||"Value is undefined")}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 Re=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 Re.loginWithToken(o.authentication.accessToken,o.authentication.refreshToken),o.authentication}catch(n){return Re.waitingForAuth.forEach(o=>o(!1)),Re.waitingForAuth=[],Promise.reject(n)}}static async loginWithToken(t,r){const n=JSON.parse(atob(t.split(".")[1]));try{let o;if(Re.isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(Re.currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(Re.currentOrganization=n["custom:organization_id"]),Re.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);Re.currentUser=s}Re.token=t,Re.waitingForAuth.forEach(l=>l(!0))}catch(o){console.error(o),Re.waitingForAuth.forEach(l=>l(!1))}Re.waitingForAuth=[],r&&(Re.refreshToken=r,setInterval(async()=>{if(Re.refreshToken){const l=await(await fetch(`${FORMANT_API_URL}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:Re.refreshToken})})).json();Re.token=l.authentication.accessToken}},1e3*60*60))}static isAuthenticated(){return Re.token!==void 0}static getCurrentUser(){return Re.currentUser}static async waitTilAuthenticated(){return Re.token!==void 0?!0:new Promise(t=>{Re.waitingForAuth.push(function(r){t(r)})})}static async listenForRefresh(){App.addAccessTokenRefreshListener(t=>{this.loginWithToken(t)}),setInterval(async()=>{App.refreshAuthToken()},1e3*60*60)}};let Authentication=Re;je(Authentication,"token"),je(Authentication,"refreshToken"),je(Authentication,"currentUser"),je(Authentication,"currentOrganization"),je(Authentication,"isShareToken",!1),je(Authentication,"defaultDeviceId"),je(Authentication,"waitingForAuth",[]);class DataChannel{constructor(t){je(this,"ready",!1);je(this,"listeners",[]);je(this,"binaryListeners",[]);je(this,"error");je(this,"decoder",new TextDecoder);this.dataChannel=t,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.ready=!0},this.dataChannel.onclose=()=>{this.ready=!1},this.dataChannel.onerror=r=>{console.error(r),this.error="An error occurred in DataChannel"},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))})}}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){je(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){je(this,"currentListeners",[]);je(this,"onRealtimeMessage",(t,r)=>{r.payload.jointState&&this.currentListeners.forEach(n=>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){je(this,"channel");je(this,"requestIdToResponseMap",new Map);this.device=t,this.channel_name=r,this.timeout=n}}class BinaryRequestDataChannel extends RequestDataChannel{constructor(){super(...arguments);je(this,"RESPONSE_SUCCESS_BYTE",0);je(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 g=new Date().getTime();for(;new Date().getTime()<g+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{name:"AdapterError",message:this.decoder.decode(A)}}}throw o.delete(i),{name:"TimeoutError",message:`Request timed out after ${l/1e3} seconds`}}}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:g,error:u}=i;if(g)return g;if(u)throw{name:"AdapterError",message:u}}}throw n.delete(l),{name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}}}var SessionType=(e=>(e[e.Teleop=1]="Teleop",e[e.Observe=3]="Observe",e))(SessionType||{});class Device{constructor(t,r,n){je(this,"rtcClient");je(this,"remoteDevicePeerId");je(this,"realtimeListeners",[]);je(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,{sessionType:t===void 0?1:t});r.getConnectionStatus(this.remoteDevicePeerId)!=="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(){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}))}async sendCommand(t,r,n,o){var A;const s=(await this.getAvailableCommands()).find(_=>_.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 g={value:i,scrubberTime:(n||new Date).toISOString(),meta:it(it({},s.parameterMeta),o)};return(await(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:g,userId:(A=Authentication.currentUser)==null?void 0:A.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+Authentication.token}})).json()).fileUrls}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,it({ordered:!0},r),!1,(i,g)=>{const u=new DataChannel(g);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,g;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(g=(i=t.telemetry)==null?void 0:i.streams)==null||g.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){je(this,"rtcClient");je(this,"remoteDevicePeerId");je(this,"realtimeListeners",[]);je(this,"id");je(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,it({ordered:!0},r),!1,(i,g)=>{const u=new DataChannel(g);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 Ce=class{static async setDefaultDevice(t){Ce.defaultDeviceId=t}static async getCurrentDevice(){if(!Authentication.token)throw new Error("Not authenticated");if(!Ce.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===Ce.defaultDeviceId).name,l=new Device(Ce.defaultDeviceId,o,defined(Authentication.currentOrganization));return Ce.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 Ce.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 Ce.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 Ce.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 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 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=Ce;je(Fleet,"defaultDeviceId"),je(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",body:JSON.stringify({organizationId:defined(Authentication.currentUser).organizationId}),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}}}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.Authentication=Authentication,exports.BinaryRequestDataChannel=BinaryRequestDataChannel,exports.CaptureStream=CaptureStream,exports.DataChannel=DataChannel,exports.Device=Device,exports.Fleet=Fleet,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"}})});
|
|
@@ -81,7 +81,7 @@ export declare class Device implements IRealtimeDevice {
|
|
|
81
81
|
private handleMessage;
|
|
82
82
|
getRealtimeStatus(): "disconnected" | "connecting" | "connected";
|
|
83
83
|
getRealtimePing(): number | undefined;
|
|
84
|
-
startRealtimeConnection(): Promise<void>;
|
|
84
|
+
startRealtimeConnection(sessionType?: SessionType): Promise<void>;
|
|
85
85
|
addRealtimeListener(listener: RealtimeListener): void;
|
|
86
86
|
removeRealtimeListener(listener: RealtimeListener): void;
|
|
87
87
|
getRealtimeVideoStreams(): Promise<RealtimeVideoStream[]>;
|
package/package.json
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"require": "./dist/data-sdk.umd.js"
|
|
19
19
|
}
|
|
20
20
|
},
|
|
21
|
-
"version": "0.0.
|
|
21
|
+
"version": "0.0.89",
|
|
22
22
|
"scripts": {
|
|
23
23
|
"dev": "vite --port 9146",
|
|
24
24
|
"build": "tsc && vite build",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
},
|
|
33
33
|
"types": "./dist/types/data-sdk/src/main.d.ts",
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@formant/realtime-sdk": "0.0.
|
|
35
|
+
"@formant/realtime-sdk": "0.0.12",
|
|
36
36
|
"@types/google-protobuf": "^3.15.5",
|
|
37
37
|
"typedoc": "^0.22.13"
|
|
38
38
|
}
|