@formant/data-sdk 1.14.0 → 1.14.1

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.
@@ -1,3 +1,3 @@
1
- "use strict";var Se=Object.defineProperty;var Ee=(a,e,t)=>e in a?Se(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var s=(a,e,t)=>(Ee(a,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("base-64"),N=require("date-fns"),C=require("@formant/realtime-sdk"),ke=require("eventemitter3"),Oe=require("pako"),Re=require("base64-js");function be(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const u=be(N),Ae="https://api.formant.io";function De(a,e){try{if(e.get("formant_stage"))return"https://api-stage.formant.io";if(e.get("formant_dev"))return"https://api-dev.formant.io";if(e.get("formant_local"))return"https://api.formant.local";if(e.get("formant_url")){const t=e.get("formant_url");if(t!==null)try{return new URL(t).origin}catch{console.warn(`Ignoring malformed \`formant_url\` url parameter: ${t}`)}}}catch{}return typeof a<"u"&&"FORMANT_API_URL"in a&&typeof a.FORMANT_API_URL=="string"?a.FORMANT_API_URL:Ae}const h=De(typeof window<"u"?window:globalThis,new URLSearchParams(typeof window<"u"&&window.location?window.location.search:void 0));class U extends Error{constructor(t){super("login failed");s(this,"reason");this.reason=t,this.name="LoginFailureError",Object.setPrototypeOf(this,new.target.prototype)}}class J extends Error{constructor(t){super("login challenged");s(this,"challenge");this.challenge=t,this.name="LoginChallengedError",Object.setPrototypeOf(this,new.target.prototype)}}class Pe{constructor({apiUrl:e,refreshAuthToken:t,addAccessTokenRefreshListener:n}){s(this,"_refreshToken");s(this,"_isShareToken",!1);s(this,"_currentOrganization");s(this,"_currentUser");s(this,"_defaultDeviceId");s(this,"_token");s(this,"_waitingForAuth",new Set);s(this,"_refreshTimer");s(this,"_apiUrl");s(this,"_refreshAuthToken");s(this,"_addAccessTokenRefreshListener");this._apiUrl=e,this._refreshAuthToken=t,this._addAccessTokenRefreshListener=n}get token(){return this._token}get currentUser(){return this._currentUser}get currentOrganization(){return this._currentOrganization}get defaultDeviceId(){return this._defaultDeviceId}get refreshToken(){return this._refreshToken}get isShareToken(){return this._isShareToken}async login(e,t,n={}){const{advanced:i=!1}=n;try{const o=await fetch(`${this._apiUrl}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:e,password:t}),headers:{"Content-Type":"application/json"}}),c=await o.json();if(o.status!==200)throw new U(c.message);if("challenge"in c)throw new J(c.challenge);const{authentication:d}=c;return await this.loginWithToken(d.accessToken,d.refreshToken),i?{result:"success",authentication:d}:d}catch(o){if(i||console.error("login() failed",{err:o}),this._waitingForAuth.forEach(c=>c(!1)),this._waitingForAuth.clear(),!i)throw o;return o instanceof J?{result:"challenged",challenge:o.challenge}:{result:"failure",reason:o instanceof U?o.reason:o instanceof Error?o.message:String(o)}}}async loginWithToken(e,t){var i;const n=JSON.parse(G.decode(e.split(".")[1]));try{let o;if(this._isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(this._currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(this._currentOrganization=n["custom:organization_id"]),this._isShareToken||(o=n.sub),n["formant:claims"]&&n["formant:claims"].userId&&(o=n["formant:claims"].userId),o&&((i=this._currentUser)==null?void 0:i.id)!==o){const c=await fetch(`${this._apiUrl}/v1/admin/users/${o}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e}}),d=await c.json();if(c.status!==200)throw new Error(d.message);this._currentUser=d}this._token=e,this._waitingForAuth.forEach(c=>c(!0))}catch(o){console.error("loginWithToken() failed",{err:o}),this._waitingForAuth.forEach(c=>c(!1))}finally{this._waitingForAuth.clear()}t&&(this._refreshToken=t,setInterval(async()=>{if(this._refreshToken){const c=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:this._refreshToken})})).json();this._token=c.authentication.accessToken}},1e3*60*60))}isAuthenticated(){return this._token!==void 0}getCurrentUser(){return this._currentUser}async waitTilAuthenticated(){return this.token!==void 0?!0:new Promise(e=>{this._waitingForAuth.add(e)})}async listenForRefresh(){const t=()=>{this._refreshTimer=void 0,this._refreshAuthToken()};this._addAccessTokenRefreshListener(n=>{this._refreshTimer&&clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(t,36e5),this.loginWithToken(n)}),this._refreshTimer=setTimeout(t,36e5)}async forgotPassword(e){await fetch(`${this._apiUrl}/v1/admin/auth/forgot-password`,{method:"POST",body:JSON.stringify({email:e}),headers:{"Content-Type":"application/json"}})}async confirmForgotPassword(e){return(await fetch(`${this._apiUrl}/v1/admin/auth/confirm-forgot-password`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}})).ok}async respondToNewPasswordRequiredChallenge(e){const t=await fetch(`${this._apiUrl}/v1/admin/auth/respond-to-new-password-required-challenge`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}});if(t.ok)return await t.json();throw new Error("respond-to-new-password-required-challenge failed")}async loginWithGoogle(e){return await(await fetch(`${this._apiUrl}/v1/admin/auth/login-google`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}})).json()}async refresh(e){const n=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})})).json();await this.loginWithToken(n.authentication.accessToken,e)}}function O(){return typeof window<"u"&&window.location?new URLSearchParams(window.location.search).get("module"):null}function T(a){if(!(window&&window.parent))throw new Error("cannot send message to non-existent parent");window.parent.postMessage(a,"*")}function H(){const a=O();if(!a)throw new Error("No module context");T({type:"refresh_auth_token",module:a})}function W(a){function e(t){const n=t.data;n.type==="auth_token"&&a(n.token)}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}}const r=new Pe({apiUrl:h,refreshAuthToken:H,addAccessTokenRefreshListener:W});async function je(a){return(await(await fetch(`${h}/v1/admin/module-configurations/${a}`,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).configuration}function Ne(){T({type:"hide_analytics_date_picker"})}function Le(a){T({type:"go_to_device",deviceId:a})}function Ie(a){T({type:"go_to_time",time:a.getTime()})}function _e(){const a=O();if(!a)throw new Error("No module context");T({type:"request_module_data",module:a})}function $e(a,e){const t=O();if(!t)throw new Error("No module context");T({type:"send_channel_data",source:t,channel:a,data:e})}function ze(a,e){const t=O();if(!t)throw new Error("No module context");T({type:"set_module_data_time_range",module:t,before:a,after:e||0})}function Me(a){const e=O();if(!e)throw new Error("No module context");T({type:"setup_module_menus",module:e,menus:a})}function Be(a){T({type:"show_message",message:a})}function qe(a,e){const t=n=>{const i=n.data;i.type==="channel_data"&&i.channel===a&&e({source:i.source,data:i.data})};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function xe(a){const e=t=>{const n=t.data;n.type==="module_menu_item_clicked"&&a(n.menu)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}function Ue(a){const e=t=>{const n=t.data;n.type==="module_configuration"&&a(n)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}function Je(a){const e=O();e&&T({type:"request_module_data",module:e});const t=n=>{const i=n.data;i.type==="module_data"&&a({streams:i.streams,time:i.time,queryRange:i.queryRange})};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function Ve(a){T({type:"request_devices"});const e=t=>{const n=t.data;n.type==="overview_devices"&&a(n.data)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}const Fe=1,K=1e3,Q=60*K,X=60*Q,L=24*X,Ge=7*L,He=30*L,We=365*L,I={millisecond:Fe,second:K,minute:Q,hour:X,day:L,week:Ge,month:He,year:We};function Ke(a,e){return a.filter(t=>e.includes(t.type))}function Qe(a,e,t){const n=e.getTime(),i=t.getTime();return a.map(o=>({...o,points:o.points.filter(([c])=>c>=n&&c<i)})).filter(({points:o})=>o.length>0)}class V{constructor({capacity:e,timeout:t}={}){s(this,"entries",new Map);s(this,"metadata",new Map);s(this,"capacity");s(this,"timeout");this.capacity=e||1e4,this.timeout=t||I.minute}get(e,t){const n=this.keyToCacheKey(e),i=this.entries.get(n),o=this.metadata.get(n);return(i===void 0||o&&(o==null?void 0:o.expiration.getTime())<Date.now())&&!(o!=null&&o.generating)&&t&&this.generate(e,t()),i===void 0&&o&&o.lastValue!==void 0?o.lastValue:i}set(e,t){const n=this.keyToCacheKey(e);this.metadata.set(n,{generating:!1,expiration:new Date(Date.now()+this.timeout),lastValue:t}),this.entries.set(n,t),this.metadata.size>this.capacity&&this.deleteOldestEntry()}clear(){this.entries.clear(),[...this.metadata.values()].forEach(e=>e.generating=!1)}clearKey(e){this.metadata.delete(e),this.entries.delete(e)}keyToCacheKey(e){return JSON.stringify(e)}deleteOldestEntry(){if(this.metadata.size<1)return;const[e]=[...this.metadata.entries()].reduce(([t,n],[i,o])=>o.expiration.getTime()<n.expiration.getTime()?[i,o]:[t,n]);this.clearKey(e)}generate(e,t){const n=this.keyToCacheKey(e),i=this.metadata.get(n)||{};this.metadata.set(n,{...i,generating:!0,expiration:new Date(Date.now()+this.timeout)}),setTimeout(()=>{t.then(o=>{const c=this.metadata.get(n);!(c!=null&&c.generating)||this.set(e,o)})},0)}}async function _(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/queries`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}class Xe{constructor(){s(this,"queryStoreCache",new V({capacity:1e4,timeout:20*I.second}));s(this,"liveQueryStoreCache",new V({capacity:1e4,timeout:200*I.millisecond}))}moduleQuery(e,t,n,i,o,c=!1){const d={...e,names:[...t],types:[...n]},y=this.query(d,i,o,c);return y===void 0||y==="too much data"?y:Ke(y,n)}query(e,t,n,i=!1){const o={...e,start:N.startOfMinute(t).toISOString(),end:i?n.toISOString():N.addMinutes(N.roundToNearestMinutes(n),1).toISOString(),latestOnly:i},c=n>N.addSeconds(new Date,-20);let d;return c?d=this.liveQueryCache(o):d=this.queryCache(o),!d||d==="too much data"||i?d:Qe(d,t,n)}queryCache(e){return this.queryStoreCache.get(e,async()=>{try{return await _(e)}catch(t){throw t}})}liveQueryCache(e){return this.liveQueryStoreCache.get(e,async()=>{try{return await _(e)}catch(t){throw t}})}}const Ye=new Xe;function Ze(a,e,t){const n=i=>{const o=i.data;if(o.type==="module_data"){const{start:c,end:d}=o.queryRange;t(Ye.moduleQuery({},a,e,new Date(c),new Date(d),!1))}};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}async function et(a,e,t){return new Promise(n=>{T({type:"request_date",minTime:e,maxTime:t,time:a});const i=o=>{const c=o.data;c.type==="date_response"&&(window.removeEventListener("message",i),n(c.data))};window.addEventListener("message",i)})}async function tt(a,e){return new Promise(t=>{const n=Math.random().toString();T({type:"prompt",promptId:n,schema:a,okText:e==null?void 0:e.okText,cancelText:e==null?void 0:e.cancelText});const i=o=>{const c=o.data;c.type==="prompt_response"&&c.promptId===n&&t(c.data),window.removeEventListener("message",i)};window.addEventListener("message",i)})}const x=class{static isModule(){return O()!==null}static async getCurrentModuleConfiguration(){let e=new URLSearchParams("");typeof window<"u"&&window.location&&(e=new URLSearchParams(window.location.search));const t=e.get("configuration");if(!(t===null||t.trim()===""))return je(t.trim())}static get isOnline(){return x._isOnline}static listenForConnectionEvents(){const e=t=>{const{data:n}=t;n.type==="formant_online"&&(this._isOnline=n.online)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}static checkConnection(e=1e3){return new Promise((t,n)=>{const i=setTimeout(()=>n(new Error("deadline expired: took too long")),e),o=c=>{window.removeEventListener("message",o),clearTimeout(i);const{data:d}=c;d.type==="formant_online"&&(this._isOnline=d.online,t(d.online))};window.addEventListener("message",o),T({type:"formant_online"})})}static waitForConnection(e=5e3){let t=!1;const n=new Promise((c,d)=>{setTimeout(()=>{t=!0,d(new Error("deadline expired: took too long"))},e)}),i=c=>new Promise(d=>setTimeout(d,c)),o=async()=>{for(await i(50);!t&&!(this.isOnline||await this.checkConnection);)await i(500)};return Promise.race([n,o()])}};let g=x;s(g,"getCurrentModuleContext",O),s(g,"disableAnalyticsBottomBar",Ne),s(g,"goToDevice",Le),s(g,"goToTime",Ie),s(g,"refreshAuthToken",H),s(g,"requestModuleData",_e),s(g,"sendChannelData",$e),s(g,"setModuleDateTimeRange",ze),s(g,"setupModuleMenus",Me),s(g,"showMessage",Be),s(g,"addAccessTokenRefreshListener",W),s(g,"addChannelDataListener",qe),s(g,"addMenuListener",xe),s(g,"addModuleConfigurationListener",Ue),s(g,"addModuleDataListener",Je),s(g,"addOverviewDeviceListener",Ve),s(g,"addStreamListener",Ze),s(g,"getDate",et),s(g,"prompt",tt),s(g,"_isOnline",null);function f(a,e){if(a!==void 0)return a;throw new Error(e||"Value is undefined")}const p={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},nt={...p,Unknown:p.UNKNOWN,Teleop:p.TELEOP,PortForward:p.PORT_FORWARD,Observe:p.OBSERVE,Headless:p.HEADLESS,unknown:p.UNKNOWN,teleop:p.TELEOP,portForward:p.PORT_FORWARD,observe:p.OBSERVE,headless:p.HEADLESS},R=Symbol("RtcClientPool.instance");var hn;class P{constructor(e){s(this,hn,null);s(this,"createClient");s(this,"ttlMs");s(this,"proxyHandler");s(this,"proxyReceivers",new Map);s(this,"teardownTimeout",null);s(this,"dispatch",(e,t)=>{this.proxyReceivers.forEach(n=>n==null?void 0:n(e,t))});const{createClient:t,ttlMs:n=0}=e;this.createClient=t,this.ttlMs=Math.max(n,0),this.proxyHandler={get:(i,o,c)=>{switch(o){case"shutdown":return()=>this.releaseInstance(c);default:return Reflect.get(i,o,c)}}}}get isActive(){return this[R]!==null}get size(){return this.proxyReceivers.size}get(e){const t=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(t,e??null),t}allocate(){if(this[R])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[R];const e=this.createClient(this.dispatch);return this[R]=e,e}async teardown(){const e=this[R];if(!e){console.warn("singleton has already been shutdown!");return}try{await e.shutdown()}finally{this[R]=null}}async releaseInstance(e){return this.proxyReceivers.delete(e)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(t=>console.error("teardown failed",{err:t})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}hn=R;const j=async()=>f(r.token,"Realtime when user isn't authorized"),b={[p.UNKNOWN]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.UNKNOWN,receive:a})}),[p.TELEOP]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.TELEOP,receive:a})}),[p.PORT_FORWARD]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.PORT_FORWARD,receive:a})}),[p.OBSERVE]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.OBSERVE,receive:a})}),[p.HEADLESS]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.HEADLESS,receive:a})})},at={...b,unknown:b[p.UNKNOWN],teleop:b[p.TELEOP],portForward:b[p.PORT_FORWARD],observe:b[p.OBSERVE],headless:b[p.HEADLESS]},$=b[p.TELEOP],it=a=>{const{sessionType:e}=a;return e?at[e]:$};class Y{constructor(e){s(this,"token");this.captureSession=e}async ingestJSON(e){if(!this.token){const n=await(await fetch(`${h}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=n.token}await fetch(`${h}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(e)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}function A(a){return new Promise(e=>setTimeout(e,a))}const rt=a=>a!==void 0&&a.capabilities!==void 0&&a.capabilitySet!==void 0;class Z{constructor(e){s(this,"ready",!1);s(this,"listeners",[]);s(this,"openListeners",[]);s(this,"closeListeners",[]);s(this,"errorListeners",[]);s(this,"binaryListeners",[]);s(this,"error");s(this,"decoder",new TextDecoder);this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.setReady()},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(t=>t())},this.dataChannel.onerror=t=>{console.error(t),this.error="An error occurred in DataChannel",this.errorListeners.forEach(n=>n(t))},this.dataChannel.onmessage=t=>{this.listeners.forEach(n=>{const i=new Uint8Array(t.data),o=this.decoder.decode(i);n(o)}),this.binaryListeners.forEach(n=>{n(new Uint8Array(t.data))})}}setReady(){this.ready=!0,this.openListeners.forEach(e=>e())}addOpenListener(e){this.openListeners.push(e)}removeOpenListener(e){this.openListeners=this.openListeners.filter(t=>t!==e)}addCloseListener(e){this.closeListeners.push(e)}removeCloseListener(e){this.closeListeners=this.closeListeners.filter(t=>t!==e)}addErrorListener(e){this.errorListeners.push(e)}removeErrorListener(e){this.errorListeners=this.errorListeners.filter(t=>t!==e)}async waitTilReady(){return this.ready?!0:new Promise((t,n)=>{let i=setInterval(()=>{this.dataChannel.readyState==="open"&&this.setReady(),this.ready&&(clearInterval(i),t(!0)),this.error&&n(this.error)},10)})}send(e){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(e)}sendBinary(e){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(e)}addListener(e){this.listeners.push(e)}removeListener(e){const t=this.listeners.indexOf(e);if(t===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(t,1)}addBinaryListener(e){this.binaryListeners.push(e)}removeBinaryListener(e){const t=this.binaryListeners.indexOf(e);if(t===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(t,1)}}class ee{constructor(e,t){s(this,"currentListeners",[]);s(this,"onRealtimeMessage",(e,t)=>{t.payload.jointState&&this.currentListeners.forEach(n=>{t.payload.jointState&&n(t.payload.jointState)})});this.device=e,this.config=t}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(e){this.currentListeners.push(e)}}class te{constructor(e,t,n){s(this,"channel");s(this,"requestIdToResponseMap",new Map);this.device=e,this.channel_name=t,this.timeout=n}addOpenListener(e){f(this.channel,"channel not initalized").addOpenListener(e)}removeOpenListener(e){f(this.channel,"channel not initalized").removeOpenListener(e)}addCloseListener(e){f(this.channel,"channel not initalized").addCloseListener(e)}removeCloseListener(e){f(this.channel,"channel not initalized").removeCloseListener(e)}addErrorListener(e){f(this.channel,"channel not initalized").addErrorListener(e)}removeErrorListener(e){f(this.channel,"channel not initalized").removeErrorListener(e)}}class ne extends te{constructor(){super(...arguments);s(this,"RESPONSE_SUCCESS_BYTE",0);s(this,"decoder",new TextDecoder)}generateBinaryId(){const t=new Uint8Array(16);for(let n=0;n<t.length;n++)t[n]=Math.floor(Math.random()*256);return t}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(t=>{const i=t.slice(0,16).toString();if(i.length===0)throw new Error("Invalid response");const o=t.slice(16);if(o.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(i)&&this.requestIdToResponseMap.set(i,o)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:i,timeout:o}=this;await n.waitTilReady();const c=this.generateBinaryId(),d=c.toString();i.set(d,!0),n.sendBinary(new Uint8Array([...c,...t]));const y=new Date().getTime();for(;new Date().getTime()<y+o;)if(await A(50),i.has(d)){const m=i.get(d);if(m!==!0){i.delete(d);const w=m[0]===this.RESPONSE_SUCCESS_BYTE,v=m.slice(1);if(w)return v;throw console.error({name:"AdapterError",message:this.decoder.decode(v)}),new Error("Binary request datachannel adapter error")}}throw i.delete(d),console.error({name:"TimeoutError",message:`Request timed out after ${o/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class ae extends te{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(e=>{const t=JSON.parse(e),{id:n,data:i,error:o}=t;if(!n)throw new Error("Invalid response");if(!i&&!o)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,t)})}async request(e){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:t,requestIdToResponseMap:n,timeout:i}=this;await t.waitTilReady();const o=this.generateTextId();n.set(o,!0),t.send(JSON.stringify({id:o,data:e}));const c=new Date().getTime();for(;new Date().getTime()<c+i;)if(await A(50),n.has(o)){const d=n.get(o);if(d!==!0){n.delete(o);const{data:y,error:m}=d;if(y)return y;if(m)throw console.error({name:"AdapterError",message:m}),new Error("Text request datachannel adapter error")}}throw n.delete(o),console.error({name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class ie extends ke.EventEmitter{constructor(){super(...arguments);s(this,"rtcClient");s(this,"remoteDevicePeerId",null);s(this,"realtimeListeners",[]);s(this,"connectionMonitorInterval");s(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(i=>i(t,n))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(t){if(t)throw new Error("Cancelled by deadline")}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")}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeManipulators(){const t=await this.getConfiguration(),n=[];for(const i of t.teleop.rosStreams??[])i.topicType=="sensor_msgs/JointState"&&n.push(new ee(this,{currentJointStateStream:{name:i.topicName},plannedJointStateStream:i.plannedTopic?{name:i.plannedTopic}:void 0,planValidStream:i.planValidTopic?{name:i.planValidTopic}:void 0,endEffectorStream:i.endEffectorTopic?{name:i.endEffectorTopic}:void 0,endEffectorLinkName:i.endEffectorLinkName,baseReferenceFrame:i.baseReferenceFrame,localFrame:i.localFrame}));return n}async getRealtimeVideoStreams(){var i,o,c;const t=await this.getConfiguration(),n=[];for(const d of((i=t.teleop)==null?void 0:i.hardwareStreams)??[])d.rtcStreamType==="h264-video-frame"&&n.push({name:d.name});for(const d of((o=t.teleop)==null?void 0:o.rosStreams)??[])d.topicType=="formant/H264VideoFrame"&&n.push({name:d.topicName}),(d.topicType==="sensor_msgs/Image"||d.topicType==="sensor_msgs/CompressedImage")&&d.encodeVideo&&n.push({name:d.topicName});for(const d of((c=t.teleop)==null?void 0:c.customStreams)??[])d.rtcStreamType==="h264-video-frame"&&n.push({name:d.name});return n}createCustomRequestDataChannel(t,n=3e3){return new ae(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new ne(this,t,n)}async startListeningToRealtimeVideo(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(t,n){const i=f(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();i.controlRemoteStream(f(o).id,{streamName:t,setAudioFormat:n})}async createCustomDataChannel(t,n){const i=f(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer(),c=await new Promise(d=>{i.createCustomDataChannel(f(o).id,t,{ordered:!0,...n},!1,(y,m)=>{const w=new Z(m);d(w)})});return await c.waitTilReady(),c}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const i=f(this.rtcClient,"Realtime connection has not been started"),o=await this.getRemotePeer();i.send(f(o).id,t,n)}async getRealtimeAudioStreams(){var i,o,c;const t=await this.getConfiguration(),n=[];for(const d of((i=t.teleop)==null?void 0:i.hardwareStreams)??[])d.rtcStreamType==="audio-chunk"&&n.push({name:d.name});for(const d of((o=t.teleop)==null?void 0:o.rosStreams)??[])d.topicType=="audio_common_msgs/AudioData"&&n.push({name:d.topicName});for(const d of((c=t.teleop)==null?void 0:c.customStreams)??[])d.rtcStreamType==="audio-chunk"&&n.push({name:d.name});return n}}const ot=new TextEncoder;new TextDecoder;function st(a){const e=JSON.stringify(a),t=ot.encode(e),n=Oe.deflate(t);return Re.fromByteArray(n)}async function re(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/views`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function oe(a,e){if(!r.token)throw new Error("Not authenticated");const n=(await re()).filter(d=>d.name===e);if(n.length===0)return console.warn("View does not exist or it is misspell"),null;const i=await fetch(`${h}/v1/admin/shares`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),o=h.replace("api","app"),{code:c}=await i.json();return`${o}/shares/${c}#${st({viewId:n[0].id})}`}const ct=["day","week","month","year","hour","minute","quarter"],dt=["interval","start","end","sub","get"];function se(a){return a.count<2?0:a.sumOfSquares/(a.count-1)}function ce(a){return Math.sqrt(se(a))}function de(a){return a.max}function he(a){return a.min}function le(a){return a.count===0?-1:a.sum/a.count}function ue(a){return a.sum}function me(a){return a.count}const ht={min:he,max:de,"standard deviation":ce,average:le,sum:ue,count:me},z={day:{interval:u.eachDayOfInterval,start:u.startOfDay,end:u.endOfDay,sub:u.subDays,get:u.getDay},week:{interval:u.eachWeekOfInterval,start:u.startOfWeek,end:u.endOfWeek,sub:u.subWeeks,get:u.getWeek},month:{interval:u.eachMonthOfInterval,start:u.startOfMonth,end:u.endOfMonth,sub:u.subMonths,get:u.getMonth},year:{interval:u.eachYearOfInterval,start:u.startOfYear,end:u.endOfYear,sub:u.subYears,get:u.getYear},hour:{interval:u.eachHourOfInterval,start:u.startOfHour,end:u.endOfHour,sub:u.subHours,get:u.getHours},minute:{interval:u.eachMinuteOfInterval,start:u.startOfMinute,end:u.endOfMinute,sub:u.subMinutes,get:u.getMinutes},quarter:{interval:u.eachQuarterOfInterval,start:u.startOfQuarter,end:u.endOfQuarter,sub:u.subQuarters,get:u.getQuarter}},fe=(a,e)=>a.split("/")[0]+"/"+a.split("/")[1]+"–"+e.split("/")[0]+"/"+e.split("/")[1];async function M(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function we(a,e,t,n,i){const o=z[e];return await Promise.all(Array(t).fill(0).map(async(c,d)=>{const y=new Date(n),m=o.sub(o.start(y),t-d-1),w=o.sub(o.end(y),t-d-1),v=fe(m.toLocaleDateString(),w.toLocaleDateString()),S=await M({...i,eventTypes:a,start:new Date(m).toISOString(),end:new Date(w).toISOString()});return{date:v,events:S}}))}async function B(a,e){return(await M({...a,eventTypes:["annotation"]})).filter(o=>!!o.tags&&Object.keys(o.tags).includes(e)).reduce((o,c)=>{const d=c.tags[e];return d in o?(o[d]+=1,o):(o[d]=1,o)},{})}async function pe(a,e,t){const{end:n,start:i}=a,c=z[t].interval({start:new Date(i),end:new Date(n)}),d=c.map((m,w)=>{const v=new Date(m).toISOString(),S=w===c.length-1?new Date(Date.now()).toISOString():new Date(c[w+1]);return B({...a,start:v,end:S},e)}),y=await Promise.all(d);return c.map((m,w)=>({date:new Date(m).toISOString(),annotations:y[w]}))}async function ye(a,e,t,n,i){let o=a;Array.isArray(a)||(o=[a]);let c=e;return Array.isArray(e)||(c=[e]),(await(await fetch(`${h}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:o,end:n.toISOString(),names:c,start:t.toISOString(),tags:i}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function ge(){if(!r.token)throw new Error("Not authenticated");const a=$.get();try{return await a.getSessions()}finally{await a.shutdown()}}async function ve(){if(!r.token)throw new Error("Not authenticated");const a=$.get();try{return await a.getPeers()}finally{await a.shutdown()}}async function lt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function ut(a,e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices/${a}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function mt(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function ft(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function wt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices/${a}/disable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}class E extends ie{constructor(e,t,n,i){super(),this.id=e,this.name=t,this.organizationId=n,this.tags=i}async getLatestTelemetry(){return(await(await fetch(`${h}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async getConfiguration(){let e=await fetch(`${h}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}});const t=await e.json();if(!t.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const n=t.state.reportedConfiguration.version;return e=await fetch(`${h}/v1/admin/devices/${this.id}/configurations/${n}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),(await e.json()).document}async getFileUrl(e){return(await(await fetch(`${h}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[e]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).fileUrls}async startRealtimeConnection(e={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:t,deadlineMs:n=1e4,maxConnectRetries:i=3}=typeof e=="number"?{sessionType:e}:e,c=it({sessionType:t}).get(this.handleMessage);let d=!1;const y=new Promise((w,v)=>setTimeout(()=>{d=!0,v(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},n)),m=async()=>{if("isReady"in c)for(;!c.isReady();)this.assertNotCancelled(d),await A(100);const w=await this.getRemoteDevicePeerId(c);this.assertNotCancelled(d);let v;for(let D=0;D<i&&(v=await c.connect(w),!v);D++)A(100),this.assertNotCancelled(d);if(!v)throw new Error(`Session could not be created: exhausted ${i} retries`);let S=0;for(;!d&&c.getConnectionStatus(w)!=="connected";)await A(100),S+=1;return this.assertNotCancelled(d),console.debug(`${new Date().toISOString()} :: Connection completed after ${S} retries`),w};return Promise.race([m(),y]).then(w=>{this.remoteDevicePeerId=w,this.initConnectionMonitoring(),this.rtcClient=c,this.emit("connect")}).catch(w=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,w),this.remoteDevicePeerId=null,c.shutdown().catch(v=>{console.error("rtcClient cannot shutdown: %o",v)}),this.emit("connection_failed",w),w})}async getRemoteDevicePeerId(e){const n=(await e.getPeers()).find(i=>i.deviceId===this.id);if(!rt(n))throw new Error("Cannot find peer, is the robot offline?");return n.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let e=!1;if(this.rtcClient){const n=this.rtcClient.getConnections().find(i=>i.getRemotePeerId()===this.remoteDevicePeerId&&i.isActive());(n===void 0||!n.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),e=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||e)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(t=>{console.error(t)}))},1e3)}async getRemotePeer(){const t=(await f(this.rtcClient,"Realtime connection has not been started").getPeers()).find(n=>n.deviceId===this.id);return f(t,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let e=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):e=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(e)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const e=await ve(),t=await ge(),n=e.find(i=>i.deviceId===this.id);return n?t[n.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${h}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items.map(n=>({name:n.name,id:n.id,command:n.command,description:n.description,parameterEnabled:n.parameterEnabled,parameterValue:n.parameterValue,parameterMeta:n.parameterMeta,enabled:n.enabled,tags:n.tags}))}async sendCommand(e,t,n,i){var w;const c=(await this.getAvailableCommands()).find(v=>v.name===e);if(!c)throw new Error(`Could not find command with name "${e}"`);let d="";t===void 0?c.parameterEnabled&&c.parameterValue&&(d=c.parameterValue):d=t;let y={value:d,scrubberTime:(n||new Date).toISOString(),meta:{...c.parameterMeta,...i}};return await fetch(`${h}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:c.id,organizationId:this.organizationId,deviceId:this.id,command:c.command,parameter:y,userId:(w=r.currentUser)==null?void 0:w.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})}async getCommand(e){return await fetch(`${h}/v1/admin/commands/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})}async createCaptureStream(e){const n=await(await fetch(`${h}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:e,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json();return new Y(n)}async getTelemetry(e,t,n,i){return await ye(this.id,e,t,n,i)}async getTelemetryStreams(){var d,y;const e=await this.getConfiguration(),t=await fetch(`${h}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),n=[],i=[];return(y=(d=e.telemetry)==null?void 0:d.streams)==null||y.forEach(m=>{m.disabled!==!0&&n.push(m.name),m.onDemand===!0&&i.push(m.name)}),console.log(i),(await t.json()).items.filter(m=>!n.includes(m)).map(m=>({name:m,onDemand:i.includes(m)}))}async createInterventionRequest(e,t,n,i){return await(await fetch(`${h}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:e,interventionType:t,time:new Date().toISOString(),deviceId:this.id,tags:i,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async addInterventionResponse(e,t,n){return await(await fetch(`${h}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:e,interventionType:t,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async getAnnotationCount(e,t){return await B({...e,deviceIds:[this.id]},t)}async getAnnotationCountByIntervals(e,t,n){return await pe({...e,deviceIds:[this.id]},t,n)}async eventsCounter(e,t,n,i,o){return await we(e,t,n,i,{...o,deviceIds:[this.id]})}async createShareLink(e,t){return e.scope.deviceIds=[this.id],await oe(e,t)}}s(E,"createDevice",lt),s(E,"patchDevice",ut),s(E,"getDevicesData",mt),s(E,"queryDevicesData",ft),s(E,"disableDevice",wt);class Te extends ie{constructor(t){super();s(this,"id");s(this,"telemetryStreamActive",!1);s(this,"streamTelemetry",{});this.peerUrl=t}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const t=this.streamTelemetry;return Object.entries(t).map(([i,o])=>({deviceId:this.id,streamName:i,streamType:"json",currentValue:o,currentValueTime:o.timestamp,tags:{}}))}subscribeToTelemetry(){this.telemetryStreamActive=!0;let t=0;const n=new XMLHttpRequest;n.responseType="text",n.addEventListener("error",i=>{this.handleXHRError("error")}),n.addEventListener("abort",i=>{this.handleXHRError("abort")}),n.addEventListener("timeout",i=>{this.handleXHRError("timeout")}),n.addEventListener("readystatechange",i=>{n.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),n.addEventListener("progress",i=>{const o=i.loaded,c=o-t;t=o,n.responseText.substr(-c).split(`
2
- `).forEach(m=>{var w;if(m.length>0){const v=JSON.parse(m);if((w=v.result)!=null&&w.datapoint){const S=v.result.datapoint,D=S.stream;delete S.stream,this.streamTelemetry[D]=S}}})}),n.open("POST",`${this.peerUrl}/v1/telemetry`),n.send()}handleXHRError(t){console.warn(`Telemetry stream ended: ${t}`),this.telemetryStreamActive=!1}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.document}async startRealtimeConnection(t){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const n=new C.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await A(100);this.rtcClient=n,this.initConnectionMonitoring()}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;this.rtcClient&&this.rtcClient.getConnectionStatus(this.peerUrl)!=="connected"&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0),(!this.rtcClient||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.id?(await this.rtcClient.disconnect(this.id),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async sendCommand(t,n,i,o){const c={value:n,scrubberTime:(i||new Date).toISOString(),meta:o};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:t,parameter:c}),headers:{"Content-Type":"application/json"}})}}async function pt(a,e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices/${a}`,{method:"PATCH",body:JSON.stringify({fleetId:e}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function yt(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/queries`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).aggregates}async function gt(a){if(!r.token)throw new Error("Not authenticated");await fetch(`${h}/v1/admin/fleets/${a}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})}async function vt(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function Tt(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function Ct(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function Ce(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items.map(n=>new E(n.id,n.name,n.organizationId,n.tags))}async function St(){if(!r.token)throw new Error("Not authenticated");let a=new URLSearchParams("");typeof window<"u"&&window.location&&(a=new URLSearchParams(window.location.search));const e=a.get("group");if(e===null||e.trim()==="")return;const t=await fetch(`${h}/v1/admin/groups/`+e,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),{tagKey:n,tagValue:i}=await t.json();return await Ce({tags:{[n]:[i]},enabled:!0,type:"default"})}async function Et(a){if(!r.token)throw new Error("Not authenticated");const t=await(await fetch(`${h}/v1/admin/devices/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json(),n=t.name;return new E(a,n,t.organizationId,t.tags)}async function q(){if(!r.token)throw new Error("Not authenticated");const e=await(await fetch(`${h}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json();return e.items,e.items.map(t=>new E(t.id,t.name,t.organizationId,t.tags))}async function kt(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/events/query/id=${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function Ot(a){const t=await(await fetch(`${h}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[a]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json();if(t.fileUrls.length===0)throw new Error("File not found");return t.fileUrls[0]}async function Rt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/fleets/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function bt(a){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/fleets/${a}/devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function At(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function Dt(...a){const e=a.flat().filter(i=>!!i);return e.length===0?[]:(await(await fetch(`${h}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:e}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function Pt(){if(!r.token)throw new Error("Not authenticated");const t=(await(await fetch(`${h}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items;return(await q()).filter(i=>t.includes(i.id))}async function jt(){if(!r.token)throw new Error("Not authenticated");const t=(await(await fetch(`${h}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items.map(i=>i.deviceId);return(await q()).filter(i=>t.includes(i.id))}async function Nt(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items.filter(t=>t.enabled)}async function Lt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function It(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function _t(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/fleets`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function $t(a,e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/fleets/${a}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function zt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/streams/${a.id}`,{method:"PATCH",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function Mt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/views/${a.id}`,{method:"PATCH",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function Bt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function qt(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/fleets`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function xt(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/event-trigger-groups`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}async function Ut(a){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/event-trigger-groups/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}async function Jt(a,e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/event-trigger-groups/${a}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}const k=class{static async setDefaultDevice(e){k.defaultDeviceId=e}static async getCurrentDevice(){if(!r.token)throw new Error("Not authenticated");if(!k.defaultDeviceId)throw new Error("No known default device");const n=(await(await fetch(`${h}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items.find(c=>c.id===k.defaultDeviceId),i=n.name,o=new E(k.defaultDeviceId,i,f(r.currentOrganization),n.tags);return k.knownContext.push(new WeakRef(o)),o}static async getPeerDevice(e){const t=new Te(e);return t.id=await t.getDeviceId(),t}static async getDevice(e){const t=await Et(e);return k.knownContext.push(new WeakRef(t)),t}};let l=k;s(l,"defaultDeviceId"),s(l,"knownContext",[]),s(l,"createFleet",qt),s(l,"listFleets",_t),s(l,"getFleet",Rt),s(l,"patchFleet",$t),s(l,"deleteFleet",gt),s(l,"addDeviceToFleet",pt),s(l,"getFleetDevices",bt),s(l,"aggregateTelemetry",yt),s(l,"createShareLink",oe),s(l,"eventsCounter",we),s(l,"getAnalyticStreams",vt),s(l,"getAnalyticsModules",Tt),s(l,"getAnalyticsRows",Ct),s(l,"getAnnotationCount",B),s(l,"getAnnotationCountByIntervals",pe),s(l,"getCurrentGroup",St),s(l,"getDevices",q),s(l,"getEvent",kt),s(l,"getFileUrl",Ot),s(l,"getInterventions",At),s(l,"getLatestTelemetry",Dt),s(l,"getOnlineDevices",Pt),s(l,"getPeers",ve),s(l,"getRealtimeDevices",jt),s(l,"getRealtimeSessions",ge),s(l,"getStreams",Nt),s(l,"getTaskReportRows",Lt),s(l,"getTaskReportTables",It),s(l,"getTelemetry",ye),s(l,"getViews",re),s(l,"patchStream",zt),s(l,"patchView",Mt),s(l,"queryAnalytics",Bt),s(l,"queryDevices",Ce),s(l,"queryEvents",M),s(l,"queryTelemetry",_),s(l,"getAllEventTriggerGroup",xt),s(l,"getEventTriggerGroup",Ut),s(l,"patchEventTriggergroup",Jt);class Vt{static async set(e,t,n){try{const i=await fetch(h+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:f(r.currentUser).organizationId,key:e,value:t,tags:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),o=await i.json();if(i.status!==200)throw new Error(o.message)}catch(i){throw i}}static async get(e){try{const t=await fetch(h+`/v1/admin/key-value/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.value}catch(t){throw t}}static async list(){try{const e=await fetch(h+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}}),t=await e.json();if(e.status!==200)throw new Error(t.message);return t.items}catch(e){throw e}}static async delete(e){try{if(!(await fetch(h+`/v1/admin/key-value/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).ok)throw new Error("Unable to handle request");return}catch(t){throw t}}static async query(e){try{const t=await fetch(h+"/v1/admin/key-value/query",{method:"POST",body:JSON.stringify({keys:e}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}});if(!t.ok)throw new Error("Unable to handle request");return(await t.json()).items}catch(t){throw t}}}function Ft(a){return Uint8Array.from(G.decode(a),e=>e.charCodeAt(0))}function F(){const{userAgent:a}=navigator;return a?a.includes("Firefox/")?"Firefox":a.includes("Edg/")?"Edge":a.includes("Chrome/")?"Chrome":a.includes("Safari/")?"Safari":a.includes("MSIE/")||a.includes("Trident/")?"IE":"Other":"Other"}const Gt="audio-chunk";class Ht{constructor(e,t){s(this,"muted",!1);s(this,"hasReceivedData",!1);s(this,"audioContext");s(this,"chunks",[]);s(this,"isPlaying",!1);s(this,"startTime",0);s(this,"lastChunkOffset",0);s(this,"bufferSize",3);s(this,"receive",async e=>{var c;const t=(c=e.payload.audioChunk)==null?void 0:c.chunk_data;if(!t)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:n,muted:i}=this;if(!n||e.header.stream.streamType!==Gt||i!==!1)return;const o=Ft(t);try{await n.decodeAudioData(o.buffer,this.scheduleChunk)}catch(d){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:d}),this.changeAudioWireFormat("wav")}});s(this,"scheduleChunk",e=>{const{audioContext:t}=this;if(!t)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(i=>{i.stop()}),this.isPlaying=!1,this.chunks=[]);const n=this.createChunk(e);n&&n.buffer&&(this.isPlaying===!1&&(this.startTime=t.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),n.start(this.startTime+this.lastChunkOffset,0,e.duration),this.lastChunkOffset+=n.buffer.duration,this.chunks.push(n))});this.device=e,this.stream=t,this.device.startListeningToRealtimeDataStream(t),this.device.addRealtimeListener((i,o)=>{this.receive(o)}),F()==="Safari"||F()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const n=window.AudioContext||window.webkitAudioContext;this.audioContext=new n}async play(){var e,t;((e=this.audioContext)==null?void 0:e.state)==="suspended"&&await((t=this.audioContext)==null?void 0:t.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(e){const{audioContext:t}=this;if(!t)return;const n=t.createBufferSource();return n.buffer=e,n.connect(t.destination),n.loop=!1,n.onended=i=>{this.chunks.splice(this.chunks.indexOf(n),1),this.chunks.length===0&&(this.isPlaying=!1)},n}changeAudioWireFormat(e){const{stream:t}=this;(async()=>await this.device.changeStreamAudioType(t.name,e))()}}class Wt{static async listAccounts(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/accounts`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}static async createAccounts(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async getAccount(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async patchAccount(e,t){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async deleteAccount(e){if(!r.token)throw new Error("Not authenticated");if(!(await fetch(`${h}/v1/admin/accounts/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).ok)throw new Error("Unable to delete account")}static async getAccountTree(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts/${e}/tree`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}}class Kt{static async listRoles(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/roles`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}static async createRole(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/roles`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async getRole(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/roles/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async patchRole(e,t){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/roles/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async deleteRole(e){if(!r.token)throw new Error("Not authenticated");await fetch(`${h}/v1/admin/roles/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})}}class Qt{static async listUsers(){if(!r.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/users`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()).items}static async createUser(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/users`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async getUser(e){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/users/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async patchUser(e,t){if(!r.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/users/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})).json()}static async deleteUser(e){if(!r.token)throw new Error("Not authenticated");await fetch(`${h}/v1/admin/users/${e}`,{method:"PATCH",body:JSON.stringify({enabled:!1,roleId:null,teamId:null}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.token}})}}const Xt=["viewer","operator","administrator"],Yt="viewer",Zt="operator",en="administrator",tn=["year","month","week","day","hour","minute"],nn=["tag","sheet","user"],an=["triggered-event","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],rn=["unknown","operational","offline","error"],on=["selection","labeling","teleop"],sn=["info","warning","error","critical"],cn=["video/mp4"],dn=a=>new Promise(e=>setTimeout(e,a*1e3));try{const a=typeof window<"u"&&window.location?new URLSearchParams(window.location.search):new URLSearchParams(""),e=a.get("device");e&&l.setDefaultDevice(e);const t=a.get("auth");t&&r.loginWithToken(t),a.get("module")&&r.listenForRefresh(),typeof window<"u"&&g.listenForConnectionEvents()}catch{}exports.Account=Wt;exports.App=g;exports.AudioPlayer=Ht;exports.Authentication=r;exports.BinaryRequestDataChannel=ne;exports.CaptureStream=Y;exports.DataChannel=Z;exports.Device=E;exports.Fleet=l;exports.KeyValue=Vt;exports.Manipulator=ee;exports.PeerDevice=Te;exports.Role=Kt;exports.SessionType=nt;exports.TextRequestDataChannel=ae;exports.User=Qt;exports.accessLevels=Xt;exports.administrator=en;exports.aggregateByDateFunctions=z;exports.aggregateFunctionMap=ht;exports.aggregateFunctions=dt;exports.aggregateLevels=tn;exports.annotationTypes=nn;exports.eventTypes=an;exports.formatTimeFrameText=fe;exports.getAverage=le;exports.getCount=me;exports.getMax=de;exports.getMin=he;exports.getStandardDeviation=ce;exports.getSum=ue;exports.getVariance=se;exports.healthStatuses=rn;exports.interventionTypes=on;exports.operator=Zt;exports.severities=sn;exports.timeout=dn;exports.vailableAggregationIntervals=ct;exports.videoMimeTypes=cn;exports.viewer=Yt;
1
+ "use strict";var Se=Object.defineProperty;var Ee=(a,e,t)=>e in a?Se(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var s=(a,e,t)=>(Ee(a,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("base-64"),N=require("date-fns"),C=require("@formant/realtime-sdk"),ke=require("eventemitter3"),Oe=require("pako"),Re=require("base64-js");function be(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const u=be(N),Ae="https://api.formant.io";function De(a,e){try{if(e.get("formant_stage"))return"https://api-stage.formant.io";if(e.get("formant_dev"))return"https://api-dev.formant.io";if(e.get("formant_local"))return"https://api.formant.local";if(e.get("formant_url")){const t=e.get("formant_url");if(t!==null)try{return new URL(t).origin}catch{console.warn(`Ignoring malformed \`formant_url\` url parameter: ${t}`)}}}catch{}return typeof a<"u"&&"FORMANT_API_URL"in a&&typeof a.FORMANT_API_URL=="string"?a.FORMANT_API_URL:Ae}const h=De(typeof window<"u"?window:globalThis,new URLSearchParams(typeof window<"u"&&window.location?window.location.search:void 0));class U extends Error{constructor(t){super("login failed");s(this,"reason");this.reason=t,this.name="LoginFailureError",Object.setPrototypeOf(this,new.target.prototype)}}class J extends Error{constructor(t){super("login challenged");s(this,"challenge");this.challenge=t,this.name="LoginChallengedError",Object.setPrototypeOf(this,new.target.prototype)}}class Pe{constructor({apiUrl:e,refreshAuthToken:t,addAccessTokenRefreshListener:n}){s(this,"_refreshToken");s(this,"_isShareToken",!1);s(this,"_currentOrganization");s(this,"_currentUser");s(this,"_defaultDeviceId");s(this,"_token");s(this,"_waitingForAuth",new Set);s(this,"_refreshTimer");s(this,"_apiUrl");s(this,"_refreshAuthToken");s(this,"_addAccessTokenRefreshListener");this._apiUrl=e,this._refreshAuthToken=t,this._addAccessTokenRefreshListener=n}get token(){return this._token}get currentUser(){return this._currentUser}get currentOrganization(){return this._currentOrganization}get defaultDeviceId(){return this._defaultDeviceId}get refreshToken(){return this._refreshToken}get isShareToken(){return this._isShareToken}async login(e,t,n={}){const{advanced:i=!1}=n;try{const r=await fetch(`${this._apiUrl}/v1/admin/auth/login`,{method:"POST",body:JSON.stringify({email:e,password:t}),headers:{"Content-Type":"application/json"}}),c=await r.json();if(r.status!==200)throw new U(c.message);if("challenge"in c)throw new J(c.challenge);const{authentication:d}=c;return await this.loginWithToken(d.accessToken,d.refreshToken),i?{result:"success",authentication:d}:d}catch(r){if(i||console.error("login() failed",{err:r}),this._waitingForAuth.forEach(c=>c(!1)),this._waitingForAuth.clear(),!i)throw r;return r instanceof J?{result:"challenged",challenge:r.challenge}:{result:"failure",reason:r instanceof U?r.reason:r instanceof Error?r.message:String(r)}}}async loginWithToken(e,t){var i;const n=JSON.parse(G.decode(e.split(".")[1]));try{let r;if(this._isShareToken=n["formant:claims"]&&n["formant:claims"].type=="share",n["formant:claims"]&&(this._currentOrganization=n["formant:claims"].organizationId),n["custom:organization_id"]&&(this._currentOrganization=n["custom:organization_id"]),this._isShareToken||(r=n.sub),n["formant:claims"]&&n["formant:claims"].userId&&(r=n["formant:claims"].userId),r&&((i=this._currentUser)==null?void 0:i.id)!==r){const c=await fetch(`${this._apiUrl}/v1/admin/users/${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e}}),d=await c.json();if(c.status!==200)throw new Error(d.message);this._currentUser=d}this._token=e,this._waitingForAuth.forEach(c=>c(!0))}catch(r){console.error("loginWithToken() failed",{err:r}),this._waitingForAuth.forEach(c=>c(!1))}finally{this._waitingForAuth.clear()}t&&(this._refreshToken=t,setInterval(async()=>{if(this._refreshToken){const c=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:this._refreshToken})})).json();this._token=c.authentication.accessToken}},1e3*60*60))}isAuthenticated(){return this._token!==void 0}getCurrentUser(){return this._currentUser}async waitTilAuthenticated(){return this.token!==void 0?!0:new Promise(e=>{this._waitingForAuth.add(e)})}async listenForRefresh(){const t=()=>{this._refreshTimer=void 0,this._refreshAuthToken()};this._addAccessTokenRefreshListener(n=>{this._refreshTimer&&clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(t,36e5),this.loginWithToken(n)}),this._refreshTimer=setTimeout(t,36e5)}async forgotPassword(e){await fetch(`${this._apiUrl}/v1/admin/auth/forgot-password`,{method:"POST",body:JSON.stringify({email:e}),headers:{"Content-Type":"application/json"}})}async confirmForgotPassword(e){return(await fetch(`${this._apiUrl}/v1/admin/auth/confirm-forgot-password`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}})).ok}async respondToNewPasswordRequiredChallenge(e){const t=await fetch(`${this._apiUrl}/v1/admin/auth/respond-to-new-password-required-challenge`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}});if(t.ok)return await t.json();throw new Error("respond-to-new-password-required-challenge failed")}async loginWithGoogle(e){return await(await fetch(`${this._apiUrl}/v1/admin/auth/login-google`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}})).json()}async refresh(e){const n=await(await fetch(`${this._apiUrl}/v1/admin/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})})).json();await this.loginWithToken(n.authentication.accessToken,e)}}function O(){return typeof window<"u"&&window.location?new URLSearchParams(window.location.search).get("module"):null}function T(a){if(!(window&&window.parent))throw new Error("cannot send message to non-existent parent");window.parent.postMessage(a,"*")}function H(){const a=O();if(!a)throw new Error("No module context");T({type:"refresh_auth_token",module:a})}function W(a){function e(t){const n=t.data;n.type==="auth_token"&&a(n.token)}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}}const o=new Pe({apiUrl:h,refreshAuthToken:H,addAccessTokenRefreshListener:W});async function je(a){return(await(await fetch(`${h}/v1/admin/module-configurations/${a}`,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).configuration}function Ne(){T({type:"hide_analytics_date_picker"})}function Le(a){T({type:"go_to_device",deviceId:a})}function Ie(a){T({type:"go_to_time",time:a.getTime()})}function _e(){const a=O();if(!a)throw new Error("No module context");T({type:"request_module_data",module:a})}function $e(a,e){const t=O();if(!t)throw new Error("No module context");T({type:"send_channel_data",source:t,channel:a,data:e})}function ze(a,e){const t=O();if(!t)throw new Error("No module context");T({type:"set_module_data_time_range",module:t,before:a,after:e||0})}function Me(a){const e=O();if(!e)throw new Error("No module context");T({type:"setup_module_menus",module:e,menus:a})}function Be(a){T({type:"show_message",message:a})}function qe(a,e){const t=n=>{const i=n.data;i.type==="channel_data"&&i.channel===a&&e({source:i.source,data:i.data})};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function xe(a){const e=t=>{const n=t.data;n.type==="module_menu_item_clicked"&&a(n.menu)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}function Ue(a){const e=t=>{const n=t.data;n.type==="module_configuration"&&a(n)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}function Je(a){const e=O();e&&T({type:"request_module_data",module:e});const t=n=>{const i=n.data;i.type==="module_data"&&a({streams:i.streams,time:i.time,queryRange:i.queryRange})};return window.addEventListener("message",t),()=>window.removeEventListener("message",t)}function Ve(a){T({type:"request_devices"});const e=t=>{const n=t.data;n.type==="overview_devices"&&a(n.data)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}const Fe=1,K=1e3,Q=60*K,X=60*Q,L=24*X,Ge=7*L,He=30*L,We=365*L,I={millisecond:Fe,second:K,minute:Q,hour:X,day:L,week:Ge,month:He,year:We};function Ke(a,e){return a.filter(t=>e.includes(t.type))}function Qe(a,e,t){const n=e.getTime(),i=t.getTime();return a.map(r=>({...r,points:r.points.filter(([c])=>c>=n&&c<i)})).filter(({points:r})=>r.length>0)}class V{constructor({capacity:e,timeout:t}={}){s(this,"entries",new Map);s(this,"metadata",new Map);s(this,"capacity");s(this,"timeout");this.capacity=e||1e4,this.timeout=t||I.minute}get(e,t){const n=this.keyToCacheKey(e),i=this.entries.get(n),r=this.metadata.get(n);return(i===void 0||r&&(r==null?void 0:r.expiration.getTime())<Date.now())&&!(r!=null&&r.generating)&&t&&this.generate(e,t()),i===void 0&&r&&r.lastValue!==void 0?r.lastValue:i}set(e,t){const n=this.keyToCacheKey(e);this.metadata.set(n,{generating:!1,expiration:new Date(Date.now()+this.timeout),lastValue:t}),this.entries.set(n,t),this.metadata.size>this.capacity&&this.deleteOldestEntry()}clear(){this.entries.clear(),[...this.metadata.values()].forEach(e=>e.generating=!1)}clearKey(e){this.metadata.delete(e),this.entries.delete(e)}keyToCacheKey(e){return JSON.stringify(e)}deleteOldestEntry(){if(this.metadata.size<1)return;const[e]=[...this.metadata.entries()].reduce(([t,n],[i,r])=>r.expiration.getTime()<n.expiration.getTime()?[i,r]:[t,n]);this.clearKey(e)}generate(e,t){const n=this.keyToCacheKey(e),i=this.metadata.get(n)||{};this.metadata.set(n,{...i,generating:!0,expiration:new Date(Date.now()+this.timeout)}),setTimeout(()=>{t.then(r=>{const c=this.metadata.get(n);!(c!=null&&c.generating)||this.set(e,r)})},0)}}async function _(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/queries`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}class Xe{constructor(){s(this,"queryStoreCache",new V({capacity:1e4,timeout:20*I.second}));s(this,"liveQueryStoreCache",new V({capacity:1e4,timeout:200*I.millisecond}))}moduleQuery(e,t,n,i,r,c=!1){const d={...e,names:[...t],types:[...n]},y=this.query(d,i,r,c);return y===void 0||y==="too much data"?y:Ke(y,n)}query(e,t,n,i=!1){const r={...e,start:N.startOfMinute(t).toISOString(),end:i?n.toISOString():N.addMinutes(N.roundToNearestMinutes(n),1).toISOString(),latestOnly:i},c=n>N.addSeconds(new Date,-20);let d;return c?d=this.liveQueryCache(r):d=this.queryCache(r),!d||d==="too much data"||i?d:Qe(d,t,n)}queryCache(e){return this.queryStoreCache.get(e,async()=>{try{return await _(e)}catch(t){throw t}})}liveQueryCache(e){return this.liveQueryStoreCache.get(e,async()=>{try{return await _(e)}catch(t){throw t}})}}const Ye=new Xe;function Ze(a,e,t){const n=i=>{const r=i.data;if(r.type==="module_data"){const{start:c,end:d}=r.queryRange;t(Ye.moduleQuery({},a,e,new Date(c),new Date(d),!1))}};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}async function et(a,e,t){return new Promise(n=>{T({type:"request_date",minTime:e,maxTime:t,time:a});const i=r=>{const c=r.data;c.type==="date_response"&&(window.removeEventListener("message",i),n(c.data))};window.addEventListener("message",i)})}async function tt(a,e){return new Promise(t=>{const n=Math.random().toString();T({type:"prompt",promptId:n,schema:a,okText:e==null?void 0:e.okText,cancelText:e==null?void 0:e.cancelText});const i=r=>{const c=r.data;c.type==="prompt_response"&&c.promptId===n&&t(c.data),window.removeEventListener("message",i)};window.addEventListener("message",i)})}const x=class{static isModule(){return O()!==null}static async getCurrentModuleConfiguration(){let e=new URLSearchParams("");typeof window<"u"&&window.location&&(e=new URLSearchParams(window.location.search));const t=e.get("configuration");if(!(t===null||t.trim()===""))return je(t.trim())}static get isOnline(){return x._isOnline}static listenForConnectionEvents(){const e=t=>{const{data:n}=t;n.type==="formant_online"&&(this._isOnline=n.online)};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}static checkConnection(e=1e3){return new Promise((t,n)=>{const i=setTimeout(()=>n(new Error("deadline expired: took too long")),e),r=c=>{window.removeEventListener("message",r),clearTimeout(i);const{data:d}=c;d.type==="formant_online"&&(this._isOnline=d.online,t(d.online))};window.addEventListener("message",r),T({type:"formant_online"})})}static waitForConnection(e=5e3){let t=!1;const n=new Promise((c,d)=>{setTimeout(()=>{t=!0,d(new Error("deadline expired: took too long"))},e)}),i=c=>new Promise(d=>setTimeout(d,c)),r=async()=>{for(await i(50);!t&&!(this.isOnline||await this.checkConnection);)await i(500)};return Promise.race([n,r()])}};let g=x;s(g,"getCurrentModuleContext",O),s(g,"disableAnalyticsBottomBar",Ne),s(g,"goToDevice",Le),s(g,"goToTime",Ie),s(g,"refreshAuthToken",H),s(g,"requestModuleData",_e),s(g,"sendChannelData",$e),s(g,"setModuleDateTimeRange",ze),s(g,"setupModuleMenus",Me),s(g,"showMessage",Be),s(g,"addAccessTokenRefreshListener",W),s(g,"addChannelDataListener",qe),s(g,"addMenuListener",xe),s(g,"addModuleConfigurationListener",Ue),s(g,"addModuleDataListener",Je),s(g,"addOverviewDeviceListener",Ve),s(g,"addStreamListener",Ze),s(g,"getDate",et),s(g,"prompt",tt),s(g,"_isOnline",null);function f(a,e){if(a!==void 0)return a;throw new Error(e||"Value is undefined")}const p={UNKNOWN:0,TELEOP:1,PORT_FORWARD:2,OBSERVE:3,HEADLESS:4},nt={...p,Unknown:p.UNKNOWN,Teleop:p.TELEOP,PortForward:p.PORT_FORWARD,Observe:p.OBSERVE,Headless:p.HEADLESS,unknown:p.UNKNOWN,teleop:p.TELEOP,portForward:p.PORT_FORWARD,observe:p.OBSERVE,headless:p.HEADLESS},R=Symbol("RtcClientPool.instance");var hn;class P{constructor(e){s(this,hn,null);s(this,"createClient");s(this,"ttlMs");s(this,"proxyHandler");s(this,"proxyReceivers",new Map);s(this,"teardownTimeout",null);s(this,"dispatch",(e,t)=>{this.proxyReceivers.forEach(n=>n==null?void 0:n(e,t))});const{createClient:t,ttlMs:n=0}=e;this.createClient=t,this.ttlMs=Math.max(n,0),this.proxyHandler={get:(i,r,c)=>{switch(r){case"shutdown":return()=>this.releaseInstance(c);default:return Reflect.get(i,r,c)}}}}get isActive(){return this[R]!==null}get size(){return this.proxyReceivers.size}get(e){const t=new Proxy(this.allocate(),this.proxyHandler);return this.proxyReceivers.set(t,e??null),t}allocate(){if(this[R])return this.teardownTimeout&&(clearTimeout(this.teardownTimeout),this.teardownTimeout=null),this[R];const e=this.createClient(this.dispatch);return this[R]=e,e}async teardown(){const e=this[R];if(!e){console.warn("singleton has already been shutdown!");return}try{await e.shutdown()}finally{this[R]=null}}async releaseInstance(e){return this.proxyReceivers.delete(e)?this.proxyReceivers.size!==0?!1:(!this.teardownTimeout&&Number.isFinite(this.ttlMs)&&(this.ttlMs===0?await this.teardown():this.teardownTimeout=setTimeout(()=>{this.teardown().catch(t=>console.error("teardown failed",{err:t})).finally(()=>this.teardownTimeout=null)},this.ttlMs)),!0):(console.warn("this instance has already been released!"),!1)}}hn=R;const j=async()=>f(o.token,"Realtime when user isn't authorized"),b={[p.UNKNOWN]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.UNKNOWN,receive:a})}),[p.TELEOP]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.TELEOP,receive:a})}),[p.PORT_FORWARD]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.PORT_FORWARD,receive:a})}),[p.OBSERVE]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.OBSERVE,receive:a})}),[p.HEADLESS]:new P({ttlMs:2500,createClient:a=>new C.RtcClient({signalingClient:new C.SignalingPromiseClient(h),getToken:j,sessionType:p.HEADLESS,receive:a})})},at={...b,unknown:b[p.UNKNOWN],teleop:b[p.TELEOP],portForward:b[p.PORT_FORWARD],observe:b[p.OBSERVE],headless:b[p.HEADLESS]},$=b[p.TELEOP],it=a=>{const{sessionType:e}=a;return e?at[e]:$};class Y{constructor(e){s(this,"token");this.captureSession=e}async ingestJSON(e){if(!this.token){const n=await(await fetch(`${h}/v1/admin/capture-sessions/${this.captureSession.code}/authenticate`,{method:"POST"})).json();this.token=n.token}await fetch(`${h}/v1/ingest`,{method:"POST",body:JSON.stringify({deviceId:this.captureSession.deviceId,name:this.captureSession.streamName,type:"json",points:[[Date.now(),JSON.stringify(e)]]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.token}})}}function A(a){return new Promise(e=>setTimeout(e,a))}const rt=a=>a!==void 0&&a.capabilities!==void 0&&a.capabilitySet!==void 0;class Z{constructor(e){s(this,"ready",!1);s(this,"listeners",[]);s(this,"openListeners",[]);s(this,"closeListeners",[]);s(this,"errorListeners",[]);s(this,"binaryListeners",[]);s(this,"error");s(this,"decoder",new TextDecoder);this.dataChannel=e,this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.setReady()},this.dataChannel.onclose=()=>{this.ready=!1,this.closeListeners.forEach(t=>t())},this.dataChannel.onerror=t=>{console.error(t),this.error="An error occurred in DataChannel",this.errorListeners.forEach(n=>n(t))},this.dataChannel.onmessage=t=>{this.listeners.forEach(n=>{const i=new Uint8Array(t.data),r=this.decoder.decode(i);n(r)}),this.binaryListeners.forEach(n=>{n(new Uint8Array(t.data))})}}setReady(){this.ready=!0,this.openListeners.forEach(e=>e())}addOpenListener(e){this.openListeners.push(e)}removeOpenListener(e){this.openListeners=this.openListeners.filter(t=>t!==e)}addCloseListener(e){this.closeListeners.push(e)}removeCloseListener(e){this.closeListeners=this.closeListeners.filter(t=>t!==e)}addErrorListener(e){this.errorListeners.push(e)}removeErrorListener(e){this.errorListeners=this.errorListeners.filter(t=>t!==e)}async waitTilReady(){return this.ready?!0:new Promise((t,n)=>{let i=setInterval(()=>{this.dataChannel.readyState==="open"&&this.setReady(),this.ready&&(clearInterval(i),t(!0)),this.error&&n(this.error)},10)})}send(e){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(e)}sendBinary(e){if(!this.ready)throw new Error("Connection has been closed");this.dataChannel.send(e)}addListener(e){this.listeners.push(e)}removeListener(e){const t=this.listeners.indexOf(e);if(t===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.listeners.splice(t,1)}addBinaryListener(e){this.binaryListeners.push(e)}removeBinaryListener(e){const t=this.binaryListeners.indexOf(e);if(t===-1)throw new Error("Could not find data channel listener to remove");if(this.error)throw new Error(this.error);this.binaryListeners.splice(t,1)}}class ee{constructor(e,t){s(this,"currentListeners",[]);s(this,"onRealtimeMessage",(e,t)=>{t.payload.jointState&&this.currentListeners.forEach(n=>{t.payload.jointState&&n(t.payload.jointState)})});this.device=e,this.config=t}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(e){this.currentListeners.push(e)}}class te{constructor(e,t,n){s(this,"channel");s(this,"requestIdToResponseMap",new Map);this.device=e,this.channel_name=t,this.timeout=n}addOpenListener(e){f(this.channel,"channel not initalized").addOpenListener(e)}removeOpenListener(e){f(this.channel,"channel not initalized").removeOpenListener(e)}addCloseListener(e){f(this.channel,"channel not initalized").addCloseListener(e)}removeCloseListener(e){f(this.channel,"channel not initalized").removeCloseListener(e)}addErrorListener(e){f(this.channel,"channel not initalized").addErrorListener(e)}removeErrorListener(e){f(this.channel,"channel not initalized").removeErrorListener(e)}}class ne extends te{constructor(){super(...arguments);s(this,"RESPONSE_SUCCESS_BYTE",0);s(this,"decoder",new TextDecoder)}generateBinaryId(){const t=new Uint8Array(16);for(let n=0;n<t.length;n++)t[n]=Math.floor(Math.random()*256);return t}async initialize(){this.channel=await this.device.createCustomDataChannel(this.channel_name),this.channel.addBinaryListener(t=>{const i=t.slice(0,16).toString();if(i.length===0)throw new Error("Invalid response");const r=t.slice(16);if(r.length===0)throw new Error("Invalid response");this.requestIdToResponseMap.has(i)&&this.requestIdToResponseMap.set(i,r)})}async request(t){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:n,requestIdToResponseMap:i,timeout:r}=this;await n.waitTilReady();const c=this.generateBinaryId(),d=c.toString();i.set(d,!0),n.sendBinary(new Uint8Array([...c,...t]));const y=new Date().getTime();for(;new Date().getTime()<y+r;)if(await A(50),i.has(d)){const m=i.get(d);if(m!==!0){i.delete(d);const w=m[0]===this.RESPONSE_SUCCESS_BYTE,v=m.slice(1);if(w)return v;throw console.error({name:"AdapterError",message:this.decoder.decode(v)}),new Error("Binary request datachannel adapter error")}}throw i.delete(d),console.error({name:"TimeoutError",message:`Request timed out after ${r/1e3} seconds`}),new Error("Binary request data channel request timed out")}}class ae extends te{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(e=>{const t=JSON.parse(e),{id:n,data:i,error:r}=t;if(!n)throw new Error("Invalid response");if(!i&&!r)throw new Error("Invalid response");this.requestIdToResponseMap.has(n)&&this.requestIdToResponseMap.set(n,t)})}async request(e){if(this.channel||await this.initialize(),!this.channel)throw new Error("Failed to create channel");const{channel:t,requestIdToResponseMap:n,timeout:i}=this;await t.waitTilReady();const r=this.generateTextId();n.set(r,!0),t.send(JSON.stringify({id:r,data:e}));const c=new Date().getTime();for(;new Date().getTime()<c+i;)if(await A(50),n.has(r)){const d=n.get(r);if(d!==!0){n.delete(r);const{data:y,error:m}=d;if(y)return y;if(m)throw console.error({name:"AdapterError",message:m}),new Error("Text request datachannel adapter error")}}throw n.delete(r),console.error({name:"TimeoutError",message:`Request timed out after ${i/1e3} seconds`}),new Error("Text request datachannel request timed out")}}class ie extends ke.EventEmitter{constructor(){super(...arguments);s(this,"rtcClient");s(this,"remoteDevicePeerId",null);s(this,"realtimeListeners",[]);s(this,"connectionMonitorInterval");s(this,"handleMessage",(t,n)=>{this.realtimeListeners.forEach(i=>i(t,n))})}stopConnectionMonitoring(){clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=void 0}assertNotCancelled(t){if(t)throw new Error("Cancelled by deadline")}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")}addRealtimeListener(t){this.realtimeListeners.push(t)}removeRealtimeListener(t){const n=this.realtimeListeners.indexOf(t);if(n===-1)throw new Error("Could not find realtime listener to remove");this.realtimeListeners.splice(n,1)}async getRealtimeManipulators(){const t=await this.getConfiguration(),n=[];for(const i of t.teleop.rosStreams??[])i.topicType=="sensor_msgs/JointState"&&n.push(new ee(this,{currentJointStateStream:{name:i.topicName},plannedJointStateStream:i.plannedTopic?{name:i.plannedTopic}:void 0,planValidStream:i.planValidTopic?{name:i.planValidTopic}:void 0,endEffectorStream:i.endEffectorTopic?{name:i.endEffectorTopic}:void 0,endEffectorLinkName:i.endEffectorLinkName,baseReferenceFrame:i.baseReferenceFrame,localFrame:i.localFrame}));return n}async getRealtimeVideoStreams(){var i,r,c;const t=await this.getConfiguration(),n=[];for(const d of((i=t.teleop)==null?void 0:i.hardwareStreams)??[])d.rtcStreamType==="h264-video-frame"&&n.push({name:d.name});for(const d of((r=t.teleop)==null?void 0:r.rosStreams)??[])d.topicType=="formant/H264VideoFrame"&&n.push({name:d.topicName}),(d.topicType==="sensor_msgs/Image"||d.topicType==="sensor_msgs/CompressedImage")&&d.encodeVideo&&n.push({name:d.topicName});for(const d of((c=t.teleop)==null?void 0:c.customStreams)??[])d.rtcStreamType==="h264-video-frame"&&n.push({name:d.name});return n}createCustomRequestDataChannel(t,n=3e3){return new ae(this,t,n)}createCustomBinaryRequestDataChannel(t,n=3e3){return new ne(this,t,n)}async startListeningToRealtimeVideo(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeVideo(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async startListeningToRealtimeDataStream(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!0,pipeline:"rtc"})}async stopListeningToRealtimeDataStream(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t.name,enable:!1,pipeline:"rtc"})}async enableRealtimeTelemetryPriorityIngestion(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t,enablePriorityUpload:!0,pipeline:"telemetry"})}async disableRealtimeTelemetryPriorityIngestion(t){const n=f(this.rtcClient,"Realtime connection has not been started"),i=await this.getRemotePeer();n.controlRemoteStream(f(i).id,{streamName:t,enablePriorityUpload:!1,pipeline:"telemetry"})}async changeStreamAudioType(t,n){const i=f(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();i.controlRemoteStream(f(r).id,{streamName:t,setAudioFormat:n})}async createCustomDataChannel(t,n){const i=f(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer(),c=await new Promise(d=>{i.createCustomDataChannel(f(r).id,t,{ordered:!0,...n},!1,(y,m)=>{const w=new Z(m);d(w)})});return await c.waitTilReady(),c}async sendRealtimeMessage(t,n={channelLabel:"stream.reliable"}){const i=f(this.rtcClient,"Realtime connection has not been started"),r=await this.getRemotePeer();i.send(f(r).id,t,n)}async getRealtimeAudioStreams(){var i,r,c;const t=await this.getConfiguration(),n=[];for(const d of((i=t.teleop)==null?void 0:i.hardwareStreams)??[])d.rtcStreamType==="audio-chunk"&&n.push({name:d.name});for(const d of((r=t.teleop)==null?void 0:r.rosStreams)??[])d.topicType=="audio_common_msgs/AudioData"&&n.push({name:d.topicName});for(const d of((c=t.teleop)==null?void 0:c.customStreams)??[])d.rtcStreamType==="audio-chunk"&&n.push({name:d.name});return n}}const ot=new TextEncoder;new TextDecoder;function st(a){const e=JSON.stringify(a),t=ot.encode(e),n=Oe.deflate(t);return Re.fromByteArray(n)}async function re(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/views`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function oe(a,e){if(!o.token)throw new Error("Not authenticated");const n=(await re()).filter(d=>d.name===e);if(n.length===0)return console.warn("View does not exist or it is misspell"),null;const i=await fetch(`${h}/v1/admin/shares`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),r=h.replace("api","app"),{code:c}=await i.json();return`${r}/shares/${c}#${st({viewId:n[0].id})}`}const ct=["day","week","month","year","hour","minute","quarter"],dt=["interval","start","end","sub","get"];function se(a){return a.count<2?0:a.sumOfSquares/(a.count-1)}function ce(a){return Math.sqrt(se(a))}function de(a){return a.max}function he(a){return a.min}function le(a){return a.count===0?-1:a.sum/a.count}function ue(a){return a.sum}function me(a){return a.count}const ht={min:he,max:de,"standard deviation":ce,average:le,sum:ue,count:me},z={day:{interval:u.eachDayOfInterval,start:u.startOfDay,end:u.endOfDay,sub:u.subDays,get:u.getDay},week:{interval:u.eachWeekOfInterval,start:u.startOfWeek,end:u.endOfWeek,sub:u.subWeeks,get:u.getWeek},month:{interval:u.eachMonthOfInterval,start:u.startOfMonth,end:u.endOfMonth,sub:u.subMonths,get:u.getMonth},year:{interval:u.eachYearOfInterval,start:u.startOfYear,end:u.endOfYear,sub:u.subYears,get:u.getYear},hour:{interval:u.eachHourOfInterval,start:u.startOfHour,end:u.endOfHour,sub:u.subHours,get:u.getHours},minute:{interval:u.eachMinuteOfInterval,start:u.startOfMinute,end:u.endOfMinute,sub:u.subMinutes,get:u.getMinutes},quarter:{interval:u.eachQuarterOfInterval,start:u.startOfQuarter,end:u.endOfQuarter,sub:u.subQuarters,get:u.getQuarter}},fe=(a,e)=>a.split("/")[0]+"/"+a.split("/")[1]+"–"+e.split("/")[0]+"/"+e.split("/")[1];async function M(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/events/query`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function we(a,e,t,n,i){const r=z[e];return await Promise.all(Array(t).fill(0).map(async(c,d)=>{const y=new Date(n),m=r.sub(r.start(y),t-d-1),w=r.sub(r.end(y),t-d-1),v=fe(m.toLocaleDateString(),w.toLocaleDateString()),S=await M({...i,eventTypes:a,start:new Date(m).toISOString(),end:new Date(w).toISOString()});return{date:v,events:S}}))}async function B(a,e){return(await M({...a,eventTypes:["annotation"]})).filter(r=>!!r.tags&&Object.keys(r.tags).includes(e)).reduce((r,c)=>{const d=c.tags[e];return d in r?(r[d]+=1,r):(r[d]=1,r)},{})}async function pe(a,e,t){const{end:n,start:i}=a,c=z[t].interval({start:new Date(i),end:new Date(n)}),d=c.map((m,w)=>{const v=new Date(m).toISOString(),S=w===c.length-1?new Date(Date.now()).toISOString():new Date(c[w+1]);return B({...a,start:v,end:S},e)}),y=await Promise.all(d);return c.map((m,w)=>({date:new Date(m).toISOString(),annotations:y[w]}))}async function ye(a,e,t,n,i){let r=a;Array.isArray(a)||(r=[a]);let c=e;return Array.isArray(e)||(c=[e]),(await(await fetch(`${h}/v1/queries/queries`,{method:"POST",body:JSON.stringify({deviceIds:r,end:n.toISOString(),names:c,start:t.toISOString(),tags:i}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function ge(){if(!o.token)throw new Error("Not authenticated");const a=$.get();try{return await a.getSessions()}finally{await a.shutdown()}}async function ve(){if(!o.token)throw new Error("Not authenticated");const a=$.get();try{return await a.getPeers()}finally{await a.shutdown()}}async function lt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function ut(a,e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices/${a}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function mt(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function ft(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function wt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices/${a}/disable`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}class E extends ie{constructor(e,t,n,i){super(),this.id=e,this.name=t,this.organizationId=n,this.tags=i}async getLatestTelemetry(){return(await(await fetch(`${h}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async getConfiguration(e=!1){let t=await fetch(`${h}/v1/admin/devices/${this.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}});const n=await t.json();if(!n.state.reportedConfiguration)throw new Error("Device has no configuration, has it ever been turned on?");const i=e?n.desiredConfigurationVersion:n.state.reportedConfiguration.version;return t=await fetch(`${h}/v1/admin/devices/${this.id}/configurations/${i}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),(await t.json()).document}async getFileUrl(e){return(await(await fetch(`${h}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[e]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).fileUrls}async startRealtimeConnection(e={}){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const{sessionType:t,deadlineMs:n=1e4,maxConnectRetries:i=3}=typeof e=="number"?{sessionType:e}:e,c=it({sessionType:t}).get(this.handleMessage);let d=!1;const y=new Promise((w,v)=>setTimeout(()=>{d=!0,v(new Error("Connection timed out: the connection could not be finalized in time, possibly due to network issues or misconfigured settings."))},n)),m=async()=>{if("isReady"in c)for(;!c.isReady();)this.assertNotCancelled(d),await A(100);const w=await this.getRemoteDevicePeerId(c);this.assertNotCancelled(d);let v;for(let D=0;D<i&&(v=await c.connect(w),!v);D++)A(100),this.assertNotCancelled(d);if(!v)throw new Error(`Session could not be created: exhausted ${i} retries`);let S=0;for(;!d&&c.getConnectionStatus(w)!=="connected";)await A(100),S+=1;return this.assertNotCancelled(d),console.debug(`${new Date().toISOString()} :: Connection completed after ${S} retries`),w};return Promise.race([m(),y]).then(w=>{this.remoteDevicePeerId=w,this.initConnectionMonitoring(),this.rtcClient=c,this.emit("connect")}).catch(w=>{throw console.debug(`${new Date().toISOString()} :: Connection failed: %o`,w),this.remoteDevicePeerId=null,c.shutdown().catch(v=>{console.error("rtcClient cannot shutdown: %o",v)}),this.emit("connection_failed",w),w})}async getRemoteDevicePeerId(e){const n=(await e.getPeers()).find(i=>i.deviceId===this.id);if(!rt(n))throw new Error("Cannot find peer, is the robot offline?");return n.id}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let e=!1;if(this.rtcClient){const n=this.rtcClient.getConnections().find(i=>i.getRemotePeerId()===this.remoteDevicePeerId&&i.isActive());(n===void 0||!n.isReady())&&(console.debug(`${new Date().toISOString()} :: data channel closed`),e=!0)}(!this.rtcClient||!this.remoteDevicePeerId||await this.rtcClient.getConnectionStatsInfo(this.remoteDevicePeerId)===void 0||e)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(t=>{console.error(t)}))},1e3)}async getRemotePeer(){const t=(await f(this.rtcClient,"Realtime connection has not been started").getPeers()).find(n=>n.deviceId===this.id);return f(t,"Could not find remote peer for device "+this.id)}async stopRealtimeConnection(){let e=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.remoteDevicePeerId?(await this.rtcClient.disconnect(this.remoteDevicePeerId),this.remoteDevicePeerId=null):e=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(e)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async isInRealtimeSession(){const e=await ve(),t=await ge(),n=e.find(i=>i.deviceId===this.id);return n?t[n.id].length>0:!1}async getAvailableCommands(){return(await(await fetch(`${h}/v1/admin/command-templates/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items.map(n=>({name:n.name,id:n.id,command:n.command,description:n.description,parameterEnabled:n.parameterEnabled,parameterValue:n.parameterValue,parameterMeta:n.parameterMeta,enabled:n.enabled,tags:n.tags}))}async sendCommand(e,t,n,i){var w;const c=(await this.getAvailableCommands()).find(v=>v.name===e);if(!c)throw new Error(`Could not find command with name "${e}"`);let d="";t===void 0?c.parameterEnabled&&c.parameterValue&&(d=c.parameterValue):d=t;let y={value:d,scrubberTime:(n||new Date).toISOString(),meta:{...c.parameterMeta,...i}};return await fetch(`${h}/v1/admin/commands`,{method:"POST",body:JSON.stringify({commandTemplateId:c.id,organizationId:this.organizationId,deviceId:this.id,command:c.command,parameter:y,userId:(w=o.currentUser)==null?void 0:w.id}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})}async getCommand(e){return await fetch(`${h}/v1/admin/commands/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})}async createCaptureStream(e){const n=await(await fetch(`${h}/v1/admin/capture-sessions`,{method:"POST",body:JSON.stringify({deviceId:this.id,streamName:e,tags:{}}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json();return new Y(n)}async getTelemetry(e,t,n,i){return await ye(this.id,e,t,n,i)}async getTelemetryStreams(){var d,y;const e=await this.getConfiguration(),t=await fetch(`${h}/v1/queries/metadata/stream-names`,{method:"POST",body:JSON.stringify({deviceIds:[this.id]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),n=[],i=[];return(y=(d=e.telemetry)==null?void 0:d.streams)==null||y.forEach(m=>{m.disabled!==!0&&n.push(m.name),m.onDemand===!0&&i.push(m.name)}),console.log(i),(await t.json()).items.filter(m=>!n.includes(m)).map(m=>({name:m,onDemand:i.includes(m)}))}async createInterventionRequest(e,t,n,i){return await(await fetch(`${h}/v1/admin/intervention-requests`,{method:"POST",body:JSON.stringify({message:e,interventionType:t,time:new Date().toISOString(),deviceId:this.id,tags:i,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async addInterventionResponse(e,t,n){return await(await fetch(`${h}/v1/admin/intervention-responses`,{method:"POST",body:JSON.stringify({interventionId:e,interventionType:t,data:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async getAnnotationCount(e,t){return await B({...e,deviceIds:[this.id]},t)}async getAnnotationCountByIntervals(e,t,n){return await pe({...e,deviceIds:[this.id]},t,n)}async eventsCounter(e,t,n,i,r){return await we(e,t,n,i,{...r,deviceIds:[this.id]})}async createShareLink(e,t){return e.scope.deviceIds=[this.id],await oe(e,t)}}s(E,"createDevice",lt),s(E,"patchDevice",ut),s(E,"getDevicesData",mt),s(E,"queryDevicesData",ft),s(E,"disableDevice",wt);class Te extends ie{constructor(t){super();s(this,"id");s(this,"telemetryStreamActive",!1);s(this,"streamTelemetry",{});this.peerUrl=t}async getLatestTelemetry(){this.telemetryStreamActive||this.subscribeToTelemetry();const t=this.streamTelemetry;return Object.entries(t).map(([i,r])=>({deviceId:this.id,streamName:i,streamType:"json",currentValue:r,currentValueTime:r.timestamp,tags:{}}))}subscribeToTelemetry(){this.telemetryStreamActive=!0;let t=0;const n=new XMLHttpRequest;n.responseType="text",n.addEventListener("error",i=>{this.handleXHRError("error")}),n.addEventListener("abort",i=>{this.handleXHRError("abort")}),n.addEventListener("timeout",i=>{this.handleXHRError("timeout")}),n.addEventListener("readystatechange",i=>{n.readyState===XMLHttpRequest.DONE&&this.handleXHRError("closed")}),n.addEventListener("progress",i=>{const r=i.loaded,c=r-t;t=r,n.responseText.substr(-c).split(`
2
+ `).forEach(m=>{var w;if(m.length>0){const v=JSON.parse(m);if((w=v.result)!=null&&w.datapoint){const S=v.result.datapoint,D=S.stream;delete S.stream,this.streamTelemetry[D]=S}}})}),n.open("POST",`${this.peerUrl}/v1/telemetry`),n.send()}handleXHRError(t){console.warn(`Telemetry stream ended: ${t}`),this.telemetryStreamActive=!1}async getDeviceId(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.id}async getConfiguration(){return(await(await fetch(`${this.peerUrl}/v1/config`)).json()).configuration.document}async startRealtimeConnection(t){if(console.debug(`${new Date().toISOString()} :: Connection start requested`),this.rtcClient&&this.connectionMonitorInterval!==void 0)throw new Error(`Already created realtime connection to device ${this.id}`);this.rtcClient&&console.warn("overwriting existing rtcClient due to missing connectionMonitorInterval");const n=new C.RtcClient({lanOnlyMode:!0,receive:this.handleMessage,sessionType:t});for(await n.connectLan(this.peerUrl);n.getConnectionStatus(this.peerUrl)!=="connected";)await A(100);this.rtcClient=n,this.initConnectionMonitoring()}initConnectionMonitoring(){this.connectionMonitorInterval=setInterval(async()=>{let t=!1;this.rtcClient&&this.rtcClient.getConnectionStatus(this.peerUrl)!=="connected"&&(console.debug(`${new Date().toISOString()} :: data channel closed`),t=!0),(!this.rtcClient||t)&&(this.emit("disconnect"),this.stopRealtimeConnection().catch(n=>{console.error(n)}))},1e3)}async getRemotePeer(){return{id:this.peerUrl,organizationId:"",deviceId:this.id,capabilities:[],capabilitySet:{}}}async stopRealtimeConnection(){let t=!1;if(this.rtcClient){this.stopConnectionMonitoring(),this.id?(await this.rtcClient.disconnect(this.id),this.remoteDevicePeerId=null):t=!0;try{await this.rtcClient.shutdown()}finally{this.rtcClient=void 0}}if(t)throw new Error(`Realtime connection hasn't been started for ${this.id}`)}async sendCommand(t,n,i,r){const c={value:n,scrubberTime:(i||new Date).toISOString(),meta:r};return await fetch(`${this.peerUrl}/v1/enqueue-command`,{method:"POST",body:JSON.stringify({command:t,parameter:c}),headers:{"Content-Type":"application/json"}})}}async function pt(a,e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/devices/${a}`,{method:"PATCH",body:JSON.stringify({fleetId:e}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function yt(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/queries`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).aggregates}async function gt(a){if(!o.token)throw new Error("Not authenticated");await fetch(`${h}/v1/admin/fleets/${a}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})}async function vt(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/analytics/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function Tt(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/analytics-modules`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function Ct(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/queries/analytics/rows`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function Ce(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/devices/query`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items.map(n=>new E(n.id,n.name,n.organizationId,n.tags))}async function St(){if(!o.token)throw new Error("Not authenticated");let a=new URLSearchParams("");typeof window<"u"&&window.location&&(a=new URLSearchParams(window.location.search));const e=a.get("group");if(e===null||e.trim()==="")return;const t=await fetch(`${h}/v1/admin/groups/`+e,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),{tagKey:n,tagValue:i}=await t.json();return await Ce({tags:{[n]:[i]},enabled:!0,type:"default"})}async function Et(a){if(!o.token)throw new Error("Not authenticated");const t=await(await fetch(`${h}/v1/admin/devices/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json(),n=t.name;return new E(a,n,t.organizationId,t.tags)}async function q(){if(!o.token)throw new Error("Not authenticated");const e=await(await fetch(`${h}/v1/admin/device-details/query`,{method:"POST",body:JSON.stringify({enabled:!0,type:"default"}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json();return e.items,e.items.map(t=>new E(t.id,t.name,t.organizationId,t.tags))}async function kt(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/events/query/id=${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function Ot(a){const t=await(await fetch(`${h}/v1/admin/files/query`,{method:"POST",body:JSON.stringify({fileIds:[a]}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json();if(t.fileUrls.length===0)throw new Error("File not found");return t.fileUrls[0]}async function Rt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/fleets/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function bt(a){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/fleets/${a}/devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function At(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/intervention-requests`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function Dt(...a){const e=a.flat().filter(i=>!!i);return e.length===0?[]:(await(await fetch(`${h}/v1/queries/stream-current-value`,{method:"POST",body:JSON.stringify({deviceIds:e}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function Pt(){if(!o.token)throw new Error("Not authenticated");const t=(await(await fetch(`${h}/v1/queries/online-devices`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items;return(await q()).filter(i=>t.includes(i.id))}async function jt(){if(!o.token)throw new Error("Not authenticated");const t=(await(await fetch(`${h}/v1/signaling/peers`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items.map(i=>i.deviceId);return(await q()).filter(i=>t.includes(i.id))}async function Nt(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/streams`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items.filter(t=>t.enabled)}async function Lt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/queries/analytics/task-report-rows`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function It(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/queries/analytics/task-reports`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function _t(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/fleets`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function $t(a,e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/fleets/${a}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function zt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/streams/${a.id}`,{method:"PATCH",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function Mt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/views/${a.id}`,{method:"PATCH",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function Bt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/queries/analytics`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function qt(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/fleets`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function xt(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/event-trigger-groups`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}async function Ut(a){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/event-trigger-groups/${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}async function Jt(a,e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/event-trigger-groups/${a}`,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}const k=class{static async setDefaultDevice(e){k.defaultDeviceId=e}static async getCurrentDevice(){if(!o.token)throw new Error("Not authenticated");if(!k.defaultDeviceId)throw new Error("No known default device");const n=(await(await fetch(`${h}/v1/admin/device-details/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items.find(c=>c.id===k.defaultDeviceId),i=n.name,r=new E(k.defaultDeviceId,i,f(o.currentOrganization),n.tags);return k.knownContext.push(new WeakRef(r)),r}static async getPeerDevice(e){const t=new Te(e);return t.id=await t.getDeviceId(),t}static async getDevice(e){const t=await Et(e);return k.knownContext.push(new WeakRef(t)),t}};let l=k;s(l,"defaultDeviceId"),s(l,"knownContext",[]),s(l,"createFleet",qt),s(l,"listFleets",_t),s(l,"getFleet",Rt),s(l,"patchFleet",$t),s(l,"deleteFleet",gt),s(l,"addDeviceToFleet",pt),s(l,"getFleetDevices",bt),s(l,"aggregateTelemetry",yt),s(l,"createShareLink",oe),s(l,"eventsCounter",we),s(l,"getAnalyticStreams",vt),s(l,"getAnalyticsModules",Tt),s(l,"getAnalyticsRows",Ct),s(l,"getAnnotationCount",B),s(l,"getAnnotationCountByIntervals",pe),s(l,"getCurrentGroup",St),s(l,"getDevices",q),s(l,"getEvent",kt),s(l,"getFileUrl",Ot),s(l,"getInterventions",At),s(l,"getLatestTelemetry",Dt),s(l,"getOnlineDevices",Pt),s(l,"getPeers",ve),s(l,"getRealtimeDevices",jt),s(l,"getRealtimeSessions",ge),s(l,"getStreams",Nt),s(l,"getTaskReportRows",Lt),s(l,"getTaskReportTables",It),s(l,"getTelemetry",ye),s(l,"getViews",re),s(l,"patchStream",zt),s(l,"patchView",Mt),s(l,"queryAnalytics",Bt),s(l,"queryDevices",Ce),s(l,"queryEvents",M),s(l,"queryTelemetry",_),s(l,"getAllEventTriggerGroup",xt),s(l,"getEventTriggerGroup",Ut),s(l,"patchEventTriggergroup",Jt);class Vt{static async set(e,t,n){try{const i=await fetch(h+"/v1/admin/key-value",{method:"POST",body:JSON.stringify({organizationId:f(o.currentUser).organizationId,key:e,value:t,tags:n}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),r=await i.json();if(i.status!==200)throw new Error(r.message)}catch(i){throw i}}static async get(e){try{const t=await fetch(h+`/v1/admin/key-value/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),n=await t.json();if(t.status!==200)throw new Error(n.message);return n.value}catch(t){throw t}}static async list(){try{const e=await fetch(h+"/v1/admin/key-value",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}}),t=await e.json();if(e.status!==200)throw new Error(t.message);return t.items}catch(e){throw e}}static async delete(e){try{if(!(await fetch(h+`/v1/admin/key-value/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).ok)throw new Error("Unable to handle request");return}catch(t){throw t}}static async query(e){try{const t=await fetch(h+"/v1/admin/key-value/query",{method:"POST",body:JSON.stringify({keys:e}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}});if(!t.ok)throw new Error("Unable to handle request");return(await t.json()).items}catch(t){throw t}}}function Ft(a){return Uint8Array.from(G.decode(a),e=>e.charCodeAt(0))}function F(){const{userAgent:a}=navigator;return a?a.includes("Firefox/")?"Firefox":a.includes("Edg/")?"Edge":a.includes("Chrome/")?"Chrome":a.includes("Safari/")?"Safari":a.includes("MSIE/")||a.includes("Trident/")?"IE":"Other":"Other"}const Gt="audio-chunk";class Ht{constructor(e,t){s(this,"muted",!1);s(this,"hasReceivedData",!1);s(this,"audioContext");s(this,"chunks",[]);s(this,"isPlaying",!1);s(this,"startTime",0);s(this,"lastChunkOffset",0);s(this,"bufferSize",3);s(this,"receive",async e=>{var c;const t=(c=e.payload.audioChunk)==null?void 0:c.chunk_data;if(!t)return;this.hasReceivedData||(this.hasReceivedData=!0);const{audioContext:n,muted:i}=this;if(!n||e.header.stream.streamType!==Gt||i!==!1)return;const r=Ft(t);try{await n.decodeAudioData(r.buffer,this.scheduleChunk)}catch(d){console.warn("Error decoding audio buffer, changing audioWireFormat on agent",{error:d}),this.changeAudioWireFormat("wav")}});s(this,"scheduleChunk",e=>{const{audioContext:t}=this;if(!t)return;(this.chunks.length>this.bufferSize||this.isPlaying===!1)&&(this.chunks.forEach(i=>{i.stop()}),this.isPlaying=!1,this.chunks=[]);const n=this.createChunk(e);n&&n.buffer&&(this.isPlaying===!1&&(this.startTime=t.currentTime,this.lastChunkOffset=0,this.isPlaying=!0),n.start(this.startTime+this.lastChunkOffset,0,e.duration),this.lastChunkOffset+=n.buffer.duration,this.chunks.push(n))});this.device=e,this.stream=t,this.device.startListeningToRealtimeDataStream(t),this.device.addRealtimeListener((i,r)=>{this.receive(r)}),F()==="Safari"||F()==="IE"?this.changeAudioWireFormat("wav"):this.changeAudioWireFormat("opus");const n=window.AudioContext||window.webkitAudioContext;this.audioContext=new n}async play(){var e,t;((e=this.audioContext)==null?void 0:e.state)==="suspended"&&await((t=this.audioContext)==null?void 0:t.resume()),this.muted=!1}async pause(){await this.audioContext.suspend(),this.muted=!0}destroy(){this.device.stopListeningToRealtimeDataStream(this.stream)}createChunk(e){const{audioContext:t}=this;if(!t)return;const n=t.createBufferSource();return n.buffer=e,n.connect(t.destination),n.loop=!1,n.onended=i=>{this.chunks.splice(this.chunks.indexOf(n),1),this.chunks.length===0&&(this.isPlaying=!1)},n}changeAudioWireFormat(e){const{stream:t}=this;(async()=>await this.device.changeStreamAudioType(t.name,e))()}}class Wt{static async listAccounts(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/accounts`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}static async createAccounts(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async getAccount(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async patchAccount(e,t){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async deleteAccount(e){if(!o.token)throw new Error("Not authenticated");if(!(await fetch(`${h}/v1/admin/accounts/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).ok)throw new Error("Unable to delete account")}static async getAccountTree(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/accounts/${e}/tree`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}}class Kt{static async listRoles(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/roles`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}static async createRole(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/roles`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async getRole(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/roles/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async patchRole(e,t){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/roles/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async deleteRole(e){if(!o.token)throw new Error("Not authenticated");await fetch(`${h}/v1/admin/roles/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})}}class Qt{static async listUsers(){if(!o.token)throw new Error("Not authenticated");return(await(await fetch(`${h}/v1/admin/users`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()).items}static async createUser(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/users`,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async getUser(e){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/users/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async patchUser(e,t){if(!o.token)throw new Error("Not authenticated");return await(await fetch(`${h}/v1/admin/users/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})).json()}static async deleteUser(e){if(!o.token)throw new Error("Not authenticated");await fetch(`${h}/v1/admin/users/${e}`,{method:"PATCH",body:JSON.stringify({enabled:!1,roleId:null,teamId:null}),headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.token}})}}const Xt=["viewer","operator","administrator"],Yt="viewer",Zt="operator",en="administrator",tn=["year","month","week","day","hour","minute"],nn=["tag","sheet","user"],an=["triggered-event","intervention-request","teleop-session-record","port-forwarding-session-record","command-request","command-response","command-delivery","custom","comment","system","annotation"],rn=["unknown","operational","offline","error"],on=["selection","labeling","teleop"],sn=["info","warning","error","critical"],cn=["video/mp4"],dn=a=>new Promise(e=>setTimeout(e,a*1e3));try{const a=typeof window<"u"&&window.location?new URLSearchParams(window.location.search):new URLSearchParams(""),e=a.get("device");e&&l.setDefaultDevice(e);const t=a.get("auth");t&&o.loginWithToken(t),a.get("module")&&o.listenForRefresh(),typeof window<"u"&&g.listenForConnectionEvents()}catch{}exports.Account=Wt;exports.App=g;exports.AudioPlayer=Ht;exports.Authentication=o;exports.BinaryRequestDataChannel=ne;exports.CaptureStream=Y;exports.DataChannel=Z;exports.Device=E;exports.Fleet=l;exports.KeyValue=Vt;exports.Manipulator=ee;exports.PeerDevice=Te;exports.Role=Kt;exports.SessionType=nt;exports.TextRequestDataChannel=ae;exports.User=Qt;exports.accessLevels=Xt;exports.administrator=en;exports.aggregateByDateFunctions=z;exports.aggregateFunctionMap=ht;exports.aggregateFunctions=dt;exports.aggregateLevels=tn;exports.annotationTypes=nn;exports.eventTypes=an;exports.formatTimeFrameText=fe;exports.getAverage=le;exports.getCount=me;exports.getMax=de;exports.getMin=he;exports.getStandardDeviation=ce;exports.getSum=ue;exports.getVariance=se;exports.healthStatuses=rn;exports.interventionTypes=on;exports.operator=Zt;exports.severities=sn;exports.timeout=dn;exports.vailableAggregationIntervals=ct;exports.videoMimeTypes=cn;exports.viewer=Yt;
3
3
  //# sourceMappingURL=data-sdk.cjs.js.map