1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/embed-CarFBAKX.js","assets/protocol-Bj_vfKMm.js","assets/embed-CgZsMJDx.css","assets/auto-DKQ5exK4.js"])))=>i.map(i=>d[i]); 2(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=Object.defineProperty,t=(t,n,r)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,n=(e,n,r)=>(t(e,typeof n==`symbol`?n:n+``,r),r),r=`modulepreload`,i=function(e){return`/`+e},a={},o=function(e,t,n){let o=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),s=document.querySelector(`meta[property=csp-nonce]`),c=s?.nonce||s?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,new URL(`../../../src/node/plugins/importAnalysisBuild.ts`,import.meta.url)).href}o=l(t.map(t=>{if(t=i(t,n),t=u(t),t in a)return;a[t]=!0;let o=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.href===t&&(!o||r.rel===`stylesheet`))return}let s=document.createElement(`link`);if(s.rel=o?`stylesheet`:r,o||(s.as=`script`),s.crossOrigin=``,s.href=t,c&&s.setAttribute(`nonce`,c),document.head.appendChild(s),o)return new Promise((e,n)=>{s.addEventListener(`load`,e),s.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function s(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return o.then(t=>{for(let e of t||[])e.status===`rejected`&&s(e.reason);return e().catch(s)})},s=`https://huggingface.co`;async function c(e,t){let n=new l(e.url,e.status,e.headers.get(`X-Request-Id`)??t?.requestId);n.message=`Api error with status ${n.statusCode}${t?.message?`. ${t.message}`:``}`;let r=[`URL: ${n.url}`,n.requestId?`Request ID: ${n.requestId}`:void 0].filter(Boolean).join(`. `);if(e.headers.get(`Content-Type`)?.startsWith(`application/json`)){let t=await e.json();n.message=t.error||t.message||n.message,n.data=t}else n.data={message:await e.text()};throw n.message+=`. ${r}`,n}
2var l=class extends Error{constructor(e,t,r,i){super(i),n(this,`statusCode`),n(this,`url`),n(this,`requestId`),n(this,`data`),this.statusCode=t,this.requestId=r,this.url=e}};typeof window<`u`&&window.document,typeof self==`object`&&self.constructor&&self.constructor.name,new Promise(e=>{});function u(e){if(globalThis.Buffer)return globalThis.Buffer.from(e).toString(`base64`);{let t=[];return e.forEach(e=>{t.push(String.fromCharCode(e))}),globalThis.btoa(t.join(``))}}async function d(e){if(typeof window>`u`)throw Error(`oauthHandleRedirect is only available in the browser`);let t=new URLSearchParams(window.location.search),[n,r]=[t.get(`error`),t.get(`error_description`)];if(n)throw Error(`${n}: ${r}`);let i=t.get(`code`),a=localStorage.getItem(`huggingface.co:oauth:nonce`);if(!i)throw Error(`Missing oauth code from query parameters in redirected URL`);if(!a)throw Error(`Missing oauth nonce from localStorage`);let o=localStorage.getItem(`huggingface.co:oauth:code_verifier`);if(!o)throw Error(`Missing oauth code_verifier from localStorage`);let l=t.get(`state`);if(!l)throw Error(`Missing oauth state from query parameters in redirected URL`);let u;try{u=JSON.parse(l)}catch{throw Error(`Invalid oauth state in redirected URL, unable to parse JSON: `+l)}if(u.nonce!==a)throw Error(`Invalid oauth state in redirected URL`);let d=e?.hubUrl||s,f=`${new URL(d).origin}/.well-known/openid-configuration`,p=await fetch(f,{headers:{Accept:`application/json`}});if(!p.ok)throw await c(p);let m=await p.json(),h=await fetch(m.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,code:i,redirect_uri:u.redirectUri,code_verifier:o}).toString()});if(localStorage.removeItem(`huggingface.co:oauth:code_verifier`),localStorage.removeItem(`huggingface.co:oauth:nonce`),!h.ok)throw await c(h);let g=await h.json(),_=new Date(Date.now()+g.expires_in*1e3),v=await fetch(m.userinfo_endpoint,{headers:{Authorization:`Bearer ${g.access_token}`}});if(!v.ok)throw await c(v);let y=await v.json();return{accessToken:g.access_token,accessTokenExpiresAt:_,userInfo:{id:y.sub,name:y.name,fullname:y.preferred_username,email:y.email,emailVerified:y.email_verified,avatarUrl:y.picture,websiteUrl:y.website,isPro:y.isPro,orgs:y.orgs?.map(e=>({id:e.sub,name:e.name,fullname:e.name,isEnterprise:e.isEnterprise,canPay:e.canPay,avatarUrl:e.picture,roleInOrg:e.roleInOrg}))??[]},state:u.state,scope:g.scope}}async function f(e){if(typeof window>`u`)throw Error(`oauthHandleRedirect is only available in the browser`);let t=new URLSearchParams(window.location.search);return t.has(`error`)?d(e):t.has(`code`)?localStorage.getItem(`huggingface.co:oauth:nonce`)?d(e):(console.warn(`Missing oauth nonce from localStorage. This can happen when the user refreshes the page after logging in, without changing the URL.`),!1):!1}async function p(e){if(typeof window>`u`)throw Error(`oauthLogin is only available in the browser`);let t=e?.hubUrl||s,n=`${new URL(t).origin}/.well-known/openid-configuration`,r=await fetch(n,{headers:{Accept:`application/json`}});if(!r.ok)throw await c(r);let i=await r.json(),a=globalThis.crypto.randomUUID(),o=globalThis.crypto.randomUUID()+globalThis.crypto.randomUUID();localStorage.setItem(`huggingface.co:oauth:nonce`,a),localStorage.setItem(`huggingface.co:oauth:code_verifier`,o);let l=e?.redirectUrl||window.location.href,d=JSON.stringify({nonce:a,redirectUri:l,state:e?.state}),f=(window==null?void 0:window.huggingface)?.variables??null,p=e?.clientId||f?.OAUTH_CLIENT_ID;if(!p)throw Error(f?`Missing clientId, please add hf_oauth: true to the README.md's metadata in your static Space`:`Missing clientId`);let m=u(new Uint8Array(await globalThis.crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(o)))).replace(/[+]/g,`-`).replace(/[/]/g,`_`).replace(/=/g,``);return`${i.authorization_endpoint}?${new URLSearchParams({client_id:p,scope:e?.scopes||f?.OAUTH_SCOPES||`openid profile`,response_type:`code`,redirect_uri:l,state:d,code_challenge:m,code_challenge_method:`S256`}).toString()}`}function m(e){return e*Math.PI/180}function h(e,t,n){let r=m(e),i=m(t),a=m(n),o=Math.cos(a),s=Math.sin(a),c=Math.cos(i),l=Math.sin(i),u=Math.cos(r),d=Math.sin(r);return[[o*c,o*l*d-s*u,o*l*u+s*d,0],[s*c,s*l*d+o*u,s*l*u-o*d,0],[-l,c*d,c*u,0],[0,0,0,1]]}function g(){if(typeof window>`u`||!window.location.hash)return;let e=window.location.hash.startsWith(`#`)?window.location.hash.slice(1):window.location.hash,t;try{t=new URLSearchParams(e)}catch{return}let n=t.get(`hf_token`);if(!n)return;let r=t.get(`hf_username`)||`user`,i=t.get(`hf_token_expires`),a=i&&!Number.isNaN(new Date(i).getTime())?i:new Date(Date.now()+365*24*60*60*1e3).toISOString();try{sessionStorage.setItem(`hf_token`,n),sessionStorage.setItem(`hf_username`,r),sessionStorage.setItem(`hf_token_expires`,a)}
2catch(e){console.warn(`[reachy-mini] could not persist pre-seeded HF credentials:`,e)}t.delete(`hf_token`),t.delete(`hf_username`),t.delete(`hf_token_expires`);let o=t.toString(),s=window.location.pathname+window.location.search+(o?`#`+o:``);try{window.history.replaceState(null,``,s)}catch{}}function _(){if(typeof window>`u`)return null;if(window.location.hash){let e=window.location.hash.startsWith(`#`)?window.location.hash.slice(1):window.location.hash;try{let t=new URLSearchParams(e).get(`robot_peer_id`);if(t)return t}catch{}}if(window.location.search)try{let e=new URLSearchParams(window.location.search).get(`robot_peer_id`);if(e)return e}catch{}return null}function v(e){let t=e.split(`\r 3`),n=!1;for(let e of t)if(e.startsWith(`m=audio`)?n=!0:e.startsWith(`m=`)&&(n=!1),n&&e===`a=sendrecv`)return!0;return!1}var y=12*1024;function b(){return typeof CompressionStream<`u`}function x(){return`u`+Math.random().toString(36).slice(2,11)+Date.now().toString(36)}function S(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode.apply(null,Array.from(e.subarray(r,r+n)));return btoa(t)}async function C(e){let t=new TextEncoder().encode(e),n=await new Response(new Blob([t]).stream().pipeThrough(new CompressionStream(`gzip`))).arrayBuffer();return S(new Uint8Array(n))}function w(e){let t=Math.round(Number(e)||0);return Math.max(0,Math.min(100,t))}var T=3e3,E=1e3,D=6e4;window.ReachyMini=class extends EventTarget{_signalingUrl;_clientId;_appName;_videoJitterBufferTargetMs;_autoStartFromUrl;_autoStartAttempted;_state=`disconnected`;_robots=[];_robotState={};_preselectedRobotId;_token=null;_username=null;_tokenExpires=null;_sseAbortController=null;_pc=null;_dc=null;_sessionId=null;_selectedRobotId=null;_pendingRemoteIce=[];_micStream=null;_micMuted=!0;_audioMuted=!0;_micSupported=!1;_latencyMonitorId=null;_stateRefreshInterval=null;_versionResolve=null;_hardwareIdResolve=null;_volumeResolve=null;_micVolumeResolve=null;_applyAudioConfigResolve=null;_readAudioParameterResolve=null;_logSubscribers=new Set;_updateProgressSubscribers=new Set;_broadcastWaiters=[];_activeMoveUploadId=null;_activeAudioUploadId=null;_sessionResolve=null;_sessionReject=null;_iceConnected=!1;_dcOpen=!1;_iceGraceTimer=null;_iceGraceReason=null;_pendingVisibilityHandler=null;_onlineHandler=null;_offlineHandler=null;_connectionChangeHandler=null;_pendingMotionCompletions={wake_up:[],goto_sleep:[]};_videoElement=null;constructor(e={}){super(),this._signalingUrl=e.signalingUrl||`https://pollen-robotics-reachy-mini-central.hf.space`,this._clientId=e.clientId||null,this._appName=e.appName||`unknown`,this._videoJitterBufferTargetMs=e.videoJitterBufferTargetMs??0,this._autoStartFromUrl=e.autoStartFromUrl===!0,this._autoStartAttempted=!1,this._preselectedRobotId=_()}get state(){return this._state}get robots(){return this._robots}get robotState(){return this._robotState}get username(){return this._username}get isAuthenticated(){return!!this._token}get micSupported(){return this._micSupported}get micMuted(){return this._micMuted}get audioMuted(){return this._audioMuted}get preselectedRobotId(){return this._preselectedRobotId}get isEmbedded(){return this._preselectedRobotId!==null}_maybeAutoStart(){if(!this._autoStartFromUrl||this._autoStartAttempted||!this._preselectedRobotId||this._state!==`connected`||!this._robots.find(e=>e.id===this._preselectedRobotId))return;this._autoStartAttempted=!0;let e=this._preselectedRobotId;setTimeout(()=>{this._state===`connected`&&this.startSession(e).catch(e=>{console.warn(`[reachy-mini] autoStartFromUrl: startSession rejected:`,e)})},0)}async authenticate(){try{g();let e=await f();if(e)return this._username=e.userInfo.preferred_username||e.userInfo.name||null,this._token=e.accessToken,this._tokenExpires=e.accessTokenExpiresAt,sessionStorage.setItem(`hf_token`,this._token),sessionStorage.setItem(`hf_username`,this._username??``),sessionStorage.setItem(`hf_token_expires`,typeof this._tokenExpires==`string`?this._tokenExpires:this._tokenExpires.toISOString()),!0;let t=sessionStorage.getItem(`hf_token`),n=sessionStorage.getItem(`hf_username`),r=sessionStorage.getItem(`hf_token_expires`);return t&&n&&r&&new Date(r)>new Date?(this._token=t,this._username=n,this._tokenExpires=r,!0):!1}catch(e){return console.error(`Auth error:`,e),!1}}async login(){let e={};this._clientId&&(e.clientId=this._clientId),window.location.href=await p(e)}logout(){sessionStorage.removeItem(`hf_token`),sessionStorage.removeItem(`hf_username`),sessionStorage.removeItem(`hf_token_expires`),this._username=null,this._tokenExpires=null,this.disconnect()}async connect(e){if(this._state!==`disconnected`)throw Error(`Already connected`);
3if(e&&(this._token=e),!this._token)throw Error(`No token â call authenticate() first or pass a token`);this._sseAbortController=new AbortController;let t;try{t=await fetch(`${this._signalingUrl}/events`,{signal:this._sseAbortController.signal,headers:{Authorization:`Bearer ${this._token}`}})}catch(e){throw this._sseAbortController=null,e}if(!t.ok)throw this._sseAbortController=null,Error(`HTTP ${t.status}`);return new Promise((e,n)=>{let r=!1,i=t.body.getReader(),a=new TextDecoder,o=``;(async()=>{try{for(;;){let{done:t,value:n}=await i.read();if(t)break;o+=a.decode(n,{stream:!0});let s=o.split(` 4`);o=s.pop()??``;for(let t of s)if(t.startsWith(`data:`))try{let n=JSON.parse(t.slice(5).trim());!r&&n.type===`welcome`&&n.peerId&&(r=!0,this._state=`connected`,await this._sendToServer({type:`setPeerStatus`,roles:[`listener`],meta:{name:this._appName}}),this._emit(`connected`,{peerId:n.peerId}),e()),this._handleSignalingMessage(n)}catch{}}}catch(e){if(e.name!==`AbortError`&&this._emit(`error`,{source:`signaling`,error:e}),!r){n(e);return}}this._state!==`disconnected`&&(this._state=`disconnected`,this._emit(`disconnected`,{reason:`SSE closed`})),r||n(Error(`Connection closed before welcome`))})()})}async autoConnect(e={}){let{token:t,pickRobot:n,autoPickIfSingle:r=!0,filterBusy:i=!0,wakeOnConnect:a=!0}=e;if(this._state===`streaming`){let e=this._robots?.find(e=>e.id===this._selectedRobotId);return{robotId:this._selectedRobotId,robotName:e?.meta?.name??null,isEmbedded:this.isEmbedded,alreadyStreaming:!0}}let o=this._autoStartFromUrl;this._autoStartFromUrl=!1;try{if(t)this._token=t;else if(!this._token&&!await this.authenticate())throw Error(`Not authenticated â call login() or pass a token`);this._state===`disconnected`&&await this.connect();let e,o=null;if(this.isEmbedded){e=this._preselectedRobotId;try{await this._waitForRobotInList(e,5e3)}catch{}o=(this._robots?.find(t=>t.id===e))?.meta?.name??null}else{let t=await this._fetchOwnedRobots({filterBusy:i});if(t.length===0)throw Error(`No reachable robots`);if(r&&t.length===1&&!t[0].busy)e=t[0].id,o=t[0].name;else if(n){let r=await n(t);if(!r)throw Error(`Robot selection cancelled`);e=r,o=t.find(e=>e.id===r)?.name??null}else throw Error(`Multiple robots available â pass a pickRobot callback to autoConnect()`)}if(await this.startSession(e),a&&typeof this.ensureAwake==`function`)try{await this.ensureAwake()}catch(e){console.warn(`[reachy-mini] autoConnect: ensureAwake failed:`,e)}return{robotId:e,robotName:o,isEmbedded:this.isEmbedded}}finally{this._autoStartFromUrl=o}}async _fetchOwnedRobots({filterBusy:e=!0}={}){try{let t=await fetch(`${this._signalingUrl}/api/robot-status`,{headers:{Authorization:`Bearer ${this._token}`}});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json(),r=new Map;for(let t of n.robots||[]){if(e&&t.busy)continue;let n=t.meta?.install_id??t.meta?.hardware_id??t.peerId;r.set(n,{id:t.peerId,name:t.robotName??t.meta?.name??null,busy:!!t.busy,activeApp:t.activeApp??null,meta:t.meta??{},lastSeenAgeSeconds:t.last_seen_age_seconds??null})}return Array.from(r.values()).sort((e,t)=>(e.lastSeenAgeSeconds??1/0)-(t.lastSeenAgeSeconds??1/0))}catch(e){return console.warn(`[reachy-mini] /api/robot-status unavailable, using SSE list:`,e),(this._robots||[]).map(e=>({id:e.id,name:e.meta?.name??null,busy:!1,activeApp:null,meta:e.meta??{},lastSeenAgeSeconds:null}))}}_waitForRobotInList(e,t){return this._robots?.find(t=>t.id===e)?Promise.resolve():new Promise((n,r)=>{let i=()=>{this._robots?.find(t=>t.id===e)&&(this.removeEventListener(`robotsChanged`,i),clearTimeout(a),n())},a=setTimeout(()=>{this.removeEventListener(`robotsChanged`,i),r(Error(`Timeout waiting for robot ${e} in list`))},t);this.addEventListener(`robotsChanged`,i)})}async startSession(e){if(this._state!==`connected`)throw Error(`Not connected`);this._selectedRobotId=e,this._iceConnected=!1,this._dcOpen=!1,this._micSupported=!1,this._pendingRemoteIce=[];try{let e=window,t=e.AudioContext??e.webkitAudioContext;if(!t)throw Error(`AudioContext not supported`);let n=new t,r=n.createMediaStreamDestination(),i=n.createOscillator(),a=n.createGain();a.gain.value=0,i.connect(a).connect(r),i.start();let o=r.stream;
4o.getAudioTracks().forEach(e=>{e.enabled=!1}),this._micStream=o,this._micMuted=!0}catch(e){console.warn(`Audio sender placeholder setup failed:`,e),this._micStream=null}return this._pc=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]}),this._installNetworkListeners(),new Promise((t,n)=>{this._sessionResolve=t,this._sessionReject=n,this._pc.ontrack=e=>{if(e.track.kind===`video`){let t=this._videoJitterBufferTargetMs;try{e.receiver.jitterBufferTarget=t}catch{}try{e.receiver.playoutDelayHint=t/1e3}catch{}this._emit(`videoTrack`,{track:e.track,stream:e.streams[0]})}},this._pc.onicecandidate=async e=>{e.candidate&&this._sessionId&&await this._sendToServer({type:`peer`,sessionId:this._sessionId,ice:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}})},this._pc.oniceconnectionstatechange=()=>{let e=this._pc?.iceConnectionState;if(e){if(this._emit(`iceStateChange`,{state:e}),e===`connected`||e===`completed`){this._clearIceGrace(),this._iceConnected=!0,this._checkSessionReady();return}if(e===`disconnected`){typeof document<`u`&&document.hidden?this._armIceGraceOnVisibility():this._scheduleIceGrace(T,`disconnected`);return}if(e===`failed`){this._scheduleIceGrace(E,`failed`);return}}},this._pc.ondatachannel=e=>{this._dc=e.channel,this._dc.onopen=()=>{this._dcOpen=!0,this._checkSessionReady()},this._dc.onmessage=e=>this._handleRobotMessage(JSON.parse(e.data))},this._sendToServer({type:`startSession`,peerId:e}).then(e=>{if(e?.type===`sessionRejected`){this._failSessionRejected(e);return}e?.sessionId&&(this._sessionId=e.sessionId)})})}_failSessionRejected(e){let t=Error(e.reason===`robot_busy`?`Robot is busy: "${e.activeApp||`another app`}" is already connected`:`Session rejected: ${e.reason||`unknown reason`}`);if(t.reason=e.reason??null,t.activeApp=e.activeApp??null,this._clearIceGrace(),this._uninstallNetworkListeners(),this._pc&&=(this._pc.close(),null),this._micStream&&=(this._micStream.getTracks().forEach(e=>e.stop()),null),this._iceConnected=!1,this._dcOpen=!1,this._micMuted=!0,this._micSupported=!1,this._emit(`sessionRejected`,{reason:e.reason,activeApp:e.activeApp}),this._sessionReject){let e=this._sessionReject;this._sessionResolve=null,this._sessionReject=null,e(t)}}async stopSession(){this._versionResolve&&=(this._versionResolve(null),null),this._hardwareIdResolve&&=(this._hardwareIdResolve(null),null),this._volumeResolve&&=(this._volumeResolve(null),null),this._micVolumeResolve&&=(this._micVolumeResolve(null),null),this._applyAudioConfigResolve&&=(this._applyAudioConfigResolve(!1),null),this._readAudioParameterResolve&&=(this._readAudioParameterResolve(null),null),this._logSubscribers.clear(),this._updateProgressSubscribers.clear(),this._rejectPendingMotionCompletions(Error(`Session stopped`)),this._clearIceGrace(),this._uninstallNetworkListeners(),this._sessionReject&&=(this._sessionReject(Error(`Session stopped`)),this._sessionResolve=null,null),this._stateRefreshInterval&&=(clearInterval(this._stateRefreshInterval),null),this._latencyMonitorId&&=(clearInterval(this._latencyMonitorId),null),this._sessionId&&await this._sendToServer({type:`endSession`,sessionId:this._sessionId}),this._micStream&&=(this._micStream.getTracks().forEach(e=>e.stop()),null),this._micMuted=!0,this._micSupported=!1,this._pc&&=(this._pc.close(),null),this._dc&&=(this._dc.close(),null),this._sessionId=null,this._iceConnected=!1,this._dcOpen=!1,this._state===`streaming`&&(this._state=`connected`,this._emit(`sessionStopped`,{reason:`user`}))}disconnect(){this._sseAbortController&&=(this._sseAbortController.abort(),null),this._versionResolve&&=(this._versionResolve(null),null),this._hardwareIdResolve&&=(this._hardwareIdResolve(null),null),this._volumeResolve&&=(this._volumeResolve(null),null),this._micVolumeResolve&&=(this._micVolumeResolve(null),null),this._applyAudioConfigResolve&&=(this._applyAudioConfigResolve(!1),null),this._readAudioParameterResolve&&=(this._readAudioParameterResolve(null),null),this._logSubscribers.clear(),this._updateProgressSubscribers.clear(),this._rejectPendingMotionCompletions(Error(`Disconnected`)),this._clearIceGrace(),this._uninstallNetworkListeners(),this._sessionReject&&=(this._sessionReject(Error(`Disconnected`)),this._sessionResolve=null,null),this._stateRefresh
4Interval&&=(clearInterval(this._stateRefreshInterval),null),this._latencyMonitorId&&=(clearInterval(this._latencyMonitorId),null),this._sessionId&&this._token&&this._sendToServer({type:`endSession`,sessionId:this._sessionId}),this._micStream&&=(this._micStream.getTracks().forEach(e=>e.stop()),null),this._pc&&=(this._pc.close(),null),this._dc&&=(this._dc.close(),null),this._sessionId=null,this._micMuted=!0,this._micSupported=!1,this._iceConnected=!1,this._dcOpen=!1,this._robots=[],this._state=`disconnected`,this._emit(`disconnected`,{reason:`user`})}_clearIceGrace(){this._iceGraceTimer!==null&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null),this._iceGraceReason=null,this._pendingVisibilityHandler&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,this._pendingVisibilityHandler),this._pendingVisibilityHandler=null}_scheduleIceGrace(e,t){if(this._iceGraceTimer!==null){if(this._iceGraceReason===t)return;clearTimeout(this._iceGraceTimer)}this._iceGraceReason=t,this._iceGraceTimer=setTimeout(()=>{this._iceGraceTimer=null;let t=this._iceGraceReason;this._iceGraceReason=null;let n=this._pc?.iceConnectionState;if(!(n===`connected`||n===`completed`)){if(t===`disconnected`&&n===`disconnected`){this._emit(`error`,{source:`webrtc`,error:Error(`ICE stuck in 'disconnected' for > ${e}ms`)});return}if(t===`failed`||n===`failed`){let e=Error(`ICE connection failed`);this._sessionReject&&=(this._sessionReject(e),this._sessionResolve=null,null),this._emit(`error`,{source:`webrtc`,error:e})}}},e)}_armIceGraceOnVisibility(){if(this._pendingVisibilityHandler)return;let e=Date.now(),t=()=>{if(typeof document<`u`&&document.hidden||(document.removeEventListener(`visibilitychange`,t),this._pendingVisibilityHandler=null,!this._pc))return;let n=this._pc.iceConnectionState;if(!(n===`connected`||n===`completed`)){if(Date.now()-e>D){let e=Error(`Session expired while tab was backgrounded`);this._sessionReject&&=(this._sessionReject(e),this._sessionResolve=null,null),this._emit(`error`,{source:`webrtc`,error:e});return}if(n===`failed`){this._scheduleIceGrace(E,`failed`);return}this._scheduleIceGrace(T,`disconnected`)}};document.addEventListener(`visibilitychange`,t),this._pendingVisibilityHandler=t}_installNetworkListeners(){if(this._onlineHandler||typeof window>`u`)return;let e=()=>this._emit(`networkOnline`,{}),t=()=>this._emit(`networkOffline`,{});window.addEventListener(`online`,e),window.addEventListener(`offline`,t),this._onlineHandler=e,this._offlineHandler=t;let n=navigator.connection;if(n&&typeof n.addEventListener==`function`){let e=()=>this._emit(`networkChange`,{effectiveType:n.effectiveType,downlink:n.downlink,rtt:n.rtt,saveData:n.saveData});n.addEventListener(`change`,e),this._connectionChangeHandler=e}}_uninstallNetworkListeners(){typeof window<`u`&&(this._onlineHandler&&window.removeEventListener(`online`,this._onlineHandler),this._offlineHandler&&window.removeEventListener(`offline`,this._offlineHandler));let e=navigator.connection;e&&this._connectionChangeHandler&&typeof e.removeEventListener==`function`&&e.removeEventListener(`change`,this._connectionChangeHandler),this._onlineHandler=null,this._offlineHandler=null,this._connectionChangeHandler=null}setTarget({head:e,antennas:t,body_yaw:n}={}){let r={type:`set_full_target`};if(e!==void 0){if(!Array.isArray(e)||e.length!==16||!e.every(e=>Number.isFinite(e)))throw TypeError(`setTarget: head must be a 16-element flat row-major 4Ã4 matrix of finite numbers; got ${Array.isArray(e)?`Array(${e.length})`:typeof e}`);r.head=e}if(t!==void 0){if(!Array.isArray(t)||t.length!==2||!t.every(e=>Number.isFinite(e)))throw TypeError(`setTarget: antennas must be [rightRad, leftRad] (2 finite numbers); got ${Array.isArray(t)?`Array(${t.length})`:typeof t}`);r.antennas=t}if(n!==void 0){if(!Number.isFinite(n))throw TypeError(`setTarget: body_yaw must be a finite number (radians); got ${n}`);r.body_yaw=n}return this._sendCommand(r)}gotoTarget({head:e,antennas:t,body_yaw:n,duration:r}){let i={type:`goto_target`};if(e!==void 0){if(!Array.isArray(e)||e.length!==16||!e.every(e=>Number.isFinite(e)))throw TypeError(`gotoTarget: head must be a 16-element flat row-major 4Ã4 matrix of finite numbers; got ${Array.isArray(e)?`Array(${e.length})`:typeof e}`);i.head=e}if(t!==void 0){if(!Array.isArray(t)||t.length!==2||!t.every(e=>Number.isFinite(e)))throw TypeError(`gotoTarget: antennas must be [rightRad, leftRad] (2 finite numbers); got ${Array.isArray(t)?`Array(${t.length})`:typeof t}`);i.antennas=t}if(n!==void 0){if(!Number.isFinite(n))throw TypeError(`gotoTarget: body_yaw must be a finite number (radians); got ${n}`);i.body_yaw=n}if(!Number.isFinite(r)||r<=0)throw TypeError(`gotoTarget: duration must be a positive finite number (seconds); got ${r}`);return i.duration=r,this._sendCommand(i)}setHeadRpyDeg(e,t,n){return this.setTarget({head:h(e,t,n).flat()})}setAntennasDeg(e,t){return this.setTarget({antennas:[m(e),m(t)]})}setBodyYawDeg(e){return this.setTarget({body_yaw:m(e)})}playSound(e){return this._sendCommand({type:`play_sound`,file:e})}clearIncomingAudio(){return this._sendCommand({type:`clear_incoming_audio`})}startDaemonUpdate({preRelease:e=!1,onProgress:t}={}){return t&&this._updateProgressSubscribers.add(t),this._sendCommand({type:`start_update`,pre_release:e})}setMotorMode(e){return this._sendCommand({type:`set_motor_mode`,mode:e})}setMotorTorque(e,t=null){return this._sendCommand({type:`set_torque`,on:e,ids:t})}wakeUp({timeoutMs:e=8e3}={}){return this._sendCommand({type:`set_motor_mode`,mode:`enabled`}),this._sendCommandAwaitCompletion(`wake_up`,e)}gotoSleep({timeoutMs:e=8e3}={}){return this._sendCommandAwaitCompletion(`goto_sleep`,e)}_sendCommandAwaitCompletion(e,t){return this._sendCommand({type:e})?new Promise((n,r)=>{let i={resolve:n,reject:r,timer:setTimeout(()=>
4{let n=this._pendingMotionCompletions[e],a=n.indexOf(i);a!==-1&&n.splice(a,1),r(Error(`${e} timed out after ${t}ms`))},t)};this._pendingMotionCompletions[e].push(i)}):Promise.reject(Error(`${e}: data channel not open`))}_rejectPendingMotionCompletions(e){for(let t of Object.keys(this._pendingMotionCompletions)){let n=this._pendingMotionCompletions[t];for(;n.length;){let t=n.shift();clearTimeout(t.timer),t.reject(e)}}}isAwake(){let e=this._robotState?.motor_mode;return e===`enabled`||e===`gravity_compensation`}async ensureAwake(e=1e3){return this._robotState?.motor_mode===void 0&&await new Promise(t=>{let n=()=>{this.removeEventListener(`state`,n),clearTimeout(r),t()},r=setTimeout(n,e);this.addEventListener(`state`,n),this.requestState()}),this.isAwake()||this.wakeUp().catch(()=>{}),!0}getVersion(){return new Promise((e,t)=>{if(!this._dc||this._dc.readyState!==`open`){t(Error(`Data channel not open`));return}this._versionResolve&&this._versionResolve(null),this._versionResolve=e,this._sendCommand({type:`get_version`})})}getHardwareId(){return new Promise((e,t)=>{if(!this._dc||this._dc.readyState!==`open`){t(Error(`Data channel not open`));return}this._hardwareIdResolve&&this._hardwareIdResolve(null),this._hardwareIdResolve=e,this._sendCommand({type:`get_hardware_id`})})}getVolume(){return this._slotRoundtrip(()=>this._volumeResolve,e=>{this._volumeResolve=e},{type:`get_volume`})}setVolume(e){return this._slotRoundtrip(()=>this._volumeResolve,e=>{this._volumeResolve=e},{type:`set_volume`,volume:w(e)})}getMicrophoneVolume(){return this._slotRoundtrip(()=>this._micVolumeResolve,e=>{this._micVolumeResolve=e},{type:`get_microphone_volume`})}setMicrophoneVolume(e){return this._slotRoundtrip(()=>this._micVolumeResolve,e=>{this._micVolumeResolve=e},{type:`set_microphone_volume`,volume:w(e)})}applyAudioConfig(e,{verify:t=!0}={}){return this._slotRoundtrip(()=>this._applyAudioConfigResolve,e=>{this._applyAudioConfigResolve=e},{type:`apply_audio_config`,config:e,verify:t}).then(e=>e===!0)}readAudioParameter(e){return this._slotRoundtrip(()=>this._readAudioParameterResolve,e=>{this._readAudioParameterResolve=e},{type:`read_audio_parameter`,name:e})}_slotRoundtrip(e,t,n){return new Promise((r,i)=>{if(!this._dc||this._dc.readyState!==`open`){i(Error(`Data channel not open`));return}let a=e();a&&a(null),t(r),this._sendCommand(n)})}sendRaw(e){return this._sendCommand(e)}subscribeLogs({onLine:e,onError:t}){if(typeof e!=`function`)throw TypeError(`subscribeLogs: onLine callback is required`);let n={onLine:e,onError:t},r=this._logSubscribers.size===0;this._logSubscribers.add(n),r&&this._sendCommand({type:`subscribe_logs`});let i=!1;return()=>{i||(i=!0,this._logSubscribers.delete(n),this._logSubscribers.size===0&&this._sendCommand({type:`unsubscribe_logs`}))}}requestState(){return this._sendCommand({type:`get_state`})}setAudioMuted(e){this._audioMuted=e,this._videoElement&&(this._videoElement.muted=e)}setMicMuted(e){this._micMuted=e,this._micStream&&this._micStream.getAudioTracks().forEach(t=>{t.enabled=!e})}attachVideo(e){this._videoElement=e,e.muted=this._audioMuted;let t=t=>{e.srcObject=t.detail.stream,e.playsInline=!0,`requestVideoFrameCallback`in e&&this._startLatencyMonitor(e)},n=()=>{e.srcObject=null};return this.addEventListener(`videoTrack`,t),this.addEventListener(`sessionStopped`,n),()=>{this.removeEventListener(`videoTrack`,t),this.removeEventListener(`sessionStopped`,n),this._latencyMonitorId&&=(clearInterval(this._latencyMonitorId),null),e.srcObject=null,this._videoElement=null}}async playMove(e,{audioBlob:t=null,audioLeadMs:n=-100,description:r=`move`,encoding:i=`gzip+base64`,playFrequency:a=100,initialGotoDuration:o=0,startTimeoutMs:s=8e3,onProgress:c=()=>{},onStarted:l=()=>{}}={}){if(!this._dc||this._dc.readyState!==`open`)throw Error(`data channel not open`);if(!e?.time?.length||!e?.set_target_data?.length)throw Error(`playMove: motion must have time + set_target_data`);let u=x();this._activeMoveUploadId=u;let d={description:r,time:e.time,set_target_data:e.set_target_data},f=JSON.stringify(d),p,m;i===`gzip+base64`&&b()?(p=await C(f),m=`gzip+base64`):(p=f,m=`json`);
4let h=Math.ceil(p.length/12288)||1;c({phase:`starting`,sent:0,total:h,bytes:p.length,encoding:m}),this._sendCommand({type:`upload_move_start`,upload_id:u,total_chunks:h,description:r,encoding:m});for(let e=0;e<h;e++){this._dc.bufferedAmount>1048576&&await this._awaitDataChannelDrain();let t=e*y;this._sendCommand({type:`upload_move_chunk`,upload_id:u,chunk_index:e,chunk:p.slice(t,t+y)}),c({phase:`upload`,sent:e+1,total:h})}if(this._sendCommand({type:`upload_move_finish`,upload_id:u}),c({phase:`uploaded`,sent:h,total:h}),t){let e=S(new Uint8Array(await t.arrayBuffer())),n=Math.ceil(e.length/12288)||1;c({phase:`audio-starting`,sent:0,total:n,bytes:e.length}),this._sendCommand({type:`upload_audio_start`,upload_id:u,total_chunks:n,encoding:`wav-base64`,description:r});for(let t=0;t<n;t++){this._dc.bufferedAmount>1048576&&await this._awaitDataChannelDrain();let r=t*y;this._sendCommand({type:`upload_audio_chunk`,upload_id:u,chunk_index:t,chunk:e.slice(r,r+y)}),c({phase:`audio-upload`,sent:t+1,total:n})}this._sendCommand({type:`upload_audio_finish`,upload_id:u}),c({phase:`audio-uploaded`,sent:n,total:n})}this._sendCommand({type:`play_uploaded_move`,upload_id:u,play_frequency:a,initial_goto_duration:o,audio_lead_ms:n});let g;try{g=await this._waitForBroadcast(e=>e?.type===`play_uploaded_move`&&e?.upload_id===u&&(e.started===!0||typeof e.error==`string`),{timeoutMs:s,debugLabel:`play_uploaded_move started`})}catch(e){throw Error(`Daemon did not respond to play_uploaded_move (requires the reachy_mini daemon with feature/daemon-side-move-upload). Underlying: ${e.message}`)}if(typeof g.error==`string`)throw Error(`play_uploaded_move: ${g.error}`);try{l({duration_s:g.duration_s,has_audio:g.has_audio===!0})}catch(e){console.warn(`playMove.onStarted threw:`,e)}c({phase:`playing`,duration_s:g.duration_s});let _=await this._waitForBroadcast(e=>e?.type===`play_uploaded_move`&&e?.upload_id===u&&(e.finished===!0||e.cancelled===!0||typeof e.error==`string`),{timeoutMs:(g.duration_s+30)*1e3,debugLabel:`play_uploaded_move final`});return this._activeMoveUploadId===u&&(this._activeMoveUploadId=null),_}cancelMove(e=null){let t=e??this._activeMoveUploadId;return t?this._sendCommand({type:`cancel_move`,upload_id:t}):!1}async uploadAudio(e,{description:t=`audio`,onProgress:n=()=>{}}={}){if(!this._dc||this._dc.readyState!==`open`)throw Error(`data channel not open`);if(!(e instanceof Blob))throw TypeError(`uploadAudio: expected a Blob`);let r=x(),i=S(new Uint8Array(await e.arrayBuffer())),a=Math.ceil(i.length/12288)||1;n({phase:`audio-starting`,sent:0,total:a,bytes:i.length}),this._sendCommand({type:`upload_audio_start`,upload_id:r,total_chunks:a,encoding:`wav-base64`,description:t});for(let e=0;e<a;e++){this._dc.bufferedAmount>1048576&&await this._awaitDataChannelDrain();let t=e*y;this._sendCommand({type:`upload_audio_chunk`,upload_id:r,chunk_index:e,chunk:i.slice(t,t+y)}),n({phase:`audio-upload`,sent:e+1,total:a})}return this._sendCommand({type:`upload_audio_finish`,upload_id:r}),n({phase:`audio-uploaded`,sent:a,total:a}),r}async playUploadedAudio(e,{timeoutMs:t=8e3}={}){if(!this._dc||this._dc.readyState!==`open`)throw Error(`data channel not open`);let n=this._waitForBroadcast(t=>t?.type===`play_uploaded_audio`&&t?.upload_id===e&&(t.started===!0||typeof t.error==`string`),{timeoutMs:t,debugLabel:`play_uploaded_audio started`});this._sendCommand({type:`play_uploaded_audio`,upload_id:e});let r=await n;if(typeof r.error==`string`)throw Error(r.error);return this._activeAudioUploadId=e,r}cancelAudio(e=null){let t=e??this._activeAudioUploadId;return t?(this._activeAudioUploadId===t&&(this._activeAudioUploadId=null),this._sendCommand({type:`cancel_audio`,upload_id:t})):!1}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}_waitForBroadcast(e,{timeoutMs:t=5e3,debugLabel:n=``}={}){return new Promise((r,i)=>{let a={predicate:e,resolve:r,timer:setTimeout(()=>{let e=this._broadcastWaiters.indexOf(a);e!==-1&&this._broadcastWaiters.splice(e,1),i(Error(`broadcast timeout (${t} ms): ${n}`))},t)};this._broadcastWaiters.push(a)})}async _awaitDataChannelDrain(){for(;this._dc&&this._dc.bufferedAmount>524288;)if(await new Promise(e=>
4setTimeout(e,30)),!this._dc||this._dc.readyState!==`open`)throw Error(`data channel closed mid-upload`)}async _sendToServer(e){if(!this._token)throw Error(`No token â authenticate() first`);try{let t=await fetch(`${this._signalingUrl}/send`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this._token}`},body:JSON.stringify(e)});if(!t.ok){let n=``;try{n=await t.text()}catch{}return console.warn(`[reachy-mini] /send rejected (${t.status}) for type=${e?.type}; body=${n||`<empty>`}`),null}return await t.json()}catch(e){return console.error(`Send error:`,e),null}}_sendCommand(e){return!this._dc||this._dc.readyState!==`open`?!1:(this._dc.send(JSON.stringify(e)),!0)}_checkSessionReady(){this._iceConnected&&this._dcOpen&&this._sessionResolve&&(this._state=`streaming`,this.requestState(),this._stateRefreshInterval=setInterval(()=>this.requestState(),500),this._emit(`streaming`,{sessionId:this._sessionId,robotId:this._selectedRobotId}),this._sessionResolve(),this._sessionResolve=null,this._sessionReject=null)}async _handleSignalingMessage(e){switch(e.type){case`welcome`:break;case`list`:this._robots=e.producers||[],this._emit(`robotsChanged`,{robots:this._robots}),this._maybeAutoStart();break;case`peerStatusChanged`:{let e=await this._sendToServer({type:`list`});e?.producers&&(this._robots=e.producers,this._emit(`robotsChanged`,{robots:this._robots}),this._maybeAutoStart());break}case`sessionStarted`:this._sessionId=e.sessionId??null;break;case`sessionRejected`:this._failSessionRejected(e);break;case`endSession`:this._handleEndSession(e);break;case`peer`:this._handlePeerMessage(e);break}}_handleEndSession(e){let t=e.reason,n=t===`robot_busy_local_app`?`Robot is busy: a local Python app is running`:t===`local_app_started`?`Disconnected: a local Python app started on the robot`:t===`robot_busy_local`?`Robot is busy: another session is already active`:null;if(this._sessionReject){let e=Error(n||`Session ended before it could start: ${t||`unknown reason`}`);e.reason=t??null,this._emit(`sessionRejected`,{reason:t,activeApp:null}),this._clearIceGrace(),this._uninstallNetworkListeners(),this._pc&&=(this._pc.close(),null),this._micStream&&=(this._micStream.getTracks().forEach(e=>e.stop()),null),this._iceConnected=!1,this._dcOpen=!1,this._micMuted=!0,this._micSupported=!1;let r=this._sessionReject;this._sessionResolve=null,this._sessionReject=null,r(e);return}this._state===`streaming`&&(this._emit(`sessionStopped`,{reason:t||`remote_end`,message:n}),this.stopSession().catch(()=>{}))}async _handlePeerMessage(e){if(this._pc)try{if(e.sdp){let t=e.sdp;if(t.type===`offer`){let e=v(t.sdp);if(this._micSupported=e,this._emit(`micSupported`,{supported:e}),e&&this._micStream)for(let e of this._micStream.getAudioTracks())this._pc.addTrack(e,this._micStream);await this._pc.setRemoteDescription(new RTCSessionDescription(t));let n=await this._pc.createAnswer();await this._pc.setLocalDescription(n),await this._sendToServer({type:`peer`,sessionId:this._sessionId,sdp:{type:`answer`,sdp:n.sdp}})}else await this._pc.setRemoteDescription(new RTCSessionDescription(t));let n=this._pendingRemoteIce;if(n&&n.length){this._pendingRemoteIce=[];for(let e of n)try{await this._pc.addIceCandidate(new RTCIceCandidate(e))}catch(e){console.warn(`[reachy-mini] buffered ICE candidate rejected:`,e)}}}if(e.ice){if(!e.ice.candidate)return;this._pc.remoteDescription?await this._pc.addIceCandidate(new RTCIceCandidate(e.ice)):(this._pendingRemoteIce||=[],this._pendingRemoteIce.push(e.ice))}}catch(e){console.error(`WebRTC error:`,e),this._emit(`error`,{source:`webrtc`,error:e})}}_handleRobotMessage(e){if(`version`in e&&this._versionResolve){this._versionResolve(e.version),this._versionResolve=null;return}if(`hardware_id`in e&&this._hardwareIdResolve){this._hardwareIdResolve(e.hardware_id),this._hardwareIdResolve=null;return}if(e.command===`get_volume`||e.command===`set_volume`){this._volumeResolve&&=(this._volumeResolve(e.status===`error`?null:e.volume),null);return}if(e.command===`get_microphone_volume`||e.command===`set_microphone_volume`){this._micVolumeResolve&&=(this._micVolumeResolve(e.status===`error`?null:e.volume),null);return}if(e.command===`apply_audio_config`){this._applyAudioConfigResolve&&=(this._applyAudioConfigResolve(e.error?!1:!!e.applied),null);return}if(e.command===`read_audio_parameter`){this._readAudioParameterResolve&&=(this._readAudioParameterResolve(e.error?null:e.values??null),null);return}if((e.command===`wake_up`||e.command===`goto_sleep`)&&this._pendingMotionCompletions&&this._pendingMotionCompletions[e.command]){let t=this._pe
4ndingMotionCompletions[e.command];if(e.completed===!0&&t.length>0){let e=t.shift();clearTimeout(e.timer),e.resolve();return}if(e.error&&t.length>0){let n=t.shift();clearTimeout(n.timer),n.reject(Error(`${e.command}: ${e.error}`));return}}if(e.type===`log_line`){for(let t of this._logSubscribers)try{t.onLine({timestamp:e.timestamp,line:e.line})}catch(e){console.error(`subscribeLogs onLine threw:`,e)}return}if(e.type===`log_stream_error`){for(let t of this._logSubscribers)if(typeof t.onError==`function`)try{t.onError(e.error)}catch(e){console.error(`subscribeLogs onError threw:`,e)}return}if(e.command===`start_update`){if(typeof e.error==`string`){let t={status:`failed`,error:e.error};for(let e of this._updateProgressSubscribers)try{e(t)}catch(e){console.error(`startDaemonUpdate onProgress threw:`,e)}}return}if(e.type===`update_progress`){let t={status:e.status,line:typeof e.line==`string`?e.line:void 0,error:typeof e.error==`string`?e.error:void 0};for(let e of this._updateProgressSubscribers)try{e(t)}catch(e){console.error(`startDaemonUpdate onProgress threw:`,e)}return}if(e.state){let t=e.state;t.head_pose&&(this._robotState.head=t.head_pose.flat()),t.antennas&&(this._robotState.antennas=[t.antennas[0],t.antennas[1]]),typeof t.body_yaw==`number`&&(this._robotState.body_yaw=t.body_yaw),t.motor_mode&&(this._robotState.motor_mode=t.motor_mode),typeof t.is_move_running==`boolean`&&(this._robotState.is_move_running=t.is_move_running),this._emit(`state`,{...this._robotState})}if(e.error&&this._emit(`error`,{source:`robot`,error:e.error}),this._broadcastWaiters.length>0)for(let t=this._broadcastWaiters.length-1;t>=0;t--){let n=this._broadcastWaiters[t];if(n.predicate(e)){this._broadcastWaiters.splice(t,1),clearTimeout(n.timer),n.resolve(e);return}}}_startLatencyMonitor(e){this._latencyMonitorId&&clearInterval(this._latencyMonitorId),this._latencyMonitorId=setInterval(()=>{if(!e.srcObject||e.paused)return;let t=e.buffered;if(t.length>0){let n=t.end(t.length-1),r=n-e.currentTime;r>.5&&(console.log(`Latency correction: was ${r.toFixed(2)}s behind`),e.currentTime=n-.1)}},2e3)}},window.dispatchEvent(new Event(`reachymini:ready`));function O(e){let t=e?.trim();if(t)try{return new URL(t).hostname||void 0}catch{return t.replace(/^https?:\/\//i,``).split(`/`)[0]||void 0}}function k(e){let[t,n]=e?.trim().split(`/`)??[];if(!(!t||!n))return`${t}-${n}`.toLowerCase()+`.hf.space`}function A(){let e=window.huggingface?.variables;return O(e?.SPACE_HOST)||O(`agenticbeingsinc-reachy-aivah.hf.space`)||k(e?.SPACE_ID)||k(`AgenticBeingsInc/reachy-aivah`)}function j(e){return e.endsWith(`.hf.space`)||e.endsWith(`.static.hf.space`)}function M(){let e=A();if(!e||window.location.hostname===e||j(window.location.hostname))return!1;let t=new URLSearchParams(window.location.search),n=new URL(window.location.href);return n.protocol=`https:`,n.hostname=e,!t.has(`code`)&&!t.has(`error`)&&(n.pathname=n.pathname.replace(/\/index\.html$/i,`/`)||`/`),window.location.replace(n.href),!0}var N=new URLSearchParams(window.location.search),P=N.get(`embedded`)===`1`||N.get(`embed`)===`1`,F=N.get(`demo`)===`1`||N.get(`local`)===`1`;!P&&!F&&M()||(P||F?o(()=>import(`./embed-CarFBAKX.js`),__vite__mapDeps([0,1,2])):o(async()=>{let{mountHost:e}=await import(`./auto-DKQ5exK4.js`);return{mountHost:e}},__vite__mapDeps([3,1])).then(({mountHost:e})=>{e({appName:`Reachy Aivah`,appIconUrl:`/icon.svg`,appEmoji:`ð¤`,enableMicrophone:!0,devToken:void 0,clientId:void 0})}));export{h as t};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.