@urun-sh/react 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client"
2
- "use strict";var gr=Object.defineProperty;var Mo=Object.getOwnPropertyDescriptor;var _o=Object.getOwnPropertyNames;var No=Object.prototype.hasOwnProperty;var Io=(e,t)=>{for(var r in t)gr(e,r,{get:t[r],enumerable:!0})},Oo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _o(t))!No.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=Mo(t,n))||o.enumerable});return e};var Lo=e=>Oo(gr({},"__esModule",{value:!0}),e);var hs={};Io(hs,{Audio:()=>Nt,Camera:()=>Vr,ComponentRenderer:()=>An,CreditsClient:()=>Ge.CreditsClient,CreditsError:()=>Ge.CreditsError,CreditsUnauthorizedError:()=>Ge.CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS:()=>Dr,DEFAULT_LOG_CAP:()=>Be,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Ar,DEFAULT_SMOOTH_THRESHOLD:()=>Mr,DEFAULT_VOICE_CONSTRAINTS:()=>Ir,DocPatchForm:()=>Lt,Image:()=>Gn,ImageFrame:()=>Vn,ImageFrameSchema:()=>Dn,MetricsPanel:()=>Hn,MetricsPanelSchema:()=>Fn,Mic:()=>to,OPERATOR_CHORD_LABEL:()=>Zr,OPERATOR_TOKEN_STORAGE_KEY:()=>Jr,ProgressCard:()=>_n,ProgressCardSchema:()=>Mn,ReprojectedVideo:()=>xn,Session:()=>hn,StatusBadge:()=>In,StatusBadgeSchema:()=>Nn,Text:()=>jn,TextStream:()=>Ln,TextStreamError:()=>ct,TextStreamSchema:()=>On,UrunActivationOverlay:()=>ur,UrunAudio:()=>Yn,UrunAuthProvider:()=>Ct,UrunCamera:()=>ro,UrunControlSender:()=>fo,UrunCreditsGate:()=>Ro,UrunDocPanel:()=>po,UrunErrorBoundary:()=>nt,UrunEventSpine:()=>go,UrunIdleWarning:()=>Po,UrunJwtProvider:()=>Gr,UrunProvider:()=>nn,UrunSessionClock:()=>ko,UrunSessionEnded:()=>Co,UrunSessionGate:()=>yo,UrunSessionPaused:()=>Hr,UrunSessionStatus:()=>vo,UrunSessionWaking:()=>sr,UrunStreamTail:()=>lo,UrunVoice:()=>Qn,Video:()=>Je,Voice:()=>It,authMode:()=>Tt,createCreditsClient:()=>Ge.createCreditsClient,createDocStore:()=>zt,describeSessionPhase:()=>fr.describeSessionPhase,formatPayload:()=>ft,getUrunAudioContext:()=>Pt,isWakingPhase:()=>fr.isWakingPhase,parseJsonObject:()=>Zt,pushCapped:()=>Ve,readOperatorToken:()=>Sr,registerComponent:()=>wn,resumeUrunAudioContext:()=>ze,textDelta:()=>Ur,urunPublicEnv:()=>Re,useActivation:()=>ir,useApp:()=>an,useChat:()=>gn,useCompletion:()=>pn,useConfirmOnLeave:()=>Ht,useCredits:()=>dr,useDocStore:()=>mt,useGenerationTick:()=>co,useImageFrame:()=>Er,useInputPresence:()=>Sn,useMetricsPanel:()=>wr,useOperatorOverride:()=>Ft,useProgressCard:()=>Pr,useReferenceImage:()=>no,useRequest:()=>ln,useSession:()=>vn,useSessionDirectory:()=>cn,useSessionDoc:()=>uo,useSessionEndsAt:()=>Fr,useSessionIdle:()=>Wr,useSessionPhase:()=>be,useSessionStats:()=>wo,useSessionTrack:()=>oo,useSessionWake:()=>or,useStatusBadge:()=>Rr,useStreamMessages:()=>er,useText:()=>_r,useTextMeter:()=>Bn,useTextStream:()=>xr,useUrunAudioLevel:()=>Gt,useUrunAuth:()=>Dt,useUrunPrewake:()=>Eo,usesWorkOSAuth:()=>Kr});module.exports=Lo(hs);var ue=require("react");var Br=require("react"),bt=require("react/jsx-runtime"),nt=class extends Br.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,bt.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,bt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,bt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var jr=require("react"),qe=(0,jr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Re(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ne(typeof process<"u"?process.env?.[e]:void 0)}}function Tt(){let e=Re("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Re("VERCEL_ENV")==="production"?"workos":Re("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Kr(){return Tt()==="workos"}var ot=require("react"),Xr=require("react/jsx-runtime"),$r=(0,ot.createContext)(null);function Ct({getAccessToken:e,children:t}){let r=(0,ot.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Xr.jsx)($r.Provider,{value:r,children:t})}var Gr=Ct;function Dt(){return(0,ot.useContext)($r)}var Vt=require("react"),Jr="urun.operator_token",Yr=null,zr="op",Zr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Qr(){return typeof window<"u"}function Sr(){return Yr}function Do(){if(!Qr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(zr);if(!r)return null;Yr=r,t.delete(zr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Vo(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Ft(e){let t=(0,Vt.useRef)(e);t.current=e,(0,Vt.useEffect)(()=>{if(!Qr())return;Do();let r=o=>{if(!Vo(o))return;let n=Sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var en=require("react");function Ht(e=!0){(0,en.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var Ie=require("react/jsx-runtime"),Fo="/api/urun-token",Ho=1e4;function qo(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function tn(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function rn(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function hr(e){let t=e===void 0?void 0:JSON.stringify(e);return(0,ue.useMemo)(()=>e,[t])}function Wo(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Ie.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Ie.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Ie.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function nn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:v,sessionStats:E,confirmOnLeave:k=!1,fallback:d,errorFallback:R,children:S}){let h=n===void 0&&t===void 0;if(!h&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!h&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let y=r??o;if(h&&(typeof y!="string"||y.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Ht(k);let[p,P]=(0,ue.useState)(),[C,U]=(0,ue.useState)(null),A=(0,ue.useRef)(void 0),m=(0,ue.useRef)(null),[x,b]=(0,ue.useState)(null);Ft(M=>b({jwt:M}));let N=Dt(),$=Re("NEXT_PUBLIC_SESSION_TOKEN")??Re("NEXT_PUBLIC_URUN_JWT"),G=Tt(),O=x!==null,J=G==="workos"&&!n&&!O&&!h,ae=n??(G==="jwt"?$:void 0)??p?.token,te=O?x.jwt:ae,Ce=s??Re("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),w=J&&!te&&!N?.getAccessToken,V=t??p?.orgId,K=e??p?.gatewayUrl,B=h&&p===void 0,L=h&&p!==void 0&&!K?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,z=w?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,pe=C??L??z,se=rn("NEXT_PUBLIC_URUN_TOKEN_URL",Re("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Fo,ce=rn("NEXT_PUBLIC_URUN_EVENTS_URL",Re("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,we=(0,ue.useCallback)(async M=>{if(!M?.forceRefresh){let Z=A.current;if(!Z)return Z;let he=qo(Z);if(he===null||he-Date.now()>Ho)return Z}return(await(m.current??(m.current=(async()=>{try{let Z=await tn(se);return A.current=Z.token,P(Z),Z}finally{m.current=null}})()))).token},[se]),Se=(0,ue.useCallback)(async()=>te,[te]),He=typeof te=="string"&&te.trim().length>0,me=J?N?.getAccessToken:h&&!O?we:He?Se:void 0,le=hr(g),ne=hr(v),T=hr(E),F=(0,ue.useMemo)(()=>({appId:y,baseUrl:K??"",orgId:V??"",jwt:te,getAccessToken:J?N?.getAccessToken:h&&!O?we:void 0,authProvider:Ce,eventsUrl:ce,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:le,videoPlayout:ne,sessionStats:T,priority:O?"preempt":void 0}),[y,N,K,Ce,te,ce,V,a,u,f,l,le,ne,T,J,O,h,we]);return(0,ue.useEffect)(()=>{if(!h)return;let M=new AbortController;return U(null),(async()=>{try{let W=await tn(se,M.signal);A.current=W.token,P(W)}catch(W){if(M.signal.aborted)return;U(W instanceof Error?W:new Error(String(W)))}})(),()=>M.abort()},[h,se]),(0,Ie.jsx)(nt,{fallback:d,children:pe?Wo(R,pe):B?(0,Ie.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Ie.jsx)(qe.Provider,{value:F,children:me?(0,Ie.jsx)(Ct,{getAccessToken:me,children:S}):S})})}var fe=require("react"),on=require("@urun-sh/core");function sn(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Bo(e,t,r){let o=sn(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function jo(e,t,r,o){let n=sn(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var Xe=new Map;var vr=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},yr=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},kr=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new vr(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new yr(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function an(){let e=(0,fe.useContext)(qe);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,fe.useReducer)(i=>i+1,0),r=(0,fe.useRef)(new Map),o=(0,fe.useRef)(new Map),n=(0,fe.useRef)(null),s=(0,fe.useMemo)(()=>(0,on.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return(0,fe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Xe.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let f=Xe.get(c);f===u&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(c,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let l=Xe.get(c);!l||l.refCount!==0||(Xe.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),(0,fe.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let f=(l,g)=>{let v=Bo(c,l,g),E=r.current.get(v);if(E&&!E.disposed)return E;let k=jo(e,c,l,g),d=Xe.get(k);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),Xe.delete(k),o.current.get(k)===d&&o.current.delete(k),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new kr(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Xe.set(k,d)),o.current.get(k)!==d&&(o.current.set(k,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(v,d.handle),d.handle};return i.set(c,f),f}})},[e,s])}var qt=require("react"),un=require("@urun-sh/core");function cn(){let e=(0,qt.useContext)(qe);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return(0,qt.useMemo)(()=>(0,un.sessionDirectory)(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}var oe=require("react");function st(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Ko(e){return e instanceof Error?e:new Error(String(e))}function ln(e,t){let r=(0,oe.useMemo)(()=>st(e),[e]),[o,n]=(0,oe.useState)(void 0),[s,i]=(0,oe.useState)(null),[a,c]=(0,oe.useState)(!1),u=(0,oe.useRef)(t);u.current=t;let f=(0,oe.useRef)(0),l=(0,oe.useRef)(null),g=(0,oe.useRef)(!0);(0,oe.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=(0,oe.useCallback)(async d=>{l.current?.abort();let R=new AbortController;l.current=R;let S=++f.current,h=()=>g.current&&f.current===S;h()&&(c(!0),i(null));try{let y=await r.request(d,{...u.current,signal:R.signal});return h()&&(n(y),c(!1),u.current?.onSuccess?.(y)),y}catch(y){let p=Ko(y);throw h()&&(i(p),c(!1),u.current?.onError?.(p)),p}},[r]),E=(0,oe.useCallback)(d=>{v(d).catch(()=>{})},[v]),k=(0,oe.useCallback)(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:E,mutateAsync:v,data:o,error:s,isPending:a,reset:k}}var ie=require("react");function dn(e){return e instanceof Error?e:new Error(String(e))}var $o=e=>typeof e=="string"?e:String(e);function pn(e,t){let r=(0,ie.useMemo)(()=>st(e),[e]),[o,n]=(0,ie.useState)(""),[s,i]=(0,ie.useState)(!1),[a,c]=(0,ie.useState)(null),u=(0,ie.useRef)(t);u.current=t;let f=(0,ie.useRef)(0),l=(0,ie.useRef)(null),g=(0,ie.useRef)(!0);(0,ie.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=(0,ie.useCallback)(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),E=(0,ie.useCallback)(async k=>{l.current?.cancel();let d=++f.current,R=()=>g.current&&f.current===d,S=u.current,h=S?.parseChunk??$o,y=S?.buildPayload??(b=>({prompt:b}));R()&&(n(""),c(null),i(!0));let{parseChunk:p,buildPayload:P,onFinish:C,onError:U,...A}=S??{},m="",x;try{x=r.requestStream(y(k),A),l.current=x}catch(b){let N=dn(b);R()&&(c(N),i(!1),S?.onError?.(N));return}try{for await(let b of x){if(f.current!==d)break;m+=h(b),R()&&n(m)}R()&&(i(!1),S?.onFinish?.(m))}catch(b){let N=dn(b);R()&&(c(N),i(!1),S?.onError?.(N))}finally{l.current===x&&(l.current=null)}},[r]);return{completion:o,complete:E,stop:v,isStreaming:s,error:a}}var ee=require("react");function mn(e){return e instanceof Error?e:new Error(String(e))}var Go=e=>typeof e=="string"?e:String(e),fn=0;function br(e){return fn+=1,`${e}-${fn}`}function gn(e,t){let r=(0,ee.useMemo)(()=>st(e),[e]),[o,n]=(0,ee.useState)(()=>(t?.initialMessages??[]).map(h=>({id:h.id??br("msg"),role:h.role,content:h.content}))),[s,i]=(0,ee.useState)(""),[a,c]=(0,ee.useState)(!1),[u,f]=(0,ee.useState)(null),l=(0,ee.useRef)(t);l.current=t;let g=(0,ee.useRef)(o);g.current=o;let v=(0,ee.useRef)(s);v.current=s;let E=(0,ee.useRef)(0),k=(0,ee.useRef)(null),d=(0,ee.useRef)(!0);(0,ee.useEffect)(()=>(d.current=!0,()=>{d.current=!1,k.current?.cancel(),k.current=null}),[]);let R=(0,ee.useCallback)(()=>{E.current++,k.current?.cancel(),k.current=null,d.current&&c(!1)},[]),S=(0,ee.useCallback)(async h=>{let y=h===void 0,p=(y?v.current:h)??"";if(!p.trim())return;k.current?.cancel();let C=++E.current,U=()=>d.current&&E.current===C,A=l.current,m=A?.parseChunk??Go,x={id:br("msg"),role:"user",content:p},b={id:br("msg"),role:"assistant",content:""},N=[...g.current,x].map(L=>({role:L.role,content:L.content})),$=[...g.current,x,b];g.current=$,n($),y&&i(""),f(null),c(!0);let G=A?.buildPayload??(L=>({messages:L})),{initialMessages:O,parseChunk:J,buildPayload:ae,onFinish:te,onError:Ce,...w}=A??{},V=L=>{n(z=>z.map(pe=>pe.id===b.id?{...pe,content:L}:pe))},K="",B;try{B=r.requestStream(G(N),w),k.current=B}catch(L){let z=mn(L);U()&&(f(z),c(!1),A?.onError?.(z));return}try{for await(let L of B){if(E.current!==C)break;K+=m(L),U()&&V(K)}U()&&(c(!1),A?.onFinish?.({...b,content:K}))}catch(L){let z=mn(L);U()&&(f(z),c(!1),A?.onError?.(z))}finally{k.current===B&&(k.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:S,stop:R,isStreaming:a,error:u}}var Q=require("react"),it=require("@urun-sh/core"),Tr=[];function Sn(e,t={}){let{field:r=it.INPUT_PRESENCE_FIELD,hz:o=it.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,Q.useMemo)(()=>s?(0,it.createInputPresencePublisher)({awareness:{setLocalStateField:(p,P)=>s.setField(p,P)},field:r,hz:o}):null,[s,r,o]),a=(0,Q.useRef)(null);a.current=i;let[c,u]=(0,Q.useState)(!1),[f,l]=(0,Q.useState)(Tr),g=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let v=(0,Q.useCallback)(()=>{let p=a.current;l(p?p.heldKeys():Tr)},[]),E=(0,Q.useCallback)(()=>{a.current?.clear(),l(Tr)},[]);(0,Q.useEffect)(()=>{if(!n)return;let p=()=>!!n.pointerLockElement,P=()=>{if(p()){g.current=!1,u(!0);return}g.current||(u(!1),E())},C=b=>{p()&&(a.current?.keyDown(b.key),v())},U=b=>{a.current?.keyUp(b.key),v()},A=b=>{p()&&a.current?.movePointer(b.movementX,b.movementY)},m=b=>{p()&&a.current?.setButtons(b.buttons)},x=()=>{E()};return n.addEventListener("pointerlockchange",P),n.addEventListener("keydown",C),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",m),n.addEventListener("mouseup",m),n.defaultView?.addEventListener("blur",x),()=>{n.removeEventListener("pointerlockchange",P),n.removeEventListener("keydown",C),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",m),n.removeEventListener("mouseup",m),n.defaultView?.removeEventListener("blur",x)}},[n,E,v]);let k=(0,Q.useCallback)(p=>{p.requestPointerLock?.()},[]),d=(0,Q.useCallback)(()=>{g.current=!0,u(!0)},[]),R=(0,Q.useCallback)(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),E()},[n,E]),S=(0,Q.useCallback)(p=>{a.current?.keyDown(p),v()},[v]),h=(0,Q.useCallback)(p=>{a.current?.keyUp(p),v()},[v]),y=(0,Q.useCallback)((p,P)=>{a.current?.movePointer(p,P)},[]);return{engage:k,engageTouch:d,release:R,engaged:c,heldKeys:f,pressKey:S,releaseKey:h,movePointer:y}}var de=require("react"),Rn=require("@urun-sh/core");var D=require("react"),Pn=require("@urun-sh/core");var Wt=null;function Xo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Pt(){if(Wt)return Wt;let e=Xo();return e?(Wt=new e,Wt):null}function ze(){let e=Pt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Rt=require("react"),yn=require("react/jsx-runtime"),Cr=(0,Rt.createContext)(null);function hn({session:e,children:t}){return(0,yn.jsx)(Cr.Provider,{value:e,children:t})}function Ue(){return(0,Rt.useContext)(Cr)}function vn(){let e=(0,Rt.useContext)(Cr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var xt=require("react/jsx-runtime");function zo(e,t){return e-t>>>0<2147483648}var kn=1e3;function bn(...e){console.debug("[video]",...e)}function Tn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function Cn(e,t,r){return r?[r,t]:[e,t]}var Je=(0,D.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:f,style:l,videoClassName:g,placeholder:v,poster:E,children:k,onTrack:d,onFirstFrame:R,frameMarker:S,onFrameMarkerReached:h,onFrameMarkerUnsupported:y,onUnlockChange:p}=t,P=Ue(),C=o??P,U=(0,D.useRef)(null),A=(0,D.useRef)(null),[m,x]=(0,D.useState)(!1),[b,N]=(0,D.useState)(!1),$=(0,D.useRef)(!1),G=(0,D.useRef)(null),O=(0,D.useRef)(d);O.current=d;let J=(0,D.useRef)(p);J.current=p;let ae=(0,D.useRef)(R);ae.current=R;let te=(0,D.useRef)(h);te.current=h;let Ce=(0,D.useRef)(y);Ce.current=y;let w=(0,D.useRef)(S??null);w.current=S??null;let V=(0,D.useCallback)(T=>{G.current!==T&&(G.current=T,J.current?.(T))},[]),K=(0,D.useRef)(null),B=(0,D.useRef)(null),L=(0,D.useCallback)((T,F=!1)=>{if(!F&&T===K.current||(K.current=T,B.current?.(),B.current=null,$.current=!1,N(!1),!T))return;let M=U.current;if(!M)return;let W=w.current,Z=W?.rtpTimestamp??null,he=!1,I=()=>{he||(he=!0,Ce.current?.())};W&&Z==null&&I();let Ae=W!=null&&Z!=null,tt=_e=>{B.current?.(),B.current=null,$.current=!0,N(!0),ae.current?.(),_e&&te.current?.()};if(typeof M.requestVideoFrameCallback=="function"){let _e=!1,H=0,q=(ve,ye)=>{if(!_e){if(Ae){let Pe=ye?.rtpTimestamp;if(typeof Pe!="number"){I(),tt(!1);return}if(!zo(Pe,Z)){H=M.requestVideoFrameCallback(q);return}tt(!0);return}tt(!1)}};H=M.requestVideoFrameCallback(q),B.current=()=>{_e=!0,M.cancelVideoFrameCallback?.(H)};return}Ae&&I();let Me=()=>{let _e=M.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:M.readyState>=2&&M.videoWidth>0)&&tt(!1)};M.addEventListener("loadeddata",Me),M.addEventListener("timeupdate",Me),M.addEventListener("playing",Me),B.current=()=>{M.removeEventListener("loadeddata",Me),M.removeEventListener("timeupdate",Me),M.removeEventListener("playing",Me)},Me()},[]);(0,D.useEffect)(()=>()=>{B.current?.(),B.current=null},[]);let z=S==null?null:`${S.rtpTimestamp??""}|${S.ptsMs??""}`,pe=(0,D.useRef)(z);(0,D.useEffect)(()=>{if(pe.current===z||(pe.current=z,z==null))return;let T=K.current;T&&L(T,!0)},[z,L]);let se=(0,D.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let T=U.current;return T&&T.srcObject!==A.current&&(T.srcObject=A.current),A.current},[]),ce=(0,D.useCallback)(T=>{let F=U.current;if(!F)return;let M=F.play();!M||typeof M.then!="function"||M.then(()=>{F.muted||V(!0)}).catch(W=>{if((W instanceof Error?W.name:String(W))==="NotAllowedError"&&!F.muted){bn(`play() blocked pending a user gesture (${T})`),V(!1);return}bn(`play() failed (${T})`,W)})},[V]),we=(0,D.useCallback)(()=>{let T=U.current;T&&(se(),!T.muted&&(ce("gesture"),ze(),V(!0)))},[se,ce,V]),Se=(0,D.useCallback)(T=>{let F=se();if(F){for(let M of F.getVideoTracks())M!==T&&F.removeTrack(M);if(T&&!F.getVideoTracks().includes(T)){F.addTrack(T);let M=U.current;M&&(M.srcObject=F)}T&&ce("track-attach"),x(T!==null),L(T),O.current?.(T)}},[se,ce,L]),He=(0,D.useCallback)(T=>{let F=se();if(F){for(let M of F.getAudioTracks())M!==T&&F.removeTrack(M);T&&!F.getAudioTracks().includes(T)&&F.addTrack(T),T&&ce("audio-attach")}},[se,ce]),me=(0,D.useCallback)(T=>{U.current=T,T&&(a?(T.muted=!0,T.defaultMuted=!0,T.setAttribute("muted",""),G.current=null):(T.muted=!1,T.defaultMuted=!1,T.removeAttribute("muted")),T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),se())},[se,a]);(0,D.useImperativeHandle)(r,()=>({get element(){return U.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return $.current},unlock:we,get unlocked(){return G.current===!0}}),[we]);let le=(0,Pn.derivedLegRole)(n)!==void 0;(0,D.useEffect)(()=>{le&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[le,n]);let ne=i!==void 0;return(0,D.useEffect)(()=>{if(ne){Se(i??null);return}if(le){Se(null);return}if(!C)return;let T=Tn(C,Cn(n,"video")),F=()=>{let I=A.current;return I?I.getVideoTracks()[0]??null:null},M=I=>{if(I!==F()&&(Se(I),I)){let Ae=()=>{F()===I&&Se(null)};I.addEventListener("ended",Ae)}},W=T.track;W&&W.readyState==="live"&&M(W);let Z=T.on("track",I=>{I&&I.readyState!=="live"||M(I)}),he=setInterval(()=>{let I=T.track;I&&I.readyState==="live"&&M(I)},kn);return()=>{Z(),clearInterval(he)}},[C,n,le,ne,i,Se]),(0,D.useEffect)(()=>{if(ne||!C||s===!1||le)return;let T=Tn(C,Cn(n,"audio",s)),F=()=>{let I=A.current;return I?I.getAudioTracks()[0]??null:null},M=I=>{if(I!==F()&&(He(I),I)){let Ae=()=>{F()===I&&He(null)};I.addEventListener("ended",Ae)}},W=T.track;W&&W.readyState==="live"&&M(W);let Z=T.on("track",I=>{I&&I.readyState!=="live"||M(I)}),he=setInterval(()=>{let I=T.track;I&&I.readyState==="live"&&M(I)},kn);return()=>{Z(),clearInterval(he)}},[C,n,le,s,ne,He]),(0,xt.jsxs)("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":m?"true":"false","data-urun-video-framed":b?"true":"false",children:[(0,xt.jsx)("video",{ref:me,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),m?null:v,E===void 0?null:(0,xt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":b||void 0,style:{position:"absolute",inset:0,...b?{opacity:0,pointerEvents:"none"}:null},children:E}),k]})});var Et=require("react/jsx-runtime"),Jo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},xn=(0,de.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...f}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=(0,de.useRef)(null),v=(0,de.useRef)(null),E=(0,de.useRef)(0),k=(0,de.useRef)(f);k.current=f;let d=(0,de.useMemo)(()=>(0,Rn.createCameraWarp)(k.current),[]);return(0,de.useImperativeHandle)(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:d,get lastDrawTs(){return E.current}}),[d]),(0,de.useEffect)(()=>{if(!i)return;let R=0,S=0,h=null,y=P=>{typeof P.requestVideoFrameCallback=="function"&&(h=P,S=P.requestVideoFrameCallback(function C(){d.frameArrived(),S=P.requestVideoFrameCallback(C)}))},p=P=>{R=requestAnimationFrame(p);let C=v.current,U=g.current?.element??null;if(!C||!U||(U!==h&&(h&&S&&h.cancelVideoFrameCallback?.(S),y(U)),U.readyState<2))return;d.tick(P);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,m=Math.max(1,Math.round(C.clientWidth*A)),x=Math.max(1,Math.round(C.clientHeight*A));(C.width!==m||C.height!==x)&&(C.width=m,C.height=x);let b=C.getContext("2d");if(!b)return;let N=d.transform(),$=U.videoWidth||m,G=U.videoHeight||x,J=Math.max(m/$,x/G)*(1+a)*N.scale;b.setTransform(J,0,0,J,m/2+N.translateX*m,x/2+N.translateY*x),b.drawImage(U,-$/2,-G/2),E.current=P};return R=requestAnimationFrame(p),()=>{cancelAnimationFrame(R),h&&S&&h.cancelVideoFrameCallback?.(S)}},[i,a,d]),(0,de.useEffect)(()=>{if(!i||!c||!l)return;let R=()=>!!l.pointerLockElement,S=C=>{R()&&d.keyDown(C.key)},h=C=>d.keyUp(C.key),y=C=>{R()&&d.pointerDelta(C.movementX,C.movementY)},p=()=>{R()||d.clearKeys()},P=()=>d.clearKeys();return l.addEventListener("keydown",S),l.addEventListener("keyup",h),l.addEventListener("mousemove",y),l.addEventListener("pointerlockchange",p),l.defaultView?.addEventListener("blur",P),()=>{l.removeEventListener("keydown",S),l.removeEventListener("keyup",h),l.removeEventListener("mousemove",y),l.removeEventListener("pointerlockchange",p),l.defaultView?.removeEventListener("blur",P)}},[i,c,l,d]),i?(0,Et.jsxs)(Je,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Et.jsx)("canvas",{ref:v,style:Jo,"data-urun-warp":""}),n]}):(0,Et.jsx)(Je,{ref:g,...s,children:n})});var En=new Map;function wn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);En.set(e,{component:t,schema:r})}function Un(e,t){let r=En.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Ye=require("react/jsx-runtime");function An({name:e,props:t,fallback:r}){let o=Un(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ye.jsx)(Ye.Fragment,{children:r}):(0,Ye.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ye.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ye.jsx)(n,{...o.validatedProps})}var at=require("zod"),Ze=require("react/jsx-runtime"),Mn=at.z.object({step:at.z.number().min(0),total:at.z.number().min(1),label:at.z.string().optional(),variant:at.z.enum(["default","success","error"]).default("default")});function Pr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function _n(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Pr(e);return(0,Ze.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Ze.jsx)("div",{className:"urun-progress-label",children:o}),(0,Ze.jsx)("div",{className:"urun-progress-bar",children:(0,Ze.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Ze.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Bt=require("zod"),wt=require("react/jsx-runtime"),Nn=Bt.z.object({state:Bt.z.enum(["thinking","generating","idle","error"]),message:Bt.z.string().optional()}),Yo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Rr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Yo[t]??t;return{state:t,message:n,isActive:o}}function In(e){let{state:t,message:r,isActive:o}=Rr(e);return(0,wt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,wt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,wt.jsx)("span",{className:"urun-status-message",children:r})]})}var Ut=require("react"),jt=require("zod"),At=require("react/jsx-runtime"),On=jt.z.object({text:jt.z.string(),streaming:jt.z.boolean().default(!1)});function xr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Ln(e){let{text:t,streaming:r}=xr(e),o=(0,Ut.useRef)(null),n=(0,Ut.useRef)(0);return(0,Ut.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,At.jsxs)("div",{className:"urun-text-stream",children:[(0,At.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,At.jsx)("span",{className:"urun-text-cursor"})]})}var Mt=require("zod"),_t=require("react/jsx-runtime"),Dn=Mt.z.object({src:Mt.z.string().url(),alt:Mt.z.string().optional(),caption:Mt.z.string().optional()});function Er(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Vn(e){let{src:t,alt:r,caption:o}=Er(e);return(0,_t.jsxs)("figure",{className:"urun-image-frame",children:[(0,_t.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,_t.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Oe=require("zod"),ut=require("react/jsx-runtime"),Fn=Oe.z.object({metrics:Oe.z.array(Oe.z.object({label:Oe.z.string(),value:Oe.z.union([Oe.z.string(),Oe.z.number()]),unit:Oe.z.string().optional()}))});function wr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Hn(e){let{metrics:t}=wr(e);return(0,ut.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ut.jsxs)("div",{className:"urun-metric-card",children:[(0,ut.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ut.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var X=require("react"),Kn=require("react/jsx-runtime");function We(e){return e&&typeof e=="object"?e:null}function Ur(e){if(typeof e=="string")return e;let t=We(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function Zo(e){if(typeof e=="string")return"delta";let t=We(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function Qo(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function es(e){let t=We(e),r=t?.body;return Qo(r,We(We(r)?.error)?.message,We(r)?.error,We(r)?.message,We(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var ct=class extends Error{name="TextStreamError"},ts=4,Ar=3,Mr=240,qn=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function Wn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function rs(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function _r(e){let{session:t,stream:r}=e,o=(0,X.useRef)(e);(0,X.useEffect)(()=>{o.current=e});let n=(0,X.useRef)(null),s=(0,X.useRef)(()=>{}),i=(0,X.useRef)(null),a=(0,X.useRef)(""),c=(0,X.useRef)(""),u=(0,X.useRef)(null),f=(0,X.useRef)(!1),l=(0,X.useRef)(!1),g=(0,X.useRef)(!1),v=(0,X.useRef)(null),E=(0,X.useRef)(Wn()),k=(0,X.useCallback)(h=>{if(n.current=h,!h){i.current=null;return}let y=i.current;if(y&&y.parentNode===h)return;let p=h.ownerDocument.createTextNode(c.current);h.appendChild(p),i.current=p,a.current.length>0&&s.current()},[]),d=(0,X.useCallback)(()=>{u.current=null;let h=i.current,y=a.current;if(y.length>0){let A=o.current,m=A.smoothCharsPerFrame??Ar,x=A.smoothThreshold??Mr,b=A.smooth&&y.length<=x?y.slice(0,m):y;a.current=y.slice(b.length),c.current+=b,h?.appendData(b)}let p=E.current,P=c.current.length,C=v.current===null?0:Math.max(0,qn()-v.current),U=Math.round(P/ts);if(p.chars=P,p.tokens=U,p.elapsedMs=C,p.tokensPerSecond=C>0?U*1e3/C:0,a.current.length>0){R(),o.current.onMeter?.(p);return}if(!f.current&&!g.current){g.current=!0,p.done=!0,o.current.onMeter?.(p),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(p)},[]),R=(0,X.useCallback)(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>d()))},[d]);s.current=R,(0,X.useEffect)(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,v.current=null,f.current=!0,rs(E.current),i.current&&(i.current.data="");let h=!1,y=null;return(async()=>{try{for(y=t.stream(r).messages()[Symbol.asyncIterator]();;){let P=await y.next();if(h)return;if(P.done)break;let C=P.value,U=Zo(C);if(U==="error")throw new ct(es(C));if(U==="done")break;if(U==="ignore")continue;let A=Ur(C);A&&(v.current===null&&(v.current=qn()),a.current+=A,R())}if(h)return;y.return?.(void 0),f.current=!1,R()}catch(p){if(h)return;y?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(p instanceof Error?p:new ct(String(p))),R()}})(),()=>{h=!0,f.current=!1,y?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,R]);let S=(0,X.useCallback)(()=>c.current,[]);return{ref:k,meterRef:E,getText:S}}function Bn(e,t=250){let[r,o]=(0,X.useState)(Wn);return(0,X.useEffect)(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function jn(e){let{className:t,style:r,...o}=e,{ref:n}=_r(o);return(0,Kn.jsx)("span",{ref:n,className:t,style:r})}var $n=require("react");var Xn=require("react/jsx-runtime"),Gn=(0,$n.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Xn.jsx)(Je,{ref:r,stream:o,...n})});var Y=require("react"),Jn=require("@urun-sh/core");var Zn=require("react/jsx-runtime"),ns=1e3,zn=200;function Nr(...e){console.debug("[audio]",...e)}var Nt=(0,Y.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f}=t,l=Ue(),g=o??l,v=(0,Y.useRef)(null),E=(0,Y.useRef)(null),k=(0,Y.useRef)(null),d=(0,Y.useRef)(null),R=(0,Y.useRef)(c);R.current=c;let S=(0,Y.useRef)(u);S.current=u;let h=(0,Y.useCallback)(m=>{k.current!==m&&(k.current=m,S.current?.(m))},[]),y=(0,Y.useCallback)(()=>{if(typeof MediaStream>"u")return null;E.current||(E.current=new MediaStream);let m=v.current;return m&&m.srcObject!==E.current&&(m.srcObject=E.current),E.current},[]),p=(0,Y.useCallback)(m=>{let x=v.current;if(!x)return;let b=x.play();!b||typeof b.then!="function"||b.then(()=>{x.muted||h(!0)}).catch(N=>{let $=N instanceof Error?N.name:String(N);if($==="AbortError"){Nr(`play() aborted (${m}); retrying in ${zn}ms`),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,p(`${m}:retry`)},zn);return}if($==="NotAllowedError"){Nr(`play() blocked pending a user gesture (${m})`),h(!1);return}Nr(`play() failed (${m})`,N)})},[h]),P=(0,Y.useCallback)(m=>{let x=y();if(x){for(let b of x.getAudioTracks())b!==m&&x.removeTrack(b);m&&!x.getAudioTracks().includes(m)&&x.addTrack(m),m&&p("track-attach"),R.current?.(m)}},[y,p]),C=(0,Y.useCallback)(()=>{let m=v.current;m&&(y(),m.muted=!1,p("gesture"),ze(),h(!0))},[y,p,h]);(0,Y.useImperativeHandle)(r,()=>({unlock:C,get unlocked(){return k.current===!0},get element(){return v.current}}),[C]);let U=(0,Y.useCallback)(m=>{v.current=m,m&&(m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),y()),f?.(m)},[y,f]),A=s!==void 0;return(0,Y.useEffect)(()=>{if(A){P(s??null);return}if(!g)return;let m=g.stream(n),x=()=>{let O=E.current;return O?O.getAudioTracks()[0]??null:null},b=O=>{if(O!==x()&&(P(O),O)){let J=()=>{x()===O&&P(null)};O.addEventListener("ended",J)}},N=m.track;N&&N.readyState==="live"&&b(N);let $=m.on("track",O=>{O&&O.readyState!=="live"||b(O)}),G=setInterval(()=>{let O=m.track;O&&O.readyState==="live"&&b(O)},ns);return()=>{$(),clearInterval(G)}},[g,n,A,s,P]),(0,Y.useEffect)(()=>(0,Jn.observePageLifecycle)(()=>{ze(),k.current===!0&&p("foreground")}),[p]),(0,Y.useEffect)(()=>()=>{d.current&&clearTimeout(d.current)},[]),(0,Zn.jsx)("audio",{ref:U,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Yn=Nt;var j=require("react"),lt=require("@urun-sh/core");var eo=require("react/jsx-runtime"),Ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Kt(...e){console.debug("[voice]",...e)}var It=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=Ir,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:E,onUnlockChange:k,capture:d}=t,R=Ue(),S=o??R,h=(0,j.useRef)(null),y=(0,j.useRef)(null),p=(0,j.useRef)(null),P=(0,j.useRef)([]),C=(0,j.useRef)(!1),U=(0,j.useRef)(l);U.current=l;let A=(0,j.useRef)(g);A.current=g;let m=(0,j.useRef)(v);m.current=v;let x=(0,j.useCallback)(w=>{C.current!==w&&(C.current=w,U.current?.(w))},[]),b=(0,j.useCallback)(()=>{for(let w of P.current)w();P.current=[],p.current?.release(),p.current=null,y.current&&(y.current=null,m.current?.(null))},[]),N=(0,j.useCallback)(async()=>{let w=p.current;if(w){let L=await w.update(a);return y.current=w.stream,m.current?.(w.stream),L}let K=await(d??(0,lt.sharedCaptureController)()).claim("audio",a);p.current=K,P.current=[K.onTrack((L,z)=>{y.current=z,m.current?.(z),C.current&&S?.stream(n).attach(L).catch(pe=>Kt("mic re-attach after one-capture re-acquire failed",pe))}),K.onLost(L=>{p.current=null,P.current=[],y.current=null,m.current?.(null),x(!1),A.current?.(L)})],y.current=K.stream,m.current?.(K.stream);let B=K.track;if(!B)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return B},[d,a,S,n,x]),$=(0,j.useCallback)(async()=>{b(),x(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,b,x]),G=(0,j.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");h.current?.unlock();let w;try{w=await N()}catch(B){b();let L=(0,lt.sessionFailureFromMediaError)(B,S.status);throw A.current?.(L),L}S.connect?.();let V;for(let B=1;B<=u;B++)try{await S.whenLive(c!==void 0?{timeout:c}:void 0),await S.stream(n).attach(w),x(!0);return}catch(L){V=L,Kt(`start attempt ${B}/${u} failed`,L),B<u&&await new Promise(z=>setTimeout(z,f))}b(),x(!1);let K=V instanceof Error?V:new Error(String(V??"voice start failed"));throw A.current?.(K),K},[S,n,c,u,f,N,b,x]);(0,j.useImperativeHandle)(r,()=>({start:G,stop:$,unlock:()=>h.current?.unlock(),get active(){return C.current},get micStream(){return y.current},get audio(){return h.current}}),[G,$]);let O=(0,j.useRef)(G);O.current=G;let J=(0,j.useRef)(null),ae=(0,j.useCallback)((w,V)=>{w.promise.then(()=>{V&&(b(),x(!1)),w.session.stream(w.streamName).detach().catch(()=>{})})},[b,x]);(0,j.useEffect)(()=>{if(!i||!S)return;let w=J.current;w&&(w.session!==S||w.streamName!==n)&&(w.disposeTimer&&clearTimeout(w.disposeTimer),ae(w,!1),w=null),w?w.disposeTimer&&(clearTimeout(w.disposeTimer),w.disposeTimer=null):(w={session:S,streamName:n,promise:O.current().catch(()=>{}),refCount:0,disposeTimer:null},J.current=w),w.refCount+=1;let V=w;return()=>{V.refCount-=1,!(V.refCount>0)&&(V.disposeTimer=setTimeout(()=>{J.current===V&&(J.current=null),ae(V,!0)},0))}},[i,S,n,ae]);let te=(0,j.useRef)(!1),Ce=(0,j.useCallback)(async()=>{if(!S||!C.current||te.current)return;let w=y.current?.getAudioTracks()[0]??null;if(w&&w.readyState==="live"){try{await S.stream(n).attach(w)}catch(V){Kt("foreground mic re-assert failed (will retry on next pass)",V)}return}te.current=!0;try{let V=await N();await S.stream(n).attach(V)}catch(V){let K=V instanceof Error?V:new Error(String(V));Kt("foreground mic re-acquire failed",K),A.current?.(K)}finally{te.current=!1}},[S,n,N]);return(0,j.useEffect)(()=>{let w=()=>{Ce()};return S&&typeof S.onRecovery=="function"?S.onRecovery(w):(0,lt.observePageLifecycle)(w)},[S,Ce]),(0,j.useEffect)(()=>b,[b]),s?(0,eo.jsx)(Nt,{ref:h,session:S,stream:n,onTrack:E,onUnlockChange:k}):null}),Qn=It;var De=require("react");var $t=require("react");var Or={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,$t.useState)(Or);return(0,$t.useEffect)(()=>{if(!e){i(Or);return}let a=Pt();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,f;try{u=a.createMediaStreamSource(c),f=a.createAnalyser(),f.fftSize=r,u.connect(f)}catch{return}let l=new Uint8Array(f.fftSize),v=setInterval(()=>{f.getByteTimeDomainData(l);let E=0;for(let d=0;d<l.length;d++){let R=(l[d]-128)/128;E+=R*R}let k=Math.sqrt(E/l.length);i(d=>{let R=k>n;return Math.abs(d.level-k)<.005&&d.speaking===R?d:{level:k,speaking:R}})},o);return()=>{clearInterval(v),u.disconnect(),i(Or)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),os={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ss={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},to=(0,De.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:f,onMicStream:l,capture:g}=t,v=Ue(),E=o??v,k=(0,De.useRef)(null),[d,R]=(0,De.useState)(null),S=(0,De.useRef)(l);S.current=l;let{level:h,speaking:y}=Gt(a?d:null);return(0,De.useImperativeHandle)(r,()=>({start:()=>{let p=k.current;return p?p.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>k.current?.stop()??Promise.resolve(),get active(){return k.current?.active??!1},get micStream(){return k.current?.micStream??null}}),[]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(It,{ref:k,session:E,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:p=>{R(p),S.current?.(p)}}),a?(0,Le.jsx)("span",{className:c,style:os,"data-urun-mic":"","data-urun-mic-active":d?"true":"false","data-urun-mic-speaking":y?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(h*100)/100,children:(0,Le.jsx)("span",{style:ss,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(h*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var dt=require("@urun-sh/core"),_=require("react");var ke=require("react/jsx-runtime"),Dr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Lr(...e){console.debug("[camera]",...e)}function is(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function as(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var Vr=(0,_.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:f="auto",connectTimeoutMs:l,visible:g=!1,className:v,videoClassName:E,onActiveChange:k,onError:d,onStream:R,onTrack:S,children:h,capture:y,flipControl:p="auto",flipControlClassName:P,onDevices:C}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":c??"environment",A=Ue(),m=o??A,x=(0,_.useRef)(null),b=(0,_.useRef)(null),N=(0,_.useRef)(null),$=(0,_.useRef)([]),G=(0,_.useRef)(null),O=(0,_.useRef)(!1),J=(0,_.useRef)(!1),ae=(0,_.useRef)(U),[te,Ce]=(0,_.useState)(U),[w,V]=(0,_.useState)(!1),[K,B]=(0,_.useState)(null),[L,z]=(0,_.useState)(!1),[pe]=(0,_.useState)(is),se=(0,_.useRef)(k);se.current=k;let ce=(0,_.useRef)(d);ce.current=d;let we=(0,_.useRef)(R);we.current=R;let Se=(0,_.useRef)(S);Se.current=S;let He=(0,_.useRef)(C);He.current=C;let me=(0,_.useCallback)(H=>{O.current!==H&&(O.current=H,V(H),se.current?.(H))},[]);(0,_.useEffect)(()=>{if(!w){B(null);return}let H=!1,q=()=>{as().then(ye=>{H||(B(ye),ye&&He.current?.(ye))})};q();let ve=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ve?.addEventListener=="function"?(ve.addEventListener("devicechange",q),()=>{H=!0,ve.removeEventListener?.("devicechange",q)}):()=>{H=!0}},[w]);let le=(0,_.useCallback)(H=>{let q=x.current;q&&(q.muted=!0,q.defaultMuted=!0,q.setAttribute("muted",""),q.setAttribute("playsinline",""),q.setAttribute("webkit-playsinline",""),q.srcObject=H,H&&q.play()?.catch?.(ve=>Lr("preview play() failed",ve)))},[]),ne=(0,_.useCallback)(()=>{J.current=!1,G.current?.(),G.current=null;for(let H of $.current)H();$.current=[],N.current?.release(),N.current=null,b.current&&(b.current=null,we.current?.(null),Se.current?.(null)),le(null)},[le]),T=(0,_.useCallback)((H,q)=>{G.current?.(),b.current=q,le(q),we.current?.(q);let ve=()=>{b.current===q&&(Lr("camera track ended (device removed or permission revoked)"),ne(),me(!1))};H.addEventListener("ended",ve),G.current=()=>H.removeEventListener("ended",ve)},[le,ne,me]),F=(0,_.useCallback)(async H=>{let q=n!==!1;if(q&&!m)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ve={...Dr,...s,facingMode:H},ye;try{let Pe=N.current;if(Pe)ye=await Pe.update(ve);else{let yt=await(y??(0,dt.sharedCaptureController)()).claim("video",ve);if(N.current=yt,$.current=[yt.onTrack((kt,Uo)=>{T(kt,Uo),O.current&&(!q||!m||m.stream(n).attachVideo(kt).then(()=>Se.current?.(kt)).catch(Ao=>Lr("camera re-publish after one-capture re-acquire failed",Ao)))}),yt.onLost(kt=>{N.current=null,$.current=[],ne(),me(!1),ce.current?.(kt)})],!yt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ye=yt.track}}catch(Pe){let rt=(0,dt.sessionFailureFromMediaError)(Pe,m?.status);throw ce.current?.(rt),rt}ae.current=H,Ce(H),T(ye,N.current?.stream??new MediaStream([ye]));try{q&&m&&(m.connect?.(),await m.whenLive(l!==void 0?{timeout:l}:void 0),await m.stream(n).attachVideo(ye)),J.current=q?n:!1}catch(Pe){ne(),me(!1);let rt=Pe instanceof Error?Pe:new Error(String(Pe));throw ce.current?.(rt),rt}Se.current?.(ye),me(!0)},[m,n,s,l,y,T,ne,me]),M=(0,_.useCallback)(H=>F(H?.facingMode??ae.current),[F]),W=(0,_.useCallback)(async H=>{let q=J.current===n;O.current&&ae.current===H&&q||await F(H)},[F,n]),Z=(0,_.useCallback)(()=>F(ae.current==="environment"?"user":"environment"),[F]),he=(0,_.useCallback)(async()=>{ne(),me(!1),n!==!1&&await m?.stream(n).detachVideo().catch(()=>{})},[m,n,ne,me]),I=(0,_.useCallback)(async H=>{let q=x.current;if(!q)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,dt.captureStillFromVideo)(q,H)},[]);(0,_.useImperativeHandle)(r,()=>({start:M,stop:he,flip:Z,setFacingMode:W,capturePhoto:I,get active(){return O.current},get facingMode(){return ae.current},get stream(){return b.current},get element(){return x.current}}),[M,he,Z,W,I]);let Ae=(0,_.useRef)(W);if(Ae.current=W,(0,_.useEffect)(()=>{u&&(n!==!1&&!m||Ae.current(U).catch(()=>{}))},[u,m,U,n]),(0,_.useEffect)(()=>ne,[ne]),!g)return null;let tt=f==="auto"?te==="user":f,Me=w&&(p===!0||p==="auto"&&pe&&(K?.length??0)>1),_e=()=>{L||(z(!0),Z().catch(()=>{}).finally(()=>z(!1)))};return(0,ke.jsxs)("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":te,children:[(0,ke.jsx)("video",{ref:x,className:E,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...tt?{transform:"scaleX(-1)"}:{}}}),Me?(0,ke.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:L,className:P,style:P?{opacity:L?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:L?.6:1},children:(0,ke.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,ke.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ke.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ke.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ke.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ke.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,h]})}),ro=(0,_.forwardRef)(function({preview:t=!0,...r},o){return(0,ke.jsx)(Vr,{ref:o,...r,visible:t,autoStart:!1})});var pt=require("@urun-sh/core"),re=require("react");function no(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,re.useState)(null),[a,c]=(0,re.useState)(null),[u,f]=(0,re.useState)(!1),[l,g]=(0,re.useState)(null),[v]=(0,re.useState)(pt.cameraCaptureAvailable),E=(0,re.useRef)(n);E.current=n;let k=(0,re.useRef)(null),d=(0,re.useRef)(0),R=(0,re.useCallback)(P=>{k.current&&URL.revokeObjectURL(k.current),k.current=P?URL.createObjectURL(new Blob([P.bytes],{type:P.type})):null,c(k.current),i(P),E.current?.(P)},[]);(0,re.useEffect)(()=>()=>{d.current++,k.current&&URL.revokeObjectURL(k.current),k.current=null},[]);let S=(0,re.useCallback)(async P=>{let C=++d.current;f(!0),g(null);try{let U=await P();if(d.current!==C)return;R(U)}catch(U){if(d.current!==C)return;g((0,pt.referenceImageErrorMessage)(U))}finally{d.current===C&&f(!1)}},[R]),h=(0,re.useCallback)(P=>S(()=>(0,pt.normalizeReferenceImage)(P,{maxSize:t,type:r,quality:o,source:"file"})),[S,t,r,o]),y=(0,re.useCallback)(P=>S(()=>P.capturePhoto({maxSize:t,type:r,quality:o})),[S,t,r,o]),p=(0,re.useCallback)(()=>{d.current++,g(null),f(!1),R(null)},[R]);return{reference:s,previewUrl:a,pick:h,capture:y,clear:p,busy:u,error:l,cameraAvailable:v}}var Xt=require("react");function oo(e,t){let[r,o]=(0,Xt.useState)(null);return(0,Xt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var ao=require("react");var Jt=require("react");var so=require("zustand/vanilla"),io=require("zustand"),us=()=>{};function zt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,so.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):us,c=(u=>(0,io.useStore)(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function mt(e,t){let r=(0,Jt.useMemo)(()=>zt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Jt.useEffect)(()=>r.bind(),[r]),r}function uo(e,t,r){let n=mt(e,t)(r??(a=>a)),s=(0,ao.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Yt=require("react");function co(e){let[t,r]=(0,Yt.useState)(null);return(0,Yt.useEffect)(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}var Qt=require("react");var Be=200;function Ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ft(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Zt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function er(e,t,r={}){let o=r.cap??200,[n,s]=(0,Qt.useState)([]);return(0,Qt.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>Ve(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var xe=require("react/jsx-runtime");function lo({session:e,name:t,cap:r,className:o}){let n=er(e,t,{cap:r});return(0,xe.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,xe.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,xe.jsx)("code",{children:t}),(0,xe.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,xe.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,xe.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,xe.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,xe.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,xe.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ft(s.payload)]},`${s.at}-${i}`))})]})}var Ot=require("react");var ge=require("react/jsx-runtime");function Lt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,Ot.useState)(""),[i,a]=(0,Ot.useState)(null),c=(0,Ot.useCallback)(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return(0,ge.jsxs)("div",{className:"urun-doc-patch",children:[(0,ge.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,ge.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,ge.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?(0,ge.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function po({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=mt(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return(0,ge.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,ge.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,ge.jsx)("code",{children:t}),(0,ge.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,ge.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,ge.jsx)(Lt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}var tr=require("react");var Fe=require("react/jsx-runtime");function mo(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function fo({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,tr.useState)([]);return(0,tr.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ve(c,{at:Date.now(),direction:"in",text:mo(ft(a))},r))}):void 0),[e,t,r]),(0,Fe.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,Fe.jsx)(Lt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>Ve(c,{at:Date.now(),direction:"out",text:mo(a)},r))}}),(0,Fe.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,Fe.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,Fe.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Fe.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Fe.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var rr=require("react");var Qe=require("react/jsx-runtime");function go({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,rr.useState)([]),a=t.join(","),c=r.join(",");return(0,rr.useEffect)(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>Ve(v,{at:Date.now(),kind:l,text:g},o)),f=[];f.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);f.push(g.on("track",v=>u("track",`${l}: ${v?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);f.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>f.forEach(l=>l())},[e,a,c,o]),(0,Qe.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Qe.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,f)=>(0,Qe.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,Qe.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,Qe.jsx)("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${f}`))})}var cr=require("@urun-sh/core");var nr=require("react");function be(e){let[t,r]=(0,nr.useState)(e?.phase??null);return(0,nr.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var ho=require("@urun-sh/core");var gt=require("react"),So=require("@urun-sh/core");function or(e){let t=be(e),r=(0,So.isWakingPhase)(t?.name),o=(0,gt.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,gt.useState)(s);return(0,gt.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var je=require("react/jsx-runtime");function sr({session:e,render:t,className:r}){let o=or(e);return!o.waking||!o.phase?null:(0,je.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)("span",{className:"urun-session-waking-label",children:(0,ho.describeSessionPhase)(o.phase)})," ",(0,je.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var ar=require("react");var Ke=require("react"),cs={event:null,elapsedMs:0};function ir(e,t){let[r,o]=(0,Ke.useState)(null),n=(0,Ke.useRef)(0);(0,Ke.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,Ke.useState)(0);return(0,Ke.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:cs}var St=require("react/jsx-runtime"),ls={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function ds(e){let[t,r]=(0,ar.useState)(!1);return(0,ar.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function ur({session:e,stream:t,videoElement:r,render:o,className:n}){let s=ir(e,t),i=ds(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return(0,St.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):(0,St.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,St.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??ls[c]})," ",(0,St.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Te=require("react/jsx-runtime"),ps={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function vo({session:e,className:t}){let r=be(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,Te.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,Te.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,Te.jsx)("span",{className:"urun-session-status-label",children:ps[o]}),n?(0,Te.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function yo({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=be(e);if(s?.name==="live")return(0,Te.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,Te.jsx)(ur,{session:e})]});let i=r?r(s):(0,Te.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&(0,cr.isWakingPhase)(s.name)?(0,Te.jsx)(sr,{session:e}):s&&s.name!=="idle"?(0,cr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return(0,Te.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,Te.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var lr=require("react");var bo=require("react/jsx-runtime");function Fr(e){return be(e)?.endsAt??null}function ms(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function ko({session:e,urgentMs:t=6e4,className:r}){let n=Fr(e)?.getTime()??null,[s,i]=(0,lr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,lr.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=ms(s);return(0,bo.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var To=require("@urun-sh/core");var ht=require("react/jsx-runtime"),fs=new Set(["paused","error"]);function Hr({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=be(e);if(!s||!fs.has(s.name))return null;let i=o?o(s):(0,ht.jsx)("span",{className:"urun-session-paused-copy",children:(0,To.describeSessionPhase)(s)});return(0,ht.jsxs)("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var Co=Hr;var $e=require("react"),et=require("react/jsx-runtime");function qr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Wr(e){let t=(0,$e.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,$e.useState)(()=>t?qr(t.get("idle")):null);return(0,$e.useEffect)(()=>{if(!t){o(null);return}return o(qr(t.get("idle"))),t.on("change",()=>o(qr(t.get("idle"))))},[t]),r}function gs(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Po({session:e,onStillHere:t,className:r}){let o=Wr(e),n=o?.deadlineEpochS??null,[s,i]=(0,$e.useState)(null);if((0,$e.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,et.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,et.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,et.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,et.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${gs(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,et.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Ee=require("react");function Ss(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function dr(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=(0,Ee.useState)(null),[s,i]=(0,Ee.useState)(e!==null),[a,c]=(0,Ee.useState)(null),u=(0,Ee.useRef)(e),f=(0,Ee.useCallback)(async g=>{i(!0);try{let v=await g.getBalance();if(u.current!==g)return;n(v),c(null)}catch(v){if(u.current!==g)return;c(v instanceof Error?v:new Error(String(v)))}finally{u.current===g&&i(!1)}},[]);(0,Ee.useEffect)(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(f(e),r!==void 0&&r>0){let g=setInterval(()=>{f(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,f]);let l=(0,Ee.useCallback)(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:Ss(o),loading:s,error:a,refresh:l}}var pr=require("react/jsx-runtime");function Ro({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=dr(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return(0,pr.jsx)("div",{className:i,children:t});let a=r?r(n):(0,pr.jsx)("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return(0,pr.jsx)("div",{className:i,children:a})}var Ge=require("@urun-sh/core");var vt=require("react"),xo=require("@urun-sh/core");function Eo(e){let t=(0,vt.useContext)(qe),[r,o]=(0,vt.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,f=t?.getAccessToken,l=t?.authProvider;return(0,vt.useEffect)(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{(0,xo.prewake)({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(k=>{g||o(k)}).catch(()=>{})};v();let E=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(E)}},[n,s,i,a,c,u,f,l]),r}var mr=require("react");function wo(e){let[t,r]=(0,mr.useState)(null);return(0,mr.useEffect)(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}var fr=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,CreditsClient,CreditsError,CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_SMOOTH_CHARS_PER_FRAME,DEFAULT_SMOOTH_THRESHOLD,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,ReprojectedVideo,Session,StatusBadge,StatusBadgeSchema,Text,TextStream,TextStreamError,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunCreditsGate,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionPaused,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createCreditsClient,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,textDelta,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useCredits,useDocStore,useGenerationTick,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useReferenceImage,useRequest,useSession,useSessionDirectory,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionStats,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useText,useTextMeter,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
2
+ "use strict";var gr=Object.defineProperty;var Mo=Object.getOwnPropertyDescriptor;var _o=Object.getOwnPropertyNames;var No=Object.prototype.hasOwnProperty;var Io=(e,t)=>{for(var r in t)gr(e,r,{get:t[r],enumerable:!0})},Oo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _o(t))!No.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=Mo(t,n))||o.enumerable});return e};var Lo=e=>Oo(gr({},"__esModule",{value:!0}),e);var hs={};Io(hs,{Audio:()=>Nt,Camera:()=>Vr,ComponentRenderer:()=>An,CreditsClient:()=>Ge.CreditsClient,CreditsError:()=>Ge.CreditsError,CreditsUnauthorizedError:()=>Ge.CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS:()=>Dr,DEFAULT_LOG_CAP:()=>Be,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Ar,DEFAULT_SMOOTH_THRESHOLD:()=>Mr,DEFAULT_VOICE_CONSTRAINTS:()=>Ir,DocPatchForm:()=>Lt,Image:()=>Gn,ImageFrame:()=>Vn,ImageFrameSchema:()=>Dn,MetricsPanel:()=>Hn,MetricsPanelSchema:()=>Fn,Mic:()=>to,OPERATOR_CHORD_LABEL:()=>Zr,OPERATOR_TOKEN_STORAGE_KEY:()=>Jr,ProgressCard:()=>_n,ProgressCardSchema:()=>Mn,ReprojectedVideo:()=>xn,Session:()=>hn,StatusBadge:()=>In,StatusBadgeSchema:()=>Nn,Text:()=>jn,TextStream:()=>Ln,TextStreamError:()=>ct,TextStreamSchema:()=>On,UrunActivationOverlay:()=>ur,UrunAudio:()=>Yn,UrunAuthProvider:()=>Ct,UrunCamera:()=>ro,UrunControlSender:()=>fo,UrunCreditsGate:()=>Ro,UrunDocPanel:()=>po,UrunErrorBoundary:()=>nt,UrunEventSpine:()=>go,UrunIdleWarning:()=>Po,UrunJwtProvider:()=>Gr,UrunProvider:()=>nn,UrunSessionClock:()=>ko,UrunSessionEnded:()=>Co,UrunSessionGate:()=>yo,UrunSessionPaused:()=>Hr,UrunSessionStatus:()=>vo,UrunSessionWaking:()=>sr,UrunStreamTail:()=>lo,UrunVoice:()=>Qn,Video:()=>Je,Voice:()=>It,authMode:()=>Tt,createCreditsClient:()=>Ge.createCreditsClient,createDocStore:()=>zt,describeSessionPhase:()=>fr.describeSessionPhase,formatPayload:()=>ft,getUrunAudioContext:()=>Pt,isWakingPhase:()=>fr.isWakingPhase,parseJsonObject:()=>Zt,pushCapped:()=>Ve,readOperatorToken:()=>Sr,registerComponent:()=>wn,resumeUrunAudioContext:()=>ze,textDelta:()=>Ur,urunPublicEnv:()=>Re,useActivation:()=>ir,useApp:()=>an,useChat:()=>gn,useCompletion:()=>pn,useConfirmOnLeave:()=>Ht,useCredits:()=>dr,useDocStore:()=>mt,useGenerationTick:()=>co,useImageFrame:()=>Er,useInputPresence:()=>Sn,useMetricsPanel:()=>wr,useOperatorOverride:()=>Ft,useProgressCard:()=>Pr,useReferenceImage:()=>no,useRequest:()=>ln,useSession:()=>vn,useSessionDirectory:()=>cn,useSessionDoc:()=>uo,useSessionEndsAt:()=>Fr,useSessionIdle:()=>Wr,useSessionPhase:()=>be,useSessionStats:()=>wo,useSessionTrack:()=>oo,useSessionWake:()=>or,useStatusBadge:()=>Rr,useStreamMessages:()=>er,useText:()=>_r,useTextMeter:()=>Bn,useTextStream:()=>xr,useUrunAudioLevel:()=>Gt,useUrunAuth:()=>Dt,useUrunPrewake:()=>Eo,usesWorkOSAuth:()=>Kr});module.exports=Lo(hs);var ue=require("react");var Br=require("react"),bt=require("react/jsx-runtime"),nt=class extends Br.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,bt.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,bt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,bt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var jr=require("react"),qe=(0,jr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Re(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ne(typeof process<"u"?process.env?.[e]:void 0)}}function Tt(){let e=Re("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Re("VERCEL_ENV")==="production"?"workos":Re("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Kr(){return Tt()==="workos"}var ot=require("react"),Xr=require("react/jsx-runtime"),$r=(0,ot.createContext)(null);function Ct({getAccessToken:e,children:t}){let r=(0,ot.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Xr.jsx)($r.Provider,{value:r,children:t})}var Gr=Ct;function Dt(){return(0,ot.useContext)($r)}var Vt=require("react"),Jr="urun.operator_token",Yr=null,zr="op",Zr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Qr(){return typeof window<"u"}function Sr(){return Yr}function Do(){if(!Qr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(zr);if(!r)return null;Yr=r,t.delete(zr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Vo(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Ft(e){let t=(0,Vt.useRef)(e);t.current=e,(0,Vt.useEffect)(()=>{if(!Qr())return;Do();let r=o=>{if(!Vo(o))return;let n=Sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var en=require("react");function Ht(e=!0){(0,en.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var Ie=require("react/jsx-runtime"),Fo="/api/urun-token",Ho=1e4;function qo(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function tn(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function rn(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function hr(e){let t=e===void 0?void 0:JSON.stringify(e);return(0,ue.useMemo)(()=>e,[t])}function Wo(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Ie.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Ie.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Ie.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function nn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:v,sessionStats:E,confirmOnLeave:k=!1,fallback:d,errorFallback:R,children:S}){let h=n===void 0&&t===void 0;if(!h&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!h&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let y=r??o;if(h&&(typeof y!="string"||y.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Ht(k);let[p,P]=(0,ue.useState)(),[C,U]=(0,ue.useState)(null),A=(0,ue.useRef)(void 0),m=(0,ue.useRef)(null),[x,b]=(0,ue.useState)(null);Ft(M=>b({jwt:M}));let N=Dt(),$=Re("NEXT_PUBLIC_SESSION_TOKEN")??Re("NEXT_PUBLIC_URUN_JWT"),G=Tt(),O=x!==null,J=G==="workos"&&!n&&!O&&!h,ae=n??(G==="jwt"?$:void 0)??p?.token,te=O?x.jwt:ae,Ce=s??Re("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),w=J&&!te&&!N?.getAccessToken,V=t??p?.orgId,K=e??p?.gatewayUrl,B=h&&p===void 0,L=h&&p!==void 0&&!K?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,z=w?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,pe=C??L??z,se=rn("NEXT_PUBLIC_URUN_TOKEN_URL",Re("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Fo,ce=rn("NEXT_PUBLIC_URUN_EVENTS_URL",Re("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,we=(0,ue.useCallback)(async M=>{if(!M?.forceRefresh){let Z=A.current;if(!Z)return Z;let he=qo(Z);if(he===null||he-Date.now()>Ho)return Z}return(await(m.current??(m.current=(async()=>{try{let Z=await tn(se);return A.current=Z.token,P(Z),Z}finally{m.current=null}})()))).token},[se]),Se=(0,ue.useCallback)(async()=>te,[te]),He=typeof te=="string"&&te.trim().length>0,me=J?N?.getAccessToken:h&&!O?we:He?Se:void 0,le=hr(g),ne=hr(v),T=hr(E),F=(0,ue.useMemo)(()=>({appId:y,baseUrl:K??"",orgId:V??"",jwt:te,getAccessToken:J?N?.getAccessToken:h&&!O?we:void 0,authProvider:Ce,eventsUrl:ce,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:le,videoPlayout:ne,sessionStats:T,priority:O?"preempt":void 0}),[y,N,K,Ce,te,ce,V,a,u,f,l,le,ne,T,J,O,h,we]);return(0,ue.useEffect)(()=>{if(!h)return;let M=new AbortController;return U(null),(async()=>{try{let W=await tn(se,M.signal);A.current=W.token,P(W)}catch(W){if(M.signal.aborted)return;U(W instanceof Error?W:new Error(String(W)))}})(),()=>M.abort()},[h,se]),(0,Ie.jsx)(nt,{fallback:d,children:pe?Wo(R,pe):B?(0,Ie.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Ie.jsx)(qe.Provider,{value:F,children:me?(0,Ie.jsx)(Ct,{getAccessToken:me,children:S}):S})})}var fe=require("react"),on=require("@urun-sh/core");function sn(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Bo(e,t,r){let o=sn(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function jo(e,t,r,o){let n=sn(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var Xe=new Map;var vr=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},yr=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},kr=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}watchDownlinkStall(t={}){return this._session.watchDownlinkStall?this._session.watchDownlinkStall(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new vr(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new yr(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function an(){let e=(0,fe.useContext)(qe);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,fe.useReducer)(i=>i+1,0),r=(0,fe.useRef)(new Map),o=(0,fe.useRef)(new Map),n=(0,fe.useRef)(null),s=(0,fe.useMemo)(()=>(0,on.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return(0,fe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Xe.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let f=Xe.get(c);f===u&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(c,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let l=Xe.get(c);!l||l.refCount!==0||(Xe.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),(0,fe.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let f=(l,g)=>{let v=Bo(c,l,g),E=r.current.get(v);if(E&&!E.disposed)return E;let k=jo(e,c,l,g),d=Xe.get(k);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),Xe.delete(k),o.current.get(k)===d&&o.current.delete(k),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new kr(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Xe.set(k,d)),o.current.get(k)!==d&&(o.current.set(k,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(v,d.handle),d.handle};return i.set(c,f),f}})},[e,s])}var qt=require("react"),un=require("@urun-sh/core");function cn(){let e=(0,qt.useContext)(qe);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return(0,qt.useMemo)(()=>(0,un.sessionDirectory)(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}var oe=require("react");function st(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Ko(e){return e instanceof Error?e:new Error(String(e))}function ln(e,t){let r=(0,oe.useMemo)(()=>st(e),[e]),[o,n]=(0,oe.useState)(void 0),[s,i]=(0,oe.useState)(null),[a,c]=(0,oe.useState)(!1),u=(0,oe.useRef)(t);u.current=t;let f=(0,oe.useRef)(0),l=(0,oe.useRef)(null),g=(0,oe.useRef)(!0);(0,oe.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=(0,oe.useCallback)(async d=>{l.current?.abort();let R=new AbortController;l.current=R;let S=++f.current,h=()=>g.current&&f.current===S;h()&&(c(!0),i(null));try{let y=await r.request(d,{...u.current,signal:R.signal});return h()&&(n(y),c(!1),u.current?.onSuccess?.(y)),y}catch(y){let p=Ko(y);throw h()&&(i(p),c(!1),u.current?.onError?.(p)),p}},[r]),E=(0,oe.useCallback)(d=>{v(d).catch(()=>{})},[v]),k=(0,oe.useCallback)(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:E,mutateAsync:v,data:o,error:s,isPending:a,reset:k}}var ie=require("react");function dn(e){return e instanceof Error?e:new Error(String(e))}var $o=e=>typeof e=="string"?e:String(e);function pn(e,t){let r=(0,ie.useMemo)(()=>st(e),[e]),[o,n]=(0,ie.useState)(""),[s,i]=(0,ie.useState)(!1),[a,c]=(0,ie.useState)(null),u=(0,ie.useRef)(t);u.current=t;let f=(0,ie.useRef)(0),l=(0,ie.useRef)(null),g=(0,ie.useRef)(!0);(0,ie.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=(0,ie.useCallback)(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),E=(0,ie.useCallback)(async k=>{l.current?.cancel();let d=++f.current,R=()=>g.current&&f.current===d,S=u.current,h=S?.parseChunk??$o,y=S?.buildPayload??(b=>({prompt:b}));R()&&(n(""),c(null),i(!0));let{parseChunk:p,buildPayload:P,onFinish:C,onError:U,...A}=S??{},m="",x;try{x=r.requestStream(y(k),A),l.current=x}catch(b){let N=dn(b);R()&&(c(N),i(!1),S?.onError?.(N));return}try{for await(let b of x){if(f.current!==d)break;m+=h(b),R()&&n(m)}R()&&(i(!1),S?.onFinish?.(m))}catch(b){let N=dn(b);R()&&(c(N),i(!1),S?.onError?.(N))}finally{l.current===x&&(l.current=null)}},[r]);return{completion:o,complete:E,stop:v,isStreaming:s,error:a}}var ee=require("react");function mn(e){return e instanceof Error?e:new Error(String(e))}var Go=e=>typeof e=="string"?e:String(e),fn=0;function br(e){return fn+=1,`${e}-${fn}`}function gn(e,t){let r=(0,ee.useMemo)(()=>st(e),[e]),[o,n]=(0,ee.useState)(()=>(t?.initialMessages??[]).map(h=>({id:h.id??br("msg"),role:h.role,content:h.content}))),[s,i]=(0,ee.useState)(""),[a,c]=(0,ee.useState)(!1),[u,f]=(0,ee.useState)(null),l=(0,ee.useRef)(t);l.current=t;let g=(0,ee.useRef)(o);g.current=o;let v=(0,ee.useRef)(s);v.current=s;let E=(0,ee.useRef)(0),k=(0,ee.useRef)(null),d=(0,ee.useRef)(!0);(0,ee.useEffect)(()=>(d.current=!0,()=>{d.current=!1,k.current?.cancel(),k.current=null}),[]);let R=(0,ee.useCallback)(()=>{E.current++,k.current?.cancel(),k.current=null,d.current&&c(!1)},[]),S=(0,ee.useCallback)(async h=>{let y=h===void 0,p=(y?v.current:h)??"";if(!p.trim())return;k.current?.cancel();let C=++E.current,U=()=>d.current&&E.current===C,A=l.current,m=A?.parseChunk??Go,x={id:br("msg"),role:"user",content:p},b={id:br("msg"),role:"assistant",content:""},N=[...g.current,x].map(L=>({role:L.role,content:L.content})),$=[...g.current,x,b];g.current=$,n($),y&&i(""),f(null),c(!0);let G=A?.buildPayload??(L=>({messages:L})),{initialMessages:O,parseChunk:J,buildPayload:ae,onFinish:te,onError:Ce,...w}=A??{},V=L=>{n(z=>z.map(pe=>pe.id===b.id?{...pe,content:L}:pe))},K="",B;try{B=r.requestStream(G(N),w),k.current=B}catch(L){let z=mn(L);U()&&(f(z),c(!1),A?.onError?.(z));return}try{for await(let L of B){if(E.current!==C)break;K+=m(L),U()&&V(K)}U()&&(c(!1),A?.onFinish?.({...b,content:K}))}catch(L){let z=mn(L);U()&&(f(z),c(!1),A?.onError?.(z))}finally{k.current===B&&(k.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:S,stop:R,isStreaming:a,error:u}}var Q=require("react"),it=require("@urun-sh/core"),Tr=[];function Sn(e,t={}){let{field:r=it.INPUT_PRESENCE_FIELD,hz:o=it.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,Q.useMemo)(()=>s?(0,it.createInputPresencePublisher)({awareness:{setLocalStateField:(p,P)=>s.setField(p,P)},field:r,hz:o}):null,[s,r,o]),a=(0,Q.useRef)(null);a.current=i;let[c,u]=(0,Q.useState)(!1),[f,l]=(0,Q.useState)(Tr),g=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let v=(0,Q.useCallback)(()=>{let p=a.current;l(p?p.heldKeys():Tr)},[]),E=(0,Q.useCallback)(()=>{a.current?.clear(),l(Tr)},[]);(0,Q.useEffect)(()=>{if(!n)return;let p=()=>!!n.pointerLockElement,P=()=>{if(p()){g.current=!1,u(!0);return}g.current||(u(!1),E())},C=b=>{p()&&(a.current?.keyDown(b.key),v())},U=b=>{a.current?.keyUp(b.key),v()},A=b=>{p()&&a.current?.movePointer(b.movementX,b.movementY)},m=b=>{p()&&a.current?.setButtons(b.buttons)},x=()=>{E()};return n.addEventListener("pointerlockchange",P),n.addEventListener("keydown",C),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",m),n.addEventListener("mouseup",m),n.defaultView?.addEventListener("blur",x),()=>{n.removeEventListener("pointerlockchange",P),n.removeEventListener("keydown",C),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",m),n.removeEventListener("mouseup",m),n.defaultView?.removeEventListener("blur",x)}},[n,E,v]);let k=(0,Q.useCallback)(p=>{p.requestPointerLock?.()},[]),d=(0,Q.useCallback)(()=>{g.current=!0,u(!0)},[]),R=(0,Q.useCallback)(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),E()},[n,E]),S=(0,Q.useCallback)(p=>{a.current?.keyDown(p),v()},[v]),h=(0,Q.useCallback)(p=>{a.current?.keyUp(p),v()},[v]),y=(0,Q.useCallback)((p,P)=>{a.current?.movePointer(p,P)},[]);return{engage:k,engageTouch:d,release:R,engaged:c,heldKeys:f,pressKey:S,releaseKey:h,movePointer:y}}var de=require("react"),Rn=require("@urun-sh/core");var D=require("react"),Pn=require("@urun-sh/core");var Wt=null;function Xo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Pt(){if(Wt)return Wt;let e=Xo();return e?(Wt=new e,Wt):null}function ze(){let e=Pt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Rt=require("react"),yn=require("react/jsx-runtime"),Cr=(0,Rt.createContext)(null);function hn({session:e,children:t}){return(0,yn.jsx)(Cr.Provider,{value:e,children:t})}function Ue(){return(0,Rt.useContext)(Cr)}function vn(){let e=(0,Rt.useContext)(Cr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var xt=require("react/jsx-runtime");function zo(e,t){return e-t>>>0<2147483648}var kn=1e3;function bn(...e){console.debug("[video]",...e)}function Tn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function Cn(e,t,r){return r?[r,t]:[e,t]}var Je=(0,D.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:f,style:l,videoClassName:g,placeholder:v,poster:E,children:k,onTrack:d,onFirstFrame:R,frameMarker:S,onFrameMarkerReached:h,onFrameMarkerUnsupported:y,onUnlockChange:p}=t,P=Ue(),C=o??P,U=(0,D.useRef)(null),A=(0,D.useRef)(null),[m,x]=(0,D.useState)(!1),[b,N]=(0,D.useState)(!1),$=(0,D.useRef)(!1),G=(0,D.useRef)(null),O=(0,D.useRef)(d);O.current=d;let J=(0,D.useRef)(p);J.current=p;let ae=(0,D.useRef)(R);ae.current=R;let te=(0,D.useRef)(h);te.current=h;let Ce=(0,D.useRef)(y);Ce.current=y;let w=(0,D.useRef)(S??null);w.current=S??null;let V=(0,D.useCallback)(T=>{G.current!==T&&(G.current=T,J.current?.(T))},[]),K=(0,D.useRef)(null),B=(0,D.useRef)(null),L=(0,D.useCallback)((T,F=!1)=>{if(!F&&T===K.current||(K.current=T,B.current?.(),B.current=null,$.current=!1,N(!1),!T))return;let M=U.current;if(!M)return;let W=w.current,Z=W?.rtpTimestamp??null,he=!1,I=()=>{he||(he=!0,Ce.current?.())};W&&Z==null&&I();let Ae=W!=null&&Z!=null,tt=_e=>{B.current?.(),B.current=null,$.current=!0,N(!0),ae.current?.(),_e&&te.current?.()};if(typeof M.requestVideoFrameCallback=="function"){let _e=!1,H=0,q=(ve,ye)=>{if(!_e){if(Ae){let Pe=ye?.rtpTimestamp;if(typeof Pe!="number"){I(),tt(!1);return}if(!zo(Pe,Z)){H=M.requestVideoFrameCallback(q);return}tt(!0);return}tt(!1)}};H=M.requestVideoFrameCallback(q),B.current=()=>{_e=!0,M.cancelVideoFrameCallback?.(H)};return}Ae&&I();let Me=()=>{let _e=M.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:M.readyState>=2&&M.videoWidth>0)&&tt(!1)};M.addEventListener("loadeddata",Me),M.addEventListener("timeupdate",Me),M.addEventListener("playing",Me),B.current=()=>{M.removeEventListener("loadeddata",Me),M.removeEventListener("timeupdate",Me),M.removeEventListener("playing",Me)},Me()},[]);(0,D.useEffect)(()=>()=>{B.current?.(),B.current=null},[]);let z=S==null?null:`${S.rtpTimestamp??""}|${S.ptsMs??""}`,pe=(0,D.useRef)(z);(0,D.useEffect)(()=>{if(pe.current===z||(pe.current=z,z==null))return;let T=K.current;T&&L(T,!0)},[z,L]);let se=(0,D.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let T=U.current;return T&&T.srcObject!==A.current&&(T.srcObject=A.current),A.current},[]),ce=(0,D.useCallback)(T=>{let F=U.current;if(!F)return;let M=F.play();!M||typeof M.then!="function"||M.then(()=>{F.muted||V(!0)}).catch(W=>{if((W instanceof Error?W.name:String(W))==="NotAllowedError"&&!F.muted){bn(`play() blocked pending a user gesture (${T})`),V(!1);return}bn(`play() failed (${T})`,W)})},[V]),we=(0,D.useCallback)(()=>{let T=U.current;T&&(se(),!T.muted&&(ce("gesture"),ze(),V(!0)))},[se,ce,V]),Se=(0,D.useCallback)(T=>{let F=se();if(F){for(let M of F.getVideoTracks())M!==T&&F.removeTrack(M);if(T&&!F.getVideoTracks().includes(T)){F.addTrack(T);let M=U.current;M&&(M.srcObject=F)}T&&ce("track-attach"),x(T!==null),L(T),O.current?.(T)}},[se,ce,L]),He=(0,D.useCallback)(T=>{let F=se();if(F){for(let M of F.getAudioTracks())M!==T&&F.removeTrack(M);T&&!F.getAudioTracks().includes(T)&&F.addTrack(T),T&&ce("audio-attach")}},[se,ce]),me=(0,D.useCallback)(T=>{U.current=T,T&&(a?(T.muted=!0,T.defaultMuted=!0,T.setAttribute("muted",""),G.current=null):(T.muted=!1,T.defaultMuted=!1,T.removeAttribute("muted")),T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),se())},[se,a]);(0,D.useImperativeHandle)(r,()=>({get element(){return U.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return $.current},unlock:we,get unlocked(){return G.current===!0}}),[we]);let le=(0,Pn.derivedLegRole)(n)!==void 0;(0,D.useEffect)(()=>{le&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[le,n]);let ne=i!==void 0;return(0,D.useEffect)(()=>{if(ne){Se(i??null);return}if(le){Se(null);return}if(!C)return;let T=Tn(C,Cn(n,"video")),F=()=>{let I=A.current;return I?I.getVideoTracks()[0]??null:null},M=I=>{if(I!==F()&&(Se(I),I)){let Ae=()=>{F()===I&&Se(null)};I.addEventListener("ended",Ae)}},W=T.track;W&&W.readyState==="live"&&M(W);let Z=T.on("track",I=>{I&&I.readyState!=="live"||M(I)}),he=setInterval(()=>{let I=T.track;I&&I.readyState==="live"&&M(I)},kn);return()=>{Z(),clearInterval(he)}},[C,n,le,ne,i,Se]),(0,D.useEffect)(()=>{if(ne||!C||s===!1||le)return;let T=Tn(C,Cn(n,"audio",s)),F=()=>{let I=A.current;return I?I.getAudioTracks()[0]??null:null},M=I=>{if(I!==F()&&(He(I),I)){let Ae=()=>{F()===I&&He(null)};I.addEventListener("ended",Ae)}},W=T.track;W&&W.readyState==="live"&&M(W);let Z=T.on("track",I=>{I&&I.readyState!=="live"||M(I)}),he=setInterval(()=>{let I=T.track;I&&I.readyState==="live"&&M(I)},kn);return()=>{Z(),clearInterval(he)}},[C,n,le,s,ne,He]),(0,xt.jsxs)("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":m?"true":"false","data-urun-video-framed":b?"true":"false",children:[(0,xt.jsx)("video",{ref:me,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),m?null:v,E===void 0?null:(0,xt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":b||void 0,style:{position:"absolute",inset:0,...b?{opacity:0,pointerEvents:"none"}:null},children:E}),k]})});var Et=require("react/jsx-runtime"),Jo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},xn=(0,de.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...f}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=(0,de.useRef)(null),v=(0,de.useRef)(null),E=(0,de.useRef)(0),k=(0,de.useRef)(f);k.current=f;let d=(0,de.useMemo)(()=>(0,Rn.createCameraWarp)(k.current),[]);return(0,de.useImperativeHandle)(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:d,get lastDrawTs(){return E.current}}),[d]),(0,de.useEffect)(()=>{if(!i)return;let R=0,S=0,h=null,y=P=>{typeof P.requestVideoFrameCallback=="function"&&(h=P,S=P.requestVideoFrameCallback(function C(){d.frameArrived(),S=P.requestVideoFrameCallback(C)}))},p=P=>{R=requestAnimationFrame(p);let C=v.current,U=g.current?.element??null;if(!C||!U||(U!==h&&(h&&S&&h.cancelVideoFrameCallback?.(S),y(U)),U.readyState<2))return;d.tick(P);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,m=Math.max(1,Math.round(C.clientWidth*A)),x=Math.max(1,Math.round(C.clientHeight*A));(C.width!==m||C.height!==x)&&(C.width=m,C.height=x);let b=C.getContext("2d");if(!b)return;let N=d.transform(),$=U.videoWidth||m,G=U.videoHeight||x,J=Math.max(m/$,x/G)*(1+a)*N.scale;b.setTransform(J,0,0,J,m/2+N.translateX*m,x/2+N.translateY*x),b.drawImage(U,-$/2,-G/2),E.current=P};return R=requestAnimationFrame(p),()=>{cancelAnimationFrame(R),h&&S&&h.cancelVideoFrameCallback?.(S)}},[i,a,d]),(0,de.useEffect)(()=>{if(!i||!c||!l)return;let R=()=>!!l.pointerLockElement,S=C=>{R()&&d.keyDown(C.key)},h=C=>d.keyUp(C.key),y=C=>{R()&&d.pointerDelta(C.movementX,C.movementY)},p=()=>{R()||d.clearKeys()},P=()=>d.clearKeys();return l.addEventListener("keydown",S),l.addEventListener("keyup",h),l.addEventListener("mousemove",y),l.addEventListener("pointerlockchange",p),l.defaultView?.addEventListener("blur",P),()=>{l.removeEventListener("keydown",S),l.removeEventListener("keyup",h),l.removeEventListener("mousemove",y),l.removeEventListener("pointerlockchange",p),l.defaultView?.removeEventListener("blur",P)}},[i,c,l,d]),i?(0,Et.jsxs)(Je,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Et.jsx)("canvas",{ref:v,style:Jo,"data-urun-warp":""}),n]}):(0,Et.jsx)(Je,{ref:g,...s,children:n})});var En=new Map;function wn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);En.set(e,{component:t,schema:r})}function Un(e,t){let r=En.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Ye=require("react/jsx-runtime");function An({name:e,props:t,fallback:r}){let o=Un(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ye.jsx)(Ye.Fragment,{children:r}):(0,Ye.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ye.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ye.jsx)(n,{...o.validatedProps})}var at=require("zod"),Ze=require("react/jsx-runtime"),Mn=at.z.object({step:at.z.number().min(0),total:at.z.number().min(1),label:at.z.string().optional(),variant:at.z.enum(["default","success","error"]).default("default")});function Pr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function _n(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Pr(e);return(0,Ze.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Ze.jsx)("div",{className:"urun-progress-label",children:o}),(0,Ze.jsx)("div",{className:"urun-progress-bar",children:(0,Ze.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Ze.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Bt=require("zod"),wt=require("react/jsx-runtime"),Nn=Bt.z.object({state:Bt.z.enum(["thinking","generating","idle","error"]),message:Bt.z.string().optional()}),Yo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Rr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Yo[t]??t;return{state:t,message:n,isActive:o}}function In(e){let{state:t,message:r,isActive:o}=Rr(e);return(0,wt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,wt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,wt.jsx)("span",{className:"urun-status-message",children:r})]})}var Ut=require("react"),jt=require("zod"),At=require("react/jsx-runtime"),On=jt.z.object({text:jt.z.string(),streaming:jt.z.boolean().default(!1)});function xr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Ln(e){let{text:t,streaming:r}=xr(e),o=(0,Ut.useRef)(null),n=(0,Ut.useRef)(0);return(0,Ut.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,At.jsxs)("div",{className:"urun-text-stream",children:[(0,At.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,At.jsx)("span",{className:"urun-text-cursor"})]})}var Mt=require("zod"),_t=require("react/jsx-runtime"),Dn=Mt.z.object({src:Mt.z.string().url(),alt:Mt.z.string().optional(),caption:Mt.z.string().optional()});function Er(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Vn(e){let{src:t,alt:r,caption:o}=Er(e);return(0,_t.jsxs)("figure",{className:"urun-image-frame",children:[(0,_t.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,_t.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Oe=require("zod"),ut=require("react/jsx-runtime"),Fn=Oe.z.object({metrics:Oe.z.array(Oe.z.object({label:Oe.z.string(),value:Oe.z.union([Oe.z.string(),Oe.z.number()]),unit:Oe.z.string().optional()}))});function wr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Hn(e){let{metrics:t}=wr(e);return(0,ut.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ut.jsxs)("div",{className:"urun-metric-card",children:[(0,ut.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ut.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var X=require("react"),Kn=require("react/jsx-runtime");function We(e){return e&&typeof e=="object"?e:null}function Ur(e){if(typeof e=="string")return e;let t=We(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function Zo(e){if(typeof e=="string")return"delta";let t=We(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function Qo(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function es(e){let t=We(e),r=t?.body;return Qo(r,We(We(r)?.error)?.message,We(r)?.error,We(r)?.message,We(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var ct=class extends Error{name="TextStreamError"},ts=4,Ar=3,Mr=240,qn=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function Wn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function rs(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function _r(e){let{session:t,stream:r}=e,o=(0,X.useRef)(e);(0,X.useEffect)(()=>{o.current=e});let n=(0,X.useRef)(null),s=(0,X.useRef)(()=>{}),i=(0,X.useRef)(null),a=(0,X.useRef)(""),c=(0,X.useRef)(""),u=(0,X.useRef)(null),f=(0,X.useRef)(!1),l=(0,X.useRef)(!1),g=(0,X.useRef)(!1),v=(0,X.useRef)(null),E=(0,X.useRef)(Wn()),k=(0,X.useCallback)(h=>{if(n.current=h,!h){i.current=null;return}let y=i.current;if(y&&y.parentNode===h)return;let p=h.ownerDocument.createTextNode(c.current);h.appendChild(p),i.current=p,a.current.length>0&&s.current()},[]),d=(0,X.useCallback)(()=>{u.current=null;let h=i.current,y=a.current;if(y.length>0){let A=o.current,m=A.smoothCharsPerFrame??Ar,x=A.smoothThreshold??Mr,b=A.smooth&&y.length<=x?y.slice(0,m):y;a.current=y.slice(b.length),c.current+=b,h?.appendData(b)}let p=E.current,P=c.current.length,C=v.current===null?0:Math.max(0,qn()-v.current),U=Math.round(P/ts);if(p.chars=P,p.tokens=U,p.elapsedMs=C,p.tokensPerSecond=C>0?U*1e3/C:0,a.current.length>0){R(),o.current.onMeter?.(p);return}if(!f.current&&!g.current){g.current=!0,p.done=!0,o.current.onMeter?.(p),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(p)},[]),R=(0,X.useCallback)(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>d()))},[d]);s.current=R,(0,X.useEffect)(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,v.current=null,f.current=!0,rs(E.current),i.current&&(i.current.data="");let h=!1,y=null;return(async()=>{try{for(y=t.stream(r).messages()[Symbol.asyncIterator]();;){let P=await y.next();if(h)return;if(P.done)break;let C=P.value,U=Zo(C);if(U==="error")throw new ct(es(C));if(U==="done")break;if(U==="ignore")continue;let A=Ur(C);A&&(v.current===null&&(v.current=qn()),a.current+=A,R())}if(h)return;y.return?.(void 0),f.current=!1,R()}catch(p){if(h)return;y?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(p instanceof Error?p:new ct(String(p))),R()}})(),()=>{h=!0,f.current=!1,y?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,R]);let S=(0,X.useCallback)(()=>c.current,[]);return{ref:k,meterRef:E,getText:S}}function Bn(e,t=250){let[r,o]=(0,X.useState)(Wn);return(0,X.useEffect)(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function jn(e){let{className:t,style:r,...o}=e,{ref:n}=_r(o);return(0,Kn.jsx)("span",{ref:n,className:t,style:r})}var $n=require("react");var Xn=require("react/jsx-runtime"),Gn=(0,$n.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Xn.jsx)(Je,{ref:r,stream:o,...n})});var Y=require("react"),Jn=require("@urun-sh/core");var Zn=require("react/jsx-runtime"),ns=1e3,zn=200;function Nr(...e){console.debug("[audio]",...e)}var Nt=(0,Y.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f}=t,l=Ue(),g=o??l,v=(0,Y.useRef)(null),E=(0,Y.useRef)(null),k=(0,Y.useRef)(null),d=(0,Y.useRef)(null),R=(0,Y.useRef)(c);R.current=c;let S=(0,Y.useRef)(u);S.current=u;let h=(0,Y.useCallback)(m=>{k.current!==m&&(k.current=m,S.current?.(m))},[]),y=(0,Y.useCallback)(()=>{if(typeof MediaStream>"u")return null;E.current||(E.current=new MediaStream);let m=v.current;return m&&m.srcObject!==E.current&&(m.srcObject=E.current),E.current},[]),p=(0,Y.useCallback)(m=>{let x=v.current;if(!x)return;let b=x.play();!b||typeof b.then!="function"||b.then(()=>{x.muted||h(!0)}).catch(N=>{let $=N instanceof Error?N.name:String(N);if($==="AbortError"){Nr(`play() aborted (${m}); retrying in ${zn}ms`),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,p(`${m}:retry`)},zn);return}if($==="NotAllowedError"){Nr(`play() blocked pending a user gesture (${m})`),h(!1);return}Nr(`play() failed (${m})`,N)})},[h]),P=(0,Y.useCallback)(m=>{let x=y();if(x){for(let b of x.getAudioTracks())b!==m&&x.removeTrack(b);m&&!x.getAudioTracks().includes(m)&&x.addTrack(m),m&&p("track-attach"),R.current?.(m)}},[y,p]),C=(0,Y.useCallback)(()=>{let m=v.current;m&&(y(),m.muted=!1,p("gesture"),ze(),h(!0))},[y,p,h]);(0,Y.useImperativeHandle)(r,()=>({unlock:C,get unlocked(){return k.current===!0},get element(){return v.current}}),[C]);let U=(0,Y.useCallback)(m=>{v.current=m,m&&(m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),y()),f?.(m)},[y,f]),A=s!==void 0;return(0,Y.useEffect)(()=>{if(A){P(s??null);return}if(!g)return;let m=g.stream(n),x=()=>{let O=E.current;return O?O.getAudioTracks()[0]??null:null},b=O=>{if(O!==x()&&(P(O),O)){let J=()=>{x()===O&&P(null)};O.addEventListener("ended",J)}},N=m.track;N&&N.readyState==="live"&&b(N);let $=m.on("track",O=>{O&&O.readyState!=="live"||b(O)}),G=setInterval(()=>{let O=m.track;O&&O.readyState==="live"&&b(O)},ns);return()=>{$(),clearInterval(G)}},[g,n,A,s,P]),(0,Y.useEffect)(()=>(0,Jn.observePageLifecycle)(()=>{ze(),k.current===!0&&p("foreground")}),[p]),(0,Y.useEffect)(()=>()=>{d.current&&clearTimeout(d.current)},[]),(0,Zn.jsx)("audio",{ref:U,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Yn=Nt;var j=require("react"),lt=require("@urun-sh/core");var eo=require("react/jsx-runtime"),Ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Kt(...e){console.debug("[voice]",...e)}var It=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=Ir,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:E,onUnlockChange:k,capture:d}=t,R=Ue(),S=o??R,h=(0,j.useRef)(null),y=(0,j.useRef)(null),p=(0,j.useRef)(null),P=(0,j.useRef)([]),C=(0,j.useRef)(!1),U=(0,j.useRef)(l);U.current=l;let A=(0,j.useRef)(g);A.current=g;let m=(0,j.useRef)(v);m.current=v;let x=(0,j.useCallback)(w=>{C.current!==w&&(C.current=w,U.current?.(w))},[]),b=(0,j.useCallback)(()=>{for(let w of P.current)w();P.current=[],p.current?.release(),p.current=null,y.current&&(y.current=null,m.current?.(null))},[]),N=(0,j.useCallback)(async()=>{let w=p.current;if(w){let L=await w.update(a);return y.current=w.stream,m.current?.(w.stream),L}let K=await(d??(0,lt.sharedCaptureController)()).claim("audio",a);p.current=K,P.current=[K.onTrack((L,z)=>{y.current=z,m.current?.(z),C.current&&S?.stream(n).attach(L).catch(pe=>Kt("mic re-attach after one-capture re-acquire failed",pe))}),K.onLost(L=>{p.current=null,P.current=[],y.current=null,m.current?.(null),x(!1),A.current?.(L)})],y.current=K.stream,m.current?.(K.stream);let B=K.track;if(!B)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return B},[d,a,S,n,x]),$=(0,j.useCallback)(async()=>{b(),x(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,b,x]),G=(0,j.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");h.current?.unlock();let w;try{w=await N()}catch(B){b();let L=(0,lt.sessionFailureFromMediaError)(B,S.status);throw A.current?.(L),L}S.connect?.();let V;for(let B=1;B<=u;B++)try{await S.whenLive(c!==void 0?{timeout:c}:void 0),await S.stream(n).attach(w),x(!0);return}catch(L){V=L,Kt(`start attempt ${B}/${u} failed`,L),B<u&&await new Promise(z=>setTimeout(z,f))}b(),x(!1);let K=V instanceof Error?V:new Error(String(V??"voice start failed"));throw A.current?.(K),K},[S,n,c,u,f,N,b,x]);(0,j.useImperativeHandle)(r,()=>({start:G,stop:$,unlock:()=>h.current?.unlock(),get active(){return C.current},get micStream(){return y.current},get audio(){return h.current}}),[G,$]);let O=(0,j.useRef)(G);O.current=G;let J=(0,j.useRef)(null),ae=(0,j.useCallback)((w,V)=>{w.promise.then(()=>{V&&(b(),x(!1)),w.session.stream(w.streamName).detach().catch(()=>{})})},[b,x]);(0,j.useEffect)(()=>{if(!i||!S)return;let w=J.current;w&&(w.session!==S||w.streamName!==n)&&(w.disposeTimer&&clearTimeout(w.disposeTimer),ae(w,!1),w=null),w?w.disposeTimer&&(clearTimeout(w.disposeTimer),w.disposeTimer=null):(w={session:S,streamName:n,promise:O.current().catch(()=>{}),refCount:0,disposeTimer:null},J.current=w),w.refCount+=1;let V=w;return()=>{V.refCount-=1,!(V.refCount>0)&&(V.disposeTimer=setTimeout(()=>{J.current===V&&(J.current=null),ae(V,!0)},0))}},[i,S,n,ae]);let te=(0,j.useRef)(!1),Ce=(0,j.useCallback)(async()=>{if(!S||!C.current||te.current)return;let w=y.current?.getAudioTracks()[0]??null;if(w&&w.readyState==="live"){try{await S.stream(n).attach(w)}catch(V){Kt("foreground mic re-assert failed (will retry on next pass)",V)}return}te.current=!0;try{let V=await N();await S.stream(n).attach(V)}catch(V){let K=V instanceof Error?V:new Error(String(V));Kt("foreground mic re-acquire failed",K),A.current?.(K)}finally{te.current=!1}},[S,n,N]);return(0,j.useEffect)(()=>{let w=()=>{Ce()};return S&&typeof S.onRecovery=="function"?S.onRecovery(w):(0,lt.observePageLifecycle)(w)},[S,Ce]),(0,j.useEffect)(()=>b,[b]),s?(0,eo.jsx)(Nt,{ref:h,session:S,stream:n,onTrack:E,onUnlockChange:k}):null}),Qn=It;var De=require("react");var $t=require("react");var Or={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,$t.useState)(Or);return(0,$t.useEffect)(()=>{if(!e){i(Or);return}let a=Pt();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,f;try{u=a.createMediaStreamSource(c),f=a.createAnalyser(),f.fftSize=r,u.connect(f)}catch{return}let l=new Uint8Array(f.fftSize),v=setInterval(()=>{f.getByteTimeDomainData(l);let E=0;for(let d=0;d<l.length;d++){let R=(l[d]-128)/128;E+=R*R}let k=Math.sqrt(E/l.length);i(d=>{let R=k>n;return Math.abs(d.level-k)<.005&&d.speaking===R?d:{level:k,speaking:R}})},o);return()=>{clearInterval(v),u.disconnect(),i(Or)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),os={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ss={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},to=(0,De.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:f,onMicStream:l,capture:g}=t,v=Ue(),E=o??v,k=(0,De.useRef)(null),[d,R]=(0,De.useState)(null),S=(0,De.useRef)(l);S.current=l;let{level:h,speaking:y}=Gt(a?d:null);return(0,De.useImperativeHandle)(r,()=>({start:()=>{let p=k.current;return p?p.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>k.current?.stop()??Promise.resolve(),get active(){return k.current?.active??!1},get micStream(){return k.current?.micStream??null}}),[]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(It,{ref:k,session:E,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:p=>{R(p),S.current?.(p)}}),a?(0,Le.jsx)("span",{className:c,style:os,"data-urun-mic":"","data-urun-mic-active":d?"true":"false","data-urun-mic-speaking":y?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(h*100)/100,children:(0,Le.jsx)("span",{style:ss,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(h*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var dt=require("@urun-sh/core"),_=require("react");var ke=require("react/jsx-runtime"),Dr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Lr(...e){console.debug("[camera]",...e)}function is(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function as(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var Vr=(0,_.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:f="auto",connectTimeoutMs:l,visible:g=!1,className:v,videoClassName:E,onActiveChange:k,onError:d,onStream:R,onTrack:S,children:h,capture:y,flipControl:p="auto",flipControlClassName:P,onDevices:C}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":c??"environment",A=Ue(),m=o??A,x=(0,_.useRef)(null),b=(0,_.useRef)(null),N=(0,_.useRef)(null),$=(0,_.useRef)([]),G=(0,_.useRef)(null),O=(0,_.useRef)(!1),J=(0,_.useRef)(!1),ae=(0,_.useRef)(U),[te,Ce]=(0,_.useState)(U),[w,V]=(0,_.useState)(!1),[K,B]=(0,_.useState)(null),[L,z]=(0,_.useState)(!1),[pe]=(0,_.useState)(is),se=(0,_.useRef)(k);se.current=k;let ce=(0,_.useRef)(d);ce.current=d;let we=(0,_.useRef)(R);we.current=R;let Se=(0,_.useRef)(S);Se.current=S;let He=(0,_.useRef)(C);He.current=C;let me=(0,_.useCallback)(H=>{O.current!==H&&(O.current=H,V(H),se.current?.(H))},[]);(0,_.useEffect)(()=>{if(!w){B(null);return}let H=!1,q=()=>{as().then(ye=>{H||(B(ye),ye&&He.current?.(ye))})};q();let ve=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ve?.addEventListener=="function"?(ve.addEventListener("devicechange",q),()=>{H=!0,ve.removeEventListener?.("devicechange",q)}):()=>{H=!0}},[w]);let le=(0,_.useCallback)(H=>{let q=x.current;q&&(q.muted=!0,q.defaultMuted=!0,q.setAttribute("muted",""),q.setAttribute("playsinline",""),q.setAttribute("webkit-playsinline",""),q.srcObject=H,H&&q.play()?.catch?.(ve=>Lr("preview play() failed",ve)))},[]),ne=(0,_.useCallback)(()=>{J.current=!1,G.current?.(),G.current=null;for(let H of $.current)H();$.current=[],N.current?.release(),N.current=null,b.current&&(b.current=null,we.current?.(null),Se.current?.(null)),le(null)},[le]),T=(0,_.useCallback)((H,q)=>{G.current?.(),b.current=q,le(q),we.current?.(q);let ve=()=>{b.current===q&&(Lr("camera track ended (device removed or permission revoked)"),ne(),me(!1))};H.addEventListener("ended",ve),G.current=()=>H.removeEventListener("ended",ve)},[le,ne,me]),F=(0,_.useCallback)(async H=>{let q=n!==!1;if(q&&!m)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ve={...Dr,...s,facingMode:H},ye;try{let Pe=N.current;if(Pe)ye=await Pe.update(ve);else{let yt=await(y??(0,dt.sharedCaptureController)()).claim("video",ve);if(N.current=yt,$.current=[yt.onTrack((kt,Uo)=>{T(kt,Uo),O.current&&(!q||!m||m.stream(n).attachVideo(kt).then(()=>Se.current?.(kt)).catch(Ao=>Lr("camera re-publish after one-capture re-acquire failed",Ao)))}),yt.onLost(kt=>{N.current=null,$.current=[],ne(),me(!1),ce.current?.(kt)})],!yt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ye=yt.track}}catch(Pe){let rt=(0,dt.sessionFailureFromMediaError)(Pe,m?.status);throw ce.current?.(rt),rt}ae.current=H,Ce(H),T(ye,N.current?.stream??new MediaStream([ye]));try{q&&m&&(m.connect?.(),await m.whenLive(l!==void 0?{timeout:l}:void 0),await m.stream(n).attachVideo(ye)),J.current=q?n:!1}catch(Pe){ne(),me(!1);let rt=Pe instanceof Error?Pe:new Error(String(Pe));throw ce.current?.(rt),rt}Se.current?.(ye),me(!0)},[m,n,s,l,y,T,ne,me]),M=(0,_.useCallback)(H=>F(H?.facingMode??ae.current),[F]),W=(0,_.useCallback)(async H=>{let q=J.current===n;O.current&&ae.current===H&&q||await F(H)},[F,n]),Z=(0,_.useCallback)(()=>F(ae.current==="environment"?"user":"environment"),[F]),he=(0,_.useCallback)(async()=>{ne(),me(!1),n!==!1&&await m?.stream(n).detachVideo().catch(()=>{})},[m,n,ne,me]),I=(0,_.useCallback)(async H=>{let q=x.current;if(!q)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,dt.captureStillFromVideo)(q,H)},[]);(0,_.useImperativeHandle)(r,()=>({start:M,stop:he,flip:Z,setFacingMode:W,capturePhoto:I,get active(){return O.current},get facingMode(){return ae.current},get stream(){return b.current},get element(){return x.current}}),[M,he,Z,W,I]);let Ae=(0,_.useRef)(W);if(Ae.current=W,(0,_.useEffect)(()=>{u&&(n!==!1&&!m||Ae.current(U).catch(()=>{}))},[u,m,U,n]),(0,_.useEffect)(()=>ne,[ne]),!g)return null;let tt=f==="auto"?te==="user":f,Me=w&&(p===!0||p==="auto"&&pe&&(K?.length??0)>1),_e=()=>{L||(z(!0),Z().catch(()=>{}).finally(()=>z(!1)))};return(0,ke.jsxs)("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":te,children:[(0,ke.jsx)("video",{ref:x,className:E,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...tt?{transform:"scaleX(-1)"}:{}}}),Me?(0,ke.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:L,className:P,style:P?{opacity:L?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:L?.6:1},children:(0,ke.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,ke.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ke.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ke.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ke.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ke.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,h]})}),ro=(0,_.forwardRef)(function({preview:t=!0,...r},o){return(0,ke.jsx)(Vr,{ref:o,...r,visible:t,autoStart:!1})});var pt=require("@urun-sh/core"),re=require("react");function no(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,re.useState)(null),[a,c]=(0,re.useState)(null),[u,f]=(0,re.useState)(!1),[l,g]=(0,re.useState)(null),[v]=(0,re.useState)(pt.cameraCaptureAvailable),E=(0,re.useRef)(n);E.current=n;let k=(0,re.useRef)(null),d=(0,re.useRef)(0),R=(0,re.useCallback)(P=>{k.current&&URL.revokeObjectURL(k.current),k.current=P?URL.createObjectURL(new Blob([P.bytes],{type:P.type})):null,c(k.current),i(P),E.current?.(P)},[]);(0,re.useEffect)(()=>()=>{d.current++,k.current&&URL.revokeObjectURL(k.current),k.current=null},[]);let S=(0,re.useCallback)(async P=>{let C=++d.current;f(!0),g(null);try{let U=await P();if(d.current!==C)return;R(U)}catch(U){if(d.current!==C)return;g((0,pt.referenceImageErrorMessage)(U))}finally{d.current===C&&f(!1)}},[R]),h=(0,re.useCallback)(P=>S(()=>(0,pt.normalizeReferenceImage)(P,{maxSize:t,type:r,quality:o,source:"file"})),[S,t,r,o]),y=(0,re.useCallback)(P=>S(()=>P.capturePhoto({maxSize:t,type:r,quality:o})),[S,t,r,o]),p=(0,re.useCallback)(()=>{d.current++,g(null),f(!1),R(null)},[R]);return{reference:s,previewUrl:a,pick:h,capture:y,clear:p,busy:u,error:l,cameraAvailable:v}}var Xt=require("react");function oo(e,t){let[r,o]=(0,Xt.useState)(null);return(0,Xt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var ao=require("react");var Jt=require("react");var so=require("zustand/vanilla"),io=require("zustand"),us=()=>{};function zt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,so.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):us,c=(u=>(0,io.useStore)(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function mt(e,t){let r=(0,Jt.useMemo)(()=>zt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Jt.useEffect)(()=>r.bind(),[r]),r}function uo(e,t,r){let n=mt(e,t)(r??(a=>a)),s=(0,ao.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var Yt=require("react");function co(e){let[t,r]=(0,Yt.useState)(null);return(0,Yt.useEffect)(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}var Qt=require("react");var Be=200;function Ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ft(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Zt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function er(e,t,r={}){let o=r.cap??200,[n,s]=(0,Qt.useState)([]);return(0,Qt.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>Ve(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var xe=require("react/jsx-runtime");function lo({session:e,name:t,cap:r,className:o}){let n=er(e,t,{cap:r});return(0,xe.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,xe.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,xe.jsx)("code",{children:t}),(0,xe.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,xe.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,xe.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,xe.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,xe.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,xe.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ft(s.payload)]},`${s.at}-${i}`))})]})}var Ot=require("react");var ge=require("react/jsx-runtime");function Lt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,Ot.useState)(""),[i,a]=(0,Ot.useState)(null),c=(0,Ot.useCallback)(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return(0,ge.jsxs)("div",{className:"urun-doc-patch",children:[(0,ge.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,ge.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,ge.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?(0,ge.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function po({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=mt(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return(0,ge.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,ge.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,ge.jsx)("code",{children:t}),(0,ge.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,ge.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,ge.jsx)(Lt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}var tr=require("react");var Fe=require("react/jsx-runtime");function mo(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function fo({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,tr.useState)([]);return(0,tr.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ve(c,{at:Date.now(),direction:"in",text:mo(ft(a))},r))}):void 0),[e,t,r]),(0,Fe.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,Fe.jsx)(Lt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>Ve(c,{at:Date.now(),direction:"out",text:mo(a)},r))}}),(0,Fe.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,Fe.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,Fe.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Fe.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Fe.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var rr=require("react");var Qe=require("react/jsx-runtime");function go({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,rr.useState)([]),a=t.join(","),c=r.join(",");return(0,rr.useEffect)(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>Ve(v,{at:Date.now(),kind:l,text:g},o)),f=[];f.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);f.push(g.on("track",v=>u("track",`${l}: ${v?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);f.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>f.forEach(l=>l())},[e,a,c,o]),(0,Qe.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Qe.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,f)=>(0,Qe.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,Qe.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,Qe.jsx)("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${f}`))})}var cr=require("@urun-sh/core");var nr=require("react");function be(e){let[t,r]=(0,nr.useState)(e?.phase??null);return(0,nr.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var ho=require("@urun-sh/core");var gt=require("react"),So=require("@urun-sh/core");function or(e){let t=be(e),r=(0,So.isWakingPhase)(t?.name),o=(0,gt.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,gt.useState)(s);return(0,gt.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var je=require("react/jsx-runtime");function sr({session:e,render:t,className:r}){let o=or(e);return!o.waking||!o.phase?null:(0,je.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)("span",{className:"urun-session-waking-label",children:(0,ho.describeSessionPhase)(o.phase)})," ",(0,je.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var ar=require("react");var Ke=require("react"),cs={event:null,elapsedMs:0};function ir(e,t){let[r,o]=(0,Ke.useState)(null),n=(0,Ke.useRef)(0);(0,Ke.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,Ke.useState)(0);return(0,Ke.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:cs}var St=require("react/jsx-runtime"),ls={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function ds(e){let[t,r]=(0,ar.useState)(!1);return(0,ar.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function ur({session:e,stream:t,videoElement:r,render:o,className:n}){let s=ir(e,t),i=ds(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return(0,St.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):(0,St.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,St.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??ls[c]})," ",(0,St.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Te=require("react/jsx-runtime"),ps={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function vo({session:e,className:t}){let r=be(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,Te.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,Te.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,Te.jsx)("span",{className:"urun-session-status-label",children:ps[o]}),n?(0,Te.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function yo({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=be(e);if(s?.name==="live")return(0,Te.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,Te.jsx)(ur,{session:e})]});let i=r?r(s):(0,Te.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&(0,cr.isWakingPhase)(s.name)?(0,Te.jsx)(sr,{session:e}):s&&s.name!=="idle"?(0,cr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return(0,Te.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,Te.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var lr=require("react");var bo=require("react/jsx-runtime");function Fr(e){return be(e)?.endsAt??null}function ms(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function ko({session:e,urgentMs:t=6e4,className:r}){let n=Fr(e)?.getTime()??null,[s,i]=(0,lr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,lr.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=ms(s);return(0,bo.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var To=require("@urun-sh/core");var ht=require("react/jsx-runtime"),fs=new Set(["paused","error"]);function Hr({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=be(e);if(!s||!fs.has(s.name))return null;let i=o?o(s):(0,ht.jsx)("span",{className:"urun-session-paused-copy",children:(0,To.describeSessionPhase)(s)});return(0,ht.jsxs)("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?(0,ht.jsx)("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var Co=Hr;var $e=require("react"),et=require("react/jsx-runtime");function qr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Wr(e){let t=(0,$e.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,$e.useState)(()=>t?qr(t.get("idle")):null);return(0,$e.useEffect)(()=>{if(!t){o(null);return}return o(qr(t.get("idle"))),t.on("change",()=>o(qr(t.get("idle"))))},[t]),r}function gs(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Po({session:e,onStillHere:t,className:r}){let o=Wr(e),n=o?.deadlineEpochS??null,[s,i]=(0,$e.useState)(null);if((0,$e.useEffect)(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,et.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,et.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,et.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,et.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${gs(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,et.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Ee=require("react");function Ss(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function dr(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=(0,Ee.useState)(null),[s,i]=(0,Ee.useState)(e!==null),[a,c]=(0,Ee.useState)(null),u=(0,Ee.useRef)(e),f=(0,Ee.useCallback)(async g=>{i(!0);try{let v=await g.getBalance();if(u.current!==g)return;n(v),c(null)}catch(v){if(u.current!==g)return;c(v instanceof Error?v:new Error(String(v)))}finally{u.current===g&&i(!1)}},[]);(0,Ee.useEffect)(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(f(e),r!==void 0&&r>0){let g=setInterval(()=>{f(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,f]);let l=(0,Ee.useCallback)(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:Ss(o),loading:s,error:a,refresh:l}}var pr=require("react/jsx-runtime");function Ro({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=dr(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return(0,pr.jsx)("div",{className:i,children:t});let a=r?r(n):(0,pr.jsx)("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return(0,pr.jsx)("div",{className:i,children:a})}var Ge=require("@urun-sh/core");var vt=require("react"),xo=require("@urun-sh/core");function Eo(e){let t=(0,vt.useContext)(qe),[r,o]=(0,vt.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,f=t?.getAccessToken,l=t?.authProvider;return(0,vt.useEffect)(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{(0,xo.prewake)({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(k=>{g||o(k)}).catch(()=>{})};v();let E=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(E)}},[n,s,i,a,c,u,f,l]),r}var mr=require("react");function wo(e){let[t,r]=(0,mr.useState)(null);return(0,mr.useEffect)(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}var fr=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,CreditsClient,CreditsError,CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_SMOOTH_CHARS_PER_FRAME,DEFAULT_SMOOTH_THRESHOLD,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,ReprojectedVideo,Session,StatusBadge,StatusBadgeSchema,Text,TextStream,TextStreamError,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunCreditsGate,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionPaused,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createCreditsClient,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,textDelta,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useCredits,useDocStore,useGenerationTick,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useReferenceImage,useRequest,useSession,useSessionDirectory,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionStats,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useText,useTextMeter,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client"
2
- import{a as bt,b as xn,c as Tt}from"./chunk-WF2OBDSX.mjs";import{useCallback as fr,useEffect as Fn,useMemo as vr,useRef as gr,useState as Pt}from"react";import{Component as wn}from"react";import{jsx as cr,jsxs as Un}from"react/jsx-runtime";var Ke=class extends wn{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Un("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[cr("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),cr("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as An}from"react";var Te=An(null);function ke(e){return e&&e.trim()?e.trim():void 0}function fe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return ke(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ke(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=fe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||fe("VERCEL_ENV")==="production"?"workos":fe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Mn(){return rt()==="workos"}import{useEffect as _n,useRef as Nn}from"react";var In="urun.operator_token",dr=null,lr="op",On="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function pr(){return typeof window<"u"}function mr(){return dr}function Ln(){if(!pr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(lr);if(!r)return null;dr=r,t.delete(lr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Dn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Ct(e){let t=Nn(e);t.current=e,_n(()=>{if(!pr())return;Ln();let r=o=>{if(!Dn(o))return;let n=mr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as Vn}from"react";function Rt(e=!0){Vn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as Le,jsxs as Kn}from"react/jsx-runtime";var Hn="/api/urun-token",qn=1e4;function Wn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Sr(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function hr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function Et(e){let t=e===void 0?void 0:JSON.stringify(e);return vr(()=>e,[t])}function Bn(e,t){return typeof e=="function"?e(t):e!==void 0?e:Kn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[Le("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Le("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function jn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:v,sessionStats:x,confirmOnLeave:k=!1,fallback:d,errorFallback:P,children:S}){let h=n===void 0&&t===void 0;if(!h&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!h&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let y=r??o;if(h&&(typeof y!="string"||y.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Rt(k);let[p,R]=Pt(),[C,U]=Pt(null),A=gr(void 0),m=gr(null),[E,b]=Pt(null);Ct(M=>b({jwt:M}));let _=Tt(),B=fe("NEXT_PUBLIC_SESSION_TOKEN")??fe("NEXT_PUBLIC_URUN_JWT"),j=rt(),I=E!==null,$=j==="workos"&&!n&&!I&&!h,Y=n??(j==="jwt"?B:void 0)??p?.token,X=I?E.jwt:Y,ce=s??fe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),w=$&&!X&&!_?.getAccessToken,L=t??p?.orgId,W=e??p?.gatewayUrl,q=h&&p===void 0,O=h&&p!==void 0&&!W?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,K=w?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,te=C??O??K,J=hr("NEXT_PUBLIC_URUN_TOKEN_URL",fe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Hn,Z=hr("NEXT_PUBLIC_URUN_EVENTS_URL",fe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,me=fr(async M=>{if(!M?.forceRefresh){let G=A.current;if(!G)return G;let se=Wn(G);if(se===null||se-Date.now()>qn)return G}return(await(m.current??(m.current=(async()=>{try{let G=await Sr(J);return A.current=G.token,R(G),G}finally{m.current=null}})()))).token},[J]),oe=fr(async()=>X,[X]),be=typeof X=="string"&&X.trim().length>0,re=$?_?.getAccessToken:h&&!I?me:be?oe:void 0,Q=Et(g),z=Et(v),T=Et(x),D=vr(()=>({appId:y,baseUrl:W??"",orgId:L??"",jwt:X,getAccessToken:$?_?.getAccessToken:h&&!I?me:void 0,authProvider:ce,eventsUrl:Z,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:Q,videoPlayout:z,sessionStats:T,priority:I?"preempt":void 0}),[y,_,W,ce,X,Z,L,a,u,f,l,Q,z,T,$,I,h,me]);return Fn(()=>{if(!h)return;let M=new AbortController;return U(null),(async()=>{try{let H=await Sr(J,M.signal);A.current=H.token,R(H)}catch(H){if(M.signal.aborted)return;U(H instanceof Error?H:new Error(String(H)))}})(),()=>M.abort()},[h,J]),Le(Ke,{fallback:d,children:te?Bn(P,te):q?Le("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Le(Te.Provider,{value:D,children:re?Le(bt,{getAccessToken:re,children:S}):S})})}import{useContext as $n,useEffect as Gn,useMemo as yr,useReducer as Xn,useRef as xt}from"react";import{App as zn}from"@urun-sh/core";function kr(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Jn(e,t,r){let o=kr(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function Yn(e,t,r,o){let n=kr(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var Ue=new Map;var wt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Ut=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},At=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new wt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Ut(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Zn(){let e=$n(Te);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Xn(i=>i+1,0),r=xt(new Map),o=xt(new Map),n=xt(null),s=yr(()=>zn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return Gn(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Ue.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let f=Ue.get(c);f===u&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(c,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let l=Ue.get(c);!l||l.refCount!==0||(Ue.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),yr(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let f=(l,g)=>{let v=Jn(c,l,g),x=r.current.get(v);if(x&&!x.disposed)return x;let k=Yn(e,c,l,g),d=Ue.get(k);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),Ue.delete(k),o.current.get(k)===d&&o.current.delete(k),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new At(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Ue.set(k,d)),o.current.get(k)!==d&&(o.current.set(k,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(v,d.handle),d.handle};return i.set(c,f),f}})},[e,s])}import{useContext as Qn,useMemo as eo}from"react";import{sessionDirectory as to}from"@urun-sh/core";function ro(){let e=Qn(Te);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return eo(()=>to(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}import{useCallback as Mt,useEffect as no,useMemo as oo,useRef as nt,useState as _t}from"react";function De(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function so(e){return e instanceof Error?e:new Error(String(e))}function io(e,t){let r=oo(()=>De(e),[e]),[o,n]=_t(void 0),[s,i]=_t(null),[a,c]=_t(!1),u=nt(t);u.current=t;let f=nt(0),l=nt(null),g=nt(!0);no(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=Mt(async d=>{l.current?.abort();let P=new AbortController;l.current=P;let S=++f.current,h=()=>g.current&&f.current===S;h()&&(c(!0),i(null));try{let y=await r.request(d,{...u.current,signal:P.signal});return h()&&(n(y),c(!1),u.current?.onSuccess?.(y)),y}catch(y){let p=so(y);throw h()&&(i(p),c(!1),u.current?.onError?.(p)),p}},[r]),x=Mt(d=>{v(d).catch(()=>{})},[v]),k=Mt(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:x,mutateAsync:v,data:o,error:s,isPending:a,reset:k}}import{useCallback as br,useEffect as ao,useMemo as uo,useRef as ot,useState as Nt}from"react";function Tr(e){return e instanceof Error?e:new Error(String(e))}var co=e=>typeof e=="string"?e:String(e);function lo(e,t){let r=uo(()=>De(e),[e]),[o,n]=Nt(""),[s,i]=Nt(!1),[a,c]=Nt(null),u=ot(t);u.current=t;let f=ot(0),l=ot(null),g=ot(!0);ao(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=br(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),x=br(async k=>{l.current?.cancel();let d=++f.current,P=()=>g.current&&f.current===d,S=u.current,h=S?.parseChunk??co,y=S?.buildPayload??(b=>({prompt:b}));P()&&(n(""),c(null),i(!0));let{parseChunk:p,buildPayload:R,onFinish:C,onError:U,...A}=S??{},m="",E;try{E=r.requestStream(y(k),A),l.current=E}catch(b){let _=Tr(b);P()&&(c(_),i(!1),S?.onError?.(_));return}try{for await(let b of E){if(f.current!==d)break;m+=h(b),P()&&n(m)}P()&&(i(!1),S?.onFinish?.(m))}catch(b){let _=Tr(b);P()&&(c(_),i(!1),S?.onError?.(_))}finally{l.current===E&&(l.current=null)}},[r]);return{completion:o,complete:x,stop:v,isStreaming:s,error:a}}import{useCallback as Cr,useEffect as po,useMemo as mo,useRef as Ve,useState as st}from"react";function Rr(e){return e instanceof Error?e:new Error(String(e))}var fo=e=>typeof e=="string"?e:String(e),Pr=0;function It(e){return Pr+=1,`${e}-${Pr}`}function go(e,t){let r=mo(()=>De(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(h=>({id:h.id??It("msg"),role:h.role,content:h.content}))),[s,i]=st(""),[a,c]=st(!1),[u,f]=st(null),l=Ve(t);l.current=t;let g=Ve(o);g.current=o;let v=Ve(s);v.current=s;let x=Ve(0),k=Ve(null),d=Ve(!0);po(()=>(d.current=!0,()=>{d.current=!1,k.current?.cancel(),k.current=null}),[]);let P=Cr(()=>{x.current++,k.current?.cancel(),k.current=null,d.current&&c(!1)},[]),S=Cr(async h=>{let y=h===void 0,p=(y?v.current:h)??"";if(!p.trim())return;k.current?.cancel();let C=++x.current,U=()=>d.current&&x.current===C,A=l.current,m=A?.parseChunk??fo,E={id:It("msg"),role:"user",content:p},b={id:It("msg"),role:"assistant",content:""},_=[...g.current,E].map(O=>({role:O.role,content:O.content})),B=[...g.current,E,b];g.current=B,n(B),y&&i(""),f(null),c(!0);let j=A?.buildPayload??(O=>({messages:O})),{initialMessages:I,parseChunk:$,buildPayload:Y,onFinish:X,onError:ce,...w}=A??{},L=O=>{n(K=>K.map(te=>te.id===b.id?{...te,content:O}:te))},W="",q;try{q=r.requestStream(j(_),w),k.current=q}catch(O){let K=Rr(O);U()&&(f(K),c(!1),A?.onError?.(K));return}try{for await(let O of q){if(x.current!==C)break;W+=m(O),U()&&L(W)}U()&&(c(!1),A?.onFinish?.({...b,content:W}))}catch(O){let K=Rr(O);U()&&(f(K),c(!1),A?.onError?.(K))}finally{k.current===q&&(k.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:S,stop:P,isStreaming:a,error:u}}import{useCallback as Ce,useEffect as Er,useMemo as So,useRef as xr,useState as wr}from"react";import{createInputPresencePublisher as ho,INPUT_PRESENCE_DEFAULT_HZ as vo,INPUT_PRESENCE_FIELD as yo}from"@urun-sh/core";var Ot=[];function ko(e,t={}){let{field:r=yo,hz:o=vo}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=So(()=>s?ho({awareness:{setLocalStateField:(p,R)=>s.setField(p,R)},field:r,hz:o}):null,[s,r,o]),a=xr(null);a.current=i;let[c,u]=wr(!1),[f,l]=wr(Ot),g=xr(!1);Er(()=>{if(i)return()=>i.dispose()},[i]);let v=Ce(()=>{let p=a.current;l(p?p.heldKeys():Ot)},[]),x=Ce(()=>{a.current?.clear(),l(Ot)},[]);Er(()=>{if(!n)return;let p=()=>!!n.pointerLockElement,R=()=>{if(p()){g.current=!1,u(!0);return}g.current||(u(!1),x())},C=b=>{p()&&(a.current?.keyDown(b.key),v())},U=b=>{a.current?.keyUp(b.key),v()},A=b=>{p()&&a.current?.movePointer(b.movementX,b.movementY)},m=b=>{p()&&a.current?.setButtons(b.buttons)},E=()=>{x()};return n.addEventListener("pointerlockchange",R),n.addEventListener("keydown",C),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",m),n.addEventListener("mouseup",m),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",R),n.removeEventListener("keydown",C),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",m),n.removeEventListener("mouseup",m),n.defaultView?.removeEventListener("blur",E)}},[n,x,v]);let k=Ce(p=>{p.requestPointerLock?.()},[]),d=Ce(()=>{g.current=!0,u(!0)},[]),P=Ce(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),x()},[n,x]),S=Ce(p=>{a.current?.keyDown(p),v()},[v]),h=Ce(p=>{a.current?.keyUp(p),v()},[v]),y=Ce((p,R)=>{a.current?.movePointer(p,R)},[]);return{engage:k,engageTouch:d,release:P,engaged:c,heldKeys:f,pressKey:S,releaseKey:h,movePointer:y}}import{forwardRef as Mo,useEffect as Lr,useImperativeHandle as _o,useMemo as No,useRef as ut}from"react";import{createCameraWarp as Io}from"@urun-sh/core";import{forwardRef as Eo,useCallback as Re,useEffect as $e,useImperativeHandle as xo,useRef as ne,useState as Ar}from"react";import{derivedLegRole as wo}from"@urun-sh/core";var it=null;function bo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=bo();return e?(it=new e,it):null}function Fe(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as To,useContext as Ur}from"react";import{jsx as Po}from"react/jsx-runtime";var Lt=To(null);function Co({session:e,children:t}){return Po(Lt.Provider,{value:e,children:t})}function ge(){return Ur(Lt)}function Ro(){let e=Ur(Lt);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{jsx as Or,jsxs as Ao}from"react/jsx-runtime";function Uo(e,t){return e-t>>>0<2147483648}var Mr=1e3;function _r(...e){console.debug("[video]",...e)}function Nr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function Ir(e,t,r){return r?[r,t]:[e,t]}var He=Eo(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:f,style:l,videoClassName:g,placeholder:v,poster:x,children:k,onTrack:d,onFirstFrame:P,frameMarker:S,onFrameMarkerReached:h,onFrameMarkerUnsupported:y,onUnlockChange:p}=t,R=ge(),C=o??R,U=ne(null),A=ne(null),[m,E]=Ar(!1),[b,_]=Ar(!1),B=ne(!1),j=ne(null),I=ne(d);I.current=d;let $=ne(p);$.current=p;let Y=ne(P);Y.current=P;let X=ne(h);X.current=h;let ce=ne(y);ce.current=y;let w=ne(S??null);w.current=S??null;let L=Re(T=>{j.current!==T&&(j.current=T,$.current?.(T))},[]),W=ne(null),q=ne(null),O=Re((T,D=!1)=>{if(!D&&T===W.current||(W.current=T,q.current?.(),q.current=null,B.current=!1,_(!1),!T))return;let M=U.current;if(!M)return;let H=w.current,G=H?.rtpTimestamp??null,se=!1,N=()=>{se||(se=!0,ce.current?.())};H&&G==null&&N();let he=H!=null&&G!=null,Ie=ye=>{q.current?.(),q.current=null,B.current=!0,_(!0),Y.current?.(),ye&&X.current?.()};if(typeof M.requestVideoFrameCallback=="function"){let ye=!1,V=0,F=(ie,ae)=>{if(!ye){if(he){let le=ae?.rtpTimestamp;if(typeof le!="number"){N(),Ie(!1);return}if(!Uo(le,G)){V=M.requestVideoFrameCallback(F);return}Ie(!0);return}Ie(!1)}};V=M.requestVideoFrameCallback(F),q.current=()=>{ye=!0,M.cancelVideoFrameCallback?.(V)};return}he&&N();let ve=()=>{let ye=M.getVideoPlaybackQuality?.();(ye?ye.totalVideoFrames>0:M.readyState>=2&&M.videoWidth>0)&&Ie(!1)};M.addEventListener("loadeddata",ve),M.addEventListener("timeupdate",ve),M.addEventListener("playing",ve),q.current=()=>{M.removeEventListener("loadeddata",ve),M.removeEventListener("timeupdate",ve),M.removeEventListener("playing",ve)},ve()},[]);$e(()=>()=>{q.current?.(),q.current=null},[]);let K=S==null?null:`${S.rtpTimestamp??""}|${S.ptsMs??""}`,te=ne(K);$e(()=>{if(te.current===K||(te.current=K,K==null))return;let T=W.current;T&&O(T,!0)},[K,O]);let J=Re(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let T=U.current;return T&&T.srcObject!==A.current&&(T.srcObject=A.current),A.current},[]),Z=Re(T=>{let D=U.current;if(!D)return;let M=D.play();!M||typeof M.then!="function"||M.then(()=>{D.muted||L(!0)}).catch(H=>{if((H instanceof Error?H.name:String(H))==="NotAllowedError"&&!D.muted){_r(`play() blocked pending a user gesture (${T})`),L(!1);return}_r(`play() failed (${T})`,H)})},[L]),me=Re(()=>{let T=U.current;T&&(J(),!T.muted&&(Z("gesture"),Fe(),L(!0)))},[J,Z,L]),oe=Re(T=>{let D=J();if(D){for(let M of D.getVideoTracks())M!==T&&D.removeTrack(M);if(T&&!D.getVideoTracks().includes(T)){D.addTrack(T);let M=U.current;M&&(M.srcObject=D)}T&&Z("track-attach"),E(T!==null),O(T),I.current?.(T)}},[J,Z,O]),be=Re(T=>{let D=J();if(D){for(let M of D.getAudioTracks())M!==T&&D.removeTrack(M);T&&!D.getAudioTracks().includes(T)&&D.addTrack(T),T&&Z("audio-attach")}},[J,Z]),re=Re(T=>{U.current=T,T&&(a?(T.muted=!0,T.defaultMuted=!0,T.setAttribute("muted",""),j.current=null):(T.muted=!1,T.defaultMuted=!1,T.removeAttribute("muted")),T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),J())},[J,a]);xo(r,()=>({get element(){return U.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return B.current},unlock:me,get unlocked(){return j.current===!0}}),[me]);let Q=wo(n)!==void 0;$e(()=>{Q&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[Q,n]);let z=i!==void 0;return $e(()=>{if(z){oe(i??null);return}if(Q){oe(null);return}if(!C)return;let T=Nr(C,Ir(n,"video")),D=()=>{let N=A.current;return N?N.getVideoTracks()[0]??null:null},M=N=>{if(N!==D()&&(oe(N),N)){let he=()=>{D()===N&&oe(null)};N.addEventListener("ended",he)}},H=T.track;H&&H.readyState==="live"&&M(H);let G=T.on("track",N=>{N&&N.readyState!=="live"||M(N)}),se=setInterval(()=>{let N=T.track;N&&N.readyState==="live"&&M(N)},Mr);return()=>{G(),clearInterval(se)}},[C,n,Q,z,i,oe]),$e(()=>{if(z||!C||s===!1||Q)return;let T=Nr(C,Ir(n,"audio",s)),D=()=>{let N=A.current;return N?N.getAudioTracks()[0]??null:null},M=N=>{if(N!==D()&&(be(N),N)){let he=()=>{D()===N&&be(null)};N.addEventListener("ended",he)}},H=T.track;H&&H.readyState==="live"&&M(H);let G=T.on("track",N=>{N&&N.readyState!=="live"||M(N)}),se=setInterval(()=>{let N=T.track;N&&N.readyState==="live"&&M(N)},Mr);return()=>{G(),clearInterval(se)}},[C,n,Q,s,z,be]),Ao("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":m?"true":"false","data-urun-video-framed":b?"true":"false",children:[Or("video",{ref:re,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),m?null:v,x===void 0?null:Or("div",{"data-urun-video-poster":"","aria-hidden":b||void 0,style:{position:"absolute",inset:0,...b?{opacity:0,pointerEvents:"none"}:null},children:x}),k]})});import{jsx as Dr,jsxs as Do}from"react/jsx-runtime";var Oo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},Lo=Mo(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...f}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=ut(null),v=ut(null),x=ut(0),k=ut(f);k.current=f;let d=No(()=>Io(k.current),[]);return _o(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:d,get lastDrawTs(){return x.current}}),[d]),Lr(()=>{if(!i)return;let P=0,S=0,h=null,y=R=>{typeof R.requestVideoFrameCallback=="function"&&(h=R,S=R.requestVideoFrameCallback(function C(){d.frameArrived(),S=R.requestVideoFrameCallback(C)}))},p=R=>{P=requestAnimationFrame(p);let C=v.current,U=g.current?.element??null;if(!C||!U||(U!==h&&(h&&S&&h.cancelVideoFrameCallback?.(S),y(U)),U.readyState<2))return;d.tick(R);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,m=Math.max(1,Math.round(C.clientWidth*A)),E=Math.max(1,Math.round(C.clientHeight*A));(C.width!==m||C.height!==E)&&(C.width=m,C.height=E);let b=C.getContext("2d");if(!b)return;let _=d.transform(),B=U.videoWidth||m,j=U.videoHeight||E,$=Math.max(m/B,E/j)*(1+a)*_.scale;b.setTransform($,0,0,$,m/2+_.translateX*m,E/2+_.translateY*E),b.drawImage(U,-B/2,-j/2),x.current=R};return P=requestAnimationFrame(p),()=>{cancelAnimationFrame(P),h&&S&&h.cancelVideoFrameCallback?.(S)}},[i,a,d]),Lr(()=>{if(!i||!c||!l)return;let P=()=>!!l.pointerLockElement,S=C=>{P()&&d.keyDown(C.key)},h=C=>d.keyUp(C.key),y=C=>{P()&&d.pointerDelta(C.movementX,C.movementY)},p=()=>{P()||d.clearKeys()},R=()=>d.clearKeys();return l.addEventListener("keydown",S),l.addEventListener("keyup",h),l.addEventListener("mousemove",y),l.addEventListener("pointerlockchange",p),l.defaultView?.addEventListener("blur",R),()=>{l.removeEventListener("keydown",S),l.removeEventListener("keyup",h),l.removeEventListener("mousemove",y),l.removeEventListener("pointerlockchange",p),l.defaultView?.removeEventListener("blur",R)}},[i,c,l,d]),i?Do(He,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Dr("canvas",{ref:v,style:Oo,"data-urun-warp":""}),n]}):Dr(He,{ref:g,...s,children:n})});var Vr=new Map;function Vo(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Vr.set(e,{component:t,schema:r})}function Fr(e,t){let r=Vr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Ho,jsx as ct}from"react/jsx-runtime";function Fo({name:e,props:t,fallback:r}){let o=Fr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(Ho,{children:r}):ct("div",{className:"urun-component-error",role:"alert",children:ct("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return ct(n,{...o.validatedProps})}import{z as Ge}from"zod";import{jsx as Dt,jsxs as Hr}from"react/jsx-runtime";var qo=Ge.object({step:Ge.number().min(0),total:Ge.number().min(1),label:Ge.string().optional(),variant:Ge.enum(["default","success","error"]).default("default")});function qr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Wo(e){let{step:t,total:r,label:o,variant:n,percentage:s}=qr(e);return Hr("div",{className:"urun-progress-card","data-variant":n,children:[o&&Dt("div",{className:"urun-progress-label",children:o}),Dt("div",{className:"urun-progress-bar",children:Dt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Hr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as Wr,jsxs as $o}from"react/jsx-runtime";var Bo=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),jo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Br(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??jo[t]??t;return{state:t,message:n,isActive:o}}function Ko(e){let{state:t,message:r,isActive:o}=Br(e);return $o("span",{className:"urun-status-badge","data-state":t,children:[Wr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Wr("span",{className:"urun-status-message",children:r})]})}import{useRef as jr,useEffect as Go}from"react";import{z as Ft}from"zod";import{jsx as Kr,jsxs as Jo}from"react/jsx-runtime";var Xo=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function $r(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function zo(e){let{text:t,streaming:r}=$r(e),o=jr(null),n=jr(0);return Go(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Jo("div",{className:"urun-text-stream",children:[Kr("span",{ref:o,className:"urun-text-content"}),r&&Kr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as Gr,jsxs as Qo}from"react/jsx-runtime";var Yo=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Xr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Zo(e){let{src:t,alt:r,caption:o}=Xr(e);return Qo("figure",{className:"urun-image-frame",children:[Gr("img",{className:"urun-image",src:t,alt:r}),o&&Gr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as Pe}from"zod";import{jsx as Ht,jsxs as rs}from"react/jsx-runtime";var es=Pe.object({metrics:Pe.array(Pe.object({label:Pe.string(),value:Pe.union([Pe.string(),Pe.number()]),unit:Pe.string().optional()}))});function zr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function ts(e){let{metrics:t}=zr(e);return Ht("div",{className:"urun-metrics-panel",children:t.map((r,o)=>rs("div",{className:"urun-metric-card",children:[Ht("div",{className:"urun-metric-label",children:r.label}),Ht("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as qt,useRef as ue,useState as ns}from"react";import{jsx as ds}from"react/jsx-runtime";function Ee(e){return e&&typeof e=="object"?e:null}function Yr(e){if(typeof e=="string")return e;let t=Ee(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function os(e){if(typeof e=="string")return"delta";let t=Ee(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function ss(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function is(e){let t=Ee(e),r=t?.body;return ss(r,Ee(Ee(r)?.error)?.message,Ee(r)?.error,Ee(r)?.message,Ee(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var Xe=class extends Error{name="TextStreamError"},as=4,Zr=3,Qr=240,Jr=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function en(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function us(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function tn(e){let{session:t,stream:r}=e,o=ue(e);qt(()=>{o.current=e});let n=ue(null),s=ue(()=>{}),i=ue(null),a=ue(""),c=ue(""),u=ue(null),f=ue(!1),l=ue(!1),g=ue(!1),v=ue(null),x=ue(en()),k=dt(h=>{if(n.current=h,!h){i.current=null;return}let y=i.current;if(y&&y.parentNode===h)return;let p=h.ownerDocument.createTextNode(c.current);h.appendChild(p),i.current=p,a.current.length>0&&s.current()},[]),d=dt(()=>{u.current=null;let h=i.current,y=a.current;if(y.length>0){let A=o.current,m=A.smoothCharsPerFrame??Zr,E=A.smoothThreshold??Qr,b=A.smooth&&y.length<=E?y.slice(0,m):y;a.current=y.slice(b.length),c.current+=b,h?.appendData(b)}let p=x.current,R=c.current.length,C=v.current===null?0:Math.max(0,Jr()-v.current),U=Math.round(R/as);if(p.chars=R,p.tokens=U,p.elapsedMs=C,p.tokensPerSecond=C>0?U*1e3/C:0,a.current.length>0){P(),o.current.onMeter?.(p);return}if(!f.current&&!g.current){g.current=!0,p.done=!0,o.current.onMeter?.(p),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(p)},[]),P=dt(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>d()))},[d]);s.current=P,qt(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,v.current=null,f.current=!0,us(x.current),i.current&&(i.current.data="");let h=!1,y=null;return(async()=>{try{for(y=t.stream(r).messages()[Symbol.asyncIterator]();;){let R=await y.next();if(h)return;if(R.done)break;let C=R.value,U=os(C);if(U==="error")throw new Xe(is(C));if(U==="done")break;if(U==="ignore")continue;let A=Yr(C);A&&(v.current===null&&(v.current=Jr()),a.current+=A,P())}if(h)return;y.return?.(void 0),f.current=!1,P()}catch(p){if(h)return;y?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(p instanceof Error?p:new Xe(String(p))),P()}})(),()=>{h=!0,f.current=!1,y?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,P]);let S=dt(()=>c.current,[]);return{ref:k,meterRef:x,getText:S}}function cs(e,t=250){let[r,o]=ns(en);return qt(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function ls(e){let{className:t,style:r,...o}=e,{ref:n}=tn(o);return ds("span",{ref:n,className:t,style:r})}import{forwardRef as ps}from"react";import{jsx as fs}from"react/jsx-runtime";var ms=ps(function(t,r){let{stream:o="image",...n}=t;return fs(He,{ref:r,stream:o,...n})});import{forwardRef as gs,useCallback as qe,useEffect as Wt,useImperativeHandle as Ss,useRef as We}from"react";import{observePageLifecycle as hs}from"@urun-sh/core";import{jsx as ks}from"react/jsx-runtime";var vs=1e3,rn=200;function Bt(...e){console.debug("[audio]",...e)}var pt=gs(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f}=t,l=ge(),g=o??l,v=We(null),x=We(null),k=We(null),d=We(null),P=We(c);P.current=c;let S=We(u);S.current=u;let h=qe(m=>{k.current!==m&&(k.current=m,S.current?.(m))},[]),y=qe(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let m=v.current;return m&&m.srcObject!==x.current&&(m.srcObject=x.current),x.current},[]),p=qe(m=>{let E=v.current;if(!E)return;let b=E.play();!b||typeof b.then!="function"||b.then(()=>{E.muted||h(!0)}).catch(_=>{let B=_ instanceof Error?_.name:String(_);if(B==="AbortError"){Bt(`play() aborted (${m}); retrying in ${rn}ms`),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,p(`${m}:retry`)},rn);return}if(B==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${m})`),h(!1);return}Bt(`play() failed (${m})`,_)})},[h]),R=qe(m=>{let E=y();if(E){for(let b of E.getAudioTracks())b!==m&&E.removeTrack(b);m&&!E.getAudioTracks().includes(m)&&E.addTrack(m),m&&p("track-attach"),P.current?.(m)}},[y,p]),C=qe(()=>{let m=v.current;m&&(y(),m.muted=!1,p("gesture"),Fe(),h(!0))},[y,p,h]);Ss(r,()=>({unlock:C,get unlocked(){return k.current===!0},get element(){return v.current}}),[C]);let U=qe(m=>{v.current=m,m&&(m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),y()),f?.(m)},[y,f]),A=s!==void 0;return Wt(()=>{if(A){R(s??null);return}if(!g)return;let m=g.stream(n),E=()=>{let I=x.current;return I?I.getAudioTracks()[0]??null:null},b=I=>{if(I!==E()&&(R(I),I)){let $=()=>{E()===I&&R(null)};I.addEventListener("ended",$)}},_=m.track;_&&_.readyState==="live"&&b(_);let B=m.on("track",I=>{I&&I.readyState!=="live"||b(I)}),j=setInterval(()=>{let I=m.track;I&&I.readyState==="live"&&b(I)},vs);return()=>{B(),clearInterval(j)}},[g,n,A,s,R]),Wt(()=>hs(()=>{Fe(),k.current===!0&&p("foreground")}),[p]),Wt(()=>()=>{d.current&&clearTimeout(d.current)},[]),ks("audio",{ref:U,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),ys=pt;import{forwardRef as bs,useCallback as Ae,useEffect as jt,useImperativeHandle as Ts,useRef as de}from"react";import{observePageLifecycle as Cs,sessionFailureFromMediaError as Rs,sharedCaptureController as Ps}from"@urun-sh/core";import{jsx as xs}from"react/jsx-runtime";var nn={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}var ft=bs(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=nn,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:x,onUnlockChange:k,capture:d}=t,P=ge(),S=o??P,h=de(null),y=de(null),p=de(null),R=de([]),C=de(!1),U=de(l);U.current=l;let A=de(g);A.current=g;let m=de(v);m.current=v;let E=Ae(w=>{C.current!==w&&(C.current=w,U.current?.(w))},[]),b=Ae(()=>{for(let w of R.current)w();R.current=[],p.current?.release(),p.current=null,y.current&&(y.current=null,m.current?.(null))},[]),_=Ae(async()=>{let w=p.current;if(w){let O=await w.update(a);return y.current=w.stream,m.current?.(w.stream),O}let W=await(d??Ps()).claim("audio",a);p.current=W,R.current=[W.onTrack((O,K)=>{y.current=K,m.current?.(K),C.current&&S?.stream(n).attach(O).catch(te=>mt("mic re-attach after one-capture re-acquire failed",te))}),W.onLost(O=>{p.current=null,R.current=[],y.current=null,m.current?.(null),E(!1),A.current?.(O)})],y.current=W.stream,m.current?.(W.stream);let q=W.track;if(!q)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return q},[d,a,S,n,E]),B=Ae(async()=>{b(),E(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,b,E]),j=Ae(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");h.current?.unlock();let w;try{w=await _()}catch(q){b();let O=Rs(q,S.status);throw A.current?.(O),O}S.connect?.();let L;for(let q=1;q<=u;q++)try{await S.whenLive(c!==void 0?{timeout:c}:void 0),await S.stream(n).attach(w),E(!0);return}catch(O){L=O,mt(`start attempt ${q}/${u} failed`,O),q<u&&await new Promise(K=>setTimeout(K,f))}b(),E(!1);let W=L instanceof Error?L:new Error(String(L??"voice start failed"));throw A.current?.(W),W},[S,n,c,u,f,_,b,E]);Ts(r,()=>({start:j,stop:B,unlock:()=>h.current?.unlock(),get active(){return C.current},get micStream(){return y.current},get audio(){return h.current}}),[j,B]);let I=de(j);I.current=j;let $=de(null),Y=Ae((w,L)=>{w.promise.then(()=>{L&&(b(),E(!1)),w.session.stream(w.streamName).detach().catch(()=>{})})},[b,E]);jt(()=>{if(!i||!S)return;let w=$.current;w&&(w.session!==S||w.streamName!==n)&&(w.disposeTimer&&clearTimeout(w.disposeTimer),Y(w,!1),w=null),w?w.disposeTimer&&(clearTimeout(w.disposeTimer),w.disposeTimer=null):(w={session:S,streamName:n,promise:I.current().catch(()=>{}),refCount:0,disposeTimer:null},$.current=w),w.refCount+=1;let L=w;return()=>{L.refCount-=1,!(L.refCount>0)&&(L.disposeTimer=setTimeout(()=>{$.current===L&&($.current=null),Y(L,!0)},0))}},[i,S,n,Y]);let X=de(!1),ce=Ae(async()=>{if(!S||!C.current||X.current)return;let w=y.current?.getAudioTracks()[0]??null;if(w&&w.readyState==="live"){try{await S.stream(n).attach(w)}catch(L){mt("foreground mic re-assert failed (will retry on next pass)",L)}return}X.current=!0;try{let L=await _();await S.stream(n).attach(L)}catch(L){let W=L instanceof Error?L:new Error(String(L));mt("foreground mic re-acquire failed",W),A.current?.(W)}finally{X.current=!1}},[S,n,_]);return jt(()=>{let w=()=>{ce()};return S&&typeof S.onRecovery=="function"?S.onRecovery(w):Cs(w)},[S,ce]),jt(()=>b,[b]),s?xs(pt,{ref:h,session:S,stream:n,onTrack:x,onUnlockChange:k}):null}),Es=ft;import{forwardRef as As,useImperativeHandle as Ms,useRef as on,useState as _s}from"react";import{useEffect as ws,useState as Us}from"react";var Kt={level:0,speaking:!1};function $t(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Us(Kt);return ws(()=>{if(!e){i(Kt);return}let a=at();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,f;try{u=a.createMediaStreamSource(c),f=a.createAnalyser(),f.fftSize=r,u.connect(f)}catch{return}let l=new Uint8Array(f.fftSize),v=setInterval(()=>{f.getByteTimeDomainData(l);let x=0;for(let d=0;d<l.length;d++){let P=(l[d]-128)/128;x+=P*P}let k=Math.sqrt(x/l.length);i(d=>{let P=k>n;return Math.abs(d.level-k)<.005&&d.speaking===P?d:{level:k,speaking:P}})},o);return()=>{clearInterval(v),u.disconnect(),i(Kt)}},[e,r,o,n]),s}import{Fragment as Ls,jsx as gt,jsxs as Ds}from"react/jsx-runtime";var Ns={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Is={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Os=As(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:f,onMicStream:l,capture:g}=t,v=ge(),x=o??v,k=on(null),[d,P]=_s(null),S=on(l);S.current=l;let{level:h,speaking:y}=$t(a?d:null);return Ms(r,()=>({start:()=>{let p=k.current;return p?p.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>k.current?.stop()??Promise.resolve(),get active(){return k.current?.active??!1},get micStream(){return k.current?.micStream??null}}),[]),Ds(Ls,{children:[gt(ft,{ref:k,session:x,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:p=>{P(p),S.current?.(p)}}),a?gt("span",{className:c,style:Ns,"data-urun-mic":"","data-urun-mic-active":d?"true":"false","data-urun-mic-speaking":y?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(h*100)/100,children:gt("span",{style:Is,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(h*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as Vs,sessionFailureFromMediaError as Fs,sharedCaptureController as Hs}from"@urun-sh/core";import{forwardRef as an,useCallback as Se,useEffect as Gt,useImperativeHandle as qs,useRef as ee,useState as ze}from"react";import{jsx as xe,jsxs as sn}from"react/jsx-runtime";var un={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Xt(...e){console.debug("[camera]",...e)}function Ws(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Bs(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var cn=an(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:f="auto",connectTimeoutMs:l,visible:g=!1,className:v,videoClassName:x,onActiveChange:k,onError:d,onStream:P,onTrack:S,children:h,capture:y,flipControl:p="auto",flipControlClassName:R,onDevices:C}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":c??"environment",A=ge(),m=o??A,E=ee(null),b=ee(null),_=ee(null),B=ee([]),j=ee(null),I=ee(!1),$=ee(!1),Y=ee(U),[X,ce]=ze(U),[w,L]=ze(!1),[W,q]=ze(null),[O,K]=ze(!1),[te]=ze(Ws),J=ee(k);J.current=k;let Z=ee(d);Z.current=d;let me=ee(P);me.current=P;let oe=ee(S);oe.current=S;let be=ee(C);be.current=C;let re=Se(V=>{I.current!==V&&(I.current=V,L(V),J.current?.(V))},[]);Gt(()=>{if(!w){q(null);return}let V=!1,F=()=>{Bs().then(ae=>{V||(q(ae),ae&&be.current?.(ae))})};F();let ie=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ie?.addEventListener=="function"?(ie.addEventListener("devicechange",F),()=>{V=!0,ie.removeEventListener?.("devicechange",F)}):()=>{V=!0}},[w]);let Q=Se(V=>{let F=E.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=V,V&&F.play()?.catch?.(ie=>Xt("preview play() failed",ie)))},[]),z=Se(()=>{$.current=!1,j.current?.(),j.current=null;for(let V of B.current)V();B.current=[],_.current?.release(),_.current=null,b.current&&(b.current=null,me.current?.(null),oe.current?.(null)),Q(null)},[Q]),T=Se((V,F)=>{j.current?.(),b.current=F,Q(F),me.current?.(F);let ie=()=>{b.current===F&&(Xt("camera track ended (device removed or permission revoked)"),z(),re(!1))};V.addEventListener("ended",ie),j.current=()=>V.removeEventListener("ended",ie)},[Q,z,re]),D=Se(async V=>{let F=n!==!1;if(F&&!m)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ie={...un,...s,facingMode:V},ae;try{let le=_.current;if(le)ae=await le.update(ie);else{let Be=await(y??Hs()).claim("video",ie);if(_.current=Be,B.current=[Be.onTrack((je,Pn)=>{T(je,Pn),I.current&&(!F||!m||m.stream(n).attachVideo(je).then(()=>oe.current?.(je)).catch(En=>Xt("camera re-publish after one-capture re-acquire failed",En)))}),Be.onLost(je=>{_.current=null,B.current=[],z(),re(!1),Z.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ae=Be.track}}catch(le){let Oe=Fs(le,m?.status);throw Z.current?.(Oe),Oe}Y.current=V,ce(V),T(ae,_.current?.stream??new MediaStream([ae]));try{F&&m&&(m.connect?.(),await m.whenLive(l!==void 0?{timeout:l}:void 0),await m.stream(n).attachVideo(ae)),$.current=F?n:!1}catch(le){z(),re(!1);let Oe=le instanceof Error?le:new Error(String(le));throw Z.current?.(Oe),Oe}oe.current?.(ae),re(!0)},[m,n,s,l,y,T,z,re]),M=Se(V=>D(V?.facingMode??Y.current),[D]),H=Se(async V=>{let F=$.current===n;I.current&&Y.current===V&&F||await D(V)},[D,n]),G=Se(()=>D(Y.current==="environment"?"user":"environment"),[D]),se=Se(async()=>{z(),re(!1),n!==!1&&await m?.stream(n).detachVideo().catch(()=>{})},[m,n,z,re]),N=Se(async V=>{let F=E.current;if(!F)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await Vs(F,V)},[]);qs(r,()=>({start:M,stop:se,flip:G,setFacingMode:H,capturePhoto:N,get active(){return I.current},get facingMode(){return Y.current},get stream(){return b.current},get element(){return E.current}}),[M,se,G,H,N]);let he=ee(H);if(he.current=H,Gt(()=>{u&&(n!==!1&&!m||he.current(U).catch(()=>{}))},[u,m,U,n]),Gt(()=>z,[z]),!g)return null;let Ie=f==="auto"?X==="user":f,ve=w&&(p===!0||p==="auto"&&te&&(W?.length??0)>1),ye=()=>{O||(K(!0),G().catch(()=>{}).finally(()=>K(!1)))};return sn("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":X,children:[xe("video",{ref:E,className:x,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ie?{transform:"scaleX(-1)"}:{}}}),ve?xe("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ye,disabled:O,className:R,style:R?{opacity:O?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:O?.6:1},children:sn("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[xe("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),xe("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),xe("path",{d:"M14.5 10.5v1.6h-1.6"}),xe("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),xe("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,h]})}),js=an(function({preview:t=!0,...r},o){return xe(cn,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Ks,normalizeReferenceImage as $s,referenceImageErrorMessage as Gs}from"@urun-sh/core";import{useCallback as Je,useEffect as Xs,useRef as zt,useState as Ye}from"react";function zs(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=Ye(null),[a,c]=Ye(null),[u,f]=Ye(!1),[l,g]=Ye(null),[v]=Ye(Ks),x=zt(n);x.current=n;let k=zt(null),d=zt(0),P=Je(R=>{k.current&&URL.revokeObjectURL(k.current),k.current=R?URL.createObjectURL(new Blob([R.bytes],{type:R.type})):null,c(k.current),i(R),x.current?.(R)},[]);Xs(()=>()=>{d.current++,k.current&&URL.revokeObjectURL(k.current),k.current=null},[]);let S=Je(async R=>{let C=++d.current;f(!0),g(null);try{let U=await R();if(d.current!==C)return;P(U)}catch(U){if(d.current!==C)return;g(Gs(U))}finally{d.current===C&&f(!1)}},[P]),h=Je(R=>S(()=>$s(R,{maxSize:t,type:r,quality:o,source:"file"})),[S,t,r,o]),y=Je(R=>S(()=>R.capturePhoto({maxSize:t,type:r,quality:o})),[S,t,r,o]),p=Je(()=>{d.current++,g(null),f(!1),P(null)},[P]);return{reference:s,previewUrl:a,pick:h,capture:y,clear:p,busy:u,error:l,cameraAvailable:v}}import{useEffect as Js,useState as Ys}from"react";function Zs(e,t){let[r,o]=Ys(null);return Js(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as oi}from"react";import{useEffect as ri,useMemo as ni}from"react";import{createStore as Qs}from"zustand/vanilla";import{useStore as ei}from"zustand";var ti=()=>{};function Jt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=Qs(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):ti,c=(u=>ei(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function Ze(e,t){let r=ni(()=>Jt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return ri(()=>r.bind(),[r]),r}function si(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=oi(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as ii,useState as ai}from"react";function ui(e){let[t,r]=ai(null);return ii(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}import{useEffect as ci,useState as li}from"react";var Me=200;function we(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Qe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Yt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Zt(e,t,r={}){let o=r.cap??200,[n,s]=li([]);return ci(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>we(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as St,jsxs as et}from"react/jsx-runtime";function di({session:e,name:t,cap:r,className:o}){let n=Zt(e,t,{cap:r});return et("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[et("div",{className:"urun-stream-tail-meta",children:[St("code",{children:t}),et("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),St("div",{className:"urun-stream-tail-log",children:n.length===0?et("span",{className:"urun-stream-tail-empty",children:["Waiting for ",St("code",{children:t})," messages\u2026"]}):n.map((s,i)=>et("div",{className:"urun-stream-tail-line",children:[St("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Qe(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as pi,useState as ln}from"react";import{jsx as _e,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=ln(""),[i,a]=ln(null),c=pi(()=>{let u=Yt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return ht("div",{className:"urun-doc-patch",children:[_e("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),ht("div",{className:"urun-doc-patch-actions",children:[_e("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?_e("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function mi({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ze(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return ht("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[ht("div",{className:"urun-doc-panel-meta",children:[_e("code",{children:t}),_e("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),_e("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?_e(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as fi,useState as gi}from"react";import{jsx as tt,jsxs as pn}from"react/jsx-runtime";function dn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Si({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=gi([]);return fi(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>we(c,{at:Date.now(),direction:"in",text:dn(Qe(a))},r))}):void 0),[e,t,r]),pn("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[tt(vt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>we(c,{at:Date.now(),direction:"out",text:dn(a)},r))}}),tt("div",{className:"urun-control-sender-log",children:n.length===0?tt("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>pn("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[tt("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",tt("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as hi,useState as vi}from"react";import{jsx as yt,jsxs as ki}from"react/jsx-runtime";function yi({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=vi([]),a=t.join(","),c=r.join(",");return hi(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>we(v,{at:Date.now(),kind:l,text:g},o)),f=[];f.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);f.push(g.on("track",v=>u("track",`${l}: ${v?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);f.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>f.forEach(l=>l())},[e,a,c,o]),yt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?yt("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,f)=>ki("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[yt("span",{className:"urun-event-spine-kind",children:u.kind})," ",yt("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${f}`))})}import{describeSessionPhase as Oi,isWakingPhase as Li}from"@urun-sh/core";import{useEffect as bi,useState as Ti}from"react";function pe(e){let[t,r]=Ti(e?.phase??null);return bi(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as xi}from"@urun-sh/core";import{useEffect as Ci,useRef as Ri,useState as Pi}from"react";import{isWakingPhase as Ei}from"@urun-sh/core";function Qt(e){let t=pe(e),r=Ei(t?.name),o=Ri(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=Pi(s);return Ci(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as wi,jsx as mn,jsxs as fn}from"react/jsx-runtime";function er({session:e,render:t,className:r}){let o=Qt(e);return!o.waking||!o.phase?null:mn("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):fn(wi,{children:[mn("span",{className:"urun-session-waking-label",children:xi(o.phase)})," ",fn("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Mi,useState as _i}from"react";import{useEffect as gn,useRef as Ui,useState as Sn}from"react";var Ai={event:null,elapsedMs:0};function tr(e,t){let[r,o]=Sn(null),n=Ui(0);gn(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=Sn(0);return gn(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:Ai}import{jsx as hn,jsxs as vn}from"react/jsx-runtime";var Ni={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Ii(e){let[t,r]=_i(!1);return Mi(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function rr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=tr(e,t),i=Ii(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return hn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):vn("div",{className:"urun-activation-overlay-card",children:[hn("span",{className:"urun-activation-overlay-copy",children:a.hint??Ni[c]})," ",vn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ne,jsxs as nr}from"react/jsx-runtime";var Di={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function Vi({session:e,className:t}){let r=pe(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return nr("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ne("span",{className:"urun-session-status-dot","data-phase":o}),Ne("span",{className:"urun-session-status-label",children:Di[o]}),n?Ne("span",{className:"urun-session-status-detail",children:n}):null]})}function Fi({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=pe(e);if(s?.name==="live")return nr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ne(rr,{session:e})]});let i=r?r(s):Ne("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&Li(s.name)?Ne(er,{session:e}):s&&s.name!=="idle"?Oi(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return nr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ne("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Hi,useState as qi}from"react";import{jsx as ji}from"react/jsx-runtime";function yn(e){return pe(e)?.endsAt??null}function Wi(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Bi({session:e,urgentMs:t=6e4,className:r}){let n=yn(e)?.getTime()??null,[s,i]=qi(()=>n===null?null:Math.max(0,n-Date.now()));if(Hi(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=Wi(s);return ji("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{describeSessionPhase as Ki}from"@urun-sh/core";import{jsx as or,jsxs as Xi}from"react/jsx-runtime";var $i=new Set(["paused","error"]);function kn({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=pe(e);if(!s||!$i.has(s.name))return null;let i=o?o(s):or("span",{className:"urun-session-paused-copy",children:Ki(s)});return Xi("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?or("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?or("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var Gi=kn;import{useEffect as bn,useMemo as zi,useState as Tn}from"react";import{jsx as kt,jsxs as Zi}from"react/jsx-runtime";function sr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Cn(e){let t=zi(()=>e?e.doc("control"):null,[e]),[r,o]=Tn(()=>t?sr(t.get("idle")):null);return bn(()=>{if(!t){o(null);return}return o(sr(t.get("idle"))),t.on("change",()=>o(sr(t.get("idle"))))},[t]),r}function Ji(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Yi({session:e,onStillHere:t,className:r}){let o=Cn(e),n=o?.deadlineEpochS??null,[s,i]=Tn(null);if(bn(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return kt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:Zi("div",{className:"urun-idle-warning-card",children:[kt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),kt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Ji(s)} due to inactivity.`:"This session will end soon due to inactivity."}),kt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useCallback as Rn,useEffect as Qi,useRef as ea,useState as ir}from"react";function ta(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function ar(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=ir(null),[s,i]=ir(e!==null),[a,c]=ir(null),u=ea(e),f=Rn(async g=>{i(!0);try{let v=await g.getBalance();if(u.current!==g)return;n(v),c(null)}catch(v){if(u.current!==g)return;c(v instanceof Error?v:new Error(String(v)))}finally{u.current===g&&i(!1)}},[]);Qi(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(f(e),r!==void 0&&r>0){let g=setInterval(()=>{f(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,f]);let l=Rn(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:ta(o),loading:s,error:a,refresh:l}}import{jsx as ur}from"react/jsx-runtime";function ra({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=ar(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return ur("div",{className:i,children:t});let a=r?r(n):ur("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return ur("div",{className:i,children:a})}import{CreditsClient as Hd,createCreditsClient as qd,CreditsError as Wd,CreditsUnauthorizedError as Bd}from"@urun-sh/core";import{useContext as na,useEffect as oa,useState as sa}from"react";import{prewake as ia}from"@urun-sh/core";function aa(e){let t=na(Te),[r,o]=sa(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,f=t?.getAccessToken,l=t?.authProvider;return oa(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{ia({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(k=>{g||o(k)}).catch(()=>{})};v();let x=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(x)}},[n,s,i,a,c,u,f,l]),r}import{useEffect as ua,useState as ca}from"react";function la(e){let[t,r]=ca(null);return ua(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as Yd,isWakingPhase as Zd}from"@urun-sh/core";export{pt as Audio,cn as Camera,Fo as ComponentRenderer,Hd as CreditsClient,Wd as CreditsError,Bd as CreditsUnauthorizedError,un as DEFAULT_CAMERA_CONSTRAINTS,Me as DEFAULT_LOG_CAP,Zr as DEFAULT_SMOOTH_CHARS_PER_FRAME,Qr as DEFAULT_SMOOTH_THRESHOLD,nn as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,ms as Image,Zo as ImageFrame,Yo as ImageFrameSchema,ts as MetricsPanel,es as MetricsPanelSchema,Os as Mic,On as OPERATOR_CHORD_LABEL,In as OPERATOR_TOKEN_STORAGE_KEY,Wo as ProgressCard,qo as ProgressCardSchema,Lo as ReprojectedVideo,Co as Session,Ko as StatusBadge,Bo as StatusBadgeSchema,ls as Text,zo as TextStream,Xe as TextStreamError,Xo as TextStreamSchema,rr as UrunActivationOverlay,ys as UrunAudio,bt as UrunAuthProvider,js as UrunCamera,Si as UrunControlSender,ra as UrunCreditsGate,mi as UrunDocPanel,Ke as UrunErrorBoundary,yi as UrunEventSpine,Yi as UrunIdleWarning,xn as UrunJwtProvider,jn as UrunProvider,Bi as UrunSessionClock,Gi as UrunSessionEnded,Fi as UrunSessionGate,kn as UrunSessionPaused,Vi as UrunSessionStatus,er as UrunSessionWaking,di as UrunStreamTail,Es as UrunVoice,He as Video,ft as Voice,rt as authMode,qd as createCreditsClient,Jt as createDocStore,Yd as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,Zd as isWakingPhase,Yt as parseJsonObject,we as pushCapped,mr as readOperatorToken,Vo as registerComponent,Fe as resumeUrunAudioContext,Yr as textDelta,fe as urunPublicEnv,tr as useActivation,Zn as useApp,go as useChat,lo as useCompletion,Rt as useConfirmOnLeave,ar as useCredits,Ze as useDocStore,ui as useGenerationTick,Xr as useImageFrame,ko as useInputPresence,zr as useMetricsPanel,Ct as useOperatorOverride,qr as useProgressCard,zs as useReferenceImage,io as useRequest,Ro as useSession,ro as useSessionDirectory,si as useSessionDoc,yn as useSessionEndsAt,Cn as useSessionIdle,pe as useSessionPhase,la as useSessionStats,Zs as useSessionTrack,Qt as useSessionWake,Br as useStatusBadge,Zt as useStreamMessages,tn as useText,cs as useTextMeter,$r as useTextStream,$t as useUrunAudioLevel,Tt as useUrunAuth,aa as useUrunPrewake,Mn as usesWorkOSAuth};
2
+ import{a as bt,b as xn,c as Tt}from"./chunk-WF2OBDSX.mjs";import{useCallback as fr,useEffect as Fn,useMemo as vr,useRef as gr,useState as Pt}from"react";import{Component as wn}from"react";import{jsx as cr,jsxs as Un}from"react/jsx-runtime";var Ke=class extends wn{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Un("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[cr("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),cr("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as An}from"react";var Te=An(null);function ke(e){return e&&e.trim()?e.trim():void 0}function fe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return ke(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return ke(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ke(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=fe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||fe("VERCEL_ENV")==="production"?"workos":fe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Mn(){return rt()==="workos"}import{useEffect as _n,useRef as Nn}from"react";var In="urun.operator_token",dr=null,lr="op",On="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function pr(){return typeof window<"u"}function mr(){return dr}function Ln(){if(!pr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(lr);if(!r)return null;dr=r,t.delete(lr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Dn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Ct(e){let t=Nn(e);t.current=e,_n(()=>{if(!pr())return;Ln();let r=o=>{if(!Dn(o))return;let n=mr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as Vn}from"react";function Rt(e=!0){Vn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as Le,jsxs as Kn}from"react/jsx-runtime";var Hn="/api/urun-token",qn=1e4;function Wn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Sr(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function hr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function Et(e){let t=e===void 0?void 0:JSON.stringify(e);return vr(()=>e,[t])}function Bn(e,t){return typeof e=="function"?e(t):e!==void 0?e:Kn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[Le("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Le("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function jn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:c,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:g,videoPlayout:v,sessionStats:x,confirmOnLeave:k=!1,fallback:d,errorFallback:P,children:S}){let h=n===void 0&&t===void 0;if(!h&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!h&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let y=r??o;if(h&&(typeof y!="string"||y.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Rt(k);let[p,R]=Pt(),[C,U]=Pt(null),A=gr(void 0),m=gr(null),[E,b]=Pt(null);Ct(M=>b({jwt:M}));let _=Tt(),B=fe("NEXT_PUBLIC_SESSION_TOKEN")??fe("NEXT_PUBLIC_URUN_JWT"),j=rt(),I=E!==null,$=j==="workos"&&!n&&!I&&!h,Y=n??(j==="jwt"?B:void 0)??p?.token,X=I?E.jwt:Y,ce=s??fe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),w=$&&!X&&!_?.getAccessToken,L=t??p?.orgId,W=e??p?.gatewayUrl,q=h&&p===void 0,O=h&&p!==void 0&&!W?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,K=w?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,te=C??O??K,J=hr("NEXT_PUBLIC_URUN_TOKEN_URL",fe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Hn,Z=hr("NEXT_PUBLIC_URUN_EVENTS_URL",fe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,me=fr(async M=>{if(!M?.forceRefresh){let G=A.current;if(!G)return G;let se=Wn(G);if(se===null||se-Date.now()>qn)return G}return(await(m.current??(m.current=(async()=>{try{let G=await Sr(J);return A.current=G.token,R(G),G}finally{m.current=null}})()))).token},[J]),oe=fr(async()=>X,[X]),be=typeof X=="string"&&X.trim().length>0,re=$?_?.getAccessToken:h&&!I?me:be?oe:void 0,Q=Et(g),z=Et(v),T=Et(x),D=vr(()=>({appId:y,baseUrl:W??"",orgId:L??"",jwt:X,getAccessToken:$?_?.getAccessToken:h&&!I?me:void 0,authProvider:ce,eventsUrl:Z,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:Q,videoPlayout:z,sessionStats:T,priority:I?"preempt":void 0}),[y,_,W,ce,X,Z,L,a,u,f,l,Q,z,T,$,I,h,me]);return Fn(()=>{if(!h)return;let M=new AbortController;return U(null),(async()=>{try{let H=await Sr(J,M.signal);A.current=H.token,R(H)}catch(H){if(M.signal.aborted)return;U(H instanceof Error?H:new Error(String(H)))}})(),()=>M.abort()},[h,J]),Le(Ke,{fallback:d,children:te?Bn(P,te):q?Le("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Le(Te.Provider,{value:D,children:re?Le(bt,{getAccessToken:re,children:S}):S})})}import{useContext as $n,useEffect as Gn,useMemo as yr,useReducer as Xn,useRef as xt}from"react";import{App as zn}from"@urun-sh/core";function kr(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Jn(e,t,r){let o=kr(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function Yn(e,t,r,o){let n=kr(o);return JSON.stringify({sessionId:n.sessionId,label:n.label,appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,activity:o?.activity??"auto",fnName:t,args:r??{}})}var Ue=new Map;var wt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Ut=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},At=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"){let c=a.error,u=c?.reason??`session ${this._session.id} entered the error phase`;n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get region(){return this._session.region}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}watchDownlinkStall(t={}){return this._session.watchDownlinkStall?this._session.watchDownlinkStall(t):()=>{}}on(t,r){return this._session.on(t,r)}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}activity(){this._session.activity?this._session.activity():this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new wt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Ut(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}async cancel(){let t=await this._session.cancel();return this._disposeHandle(),t}detach(){this._disposeHandle(),this._session.detach()}disconnect(){this.detach()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Zn(){let e=$n(Te);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Xn(i=>i+1,0),r=xt(new Map),o=xt(new Map),n=xt(null),s=yr(()=>zn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.allowWebTransport,e.allowWebRtcFallback,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return Gn(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Ue.get(a);u===c&&o.current.get(a)===c&&(u.disposeTimer&&(clearTimeout(u.disposeTimer),u.disposeTimer=null),u.handle.addNotifier(t),u.refCount+=1)}}return()=>{let a=new Map;for(let[c,u]of o.current){let f=Ue.get(c);f===u&&(f.handle.removeNotifier(t),f.refCount=Math.max(0,f.refCount-1),a.set(c,f),f.refCount===0&&(f.disposeTimer=setTimeout(()=>{let l=Ue.get(c);!l||l.refCount!==0||(Ue.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),yr(()=>{let i=new Map;return new Proxy({},{get(a,c){if(typeof c!="string")return;let u=i.get(c);if(u)return u;let f=(l,g)=>{let v=Jn(c,l,g),x=r.current.get(v);if(x&&!x.disposed)return x;let k=Yn(e,c,l,g),d=Ue.get(k);return d?.handle.disposed&&(d.disposeTimer&&clearTimeout(d.disposeTimer),Ue.delete(k),o.current.get(k)===d&&o.current.delete(k),d=void 0),d?d.disposeTimer&&(clearTimeout(d.disposeTimer),d.disposeTimer=null):(d={handle:new At(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Ue.set(k,d)),o.current.get(k)!==d&&(o.current.set(k,d),d.handle.addNotifier(t),d.refCount+=1),r.current.set(v,d.handle),d.handle};return i.set(c,f),f}})},[e,s])}import{useContext as Qn,useMemo as eo}from"react";import{sessionDirectory as to}from"@urun-sh/core";function ro(){let e=Qn(Te);if(!e)throw new Error("useSessionDirectory must be used within <UrunProvider>");if(!e.appId)throw new Error('useSessionDirectory requires <UrunProvider appId="...">');let{appId:t,baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}=e;return eo(()=>to(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}import{useCallback as Mt,useEffect as no,useMemo as oo,useRef as nt,useState as _t}from"react";function De(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function so(e){return e instanceof Error?e:new Error(String(e))}function io(e,t){let r=oo(()=>De(e),[e]),[o,n]=_t(void 0),[s,i]=_t(null),[a,c]=_t(!1),u=nt(t);u.current=t;let f=nt(0),l=nt(null),g=nt(!0);no(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=Mt(async d=>{l.current?.abort();let P=new AbortController;l.current=P;let S=++f.current,h=()=>g.current&&f.current===S;h()&&(c(!0),i(null));try{let y=await r.request(d,{...u.current,signal:P.signal});return h()&&(n(y),c(!1),u.current?.onSuccess?.(y)),y}catch(y){let p=so(y);throw h()&&(i(p),c(!1),u.current?.onError?.(p)),p}},[r]),x=Mt(d=>{v(d).catch(()=>{})},[v]),k=Mt(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:x,mutateAsync:v,data:o,error:s,isPending:a,reset:k}}import{useCallback as br,useEffect as ao,useMemo as uo,useRef as ot,useState as Nt}from"react";function Tr(e){return e instanceof Error?e:new Error(String(e))}var co=e=>typeof e=="string"?e:String(e);function lo(e,t){let r=uo(()=>De(e),[e]),[o,n]=Nt(""),[s,i]=Nt(!1),[a,c]=Nt(null),u=ot(t);u.current=t;let f=ot(0),l=ot(null),g=ot(!0);ao(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=br(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),x=br(async k=>{l.current?.cancel();let d=++f.current,P=()=>g.current&&f.current===d,S=u.current,h=S?.parseChunk??co,y=S?.buildPayload??(b=>({prompt:b}));P()&&(n(""),c(null),i(!0));let{parseChunk:p,buildPayload:R,onFinish:C,onError:U,...A}=S??{},m="",E;try{E=r.requestStream(y(k),A),l.current=E}catch(b){let _=Tr(b);P()&&(c(_),i(!1),S?.onError?.(_));return}try{for await(let b of E){if(f.current!==d)break;m+=h(b),P()&&n(m)}P()&&(i(!1),S?.onFinish?.(m))}catch(b){let _=Tr(b);P()&&(c(_),i(!1),S?.onError?.(_))}finally{l.current===E&&(l.current=null)}},[r]);return{completion:o,complete:x,stop:v,isStreaming:s,error:a}}import{useCallback as Cr,useEffect as po,useMemo as mo,useRef as Ve,useState as st}from"react";function Rr(e){return e instanceof Error?e:new Error(String(e))}var fo=e=>typeof e=="string"?e:String(e),Pr=0;function It(e){return Pr+=1,`${e}-${Pr}`}function go(e,t){let r=mo(()=>De(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(h=>({id:h.id??It("msg"),role:h.role,content:h.content}))),[s,i]=st(""),[a,c]=st(!1),[u,f]=st(null),l=Ve(t);l.current=t;let g=Ve(o);g.current=o;let v=Ve(s);v.current=s;let x=Ve(0),k=Ve(null),d=Ve(!0);po(()=>(d.current=!0,()=>{d.current=!1,k.current?.cancel(),k.current=null}),[]);let P=Cr(()=>{x.current++,k.current?.cancel(),k.current=null,d.current&&c(!1)},[]),S=Cr(async h=>{let y=h===void 0,p=(y?v.current:h)??"";if(!p.trim())return;k.current?.cancel();let C=++x.current,U=()=>d.current&&x.current===C,A=l.current,m=A?.parseChunk??fo,E={id:It("msg"),role:"user",content:p},b={id:It("msg"),role:"assistant",content:""},_=[...g.current,E].map(O=>({role:O.role,content:O.content})),B=[...g.current,E,b];g.current=B,n(B),y&&i(""),f(null),c(!0);let j=A?.buildPayload??(O=>({messages:O})),{initialMessages:I,parseChunk:$,buildPayload:Y,onFinish:X,onError:ce,...w}=A??{},L=O=>{n(K=>K.map(te=>te.id===b.id?{...te,content:O}:te))},W="",q;try{q=r.requestStream(j(_),w),k.current=q}catch(O){let K=Rr(O);U()&&(f(K),c(!1),A?.onError?.(K));return}try{for await(let O of q){if(x.current!==C)break;W+=m(O),U()&&L(W)}U()&&(c(!1),A?.onFinish?.({...b,content:W}))}catch(O){let K=Rr(O);U()&&(f(K),c(!1),A?.onError?.(K))}finally{k.current===q&&(k.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:S,stop:P,isStreaming:a,error:u}}import{useCallback as Ce,useEffect as Er,useMemo as So,useRef as xr,useState as wr}from"react";import{createInputPresencePublisher as ho,INPUT_PRESENCE_DEFAULT_HZ as vo,INPUT_PRESENCE_FIELD as yo}from"@urun-sh/core";var Ot=[];function ko(e,t={}){let{field:r=yo,hz:o=vo}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=So(()=>s?ho({awareness:{setLocalStateField:(p,R)=>s.setField(p,R)},field:r,hz:o}):null,[s,r,o]),a=xr(null);a.current=i;let[c,u]=wr(!1),[f,l]=wr(Ot),g=xr(!1);Er(()=>{if(i)return()=>i.dispose()},[i]);let v=Ce(()=>{let p=a.current;l(p?p.heldKeys():Ot)},[]),x=Ce(()=>{a.current?.clear(),l(Ot)},[]);Er(()=>{if(!n)return;let p=()=>!!n.pointerLockElement,R=()=>{if(p()){g.current=!1,u(!0);return}g.current||(u(!1),x())},C=b=>{p()&&(a.current?.keyDown(b.key),v())},U=b=>{a.current?.keyUp(b.key),v()},A=b=>{p()&&a.current?.movePointer(b.movementX,b.movementY)},m=b=>{p()&&a.current?.setButtons(b.buttons)},E=()=>{x()};return n.addEventListener("pointerlockchange",R),n.addEventListener("keydown",C),n.addEventListener("keyup",U),n.addEventListener("mousemove",A),n.addEventListener("mousedown",m),n.addEventListener("mouseup",m),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",R),n.removeEventListener("keydown",C),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",m),n.removeEventListener("mouseup",m),n.defaultView?.removeEventListener("blur",E)}},[n,x,v]);let k=Ce(p=>{p.requestPointerLock?.()},[]),d=Ce(()=>{g.current=!0,u(!0)},[]),P=Ce(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),x()},[n,x]),S=Ce(p=>{a.current?.keyDown(p),v()},[v]),h=Ce(p=>{a.current?.keyUp(p),v()},[v]),y=Ce((p,R)=>{a.current?.movePointer(p,R)},[]);return{engage:k,engageTouch:d,release:P,engaged:c,heldKeys:f,pressKey:S,releaseKey:h,movePointer:y}}import{forwardRef as Mo,useEffect as Lr,useImperativeHandle as _o,useMemo as No,useRef as ut}from"react";import{createCameraWarp as Io}from"@urun-sh/core";import{forwardRef as Eo,useCallback as Re,useEffect as $e,useImperativeHandle as xo,useRef as ne,useState as Ar}from"react";import{derivedLegRole as wo}from"@urun-sh/core";var it=null;function bo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=bo();return e?(it=new e,it):null}function Fe(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as To,useContext as Ur}from"react";import{jsx as Po}from"react/jsx-runtime";var Lt=To(null);function Co({session:e,children:t}){return Po(Lt.Provider,{value:e,children:t})}function ge(){return Ur(Lt)}function Ro(){let e=Ur(Lt);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{jsx as Or,jsxs as Ao}from"react/jsx-runtime";function Uo(e,t){return e-t>>>0<2147483648}var Mr=1e3;function _r(...e){console.debug("[video]",...e)}function Nr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(c=>c.on("track",()=>i(n())));return()=>{for(let c of a)c()}}}}function Ir(e,t,r){return r?[r,t]:[e,t]}var He=Eo(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:c=!1,objectFit:u="contain",className:f,style:l,videoClassName:g,placeholder:v,poster:x,children:k,onTrack:d,onFirstFrame:P,frameMarker:S,onFrameMarkerReached:h,onFrameMarkerUnsupported:y,onUnlockChange:p}=t,R=ge(),C=o??R,U=ne(null),A=ne(null),[m,E]=Ar(!1),[b,_]=Ar(!1),B=ne(!1),j=ne(null),I=ne(d);I.current=d;let $=ne(p);$.current=p;let Y=ne(P);Y.current=P;let X=ne(h);X.current=h;let ce=ne(y);ce.current=y;let w=ne(S??null);w.current=S??null;let L=Re(T=>{j.current!==T&&(j.current=T,$.current?.(T))},[]),W=ne(null),q=ne(null),O=Re((T,D=!1)=>{if(!D&&T===W.current||(W.current=T,q.current?.(),q.current=null,B.current=!1,_(!1),!T))return;let M=U.current;if(!M)return;let H=w.current,G=H?.rtpTimestamp??null,se=!1,N=()=>{se||(se=!0,ce.current?.())};H&&G==null&&N();let he=H!=null&&G!=null,Ie=ye=>{q.current?.(),q.current=null,B.current=!0,_(!0),Y.current?.(),ye&&X.current?.()};if(typeof M.requestVideoFrameCallback=="function"){let ye=!1,V=0,F=(ie,ae)=>{if(!ye){if(he){let le=ae?.rtpTimestamp;if(typeof le!="number"){N(),Ie(!1);return}if(!Uo(le,G)){V=M.requestVideoFrameCallback(F);return}Ie(!0);return}Ie(!1)}};V=M.requestVideoFrameCallback(F),q.current=()=>{ye=!0,M.cancelVideoFrameCallback?.(V)};return}he&&N();let ve=()=>{let ye=M.getVideoPlaybackQuality?.();(ye?ye.totalVideoFrames>0:M.readyState>=2&&M.videoWidth>0)&&Ie(!1)};M.addEventListener("loadeddata",ve),M.addEventListener("timeupdate",ve),M.addEventListener("playing",ve),q.current=()=>{M.removeEventListener("loadeddata",ve),M.removeEventListener("timeupdate",ve),M.removeEventListener("playing",ve)},ve()},[]);$e(()=>()=>{q.current?.(),q.current=null},[]);let K=S==null?null:`${S.rtpTimestamp??""}|${S.ptsMs??""}`,te=ne(K);$e(()=>{if(te.current===K||(te.current=K,K==null))return;let T=W.current;T&&O(T,!0)},[K,O]);let J=Re(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let T=U.current;return T&&T.srcObject!==A.current&&(T.srcObject=A.current),A.current},[]),Z=Re(T=>{let D=U.current;if(!D)return;let M=D.play();!M||typeof M.then!="function"||M.then(()=>{D.muted||L(!0)}).catch(H=>{if((H instanceof Error?H.name:String(H))==="NotAllowedError"&&!D.muted){_r(`play() blocked pending a user gesture (${T})`),L(!1);return}_r(`play() failed (${T})`,H)})},[L]),me=Re(()=>{let T=U.current;T&&(J(),!T.muted&&(Z("gesture"),Fe(),L(!0)))},[J,Z,L]),oe=Re(T=>{let D=J();if(D){for(let M of D.getVideoTracks())M!==T&&D.removeTrack(M);if(T&&!D.getVideoTracks().includes(T)){D.addTrack(T);let M=U.current;M&&(M.srcObject=D)}T&&Z("track-attach"),E(T!==null),O(T),I.current?.(T)}},[J,Z,O]),be=Re(T=>{let D=J();if(D){for(let M of D.getAudioTracks())M!==T&&D.removeTrack(M);T&&!D.getAudioTracks().includes(T)&&D.addTrack(T),T&&Z("audio-attach")}},[J,Z]),re=Re(T=>{U.current=T,T&&(a?(T.muted=!0,T.defaultMuted=!0,T.setAttribute("muted",""),j.current=null):(T.muted=!1,T.defaultMuted=!1,T.removeAttribute("muted")),T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),J())},[J,a]);xo(r,()=>({get element(){return U.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return B.current},unlock:me,get unlocked(){return j.current===!0}}),[me]);let Q=wo(n)!==void 0;$e(()=>{Q&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[Q,n]);let z=i!==void 0;return $e(()=>{if(z){oe(i??null);return}if(Q){oe(null);return}if(!C)return;let T=Nr(C,Ir(n,"video")),D=()=>{let N=A.current;return N?N.getVideoTracks()[0]??null:null},M=N=>{if(N!==D()&&(oe(N),N)){let he=()=>{D()===N&&oe(null)};N.addEventListener("ended",he)}},H=T.track;H&&H.readyState==="live"&&M(H);let G=T.on("track",N=>{N&&N.readyState!=="live"||M(N)}),se=setInterval(()=>{let N=T.track;N&&N.readyState==="live"&&M(N)},Mr);return()=>{G(),clearInterval(se)}},[C,n,Q,z,i,oe]),$e(()=>{if(z||!C||s===!1||Q)return;let T=Nr(C,Ir(n,"audio",s)),D=()=>{let N=A.current;return N?N.getAudioTracks()[0]??null:null},M=N=>{if(N!==D()&&(be(N),N)){let he=()=>{D()===N&&be(null)};N.addEventListener("ended",he)}},H=T.track;H&&H.readyState==="live"&&M(H);let G=T.on("track",N=>{N&&N.readyState!=="live"||M(N)}),se=setInterval(()=>{let N=T.track;N&&N.readyState==="live"&&M(N)},Mr);return()=>{G(),clearInterval(se)}},[C,n,Q,s,z,be]),Ao("div",{className:f,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":m?"true":"false","data-urun-video-framed":b?"true":"false",children:[Or("video",{ref:re,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),m?null:v,x===void 0?null:Or("div",{"data-urun-video-poster":"","aria-hidden":b||void 0,style:{position:"absolute",inset:0,...b?{opacity:0,pointerEvents:"none"}:null},children:x}),k]})});import{jsx as Dr,jsxs as Do}from"react/jsx-runtime";var Oo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},Lo=Mo(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:c=!0,documentTarget:u,...f}=o??{},l=u!==void 0?u:typeof document<"u"?document:null,g=ut(null),v=ut(null),x=ut(0),k=ut(f);k.current=f;let d=No(()=>Io(k.current),[]);return _o(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:d,get lastDrawTs(){return x.current}}),[d]),Lr(()=>{if(!i)return;let P=0,S=0,h=null,y=R=>{typeof R.requestVideoFrameCallback=="function"&&(h=R,S=R.requestVideoFrameCallback(function C(){d.frameArrived(),S=R.requestVideoFrameCallback(C)}))},p=R=>{P=requestAnimationFrame(p);let C=v.current,U=g.current?.element??null;if(!C||!U||(U!==h&&(h&&S&&h.cancelVideoFrameCallback?.(S),y(U)),U.readyState<2))return;d.tick(R);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,m=Math.max(1,Math.round(C.clientWidth*A)),E=Math.max(1,Math.round(C.clientHeight*A));(C.width!==m||C.height!==E)&&(C.width=m,C.height=E);let b=C.getContext("2d");if(!b)return;let _=d.transform(),B=U.videoWidth||m,j=U.videoHeight||E,$=Math.max(m/B,E/j)*(1+a)*_.scale;b.setTransform($,0,0,$,m/2+_.translateX*m,E/2+_.translateY*E),b.drawImage(U,-B/2,-j/2),x.current=R};return P=requestAnimationFrame(p),()=>{cancelAnimationFrame(P),h&&S&&h.cancelVideoFrameCallback?.(S)}},[i,a,d]),Lr(()=>{if(!i||!c||!l)return;let P=()=>!!l.pointerLockElement,S=C=>{P()&&d.keyDown(C.key)},h=C=>d.keyUp(C.key),y=C=>{P()&&d.pointerDelta(C.movementX,C.movementY)},p=()=>{P()||d.clearKeys()},R=()=>d.clearKeys();return l.addEventListener("keydown",S),l.addEventListener("keyup",h),l.addEventListener("mousemove",y),l.addEventListener("pointerlockchange",p),l.defaultView?.addEventListener("blur",R),()=>{l.removeEventListener("keydown",S),l.removeEventListener("keyup",h),l.removeEventListener("mousemove",y),l.removeEventListener("pointerlockchange",p),l.defaultView?.removeEventListener("blur",R)}},[i,c,l,d]),i?Do(He,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Dr("canvas",{ref:v,style:Oo,"data-urun-warp":""}),n]}):Dr(He,{ref:g,...s,children:n})});var Vr=new Map;function Vo(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Vr.set(e,{component:t,schema:r})}function Fr(e,t){let r=Vr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Ho,jsx as ct}from"react/jsx-runtime";function Fo({name:e,props:t,fallback:r}){let o=Fr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(Ho,{children:r}):ct("div",{className:"urun-component-error",role:"alert",children:ct("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return ct(n,{...o.validatedProps})}import{z as Ge}from"zod";import{jsx as Dt,jsxs as Hr}from"react/jsx-runtime";var qo=Ge.object({step:Ge.number().min(0),total:Ge.number().min(1),label:Ge.string().optional(),variant:Ge.enum(["default","success","error"]).default("default")});function qr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Wo(e){let{step:t,total:r,label:o,variant:n,percentage:s}=qr(e);return Hr("div",{className:"urun-progress-card","data-variant":n,children:[o&&Dt("div",{className:"urun-progress-label",children:o}),Dt("div",{className:"urun-progress-bar",children:Dt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Hr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as Wr,jsxs as $o}from"react/jsx-runtime";var Bo=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),jo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Br(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??jo[t]??t;return{state:t,message:n,isActive:o}}function Ko(e){let{state:t,message:r,isActive:o}=Br(e);return $o("span",{className:"urun-status-badge","data-state":t,children:[Wr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Wr("span",{className:"urun-status-message",children:r})]})}import{useRef as jr,useEffect as Go}from"react";import{z as Ft}from"zod";import{jsx as Kr,jsxs as Jo}from"react/jsx-runtime";var Xo=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function $r(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function zo(e){let{text:t,streaming:r}=$r(e),o=jr(null),n=jr(0);return Go(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Jo("div",{className:"urun-text-stream",children:[Kr("span",{ref:o,className:"urun-text-content"}),r&&Kr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as Gr,jsxs as Qo}from"react/jsx-runtime";var Yo=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Xr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Zo(e){let{src:t,alt:r,caption:o}=Xr(e);return Qo("figure",{className:"urun-image-frame",children:[Gr("img",{className:"urun-image",src:t,alt:r}),o&&Gr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as Pe}from"zod";import{jsx as Ht,jsxs as rs}from"react/jsx-runtime";var es=Pe.object({metrics:Pe.array(Pe.object({label:Pe.string(),value:Pe.union([Pe.string(),Pe.number()]),unit:Pe.string().optional()}))});function zr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function ts(e){let{metrics:t}=zr(e);return Ht("div",{className:"urun-metrics-panel",children:t.map((r,o)=>rs("div",{className:"urun-metric-card",children:[Ht("div",{className:"urun-metric-label",children:r.label}),Ht("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as qt,useRef as ue,useState as ns}from"react";import{jsx as ds}from"react/jsx-runtime";function Ee(e){return e&&typeof e=="object"?e:null}function Yr(e){if(typeof e=="string")return e;let t=Ee(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function os(e){if(typeof e=="string")return"delta";let t=Ee(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function ss(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function is(e){let t=Ee(e),r=t?.body;return ss(r,Ee(Ee(r)?.error)?.message,Ee(r)?.error,Ee(r)?.message,Ee(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var Xe=class extends Error{name="TextStreamError"},as=4,Zr=3,Qr=240,Jr=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function en(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function us(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function tn(e){let{session:t,stream:r}=e,o=ue(e);qt(()=>{o.current=e});let n=ue(null),s=ue(()=>{}),i=ue(null),a=ue(""),c=ue(""),u=ue(null),f=ue(!1),l=ue(!1),g=ue(!1),v=ue(null),x=ue(en()),k=dt(h=>{if(n.current=h,!h){i.current=null;return}let y=i.current;if(y&&y.parentNode===h)return;let p=h.ownerDocument.createTextNode(c.current);h.appendChild(p),i.current=p,a.current.length>0&&s.current()},[]),d=dt(()=>{u.current=null;let h=i.current,y=a.current;if(y.length>0){let A=o.current,m=A.smoothCharsPerFrame??Zr,E=A.smoothThreshold??Qr,b=A.smooth&&y.length<=E?y.slice(0,m):y;a.current=y.slice(b.length),c.current+=b,h?.appendData(b)}let p=x.current,R=c.current.length,C=v.current===null?0:Math.max(0,Jr()-v.current),U=Math.round(R/as);if(p.chars=R,p.tokens=U,p.elapsedMs=C,p.tokensPerSecond=C>0?U*1e3/C:0,a.current.length>0){P(),o.current.onMeter?.(p);return}if(!f.current&&!g.current){g.current=!0,p.done=!0,o.current.onMeter?.(p),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(p)},[]),P=dt(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>d()))},[d]);s.current=P,qt(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",c.current="",l.current=!1,g.current=!1,v.current=null,f.current=!0,us(x.current),i.current&&(i.current.data="");let h=!1,y=null;return(async()=>{try{for(y=t.stream(r).messages()[Symbol.asyncIterator]();;){let R=await y.next();if(h)return;if(R.done)break;let C=R.value,U=os(C);if(U==="error")throw new Xe(is(C));if(U==="done")break;if(U==="ignore")continue;let A=Yr(C);A&&(v.current===null&&(v.current=Jr()),a.current+=A,P())}if(h)return;y.return?.(void 0),f.current=!1,P()}catch(p){if(h)return;y?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(p instanceof Error?p:new Xe(String(p))),P()}})(),()=>{h=!0,f.current=!1,y?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,P]);let S=dt(()=>c.current,[]);return{ref:k,meterRef:x,getText:S}}function cs(e,t=250){let[r,o]=ns(en);return qt(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function ls(e){let{className:t,style:r,...o}=e,{ref:n}=tn(o);return ds("span",{ref:n,className:t,style:r})}import{forwardRef as ps}from"react";import{jsx as fs}from"react/jsx-runtime";var ms=ps(function(t,r){let{stream:o="image",...n}=t;return fs(He,{ref:r,stream:o,...n})});import{forwardRef as gs,useCallback as qe,useEffect as Wt,useImperativeHandle as Ss,useRef as We}from"react";import{observePageLifecycle as hs}from"@urun-sh/core";import{jsx as ks}from"react/jsx-runtime";var vs=1e3,rn=200;function Bt(...e){console.debug("[audio]",...e)}var pt=gs(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f}=t,l=ge(),g=o??l,v=We(null),x=We(null),k=We(null),d=We(null),P=We(c);P.current=c;let S=We(u);S.current=u;let h=qe(m=>{k.current!==m&&(k.current=m,S.current?.(m))},[]),y=qe(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let m=v.current;return m&&m.srcObject!==x.current&&(m.srcObject=x.current),x.current},[]),p=qe(m=>{let E=v.current;if(!E)return;let b=E.play();!b||typeof b.then!="function"||b.then(()=>{E.muted||h(!0)}).catch(_=>{let B=_ instanceof Error?_.name:String(_);if(B==="AbortError"){Bt(`play() aborted (${m}); retrying in ${rn}ms`),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,p(`${m}:retry`)},rn);return}if(B==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${m})`),h(!1);return}Bt(`play() failed (${m})`,_)})},[h]),R=qe(m=>{let E=y();if(E){for(let b of E.getAudioTracks())b!==m&&E.removeTrack(b);m&&!E.getAudioTracks().includes(m)&&E.addTrack(m),m&&p("track-attach"),P.current?.(m)}},[y,p]),C=qe(()=>{let m=v.current;m&&(y(),m.muted=!1,p("gesture"),Fe(),h(!0))},[y,p,h]);Ss(r,()=>({unlock:C,get unlocked(){return k.current===!0},get element(){return v.current}}),[C]);let U=qe(m=>{v.current=m,m&&(m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),y()),f?.(m)},[y,f]),A=s!==void 0;return Wt(()=>{if(A){R(s??null);return}if(!g)return;let m=g.stream(n),E=()=>{let I=x.current;return I?I.getAudioTracks()[0]??null:null},b=I=>{if(I!==E()&&(R(I),I)){let $=()=>{E()===I&&R(null)};I.addEventListener("ended",$)}},_=m.track;_&&_.readyState==="live"&&b(_);let B=m.on("track",I=>{I&&I.readyState!=="live"||b(I)}),j=setInterval(()=>{let I=m.track;I&&I.readyState==="live"&&b(I)},vs);return()=>{B(),clearInterval(j)}},[g,n,A,s,R]),Wt(()=>hs(()=>{Fe(),k.current===!0&&p("foreground")}),[p]),Wt(()=>()=>{d.current&&clearTimeout(d.current)},[]),ks("audio",{ref:U,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),ys=pt;import{forwardRef as bs,useCallback as Ae,useEffect as jt,useImperativeHandle as Ts,useRef as de}from"react";import{observePageLifecycle as Cs,sessionFailureFromMediaError as Rs,sharedCaptureController as Ps}from"@urun-sh/core";import{jsx as xs}from"react/jsx-runtime";var nn={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}var ft=bs(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=nn,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:x,onUnlockChange:k,capture:d}=t,P=ge(),S=o??P,h=de(null),y=de(null),p=de(null),R=de([]),C=de(!1),U=de(l);U.current=l;let A=de(g);A.current=g;let m=de(v);m.current=v;let E=Ae(w=>{C.current!==w&&(C.current=w,U.current?.(w))},[]),b=Ae(()=>{for(let w of R.current)w();R.current=[],p.current?.release(),p.current=null,y.current&&(y.current=null,m.current?.(null))},[]),_=Ae(async()=>{let w=p.current;if(w){let O=await w.update(a);return y.current=w.stream,m.current?.(w.stream),O}let W=await(d??Ps()).claim("audio",a);p.current=W,R.current=[W.onTrack((O,K)=>{y.current=K,m.current?.(K),C.current&&S?.stream(n).attach(O).catch(te=>mt("mic re-attach after one-capture re-acquire failed",te))}),W.onLost(O=>{p.current=null,R.current=[],y.current=null,m.current?.(null),E(!1),A.current?.(O)})],y.current=W.stream,m.current?.(W.stream);let q=W.track;if(!q)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return q},[d,a,S,n,E]),B=Ae(async()=>{b(),E(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,b,E]),j=Ae(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");h.current?.unlock();let w;try{w=await _()}catch(q){b();let O=Rs(q,S.status);throw A.current?.(O),O}S.connect?.();let L;for(let q=1;q<=u;q++)try{await S.whenLive(c!==void 0?{timeout:c}:void 0),await S.stream(n).attach(w),E(!0);return}catch(O){L=O,mt(`start attempt ${q}/${u} failed`,O),q<u&&await new Promise(K=>setTimeout(K,f))}b(),E(!1);let W=L instanceof Error?L:new Error(String(L??"voice start failed"));throw A.current?.(W),W},[S,n,c,u,f,_,b,E]);Ts(r,()=>({start:j,stop:B,unlock:()=>h.current?.unlock(),get active(){return C.current},get micStream(){return y.current},get audio(){return h.current}}),[j,B]);let I=de(j);I.current=j;let $=de(null),Y=Ae((w,L)=>{w.promise.then(()=>{L&&(b(),E(!1)),w.session.stream(w.streamName).detach().catch(()=>{})})},[b,E]);jt(()=>{if(!i||!S)return;let w=$.current;w&&(w.session!==S||w.streamName!==n)&&(w.disposeTimer&&clearTimeout(w.disposeTimer),Y(w,!1),w=null),w?w.disposeTimer&&(clearTimeout(w.disposeTimer),w.disposeTimer=null):(w={session:S,streamName:n,promise:I.current().catch(()=>{}),refCount:0,disposeTimer:null},$.current=w),w.refCount+=1;let L=w;return()=>{L.refCount-=1,!(L.refCount>0)&&(L.disposeTimer=setTimeout(()=>{$.current===L&&($.current=null),Y(L,!0)},0))}},[i,S,n,Y]);let X=de(!1),ce=Ae(async()=>{if(!S||!C.current||X.current)return;let w=y.current?.getAudioTracks()[0]??null;if(w&&w.readyState==="live"){try{await S.stream(n).attach(w)}catch(L){mt("foreground mic re-assert failed (will retry on next pass)",L)}return}X.current=!0;try{let L=await _();await S.stream(n).attach(L)}catch(L){let W=L instanceof Error?L:new Error(String(L));mt("foreground mic re-acquire failed",W),A.current?.(W)}finally{X.current=!1}},[S,n,_]);return jt(()=>{let w=()=>{ce()};return S&&typeof S.onRecovery=="function"?S.onRecovery(w):Cs(w)},[S,ce]),jt(()=>b,[b]),s?xs(pt,{ref:h,session:S,stream:n,onTrack:x,onUnlockChange:k}):null}),Es=ft;import{forwardRef as As,useImperativeHandle as Ms,useRef as on,useState as _s}from"react";import{useEffect as ws,useState as Us}from"react";var Kt={level:0,speaking:!1};function $t(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Us(Kt);return ws(()=>{if(!e){i(Kt);return}let a=at();if(!a||typeof MediaStream>"u")return;let c;e instanceof MediaStream?c=e:(c=new MediaStream,c.addTrack(e));let u,f;try{u=a.createMediaStreamSource(c),f=a.createAnalyser(),f.fftSize=r,u.connect(f)}catch{return}let l=new Uint8Array(f.fftSize),v=setInterval(()=>{f.getByteTimeDomainData(l);let x=0;for(let d=0;d<l.length;d++){let P=(l[d]-128)/128;x+=P*P}let k=Math.sqrt(x/l.length);i(d=>{let P=k>n;return Math.abs(d.level-k)<.005&&d.speaking===P?d:{level:k,speaking:P}})},o);return()=>{clearInterval(v),u.disconnect(),i(Kt)}},[e,r,o,n]),s}import{Fragment as Ls,jsx as gt,jsxs as Ds}from"react/jsx-runtime";var Ns={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Is={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Os=As(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:c,onActiveChange:u,onError:f,onMicStream:l,capture:g}=t,v=ge(),x=o??v,k=on(null),[d,P]=_s(null),S=on(l);S.current=l;let{level:h,speaking:y}=$t(a?d:null);return Ms(r,()=>({start:()=>{let p=k.current;return p?p.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>k.current?.stop()??Promise.resolve(),get active(){return k.current?.active??!1},get micStream(){return k.current?.micStream??null}}),[]),Ds(Ls,{children:[gt(ft,{ref:k,session:x,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:p=>{P(p),S.current?.(p)}}),a?gt("span",{className:c,style:Ns,"data-urun-mic":"","data-urun-mic-active":d?"true":"false","data-urun-mic-speaking":y?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(h*100)/100,children:gt("span",{style:Is,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(h*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as Vs,sessionFailureFromMediaError as Fs,sharedCaptureController as Hs}from"@urun-sh/core";import{forwardRef as an,useCallback as Se,useEffect as Gt,useImperativeHandle as qs,useRef as ee,useState as ze}from"react";import{jsx as xe,jsxs as sn}from"react/jsx-runtime";var un={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Xt(...e){console.debug("[camera]",...e)}function Ws(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Bs(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var cn=an(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:c,autoStart:u=!0,mirror:f="auto",connectTimeoutMs:l,visible:g=!1,className:v,videoClassName:x,onActiveChange:k,onError:d,onStream:P,onTrack:S,children:h,capture:y,flipControl:p="auto",flipControlClassName:R,onDevices:C}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":c??"environment",A=ge(),m=o??A,E=ee(null),b=ee(null),_=ee(null),B=ee([]),j=ee(null),I=ee(!1),$=ee(!1),Y=ee(U),[X,ce]=ze(U),[w,L]=ze(!1),[W,q]=ze(null),[O,K]=ze(!1),[te]=ze(Ws),J=ee(k);J.current=k;let Z=ee(d);Z.current=d;let me=ee(P);me.current=P;let oe=ee(S);oe.current=S;let be=ee(C);be.current=C;let re=Se(V=>{I.current!==V&&(I.current=V,L(V),J.current?.(V))},[]);Gt(()=>{if(!w){q(null);return}let V=!1,F=()=>{Bs().then(ae=>{V||(q(ae),ae&&be.current?.(ae))})};F();let ie=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ie?.addEventListener=="function"?(ie.addEventListener("devicechange",F),()=>{V=!0,ie.removeEventListener?.("devicechange",F)}):()=>{V=!0}},[w]);let Q=Se(V=>{let F=E.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=V,V&&F.play()?.catch?.(ie=>Xt("preview play() failed",ie)))},[]),z=Se(()=>{$.current=!1,j.current?.(),j.current=null;for(let V of B.current)V();B.current=[],_.current?.release(),_.current=null,b.current&&(b.current=null,me.current?.(null),oe.current?.(null)),Q(null)},[Q]),T=Se((V,F)=>{j.current?.(),b.current=F,Q(F),me.current?.(F);let ie=()=>{b.current===F&&(Xt("camera track ended (device removed or permission revoked)"),z(),re(!1))};V.addEventListener("ended",ie),j.current=()=>V.removeEventListener("ended",ie)},[Q,z,re]),D=Se(async V=>{let F=n!==!1;if(F&&!m)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ie={...un,...s,facingMode:V},ae;try{let le=_.current;if(le)ae=await le.update(ie);else{let Be=await(y??Hs()).claim("video",ie);if(_.current=Be,B.current=[Be.onTrack((je,Pn)=>{T(je,Pn),I.current&&(!F||!m||m.stream(n).attachVideo(je).then(()=>oe.current?.(je)).catch(En=>Xt("camera re-publish after one-capture re-acquire failed",En)))}),Be.onLost(je=>{_.current=null,B.current=[],z(),re(!1),Z.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ae=Be.track}}catch(le){let Oe=Fs(le,m?.status);throw Z.current?.(Oe),Oe}Y.current=V,ce(V),T(ae,_.current?.stream??new MediaStream([ae]));try{F&&m&&(m.connect?.(),await m.whenLive(l!==void 0?{timeout:l}:void 0),await m.stream(n).attachVideo(ae)),$.current=F?n:!1}catch(le){z(),re(!1);let Oe=le instanceof Error?le:new Error(String(le));throw Z.current?.(Oe),Oe}oe.current?.(ae),re(!0)},[m,n,s,l,y,T,z,re]),M=Se(V=>D(V?.facingMode??Y.current),[D]),H=Se(async V=>{let F=$.current===n;I.current&&Y.current===V&&F||await D(V)},[D,n]),G=Se(()=>D(Y.current==="environment"?"user":"environment"),[D]),se=Se(async()=>{z(),re(!1),n!==!1&&await m?.stream(n).detachVideo().catch(()=>{})},[m,n,z,re]),N=Se(async V=>{let F=E.current;if(!F)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await Vs(F,V)},[]);qs(r,()=>({start:M,stop:se,flip:G,setFacingMode:H,capturePhoto:N,get active(){return I.current},get facingMode(){return Y.current},get stream(){return b.current},get element(){return E.current}}),[M,se,G,H,N]);let he=ee(H);if(he.current=H,Gt(()=>{u&&(n!==!1&&!m||he.current(U).catch(()=>{}))},[u,m,U,n]),Gt(()=>z,[z]),!g)return null;let Ie=f==="auto"?X==="user":f,ve=w&&(p===!0||p==="auto"&&te&&(W?.length??0)>1),ye=()=>{O||(K(!0),G().catch(()=>{}).finally(()=>K(!1)))};return sn("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":X,children:[xe("video",{ref:E,className:x,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ie?{transform:"scaleX(-1)"}:{}}}),ve?xe("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ye,disabled:O,className:R,style:R?{opacity:O?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:O?.6:1},children:sn("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[xe("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),xe("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),xe("path",{d:"M14.5 10.5v1.6h-1.6"}),xe("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),xe("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,h]})}),js=an(function({preview:t=!0,...r},o){return xe(cn,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Ks,normalizeReferenceImage as $s,referenceImageErrorMessage as Gs}from"@urun-sh/core";import{useCallback as Je,useEffect as Xs,useRef as zt,useState as Ye}from"react";function zs(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=Ye(null),[a,c]=Ye(null),[u,f]=Ye(!1),[l,g]=Ye(null),[v]=Ye(Ks),x=zt(n);x.current=n;let k=zt(null),d=zt(0),P=Je(R=>{k.current&&URL.revokeObjectURL(k.current),k.current=R?URL.createObjectURL(new Blob([R.bytes],{type:R.type})):null,c(k.current),i(R),x.current?.(R)},[]);Xs(()=>()=>{d.current++,k.current&&URL.revokeObjectURL(k.current),k.current=null},[]);let S=Je(async R=>{let C=++d.current;f(!0),g(null);try{let U=await R();if(d.current!==C)return;P(U)}catch(U){if(d.current!==C)return;g(Gs(U))}finally{d.current===C&&f(!1)}},[P]),h=Je(R=>S(()=>$s(R,{maxSize:t,type:r,quality:o,source:"file"})),[S,t,r,o]),y=Je(R=>S(()=>R.capturePhoto({maxSize:t,type:r,quality:o})),[S,t,r,o]),p=Je(()=>{d.current++,g(null),f(!1),P(null)},[P]);return{reference:s,previewUrl:a,pick:h,capture:y,clear:p,busy:u,error:l,cameraAvailable:v}}import{useEffect as Js,useState as Ys}from"react";function Zs(e,t){let[r,o]=Ys(null);return Js(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as oi}from"react";import{useEffect as ri,useMemo as ni}from"react";import{createStore as Qs}from"zustand/vanilla";import{useStore as ei}from"zustand";var ti=()=>{};function Jt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=Qs(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let u of s)u();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",u=>n.setState({doc:u})),e.onSynced(()=>n.setState({synced:!0}))]),i):ti,c=(u=>ei(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),c}function Ze(e,t){let r=ni(()=>Jt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return ri(()=>r.bind(),[r]),r}function si(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=oi(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as ii,useState as ai}from"react";function ui(e){let[t,r]=ai(null);return ii(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}import{useEffect as ci,useState as li}from"react";var Me=200;function we(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Qe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Yt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Zt(e,t,r={}){let o=r.cap??200,[n,s]=li([]);return ci(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await a.next();if(!i||c.done)break;s(u=>we(u,{at:Date.now(),payload:c.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as St,jsxs as et}from"react/jsx-runtime";function di({session:e,name:t,cap:r,className:o}){let n=Zt(e,t,{cap:r});return et("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[et("div",{className:"urun-stream-tail-meta",children:[St("code",{children:t}),et("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),St("div",{className:"urun-stream-tail-log",children:n.length===0?et("span",{className:"urun-stream-tail-empty",children:["Waiting for ",St("code",{children:t})," messages\u2026"]}):n.map((s,i)=>et("div",{className:"urun-stream-tail-line",children:[St("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Qe(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as pi,useState as ln}from"react";import{jsx as _e,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=ln(""),[i,a]=ln(null),c=pi(()=>{let u=Yt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return ht("div",{className:"urun-doc-patch",children:[_e("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),ht("div",{className:"urun-doc-patch-actions",children:[_e("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?_e("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function mi({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ze(e,t),i=s(u=>u.doc),a=s(u=>u.synced),c=s(u=>u.set);return ht("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[ht("div",{className:"urun-doc-panel-meta",children:[_e("code",{children:t}),_e("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),_e("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?_e(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as fi,useState as gi}from"react";import{jsx as tt,jsxs as pn}from"react/jsx-runtime";function dn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Si({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=gi([]);return fi(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>we(c,{at:Date.now(),direction:"in",text:dn(Qe(a))},r))}):void 0),[e,t,r]),pn("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[tt(vt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(c=>we(c,{at:Date.now(),direction:"out",text:dn(a)},r))}}),tt("div",{className:"urun-control-sender-log",children:n.length===0?tt("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>pn("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[tt("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",tt("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as hi,useState as vi}from"react";import{jsx as yt,jsxs as ki}from"react/jsx-runtime";function yi({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=vi([]),a=t.join(","),c=r.join(",");return hi(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>we(v,{at:Date.now(),kind:l,text:g},o)),f=[];f.push(e.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of t){let g=e.stream(l);f.push(g.on("track",v=>u("track",`${l}: ${v?"track arrived":"track ended"}`)))}for(let l of r){let g=e.doc(l);f.push(g.on("change",()=>u("doc",`${l} changed`)))}return()=>f.forEach(l=>l())},[e,a,c,o]),yt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?yt("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,f)=>ki("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[yt("span",{className:"urun-event-spine-kind",children:u.kind})," ",yt("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${f}`))})}import{describeSessionPhase as Oi,isWakingPhase as Li}from"@urun-sh/core";import{useEffect as bi,useState as Ti}from"react";function pe(e){let[t,r]=Ti(e?.phase??null);return bi(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as xi}from"@urun-sh/core";import{useEffect as Ci,useRef as Ri,useState as Pi}from"react";import{isWakingPhase as Ei}from"@urun-sh/core";function Qt(e){let t=pe(e),r=Ei(t?.name),o=Ri(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=Pi(s);return Ci(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as wi,jsx as mn,jsxs as fn}from"react/jsx-runtime";function er({session:e,render:t,className:r}){let o=Qt(e);return!o.waking||!o.phase?null:mn("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):fn(wi,{children:[mn("span",{className:"urun-session-waking-label",children:xi(o.phase)})," ",fn("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Mi,useState as _i}from"react";import{useEffect as gn,useRef as Ui,useState as Sn}from"react";var Ai={event:null,elapsedMs:0};function tr(e,t){let[r,o]=Sn(null),n=Ui(0);gn(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=Sn(0);return gn(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(c());let u=setInterval(()=>i(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:Ai}import{jsx as hn,jsxs as vn}from"react/jsx-runtime";var Ni={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Ii(e){let[t,r]=_i(!1);return Mi(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function rr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=tr(e,t),i=Ii(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return hn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):vn("div",{className:"urun-activation-overlay-card",children:[hn("span",{className:"urun-activation-overlay-copy",children:a.hint??Ni[c]})," ",vn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ne,jsxs as nr}from"react/jsx-runtime";var Di={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",paused:"paused",error:"error",unknown:"unrecognized state"};function Vi({session:e,className:t}){let r=pe(e),o=r?.name??"idle",n=(r?.name==="queued"||r?.name==="waiting_for_capacity")&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:r?.name==="error"&&r.error?r.error.reason:r?.reason?r.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return nr("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ne("span",{className:"urun-session-status-dot","data-phase":o}),Ne("span",{className:"urun-session-status-label",children:Di[o]}),n?Ne("span",{className:"urun-session-status-detail",children:n}):null]})}function Fi({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=pe(e);if(s?.name==="live")return nr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ne(rr,{session:e})]});let i=r?r(s):Ne("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&Li(s.name)?Ne(er,{session:e}):s&&s.name!=="idle"?Oi(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return nr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ne("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Hi,useState as qi}from"react";import{jsx as ji}from"react/jsx-runtime";function yn(e){return pe(e)?.endsAt??null}function Wi(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Bi({session:e,urgentMs:t=6e4,className:r}){let n=yn(e)?.getTime()??null,[s,i]=qi(()=>n===null?null:Math.max(0,n-Date.now()));if(Hi(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let a=Wi(s);return ji("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{describeSessionPhase as Ki}from"@urun-sh/core";import{jsx as or,jsxs as Xi}from"react/jsx-runtime";var $i=new Set(["paused","error"]);function kn({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=pe(e);if(!s||!$i.has(s.name))return null;let i=o?o(s):or("span",{className:"urun-session-paused-copy",children:Ki(s)});return Xi("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?or("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?or("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var Gi=kn;import{useEffect as bn,useMemo as zi,useState as Tn}from"react";import{jsx as kt,jsxs as Zi}from"react/jsx-runtime";function sr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Cn(e){let t=zi(()=>e?e.doc("control"):null,[e]),[r,o]=Tn(()=>t?sr(t.get("idle")):null);return bn(()=>{if(!t){o(null);return}return o(sr(t.get("idle"))),t.on("change",()=>o(sr(t.get("idle"))))},[t]),r}function Ji(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Yi({session:e,onStillHere:t,className:r}){let o=Cn(e),n=o?.deadlineEpochS??null,[s,i]=Tn(null);if(bn(()=>{if(n===null){i(null);return}let c=()=>i(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return kt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:Zi("div",{className:"urun-idle-warning-card",children:[kt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),kt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Ji(s)} due to inactivity.`:"This session will end soon due to inactivity."}),kt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useCallback as Rn,useEffect as Qi,useRef as ea,useState as ir}from"react";function ta(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function ar(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=ir(null),[s,i]=ir(e!==null),[a,c]=ir(null),u=ea(e),f=Rn(async g=>{i(!0);try{let v=await g.getBalance();if(u.current!==g)return;n(v),c(null)}catch(v){if(u.current!==g)return;c(v instanceof Error?v:new Error(String(v)))}finally{u.current===g&&i(!1)}},[]);Qi(()=>{if(u.current=e,n(null),c(null),!e){i(!1);return}if(f(e),r!==void 0&&r>0){let g=setInterval(()=>{f(e)},r);return()=>{clearInterval(g),u.current===e&&(u.current=null)}}return()=>{u.current===e&&(u.current=null)}},[e,r,f]);let l=Rn(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:ta(o),loading:s,error:a,refresh:l}}import{jsx as ur}from"react/jsx-runtime";function ra({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=ar(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return ur("div",{className:i,children:t});let a=r?r(n):ur("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return ur("div",{className:i,children:a})}import{CreditsClient as Hd,createCreditsClient as qd,CreditsError as Wd,CreditsUnauthorizedError as Bd}from"@urun-sh/core";import{useContext as na,useEffect as oa,useState as sa}from"react";import{prewake as ia}from"@urun-sh/core";function aa(e){let t=na(Te),[r,o]=sa(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,c=t?.orgId,u=t?.jwt,f=t?.getAccessToken,l=t?.authProvider;return oa(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{ia({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(k=>{g||o(k)}).catch(()=>{})};v();let x=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(x)}},[n,s,i,a,c,u,f,l]),r}import{useEffect as ua,useState as ca}from"react";function la(e){let[t,r]=ca(null);return ua(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as Yd,isWakingPhase as Zd}from"@urun-sh/core";export{pt as Audio,cn as Camera,Fo as ComponentRenderer,Hd as CreditsClient,Wd as CreditsError,Bd as CreditsUnauthorizedError,un as DEFAULT_CAMERA_CONSTRAINTS,Me as DEFAULT_LOG_CAP,Zr as DEFAULT_SMOOTH_CHARS_PER_FRAME,Qr as DEFAULT_SMOOTH_THRESHOLD,nn as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,ms as Image,Zo as ImageFrame,Yo as ImageFrameSchema,ts as MetricsPanel,es as MetricsPanelSchema,Os as Mic,On as OPERATOR_CHORD_LABEL,In as OPERATOR_TOKEN_STORAGE_KEY,Wo as ProgressCard,qo as ProgressCardSchema,Lo as ReprojectedVideo,Co as Session,Ko as StatusBadge,Bo as StatusBadgeSchema,ls as Text,zo as TextStream,Xe as TextStreamError,Xo as TextStreamSchema,rr as UrunActivationOverlay,ys as UrunAudio,bt as UrunAuthProvider,js as UrunCamera,Si as UrunControlSender,ra as UrunCreditsGate,mi as UrunDocPanel,Ke as UrunErrorBoundary,yi as UrunEventSpine,Yi as UrunIdleWarning,xn as UrunJwtProvider,jn as UrunProvider,Bi as UrunSessionClock,Gi as UrunSessionEnded,Fi as UrunSessionGate,kn as UrunSessionPaused,Vi as UrunSessionStatus,er as UrunSessionWaking,di as UrunStreamTail,Es as UrunVoice,He as Video,ft as Voice,rt as authMode,qd as createCreditsClient,Jt as createDocStore,Yd as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,Zd as isWakingPhase,Yt as parseJsonObject,we as pushCapped,mr as readOperatorToken,Vo as registerComponent,Fe as resumeUrunAudioContext,Yr as textDelta,fe as urunPublicEnv,tr as useActivation,Zn as useApp,go as useChat,lo as useCompletion,Rt as useConfirmOnLeave,ar as useCredits,Ze as useDocStore,ui as useGenerationTick,Xr as useImageFrame,ko as useInputPresence,zr as useMetricsPanel,Ct as useOperatorOverride,qr as useProgressCard,zs as useReferenceImage,io as useRequest,Ro as useSession,ro as useSessionDirectory,si as useSessionDoc,yn as useSessionEndsAt,Cn as useSessionIdle,pe as useSessionPhase,la as useSessionStats,Zs as useSessionTrack,Qt as useSessionWake,Br as useStatusBadge,Zt as useStreamMessages,tn as useText,cs as useTextMeter,$r as useTextStream,$t as useUrunAudioLevel,Tt as useUrunAuth,aa as useUrunPrewake,Mn as usesWorkOSAuth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urun-sh/react",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "React bindings for the urun TypeScript SDK",
5
5
  "repository": {
6
6
  "type": "git",
@@ -53,7 +53,7 @@
53
53
  "dev": "tsup --watch"
54
54
  },
55
55
  "peerDependencies": {
56
- "@urun-sh/core": "^0.6.0",
56
+ "@urun-sh/core": "^0.6.2",
57
57
  "@workos-inc/authkit-nextjs": "^3.0.0",
58
58
  "@workos-inc/authkit-react": "^0.15.0 || ^0.16.0",
59
59
  "next": "^15.0.0 || ^16.0.0",