@urun-sh/react 0.6.34 → 0.6.36
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/CHANGELOG.md +10 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.36
|
|
4
|
+
|
|
5
|
+
- Version alignment with `@urun-sh/core` 0.6.36 (the degraded-phase UI contract
|
|
6
|
+
ships from core; react gains only the matching UI test coverage).
|
|
7
|
+
|
|
8
|
+
## 0.6.35
|
|
9
|
+
|
|
10
|
+
- Version alignment with `@urun-sh/core` 0.6.35 (hub session backend lives in
|
|
11
|
+
core; no react code change).
|
|
12
|
+
|
|
3
13
|
## 0.6.34
|
|
4
14
|
|
|
5
15
|
- Version alignment with `@urun-sh/core` 0.6.34 (the ENG-568 media-signaling
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
"use strict";var gr=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var Io=Object.getOwnPropertyNames;var Lo=Object.prototype.hasOwnProperty;var Do=(e,t)=>{for(var r in t)gr(e,r,{get:t[r],enumerable:!0})},Vo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Io(t))!Lo.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=Oo(t,n))||o.enumerable});return e};var Fo=e=>Vo(gr({},"__esModule",{value:!0}),e);var Rs={};Do(Rs,{Audio:()=>Nt,Camera:()=>Fr,ComponentRenderer:()=>On,CreditsClient:()=>Xe.CreditsClient,CreditsError:()=>Xe.CreditsError,CreditsUnauthorizedError:()=>Xe.CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS:()=>Vr,DEFAULT_LOG_CAP:()=>je,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Ar,DEFAULT_SMOOTH_THRESHOLD:()=>Mr,DEFAULT_VOICE_CONSTRAINTS:()=>Ir,DocPatchForm:()=>Lt,Image:()=>Yn,ImageFrame:()=>Wn,ImageFrameSchema:()=>Hn,MetricsPanel:()=>jn,MetricsPanelSchema:()=>Bn,Mic:()=>oo,OPERATOR_CHORD_LABEL:()=>Qr,OPERATOR_TOKEN_STORAGE_KEY:()=>Yr,ProgressCard:()=>Ln,ProgressCardSchema:()=>In,ReprojectedVideo:()=>An,Session:()=>bn,StatusBadge:()=>Vn,StatusBadgeSchema:()=>Dn,Text:()=>Xn,TextStream:()=>qn,TextStreamError:()=>lt,TextStreamSchema:()=>Fn,UrunActivationOverlay:()=>ur,UrunAudio:()=>eo,UrunAuthProvider:()=>Ct,UrunCamera:()=>so,UrunControlSender:()=>ho,UrunCreditsGate:()=>wo,UrunDocPanel:()=>go,UrunErrorBoundary:()=>ot,UrunEventSpine:()=>vo,UrunIdleWarning:()=>Eo,UrunJwtProvider:()=>Xr,UrunProvider:()=>un,UrunSessionClock:()=>Co,UrunSessionEnded:()=>xo,UrunSessionGate:()=>To,UrunSessionPaused:()=>Hr,UrunSessionStatus:()=>bo,UrunSessionWaking:()=>sr,UrunStreamTail:()=>fo,UrunVoice:()=>ro,Video:()=>Ye,Voice:()=>Ot,authMode:()=>Tt,createCreditsClient:()=>Xe.createCreditsClient,createDocStore:()=>zt,describeSessionPhase:()=>fr.describeSessionPhase,formatPayload:()=>ft,getUrunAudioContext:()=>Rt,isWakingPhase:()=>fr.isWakingPhase,parseJsonObject:()=>Zt,pushCapped:()=>Ve,readOperatorToken:()=>Sr,registerComponent:()=>_n,resumeUrunAudioContext:()=>Je,textDelta:()=>Ur,urunPublicEnv:()=>Pe,useActivation:()=>ir,useApp:()=>dn,useChat:()=>yn,useCompletion:()=>Sn,useConfirmOnLeave:()=>qt,useCredits:()=>dr,useDocStore:()=>mt,useGenerationTick:()=>mo,useImageFrame:()=>Er,useInputPresence:()=>kn,useMetricsPanel:()=>wr,useOperatorOverride:()=>Ft,useProgressCard:()=>Rr,useReferenceImage:()=>io,useRequest:()=>fn,useSession:()=>Tn,useSessionDirectory:()=>mn,useSessionDoc:()=>po,useSessionEndsAt:()=>qr,useSessionIdle:()=>Br,useSessionPhase:()=>Te,useSessionStats:()=>Mo,useSessionTrack:()=>ao,useSessionWake:()=>or,useStatusBadge:()=>Pr,useStreamMessages:()=>er,useText:()=>_r,useTextMeter:()=>Gn,useTextStream:()=>xr,useUrunAudioLevel:()=>Gt,useUrunAuth:()=>Dt,useUrunPrewake:()=>Ao,usesWorkOSAuth:()=>$r});module.exports=Fo(Rs);var le=require("react"),an=require("@urun-sh/core/internal");var jr=require("react"),bt=require("react/jsx-runtime"),ot=class extends jr.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 Kr=require("react"),He=(0,Kr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Pe(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=Pe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Pe("VERCEL_ENV")==="production"?"workos":Pe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function $r(){return Tt()==="workos"}var st=require("react"),zr=require("react/jsx-runtime"),Gr=(0,st.createContext)(null);function Ct({getAccessToken:e,children:t}){let r=(0,st.useMemo)(()=>({getAccessToken:e}),[e]);return(0,zr.jsx)(Gr.Provider,{value:r,children:t})}var Xr=Ct;function Dt(){return(0,st.useContext)(Gr)}var Vt=require("react"),Yr="urun.operator_token",Zr=null,Jr="op",Qr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function en(){return typeof window<"u"}function Sr(){return Zr}function qo(){if(!en())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(Jr);if(!r)return null;Zr=r,t.delete(Jr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Ho(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(!en())return;qo();let r=o=>{if(!Ho(o))return;let n=Sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var tn=require("react");function qt(e=!0){(0,tn.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 Oe=require("react/jsx-runtime"),Wo="/api/urun-token",Bo=1e4;function jo(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}}var rn=3,Ko=new Set([502,503,504]);function nn(e){return new Promise(t=>setTimeout(t,(0,an.computeBackoffDelay)(e)))}async function on(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=rn-1)throw a;await nn(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!Ko.has(o.status)||r>=rn-1)throw a;await nn(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function sn(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,le.useMemo)(()=>e,[t])}function $o(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Oe.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,Oe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Oe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function un({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:C,confirmOnLeave:h=!1,fallback:p,errorFallback:k,children:R}){let d=n===void 0&&t===void 0;if(!d&&(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(!d&&(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 b=r??o;if(d&&(typeof b!="string"||b.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);qt(h);let[m,w]=(0,le.useState)(),[P,x]=(0,le.useState)(null),A=(0,le.useRef)(void 0),M=(0,le.useRef)(null),[L,E]=(0,le.useState)(null);Ft(_=>E({jwt:_}));let O=Dt(),J=Pe("NEXT_PUBLIC_SESSION_TOKEN")??Pe("NEXT_PUBLIC_URUN_JWT"),X=Tt(),z=L!==null,Z=X==="workos"&&!n&&!z&&!d,ne=n??(X==="jwt"?J:void 0)??m?.token,Q=z?L.jwt:ne,T=s??Pe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),W=Z&&!Q&&!O?.getAccessToken,S=t??m?.orgId,N=e??m?.gatewayUrl,V=d&&m===void 0,F=d&&m!==void 0&&!N?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,U=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,oe=P??F??U,se=sn("NEXT_PUBLIC_URUN_TOKEN_URL",Pe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Wo,de=sn("NEXT_PUBLIC_URUN_EVENTS_URL",Pe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,we=(0,le.useCallback)(async _=>{if(!_?.forceRefresh){let ee=A.current;if(!ee)return ee;let ve=jo(ee);if(ve===null||ve-Date.now()>Bo)return ee}return(await(M.current??(M.current=(async()=>{try{let ee=await on(se);return A.current=ee.token,w(ee),ee}finally{M.current=null}})()))).token},[se]),he=(0,le.useCallback)(async()=>Q,[Q]),qe=typeof Q=="string"&&Q.trim().length>0,fe=Z?O?.getAccessToken:d&&!z?we:qe?he:void 0,pe=hr(g),ae=hr(v),y=hr(C),q=(0,le.useMemo)(()=>({appId:b,baseUrl:N??"",orgId:S??"",jwt:Q,getAccessToken:Z?O?.getAccessToken:d&&!z?we:void 0,authProvider:T,eventsUrl:de,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:pe,videoPlayout:ae,sessionStats:y,priority:z?"preempt":void 0}),[b,O,N,T,Q,de,S,a,u,f,l,pe,ae,y,Z,z,d,we]);return(0,le.useEffect)(()=>{if(!d)return;let _=new AbortController;return x(null),(async()=>{try{let $=await on(se,_.signal);A.current=$.token,w($)}catch($){if(_.signal.aborted)return;x($ instanceof Error?$:new Error(String($)))}})(),()=>_.abort()},[d,se]),(0,Oe.jsx)(ot,{fallback:p,children:oe?$o(k,oe):V?(0,Oe.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Oe.jsx)(He.Provider,{value:q,children:fe?(0,Oe.jsx)(Ct,{getAccessToken:fe,children:R}):R})})}var ge=require("react"),cn=require("@urun-sh/core");function ln(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Go(e,t,r){let o=ln(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function Xo(e,t,r,o){let n=ln(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 ze=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}get directOut(){return this._stream.directOut}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 mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}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 dn(){let e=(0,ge.useContext)(He);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ge.useReducer)(i=>i+1,0),r=(0,ge.useRef)(new Map),o=(0,ge.useRef)(new Map),n=(0,ge.useRef)(null),s=(0,ge.useMemo)(()=>(0,cn.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,ge.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=ze.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=ze.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=ze.get(c);!l||l.refCount!==0||(ze.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),(0,ge.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=Go(c,l,g),C=r.current.get(v);if(C&&!C.disposed)return C;let h=Xo(e,c,l,g),p=ze.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),ze.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new kr(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},ze.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(c,f),f}})},[e,s])}var Ht=require("react"),pn=require("@urun-sh/core");function mn(){let e=(0,Ht.useContext)(He);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,Ht.useMemo)(()=>(0,pn.sessionDirectory)(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}var ue=require("react");function it(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 zo(e){return e instanceof Error?e:new Error(String(e))}function fn(e,t){let r=(0,ue.useMemo)(()=>it(e),[e]),[o,n]=(0,ue.useState)(void 0),[s,i]=(0,ue.useState)(null),[a,c]=(0,ue.useState)(!1),u=(0,ue.useRef)(t);u.current=t;let f=(0,ue.useRef)(0),l=(0,ue.useRef)(null),g=(0,ue.useRef)(!0);(0,ue.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=(0,ue.useCallback)(async p=>{l.current?.abort();let k=new AbortController;l.current=k;let R=++f.current,d=()=>g.current&&f.current===R;d()&&(c(!0),i(null));try{let b=await r.request(p,{...u.current,signal:k.signal});return d()&&(n(b),c(!1),u.current?.onSuccess?.(b)),b}catch(b){let m=zo(b);throw d()&&(i(m),c(!1),u.current?.onError?.(m)),m}},[r]),C=(0,ue.useCallback)(p=>{v(p).catch(()=>{})},[v]),h=(0,ue.useCallback)(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:C,mutateAsync:v,data:o,error:s,isPending:a,reset:h}}var ce=require("react");function gn(e){return e instanceof Error?e:new Error(String(e))}var Jo=e=>typeof e=="string"?e:String(e);function Sn(e,t){let r=(0,ce.useMemo)(()=>it(e),[e]),[o,n]=(0,ce.useState)(""),[s,i]=(0,ce.useState)(!1),[a,c]=(0,ce.useState)(null),u=(0,ce.useRef)(t);u.current=t;let f=(0,ce.useRef)(0),l=(0,ce.useRef)(null),g=(0,ce.useRef)(!0);(0,ce.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=(0,ce.useCallback)(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),C=(0,ce.useCallback)(async h=>{l.current?.cancel();let p=++f.current,k=()=>g.current&&f.current===p,R=u.current,d=R?.parseChunk??Jo,b=R?.buildPayload??(E=>({prompt:E}));k()&&(n(""),c(null),i(!0));let{parseChunk:m,buildPayload:w,onFinish:P,onError:x,...A}=R??{},M="",L;try{L=r.requestStream(b(h),A),l.current=L}catch(E){let O=gn(E);k()&&(c(O),i(!1),R?.onError?.(O));return}try{for await(let E of L){if(f.current!==p)break;M+=d(E),k()&&n(M)}k()&&(i(!1),R?.onFinish?.(M))}catch(E){let O=gn(E);k()&&(c(O),i(!1),R?.onError?.(O))}finally{l.current===L&&(l.current=null)}},[r]);return{completion:o,complete:C,stop:v,isStreaming:s,error:a}}var re=require("react");function hn(e){return e instanceof Error?e:new Error(String(e))}var Yo=e=>typeof e=="string"?e:String(e),vn=0;function br(e){return vn+=1,`${e}-${vn}`}function yn(e,t){let r=(0,re.useMemo)(()=>it(e),[e]),[o,n]=(0,re.useState)(()=>(t?.initialMessages??[]).map(d=>({id:d.id??br("msg"),role:d.role,content:d.content}))),[s,i]=(0,re.useState)(""),[a,c]=(0,re.useState)(!1),[u,f]=(0,re.useState)(null),l=(0,re.useRef)(t);l.current=t;let g=(0,re.useRef)(o);g.current=o;let v=(0,re.useRef)(s);v.current=s;let C=(0,re.useRef)(0),h=(0,re.useRef)(null),p=(0,re.useRef)(!0);(0,re.useEffect)(()=>(p.current=!0,()=>{p.current=!1,h.current?.cancel(),h.current=null}),[]);let k=(0,re.useCallback)(()=>{C.current++,h.current?.cancel(),h.current=null,p.current&&c(!1)},[]),R=(0,re.useCallback)(async d=>{let b=d===void 0,m=(b?v.current:d)??"";if(!m.trim())return;h.current?.cancel();let P=++C.current,x=()=>p.current&&C.current===P,A=l.current,M=A?.parseChunk??Yo,L={id:br("msg"),role:"user",content:m},E={id:br("msg"),role:"assistant",content:""},O=[...g.current,L].map(F=>({role:F.role,content:F.content})),J=[...g.current,L,E];g.current=J,n(J),b&&i(""),f(null),c(!0);let X=A?.buildPayload??(F=>({messages:F})),{initialMessages:z,parseChunk:Z,buildPayload:ne,onFinish:Q,onError:T,...W}=A??{},S=F=>{n(U=>U.map(oe=>oe.id===E.id?{...oe,content:F}:oe))},N="",V;try{V=r.requestStream(X(O),W),h.current=V}catch(F){let U=hn(F);x()&&(f(U),c(!1),A?.onError?.(U));return}try{for await(let F of V){if(C.current!==P)break;N+=M(F),x()&&S(N)}x()&&(c(!1),A?.onFinish?.({...E,content:N}))}catch(F){let U=hn(F);x()&&(f(U),c(!1),A?.onError?.(U))}finally{h.current===V&&(h.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:R,stop:k,isStreaming:a,error:u}}var te=require("react"),at=require("@urun-sh/core"),Tr=[];function kn(e,t={}){let{field:r=at.INPUT_PRESENCE_FIELD,hz:o=at.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,te.useMemo)(()=>s?(0,at.createInputPresencePublisher)({awareness:{setLocalStateField:(m,w)=>s.setField(m,w)},field:r,hz:o}):null,[s,r,o]),a=(0,te.useRef)(null);a.current=i;let[c,u]=(0,te.useState)(!1),[f,l]=(0,te.useState)(Tr),g=(0,te.useRef)(!1);(0,te.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let v=(0,te.useCallback)(()=>{let m=a.current;l(m?m.heldKeys():Tr)},[]),C=(0,te.useCallback)(()=>{a.current?.clear(),l(Tr)},[]);(0,te.useEffect)(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,w=()=>{if(m()){g.current=!1,u(!0);return}g.current||(u(!1),C())},P=E=>{m()&&(a.current?.keyDown(E.key),v())},x=E=>{a.current?.keyUp(E.key),v()},A=E=>{m()&&a.current?.movePointer(E.movementX,E.movementY)},M=E=>{m()&&a.current?.setButtons(E.buttons)},L=()=>{C()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",P),n.addEventListener("keyup",x),n.addEventListener("mousemove",A),n.addEventListener("mousedown",M),n.addEventListener("mouseup",M),n.defaultView?.addEventListener("blur",L),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",P),n.removeEventListener("keyup",x),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",M),n.removeEventListener("mouseup",M),n.defaultView?.removeEventListener("blur",L)}},[n,C,v]);let h=(0,te.useCallback)(m=>{m.requestPointerLock?.()},[]),p=(0,te.useCallback)(()=>{g.current=!0,u(!0)},[]),k=(0,te.useCallback)(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),C()},[n,C]),R=(0,te.useCallback)(m=>{a.current?.keyDown(m),v()},[v]),d=(0,te.useCallback)(m=>{a.current?.keyUp(m),v()},[v]),b=(0,te.useCallback)((m,w)=>{a.current?.movePointer(m,w)},[]);return{engage:h,engageTouch:p,release:k,engaged:c,heldKeys:f,pressKey:R,releaseKey:d,movePointer:b}}var me=require("react"),Un=require("@urun-sh/core");var H=require("react"),wn=require("@urun-sh/core");var Wt=null;function Zo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Rt(){if(Wt)return Wt;let e=Zo();return e?(Wt=new e,Wt):null}function Je(){let e=Rt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Pt=require("react"),Cn=require("react/jsx-runtime"),Cr=(0,Pt.createContext)(null);function bn({session:e,children:t}){return(0,Cn.jsx)(Cr.Provider,{value:e,children:t})}function Ue(){return(0,Pt.useContext)(Cr)}function Tn(){let e=(0,Pt.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 Qo(e,t){return e-t>>>0<2147483648}var Rn=1e3;function Pn(...e){console.debug("[video]",...e)}function xn(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 En(e,t,r){return r?[r,t]:[e,t]}var Ye=(0,H.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:C,children:h,onTrack:p,onFirstFrame:k,frameMarker:R,onFrameMarkerReached:d,onFrameMarkerUnsupported:b,onUnlockChange:m}=t,w=Ue(),P=o??w,x=(0,H.useRef)(null),A=(0,H.useRef)(null),[M,L]=(0,H.useState)(!1),[E,O]=(0,H.useState)(!1),J=(0,H.useRef)(!1),X=(0,H.useRef)(null),z=(0,H.useRef)(p);z.current=p;let Z=(0,H.useRef)(m);Z.current=m;let ne=(0,H.useRef)(k);ne.current=k;let Q=(0,H.useRef)(d);Q.current=d;let T=(0,H.useRef)(b);T.current=b;let W=(0,H.useRef)(R??null);W.current=R??null;let S=(0,H.useCallback)(y=>{X.current!==y&&(X.current=y,Z.current?.(y))},[]),N=(0,H.useRef)(null),V=(0,H.useRef)(null),F=(0,H.useCallback)((y,q=!1)=>{if(!q&&y===N.current||(N.current=y,V.current?.(),V.current=null,J.current=!1,O(!1),!y))return;let _=x.current;if(!_)return;let $=W.current,ee=$?.rtpTimestamp??null,ve=!1,D=()=>{ve||(ve=!0,T.current?.())};$&&ee==null&&D();let Ae=$!=null&&ee!=null,rt=_e=>{V.current?.(),V.current=null,J.current=!0,O(!0),ne.current?.(),_e&&Q.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let _e=!1,B=0,K=(ye,ke)=>{if(!_e){if(Ae){let Re=ke?.rtpTimestamp;if(typeof Re!="number"){D(),rt(!1);return}if(!Qo(Re,ee)){B=_.requestVideoFrameCallback(K);return}rt(!0);return}rt(!1)}};B=_.requestVideoFrameCallback(K),V.current=()=>{_e=!0,_.cancelVideoFrameCallback?.(B)};return}Ae&&D();let Me=()=>{let _e=_.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&rt(!1)};_.addEventListener("loadeddata",Me),_.addEventListener("timeupdate",Me),_.addEventListener("playing",Me),V.current=()=>{_.removeEventListener("loadeddata",Me),_.removeEventListener("timeupdate",Me),_.removeEventListener("playing",Me)},Me()},[]);(0,H.useEffect)(()=>()=>{V.current?.(),V.current=null},[]);let U=R==null?null:`${R.rtpTimestamp??""}|${R.ptsMs??""}`,oe=(0,H.useRef)(U);(0,H.useEffect)(()=>{if(oe.current===U||(oe.current=U,U==null))return;let y=N.current;y&&F(y,!0)},[U,F]);let se=(0,H.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let y=x.current;return y&&y.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(y.srcObject=A.current),A.current},[]),de=(0,H.useCallback)(y=>{let q=x.current;if(!q)return;let _=q.play();!_||typeof _.then!="function"||_.then(()=>{q.muted||S(!0)}).catch($=>{if(($ instanceof Error?$.name:String($))==="NotAllowedError"&&!q.muted){Pn(`play() blocked pending a user gesture (${y})`),S(!1);return}Pn(`play() failed (${y})`,$)})},[S]),we=(0,H.useCallback)(()=>{let y=x.current;y&&(se(),!y.muted&&(de("gesture"),Je(),S(!0)))},[se,de,S]),he=(0,H.useCallback)(y=>{let q=se();if(q){for(let _ of q.getVideoTracks())_!==y&&q.removeTrack(_);if(y&&!q.getVideoTracks().includes(y)){q.addTrack(y);let _=x.current;_&&(_.srcObject=q)}y&&de("track-attach"),L(y!==null),F(y),z.current?.(y)}},[se,de,F]),qe=(0,H.useCallback)(y=>{let q=se();if(q){for(let _ of q.getAudioTracks())_!==y&&q.removeTrack(_);if(y&&!q.getAudioTracks().includes(y)){q.addTrack(y);let _=x.current;_&&_.srcObject!==q&&(_.srcObject=q)}y&&de("audio-attach")}},[se,de]),fe=(0,H.useCallback)(y=>{x.current=y,y&&(a?(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted",""),X.current=null):(y.muted=!1,y.defaultMuted=!1,y.removeAttribute("muted")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),se())},[se,a]);(0,H.useImperativeHandle)(r,()=>({get element(){return x.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return J.current},unlock:we,get unlocked(){return X.current===!0}}),[we]);let pe=(0,wn.derivedLegRole)(n)!==void 0;(0,H.useEffect)(()=>{pe&&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.`)},[pe,n]);let ae=i!==void 0;return(0,H.useEffect)(()=>{if(ae){he(i??null);return}if(pe){he(null);return}if(!P)return;let y=xn(P,En(n,"video")),q=()=>{let D=A.current;return D?D.getVideoTracks()[0]??null:null},_=D=>{if(D!==q()&&(he(D),D)){let Ae=()=>{q()===D&&he(null)};D.addEventListener("ended",Ae)}},$=y.track;$&&$.readyState==="live"&&_($);let ee=y.on("track",D=>{D&&D.readyState!=="live"||_(D)}),ve=setInterval(()=>{let D=y.track;D&&D.readyState==="live"&&_(D)},Rn);return()=>{ee(),clearInterval(ve)}},[P,n,pe,ae,i,he]),(0,H.useEffect)(()=>{if(ae||!P||s===!1||pe)return;let y=xn(P,En(n,"audio",s)),q=()=>{let D=A.current;return D?D.getAudioTracks()[0]??null:null},_=D=>{if(D!==q()&&(qe(D),D)){let Ae=()=>{q()===D&&qe(null)};D.addEventListener("ended",Ae)}},$=y.track;$&&$.readyState==="live"&&_($);let ee=y.on("track",D=>{D&&D.readyState!=="live"||_(D)}),ve=setInterval(()=>{let D=y.track;D&&D.readyState==="live"&&_(D)},Rn);return()=>{ee(),clearInterval(ve)}},[P,n,pe,s,ae,qe]),(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":E?"true":"false",children:[(0,xt.jsx)("video",{ref:fe,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),M?null:v,C===void 0?null:(0,xt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":E||void 0,style:{position:"absolute",inset:0,...E?{opacity:0,pointerEvents:"none"}:null},children:C}),h]})});var Et=require("react/jsx-runtime"),es={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},An=(0,me.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,me.useRef)(null),v=(0,me.useRef)(null),C=(0,me.useRef)(0),h=(0,me.useRef)(f);h.current=f;let p=(0,me.useMemo)(()=>(0,Un.createCameraWarp)(h.current),[]);return(0,me.useImperativeHandle)(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:p,get lastDrawTs(){return C.current}}),[p]),(0,me.useEffect)(()=>{if(!i)return;let k=0,R=0,d=null,b=w=>{typeof w.requestVideoFrameCallback=="function"&&(d=w,R=w.requestVideoFrameCallback(function P(){p.frameArrived(),R=w.requestVideoFrameCallback(P)}))},m=w=>{k=requestAnimationFrame(m);let P=v.current,x=g.current?.element??null;if(!P||!x||(x!==d&&(d&&R&&d.cancelVideoFrameCallback?.(R),b(x)),x.readyState<2))return;p.tick(w);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,M=Math.max(1,Math.round(P.clientWidth*A)),L=Math.max(1,Math.round(P.clientHeight*A));(P.width!==M||P.height!==L)&&(P.width=M,P.height=L);let E=P.getContext("2d");if(!E)return;let O=p.transform(),J=x.videoWidth||M,X=x.videoHeight||L,Z=Math.max(M/J,L/X)*(1+a)*O.scale;E.setTransform(Z,0,0,Z,M/2+O.translateX*M,L/2+O.translateY*L),E.drawImage(x,-J/2,-X/2),C.current=w};return k=requestAnimationFrame(m),()=>{cancelAnimationFrame(k),d&&R&&d.cancelVideoFrameCallback?.(R)}},[i,a,p]),(0,me.useEffect)(()=>{if(!i||!c||!l)return;let k=()=>!!l.pointerLockElement,R=P=>{k()&&p.keyDown(P.key)},d=P=>p.keyUp(P.key),b=P=>{k()&&p.pointerDelta(P.movementX,P.movementY)},m=()=>{k()||p.clearKeys()},w=()=>p.clearKeys();return l.addEventListener("keydown",R),l.addEventListener("keyup",d),l.addEventListener("mousemove",b),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",w),()=>{l.removeEventListener("keydown",R),l.removeEventListener("keyup",d),l.removeEventListener("mousemove",b),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",w)}},[i,c,l,p]),i?(0,Et.jsxs)(Ye,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Et.jsx)("canvas",{ref:v,style:es,"data-urun-warp":""}),n]}):(0,Et.jsx)(Ye,{ref:g,...s,children:n})});var Mn=new Map;function _n(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Mn.set(e,{component:t,schema:r})}function Nn(e,t){let r=Mn.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 Ze=require("react/jsx-runtime");function On({name:e,props:t,fallback:r}){let o=Nn(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ze.jsx)(Ze.Fragment,{children:r}):(0,Ze.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ze.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ze.jsx)(n,{...o.validatedProps})}var ut=require("zod"),Qe=require("react/jsx-runtime"),In=ut.z.object({step:ut.z.number().min(0),total:ut.z.number().min(1),label:ut.z.string().optional(),variant:ut.z.enum(["default","success","error"]).default("default")});function Rr(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 Ln(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Rr(e);return(0,Qe.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Qe.jsx)("div",{className:"urun-progress-label",children:o}),(0,Qe.jsx)("div",{className:"urun-progress-bar",children:(0,Qe.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Qe.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Bt=require("zod"),wt=require("react/jsx-runtime"),Dn=Bt.z.object({state:Bt.z.enum(["thinking","generating","idle","error"]),message:Bt.z.string().optional()}),ts={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Pr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??ts[t]??t;return{state:t,message:n,isActive:o}}function Vn(e){let{state:t,message:r,isActive:o}=Pr(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"),Fn=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 qn(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"),Hn=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 Wn(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 Ie=require("zod"),ct=require("react/jsx-runtime"),Bn=Ie.z.object({metrics:Ie.z.array(Ie.z.object({label:Ie.z.string(),value:Ie.z.union([Ie.z.string(),Ie.z.number()]),unit:Ie.z.string().optional()}))});function wr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function jn(e){let{metrics:t}=wr(e);return(0,ct.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ct.jsxs)("div",{className:"urun-metric-card",children:[(0,ct.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ct.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var Y=require("react"),zn=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 rs(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 ns(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function os(e){let t=We(e),r=t?.body;return ns(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 lt=class extends Error{name="TextStreamError"},ss=4,Ar=3,Mr=240,Kn=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function $n(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function is(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,Y.useRef)(e);(0,Y.useEffect)(()=>{o.current=e});let n=(0,Y.useRef)(null),s=(0,Y.useRef)(()=>{}),i=(0,Y.useRef)(null),a=(0,Y.useRef)(""),c=(0,Y.useRef)(""),u=(0,Y.useRef)(null),f=(0,Y.useRef)(!1),l=(0,Y.useRef)(!1),g=(0,Y.useRef)(!1),v=(0,Y.useRef)(null),C=(0,Y.useRef)($n()),h=(0,Y.useCallback)(d=>{if(n.current=d,!d){i.current=null;return}let b=i.current;if(b&&b.parentNode===d)return;let m=d.ownerDocument.createTextNode(c.current);d.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),p=(0,Y.useCallback)(()=>{u.current=null;let d=i.current,b=a.current;if(b.length>0){let A=o.current,M=A.smoothCharsPerFrame??Ar,L=A.smoothThreshold??Mr,E=A.smooth&&b.length<=L?b.slice(0,M):b;a.current=b.slice(E.length),c.current+=E,d?.appendData(E)}let m=C.current,w=c.current.length,P=v.current===null?0:Math.max(0,Kn()-v.current),x=Math.round(w/ss);if(m.chars=w,m.tokens=x,m.elapsedMs=P,m.tokensPerSecond=P>0?x*1e3/P:0,a.current.length>0){k(),o.current.onMeter?.(m);return}if(!f.current&&!g.current){g.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(m)},[]),k=(0,Y.useCallback)(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>p()))},[p]);s.current=k,(0,Y.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,is(C.current),i.current&&(i.current.data="");let d=!1,b=null;return(async()=>{try{for(b=t.stream(r).messages()[Symbol.asyncIterator]();;){let w=await b.next();if(d)return;if(w.done)break;let P=w.value,x=rs(P);if(x==="error")throw new lt(os(P));if(x==="done")break;if(x==="ignore")continue;let A=Ur(P);A&&(v.current===null&&(v.current=Kn()),a.current+=A,k())}if(d)return;b.return?.(void 0),f.current=!1,k()}catch(m){if(d)return;b?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(m instanceof Error?m:new lt(String(m))),k()}})(),()=>{d=!0,f.current=!1,b?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,k]);let R=(0,Y.useCallback)(()=>c.current,[]);return{ref:h,meterRef:C,getText:R}}function Gn(e,t=250){let[r,o]=(0,Y.useState)($n);return(0,Y.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 Xn(e){let{className:t,style:r,...o}=e,{ref:n}=_r(o);return(0,zn.jsx)("span",{ref:n,className:t,style:r})}var Jn=require("react");var Zn=require("react/jsx-runtime"),Yn=(0,Jn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Zn.jsx)(Ye,{ref:r,stream:o,...n})});var j=require("react"),Qn=require("@urun-sh/core");var to=require("react/jsx-runtime"),as=1e3;function us(e){return e!==null&&Or.has(e)}var Or=new WeakSet,cs=1e3;function Nr(...e){console.debug("[audio]",...e)}var Nt=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f,directOut:l}=t,g=Ue(),v=o??g,C=(0,j.useRef)(null),h=(0,j.useRef)(null),p=(0,j.useRef)(null),k=(0,j.useRef)(null),R=(0,j.useRef)(null),d=(0,j.useRef)(0),b=(0,j.useRef)(!1),m=(0,j.useRef)(c);m.current=c;let w=(0,j.useRef)(u);w.current=u;let P=(0,j.useRef)(l);P.current=l;let x=(0,j.useCallback)(T=>{p.current!==T&&(p.current=T,w.current?.(T))},[]),A=(0,j.useCallback)(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let T=C.current;return T&&T.srcObject!==h.current&&h.current.getAudioTracks().length>0&&(T.srcObject=h.current),h.current},[]),M=(0,j.useCallback)(()=>{d.current=0,R.current!==null&&cancelAnimationFrame(R.current),R.current=null,k.current!==null&&clearTimeout(k.current),k.current=null},[]),L=(0,j.useCallback)(T=>{R.current=null,k.current=null,A(),C.current&&(C.current.muted=b.current),J.current(`${T}:retry`)},[A]),E=(0,j.useCallback)(T=>{if(!C.current||R.current!==null||k.current!==null)return;let S=h.current;if(!(!!S&&S.getAudioTracks().some(F=>F.readyState==="live"))){M();return}let V=d.current;if(d.current=V+1,V===0&&typeof requestAnimationFrame=="function"){R.current=requestAnimationFrame(()=>L(T));return}k.current=setTimeout(()=>L(T),cs)},[M,L]),O=(0,j.useCallback)(T=>{let W=C.current;if(!W)return;let S=W.play();!S||typeof S.then!="function"||S.then(()=>{W.muted=b.current,W.muted||x(!0),M()}).catch(N=>{let V=N instanceof Error?N.name:String(N);if(V==="AbortError"){Nr(`play() aborted (${T}); retrying on the ladder`),E(`${T}:abort`);return}if(V==="NotAllowedError"){Nr(`play() blocked pending a user gesture (${T})`),x(!1),E(`${T}:blocked`);return}Nr(`play() failed (${T})`,N)})},[x]),J=(0,j.useRef)(()=>{});J.current=O;let X=(0,j.useCallback)(T=>{let W=A();if(!W)return;for(let N of W.getAudioTracks())N!==T&&W.removeTrack(N);T&&!W.getAudioTracks().includes(T)&&W.addTrack(T),A();let S=P.current??us(T);b.current=!!T&&S,C.current&&(C.current.muted=b.current),T&&O("track-attach"),m.current?.(T)},[A,O]),z=(0,j.useCallback)(()=>{let T=C.current;T&&(A(),T.muted=b.current,O("gesture"),Je(),x(!0))},[A,O,x]);(0,j.useImperativeHandle)(r,()=>({unlock:z,get unlocked(){return p.current===!0},get element(){return C.current}}),[z]);let Z=(0,j.useCallback)(()=>{E("pause-event")},[E]),ne=(0,j.useCallback)(T=>{let W=C.current;W&&W!==T&&W.removeEventListener("pause",Z),C.current=T,T&&(T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),A(),T.addEventListener("pause",Z)),f?.(T)},[A,f,Z]),Q=s!==void 0;return(0,j.useEffect)(()=>{if(Q){X(s??null);return}if(!v)return;let T=v.stream(n);if(T.directOut){let U=T.track;U&&Or.add(U)}let W=()=>{let U=h.current;return U?U.getAudioTracks()[0]??null:null},S=U=>{if(U!==W()&&(T.directOut&&U&&Or.add(U),X(U),U)){let oe=()=>{W()===U&&X(null)};U.addEventListener("ended",oe)}},N=T.track;N&&N.readyState==="live"&&S(N);let V=T.on("track",U=>{U&&U.readyState!=="live"||S(U)}),F=setInterval(()=>{let U=T.track;U&&U.readyState==="live"&&S(U)},as);return()=>{V(),clearInterval(F)}},[v,n,Q,s,X]),(0,j.useEffect)(()=>(0,Qn.observePageLifecycle)(()=>{Je(),p.current===!0&&O("foreground")}),[O]),(0,j.useEffect)(()=>()=>{k.current&&clearTimeout(k.current),R.current!==null&&cancelAnimationFrame(R.current),R.current=null},[]),(0,to.jsx)("audio",{ref:ne,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),eo=Nt;var G=require("react"),Be=require("@urun-sh/core");var no=require("react/jsx-runtime"),Ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Kt(...e){console.debug("[voice]",...e)}function ls(e){return e instanceof Be.SessionFailedError&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var Ot=(0,G.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:C,onUnlockChange:h,capture:p,directOut:k}=t,R=Ue(),d=o??R,b=(0,G.useRef)(null),m=(0,G.useRef)(null),w=(0,G.useRef)(null),P=(0,G.useRef)([]),x=(0,G.useRef)(!1),A=(0,G.useRef)(l);A.current=l;let M=(0,G.useRef)(g);M.current=g;let L=(0,G.useRef)(v);L.current=v;let E=(0,G.useCallback)(S=>{x.current!==S&&(x.current=S,A.current?.(S))},[]),O=(0,G.useCallback)(()=>{for(let S of P.current)S();P.current=[],w.current?.release(),w.current=null,m.current&&(m.current=null,L.current?.(null))},[]),J=(0,G.useCallback)(async()=>{let S=w.current;if(S){let U=await S.update(a);return m.current=S.stream,L.current?.(S.stream),U}let V=await(p??(0,Be.sharedCaptureController)()).claim("audio",a);w.current=V,P.current=[V.onTrack((U,oe)=>{m.current=oe,L.current?.(oe),x.current&&d?.stream(n).attach(U).catch(se=>Kt("mic re-attach after one-capture re-acquire failed",se))}),V.onLost(U=>{w.current=null,P.current=[],m.current=null,L.current?.(null),E(!1),M.current?.(U)})],m.current=V.stream,L.current?.(V.stream);let F=V.track;if(!F)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return F},[p,a,d,n,E]),X=(0,G.useCallback)(async()=>{O(),E(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,O,E]),z=(0,G.useCallback)(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");b.current?.unlock();let S;try{S=await J()}catch(F){O();let U=(0,Be.sessionFailureFromMediaError)(F,d.status);throw M.current?.(U),U}let N;for(let F=1;F<=u;F++)try{await d.whenLive(c!==void 0?{timeout:c}:void 0),await d.stream(n).attach(S),E(!0);return}catch(U){if(N=U,Kt(`start attempt ${F}/${u} failed`,U),ls(U))break;d.connect?.(),F<u&&await new Promise(oe=>setTimeout(oe,f))}O(),E(!1);let V=N instanceof Error?N:new Error(String(N??"voice start failed"));throw M.current?.(V),V},[d,n,c,u,f,J,O,E]);(0,G.useImperativeHandle)(r,()=>({start:z,stop:X,unlock:()=>b.current?.unlock(),get active(){return x.current},get micStream(){return m.current},get audio(){return b.current}}),[z,X]);let Z=(0,G.useRef)(z);Z.current=z;let ne=(0,G.useRef)(null),Q=(0,G.useCallback)((S,N)=>{S.promise.then(()=>{N&&(O(),E(!1)),S.session.stream(S.streamName).detach().catch(()=>{})})},[O,E]);(0,G.useEffect)(()=>{if(!i||!d)return;let S=ne.current;S&&(S.session!==d||S.streamName!==n)&&(S.disposeTimer&&clearTimeout(S.disposeTimer),Q(S,!1),S=null),S?S.disposeTimer&&(clearTimeout(S.disposeTimer),S.disposeTimer=null):(S={session:d,streamName:n,promise:Z.current().catch(()=>{}),refCount:0,disposeTimer:null},ne.current=S),S.refCount+=1;let N=S;return()=>{N.refCount-=1,!(N.refCount>0)&&(N.disposeTimer=setTimeout(()=>{ne.current===N&&(ne.current=null),Q(N,!0)},0))}},[i,d,n,Q]);let T=(0,G.useRef)(!1),W=(0,G.useCallback)(async()=>{if(!d||!x.current||T.current)return;let S=m.current?.getAudioTracks()[0]??null;if(S&&S.readyState==="live"){try{await d.stream(n).attach(S)}catch(N){Kt("foreground mic re-assert failed (will retry on next pass)",N)}return}T.current=!0;try{let N=await J();await d.stream(n).attach(N)}catch(N){let V=N instanceof Error?N:new Error(String(N));Kt("foreground mic re-acquire failed",V),M.current?.(V)}finally{T.current=!1}},[d,n,J]);return(0,G.useEffect)(()=>{let S=()=>{W()};return d&&typeof d.onRecovery=="function"?d.onRecovery(S):(0,Be.observePageLifecycle)(S)},[d,W]),(0,G.useEffect)(()=>O,[O]),s?(0,no.jsx)(Nt,{ref:b,session:d,stream:n,onTrack:C,onUnlockChange:h,directOut:k}):null}),ro=Ot;var De=require("react");var $t=require("react");var Lr={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,$t.useState)(Lr);return(0,$t.useEffect)(()=>{if(!e){i(Lr);return}let a=Rt();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 C=0;for(let p=0;p<l.length;p++){let k=(l[p]-128)/128;C+=k*k}let h=Math.sqrt(C/l.length);i(p=>{let k=h>n;return Math.abs(p.level-h)<.005&&p.speaking===k?p:{level:h,speaking:k}})},o);return()=>{clearInterval(v),u.disconnect(),i(Lr)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),ds={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ps={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},oo=(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(),C=o??v,h=(0,De.useRef)(null),[p,k]=(0,De.useState)(null),R=(0,De.useRef)(l);R.current=l;let{level:d,speaking:b}=Gt(a?p:null);return(0,De.useImperativeHandle)(r,()=>({start:()=>{let m=h.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>h.current?.stop()??Promise.resolve(),get active(){return h.current?.active??!1},get micStream(){return h.current?.micStream??null}}),[]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(Ot,{ref:h,session:C,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:m=>{k(m),R.current?.(m)}}),a?(0,Le.jsx)("span",{className:c,style:ds,"data-urun-mic":"","data-urun-mic-active":p?"true":"false","data-urun-mic-speaking":b?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(d*100)/100,children:(0,Le.jsx)("span",{style:ps,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(d*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var dt=require("@urun-sh/core"),I=require("react");var be=require("react/jsx-runtime"),Vr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Dr(...e){console.debug("[camera]",...e)}function ms(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function fs(){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 Fr=(0,I.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:C,onActiveChange:h,onError:p,onStream:k,onTrack:R,children:d,capture:b,flipControl:m="auto",flipControlClassName:w,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let x=i?"user":a?"environment":c??"environment",A=Ue(),M=o??A,L=(0,I.useRef)(null),E=(0,I.useRef)(null),O=(0,I.useRef)(null),J=(0,I.useRef)([]),X=(0,I.useRef)(null),z=(0,I.useRef)(!1),Z=(0,I.useRef)(!1),ne=(0,I.useRef)(x),[Q,T]=(0,I.useState)(x),[W,S]=(0,I.useState)(!1),[N,V]=(0,I.useState)(null),[F,U]=(0,I.useState)(!1),[oe]=(0,I.useState)(ms),se=(0,I.useRef)(h);se.current=h;let de=(0,I.useRef)(p);de.current=p;let we=(0,I.useRef)(k);we.current=k;let he=(0,I.useRef)(R);he.current=R;let qe=(0,I.useRef)(P);qe.current=P;let fe=(0,I.useCallback)(B=>{z.current!==B&&(z.current=B,S(B),se.current?.(B))},[]);(0,I.useEffect)(()=>{if(!W){V(null);return}let B=!1,K=()=>{fs().then(ke=>{B||(V(ke),ke&&qe.current?.(ke))})};K();let ye=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ye?.addEventListener=="function"?(ye.addEventListener("devicechange",K),()=>{B=!0,ye.removeEventListener?.("devicechange",K)}):()=>{B=!0}},[W]);let pe=(0,I.useCallback)(B=>{let K=L.current;K&&(K.muted=!0,K.defaultMuted=!0,K.setAttribute("muted",""),K.setAttribute("playsinline",""),K.setAttribute("webkit-playsinline",""),K.srcObject=B,B&&K.play()?.catch?.(ye=>Dr("preview play() failed",ye)))},[]),ae=(0,I.useCallback)(()=>{Z.current=!1,X.current?.(),X.current=null;for(let B of J.current)B();J.current=[],O.current?.release(),O.current=null,E.current&&(E.current=null,we.current?.(null),he.current?.(null)),pe(null)},[pe]),y=(0,I.useCallback)((B,K)=>{X.current?.(),E.current=K,pe(K),we.current?.(K);let ye=()=>{E.current===K&&(Dr("camera track ended (device removed or permission revoked)"),ae(),fe(!1))};B.addEventListener("ended",ye),X.current=()=>B.removeEventListener("ended",ye)},[pe,ae,fe]),q=(0,I.useCallback)(async B=>{let K=n!==!1;if(K&&!M)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ye={...Vr,...s,facingMode:B},ke;try{let Re=O.current;if(Re)ke=await Re.update(ye);else{let yt=await(b??(0,dt.sharedCaptureController)()).claim("video",ye);if(O.current=yt,J.current=[yt.onTrack((kt,_o)=>{y(kt,_o),z.current&&(!K||!M||M.stream(n).attachVideo(kt).then(()=>he.current?.(kt)).catch(No=>Dr("camera re-publish after one-capture re-acquire failed",No)))}),yt.onLost(kt=>{O.current=null,J.current=[],ae(),fe(!1),de.current?.(kt)})],!yt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ke=yt.track}}catch(Re){let nt=(0,dt.sessionFailureFromMediaError)(Re,M?.status);throw de.current?.(nt),nt}ne.current=B,T(B),y(ke,O.current?.stream??new MediaStream([ke]));try{K&&M&&(M.connect?.(),await M.whenLive(l!==void 0?{timeout:l}:void 0),await M.stream(n).attachVideo(ke)),Z.current=K?n:!1}catch(Re){ae(),fe(!1);let nt=Re instanceof Error?Re:new Error(String(Re));throw de.current?.(nt),nt}he.current?.(ke),fe(!0)},[M,n,s,l,b,y,ae,fe]),_=(0,I.useCallback)(B=>q(B?.facingMode??ne.current),[q]),$=(0,I.useCallback)(async B=>{let K=Z.current===n;z.current&&ne.current===B&&K||await q(B)},[q,n]),ee=(0,I.useCallback)(()=>q(ne.current==="environment"?"user":"environment"),[q]),ve=(0,I.useCallback)(async()=>{ae(),fe(!1),n!==!1&&await M?.stream(n).detachVideo().catch(()=>{})},[M,n,ae,fe]),D=(0,I.useCallback)(async B=>{let K=L.current;if(!K)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,dt.captureStillFromVideo)(K,B)},[]);(0,I.useImperativeHandle)(r,()=>({start:_,stop:ve,flip:ee,setFacingMode:$,capturePhoto:D,get active(){return z.current},get facingMode(){return ne.current},get stream(){return E.current},get element(){return L.current}}),[_,ve,ee,$,D]);let Ae=(0,I.useRef)($);if(Ae.current=$,(0,I.useEffect)(()=>{u&&(n!==!1&&!M||Ae.current(x).catch(()=>{}))},[u,M,x,n]),(0,I.useEffect)(()=>ae,[ae]),!g)return null;let rt=f==="auto"?Q==="user":f,Me=W&&(m===!0||m==="auto"&&oe&&(N?.length??0)>1),_e=()=>{F||(U(!0),ee().catch(()=>{}).finally(()=>U(!1)))};return(0,be.jsxs)("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":Q,children:[(0,be.jsx)("video",{ref:L,className:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...rt?{transform:"scaleX(-1)"}:{}}}),Me?(0,be.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:F,className:w,style:w?{opacity:F?.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:F?.6:1},children:(0,be.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,be.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,be.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,be.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,be.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,be.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,d]})}),so=(0,I.forwardRef)(function({preview:t=!0,...r},o){return(0,be.jsx)(Fr,{ref:o,...r,visible:t,autoStart:!1})});var pt=require("@urun-sh/core"),ie=require("react");function io(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,ie.useState)(null),[a,c]=(0,ie.useState)(null),[u,f]=(0,ie.useState)(!1),[l,g]=(0,ie.useState)(null),[v]=(0,ie.useState)(pt.cameraCaptureAvailable),C=(0,ie.useRef)(n);C.current=n;let h=(0,ie.useRef)(null),p=(0,ie.useRef)(0),k=(0,ie.useCallback)(w=>{h.current&&URL.revokeObjectURL(h.current),h.current=w?URL.createObjectURL(new Blob([w.bytes],{type:w.type})):null,c(h.current),i(w),C.current?.(w)},[]);(0,ie.useEffect)(()=>()=>{p.current++,h.current&&URL.revokeObjectURL(h.current),h.current=null},[]);let R=(0,ie.useCallback)(async w=>{let P=++p.current;f(!0),g(null);try{let x=await w();if(p.current!==P)return;k(x)}catch(x){if(p.current!==P)return;g((0,pt.referenceImageErrorMessage)(x))}finally{p.current===P&&f(!1)}},[k]),d=(0,ie.useCallback)(w=>R(()=>(0,pt.normalizeReferenceImage)(w,{maxSize:t,type:r,quality:o,source:"file"})),[R,t,r,o]),b=(0,ie.useCallback)(w=>R(()=>w.capturePhoto({maxSize:t,type:r,quality:o})),[R,t,r,o]),m=(0,ie.useCallback)(()=>{p.current++,g(null),f(!1),k(null)},[k]);return{reference:s,previewUrl:a,pick:d,capture:b,clear:m,busy:u,error:l,cameraAvailable:v}}var Xt=require("react");function ao(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 lo=require("react");var Jt=require("react");var uo=require("zustand/vanilla"),co=require("zustand"),gs=()=>{};function zt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,uo.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):gs,c=(u=>(0,co.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 po(e,t,r){let n=mt(e,t)(r??(a=>a)),s=(0,lo.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 mo(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 je=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 fo({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 It=require("react");var Se=require("react/jsx-runtime");function Lt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,It.useState)(""),[i,a]=(0,It.useState)(null),c=(0,It.useCallback)(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return(0,Se.jsxs)("div",{className:"urun-doc-patch",children:[(0,Se.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,Se.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,Se.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?(0,Se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function go({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,Se.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,Se.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,Se.jsx)("code",{children:t}),(0,Se.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,Se.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,Se.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 So(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ho({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:So(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:So(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 et=require("react/jsx-runtime");function vo({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,et.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,et.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,et.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,et.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,et.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 Te(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 ko=require("@urun-sh/core");var gt=require("react"),yo=require("@urun-sh/core");function or(e){let t=Te(e),r=(0,yo.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 Ke=require("react/jsx-runtime");function sr({session:e,render:t,className:r}){let o=or(e);return!o.waking||!o.phase?null:(0,Ke.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,Ke.jsxs)(Ke.Fragment,{children:[(0,Ke.jsx)("span",{className:"urun-session-waking-label",children:(0,ko.describeSessionPhase)(o.phase)})," ",(0,Ke.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var ar=require("react");var $e=require("react"),Ss={event:null,elapsedMs:0};function ir(e,t){let[r,o]=(0,$e.useState)(null),n=(0,$e.useRef)(0);(0,$e.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,$e.useState)(0);return(0,$e.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}:Ss}var St=require("react/jsx-runtime"),hs={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 vs(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=vs(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??hs[c]})," ",(0,St.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Ce=require("react/jsx-runtime"),ys={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 bo({session:e,className:t}){let r=Te(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,Ce.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,Ce.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,Ce.jsx)("span",{className:"urun-session-status-label",children:ys[o]}),n?(0,Ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function To({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Te(e);if(s?.name==="live")return(0,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,Ce.jsx)(ur,{session:e})]});let i=r?r(s):(0,Ce.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&(0,cr.isWakingPhase)(s.name)?(0,Ce.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,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,Ce.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var lr=require("react");var Ro=require("react/jsx-runtime");function qr(e){return Te(e)?.endsAt??null}function ks(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 Co({session:e,urgentMs:t=6e4,className:r}){let n=qr(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=ks(s);return(0,Ro.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 Po=require("@urun-sh/core");var ht=require("react/jsx-runtime"),bs=new Set(["paused","error"]);function Hr({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=Te(e);if(!s||!bs.has(s.name))return null;let i=o?o(s):(0,ht.jsx)("span",{className:"urun-session-paused-copy",children:(0,Po.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 xo=Hr;var Ge=require("react"),tt=require("react/jsx-runtime");function Wr(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 Br(e){let t=(0,Ge.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Ge.useState)(()=>t?Wr(t.get("idle")):null);return(0,Ge.useEffect)(()=>{if(!t){o(null);return}return o(Wr(t.get("idle"))),t.on("change",()=>o(Wr(t.get("idle"))))},[t]),r}function Ts(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Eo({session:e,onStillHere:t,className:r}){let o=Br(e),n=o?.deadlineEpochS??null,[s,i]=(0,Ge.useState)(null);if((0,Ge.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,tt.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,tt.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,tt.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,tt.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Ts(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,tt.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Ee=require("react");function Cs(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:Cs(o),loading:s,error:a,refresh:l}}var pr=require("react/jsx-runtime");function wo({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 Xe=require("@urun-sh/core");var vt=require("react"),Uo=require("@urun-sh/core");function Ao(e){let t=(0,vt.useContext)(He),[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,Uo.prewake)({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(h=>{g||o(h)}).catch(()=>{})};v();let C=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(C)}},[n,s,i,a,c,u,f,l]),r}var mr=require("react");function Mo(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 Oo=Object.getOwnPropertyDescriptor;var Io=Object.getOwnPropertyNames;var Lo=Object.prototype.hasOwnProperty;var Do=(e,t)=>{for(var r in t)gr(e,r,{get:t[r],enumerable:!0})},Vo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Io(t))!Lo.call(e,n)&&n!==r&&gr(e,n,{get:()=>t[n],enumerable:!(o=Oo(t,n))||o.enumerable});return e};var Fo=e=>Vo(gr({},"__esModule",{value:!0}),e);var Rs={};Do(Rs,{Audio:()=>Nt,Camera:()=>Fr,ComponentRenderer:()=>On,CreditsClient:()=>Xe.CreditsClient,CreditsError:()=>Xe.CreditsError,CreditsUnauthorizedError:()=>Xe.CreditsUnauthorizedError,DEFAULT_CAMERA_CONSTRAINTS:()=>Vr,DEFAULT_LOG_CAP:()=>je,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Ar,DEFAULT_SMOOTH_THRESHOLD:()=>Mr,DEFAULT_VOICE_CONSTRAINTS:()=>Ir,DocPatchForm:()=>Lt,Image:()=>Yn,ImageFrame:()=>Wn,ImageFrameSchema:()=>Hn,MetricsPanel:()=>jn,MetricsPanelSchema:()=>Bn,Mic:()=>oo,OPERATOR_CHORD_LABEL:()=>Qr,OPERATOR_TOKEN_STORAGE_KEY:()=>Yr,ProgressCard:()=>Ln,ProgressCardSchema:()=>In,ReprojectedVideo:()=>An,Session:()=>bn,StatusBadge:()=>Vn,StatusBadgeSchema:()=>Dn,Text:()=>Xn,TextStream:()=>qn,TextStreamError:()=>lt,TextStreamSchema:()=>Fn,UrunActivationOverlay:()=>ur,UrunAudio:()=>eo,UrunAuthProvider:()=>Ct,UrunCamera:()=>so,UrunControlSender:()=>ho,UrunCreditsGate:()=>wo,UrunDocPanel:()=>go,UrunErrorBoundary:()=>ot,UrunEventSpine:()=>vo,UrunIdleWarning:()=>Eo,UrunJwtProvider:()=>Xr,UrunProvider:()=>un,UrunSessionClock:()=>Co,UrunSessionEnded:()=>xo,UrunSessionGate:()=>To,UrunSessionPaused:()=>Hr,UrunSessionStatus:()=>bo,UrunSessionWaking:()=>sr,UrunStreamTail:()=>fo,UrunVoice:()=>ro,Video:()=>Ye,Voice:()=>Ot,authMode:()=>Tt,createCreditsClient:()=>Xe.createCreditsClient,createDocStore:()=>zt,describeSessionPhase:()=>fr.describeSessionPhase,formatPayload:()=>ft,getUrunAudioContext:()=>Rt,isWakingPhase:()=>fr.isWakingPhase,parseJsonObject:()=>Zt,pushCapped:()=>Ve,readOperatorToken:()=>Sr,registerComponent:()=>_n,resumeUrunAudioContext:()=>Je,textDelta:()=>Ur,urunPublicEnv:()=>Pe,useActivation:()=>ir,useApp:()=>dn,useChat:()=>yn,useCompletion:()=>Sn,useConfirmOnLeave:()=>qt,useCredits:()=>dr,useDocStore:()=>mt,useGenerationTick:()=>mo,useImageFrame:()=>Er,useInputPresence:()=>kn,useMetricsPanel:()=>wr,useOperatorOverride:()=>Ft,useProgressCard:()=>Rr,useReferenceImage:()=>io,useRequest:()=>fn,useSession:()=>Tn,useSessionDirectory:()=>mn,useSessionDoc:()=>po,useSessionEndsAt:()=>qr,useSessionIdle:()=>Br,useSessionPhase:()=>Te,useSessionStats:()=>Mo,useSessionTrack:()=>ao,useSessionWake:()=>or,useStatusBadge:()=>Pr,useStreamMessages:()=>er,useText:()=>_r,useTextMeter:()=>Gn,useTextStream:()=>xr,useUrunAudioLevel:()=>Gt,useUrunAuth:()=>Dt,useUrunPrewake:()=>Ao,usesWorkOSAuth:()=>$r});module.exports=Fo(Rs);var le=require("react"),an=require("@urun-sh/core/internal");var jr=require("react"),bt=require("react/jsx-runtime"),ot=class extends jr.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 Kr=require("react"),He=(0,Kr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Pe(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=Pe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Pe("VERCEL_ENV")==="production"?"workos":Pe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function $r(){return Tt()==="workos"}var st=require("react"),zr=require("react/jsx-runtime"),Gr=(0,st.createContext)(null);function Ct({getAccessToken:e,children:t}){let r=(0,st.useMemo)(()=>({getAccessToken:e}),[e]);return(0,zr.jsx)(Gr.Provider,{value:r,children:t})}var Xr=Ct;function Dt(){return(0,st.useContext)(Gr)}var Vt=require("react"),Yr="urun.operator_token",Zr=null,Jr="op",Qr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function en(){return typeof window<"u"}function Sr(){return Zr}function qo(){if(!en())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(Jr);if(!r)return null;Zr=r,t.delete(Jr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Ho(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(!en())return;qo();let r=o=>{if(!Ho(o))return;let n=Sr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var tn=require("react");function qt(e=!0){(0,tn.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 Oe=require("react/jsx-runtime"),Wo="/api/urun-token",Bo=1e4;function jo(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}}var rn=3,Ko=new Set([502,503,504]);function nn(e){return new Promise(t=>setTimeout(t,(0,an.computeBackoffDelay)(e)))}async function on(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=rn-1)throw a;await nn(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!Ko.has(o.status)||r>=rn-1)throw a;await nn(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function sn(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,le.useMemo)(()=>e,[t])}function $o(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Oe.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,Oe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Oe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function un({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:C,confirmOnLeave:h=!1,fallback:p,errorFallback:k,children:R}){let d=n===void 0&&t===void 0;if(!d&&(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(!d&&(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 b=r??o;if(d&&(typeof b!="string"||b.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);qt(h);let[m,w]=(0,le.useState)(),[P,x]=(0,le.useState)(null),A=(0,le.useRef)(void 0),M=(0,le.useRef)(null),[L,E]=(0,le.useState)(null);Ft(_=>E({jwt:_}));let O=Dt(),J=Pe("NEXT_PUBLIC_SESSION_TOKEN")??Pe("NEXT_PUBLIC_URUN_JWT"),X=Tt(),z=L!==null,Z=X==="workos"&&!n&&!z&&!d,ne=n??(X==="jwt"?J:void 0)??m?.token,Q=z?L.jwt:ne,T=s??Pe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),W=Z&&!Q&&!O?.getAccessToken,S=t??m?.orgId,N=e??m?.gatewayUrl,V=d&&m===void 0,F=d&&m!==void 0&&!N?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,U=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,oe=P??F??U,se=sn("NEXT_PUBLIC_URUN_TOKEN_URL",Pe("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Wo,de=sn("NEXT_PUBLIC_URUN_EVENTS_URL",Pe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,we=(0,le.useCallback)(async _=>{if(!_?.forceRefresh){let ee=A.current;if(!ee)return ee;let ve=jo(ee);if(ve===null||ve-Date.now()>Bo)return ee}return(await(M.current??(M.current=(async()=>{try{let ee=await on(se);return A.current=ee.token,w(ee),ee}finally{M.current=null}})()))).token},[se]),he=(0,le.useCallback)(async()=>Q,[Q]),qe=typeof Q=="string"&&Q.trim().length>0,fe=Z?O?.getAccessToken:d&&!z?we:qe?he:void 0,pe=hr(g),ae=hr(v),y=hr(C),q=(0,le.useMemo)(()=>({appId:b,baseUrl:N??"",orgId:S??"",jwt:Q,getAccessToken:Z?O?.getAccessToken:d&&!z?we:void 0,authProvider:T,eventsUrl:de,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:pe,videoPlayout:ae,sessionStats:y,priority:z?"preempt":void 0}),[b,O,N,T,Q,de,S,a,u,f,l,pe,ae,y,Z,z,d,we]);return(0,le.useEffect)(()=>{if(!d)return;let _=new AbortController;return x(null),(async()=>{try{let $=await on(se,_.signal);A.current=$.token,w($)}catch($){if(_.signal.aborted)return;x($ instanceof Error?$:new Error(String($)))}})(),()=>_.abort()},[d,se]),(0,Oe.jsx)(ot,{fallback:p,children:oe?$o(k,oe):V?(0,Oe.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Oe.jsx)(He.Provider,{value:q,children:fe?(0,Oe.jsx)(Ct,{getAccessToken:fe,children:R}):R})})}var ge=require("react"),cn=require("@urun-sh/core");function ln(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function Go(e,t,r){let o=ln(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function Xo(e,t,r,o){let n=ln(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 ze=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}get directOut(){return this._stream.directOut}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 mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}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 dn(){let e=(0,ge.useContext)(He);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ge.useReducer)(i=>i+1,0),r=(0,ge.useRef)(new Map),o=(0,ge.useRef)(new Map),n=(0,ge.useRef)(null),s=(0,ge.useMemo)(()=>(0,cn.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,ge.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=ze.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=ze.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=ze.get(c);!l||l.refCount!==0||(ze.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),(0,ge.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=Go(c,l,g),C=r.current.get(v);if(C&&!C.disposed)return C;let h=Xo(e,c,l,g),p=ze.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),ze.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new kr(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},ze.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(c,f),f}})},[e,s])}var Ht=require("react"),pn=require("@urun-sh/core");function mn(){let e=(0,Ht.useContext)(He);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,Ht.useMemo)(()=>(0,pn.sessionDirectory)(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}var ue=require("react");function it(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 zo(e){return e instanceof Error?e:new Error(String(e))}function fn(e,t){let r=(0,ue.useMemo)(()=>it(e),[e]),[o,n]=(0,ue.useState)(void 0),[s,i]=(0,ue.useState)(null),[a,c]=(0,ue.useState)(!1),u=(0,ue.useRef)(t);u.current=t;let f=(0,ue.useRef)(0),l=(0,ue.useRef)(null),g=(0,ue.useRef)(!0);(0,ue.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=(0,ue.useCallback)(async p=>{l.current?.abort();let k=new AbortController;l.current=k;let R=++f.current,d=()=>g.current&&f.current===R;d()&&(c(!0),i(null));try{let b=await r.request(p,{...u.current,signal:k.signal});return d()&&(n(b),c(!1),u.current?.onSuccess?.(b)),b}catch(b){let m=zo(b);throw d()&&(i(m),c(!1),u.current?.onError?.(m)),m}},[r]),C=(0,ue.useCallback)(p=>{v(p).catch(()=>{})},[v]),h=(0,ue.useCallback)(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:C,mutateAsync:v,data:o,error:s,isPending:a,reset:h}}var ce=require("react");function gn(e){return e instanceof Error?e:new Error(String(e))}var Jo=e=>typeof e=="string"?e:String(e);function Sn(e,t){let r=(0,ce.useMemo)(()=>it(e),[e]),[o,n]=(0,ce.useState)(""),[s,i]=(0,ce.useState)(!1),[a,c]=(0,ce.useState)(null),u=(0,ce.useRef)(t);u.current=t;let f=(0,ce.useRef)(0),l=(0,ce.useRef)(null),g=(0,ce.useRef)(!0);(0,ce.useEffect)(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=(0,ce.useCallback)(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),C=(0,ce.useCallback)(async h=>{l.current?.cancel();let p=++f.current,k=()=>g.current&&f.current===p,R=u.current,d=R?.parseChunk??Jo,b=R?.buildPayload??(E=>({prompt:E}));k()&&(n(""),c(null),i(!0));let{parseChunk:m,buildPayload:w,onFinish:P,onError:x,...A}=R??{},M="",L;try{L=r.requestStream(b(h),A),l.current=L}catch(E){let O=gn(E);k()&&(c(O),i(!1),R?.onError?.(O));return}try{for await(let E of L){if(f.current!==p)break;M+=d(E),k()&&n(M)}k()&&(i(!1),R?.onFinish?.(M))}catch(E){let O=gn(E);k()&&(c(O),i(!1),R?.onError?.(O))}finally{l.current===L&&(l.current=null)}},[r]);return{completion:o,complete:C,stop:v,isStreaming:s,error:a}}var re=require("react");function hn(e){return e instanceof Error?e:new Error(String(e))}var Yo=e=>typeof e=="string"?e:String(e),vn=0;function br(e){return vn+=1,`${e}-${vn}`}function yn(e,t){let r=(0,re.useMemo)(()=>it(e),[e]),[o,n]=(0,re.useState)(()=>(t?.initialMessages??[]).map(d=>({id:d.id??br("msg"),role:d.role,content:d.content}))),[s,i]=(0,re.useState)(""),[a,c]=(0,re.useState)(!1),[u,f]=(0,re.useState)(null),l=(0,re.useRef)(t);l.current=t;let g=(0,re.useRef)(o);g.current=o;let v=(0,re.useRef)(s);v.current=s;let C=(0,re.useRef)(0),h=(0,re.useRef)(null),p=(0,re.useRef)(!0);(0,re.useEffect)(()=>(p.current=!0,()=>{p.current=!1,h.current?.cancel(),h.current=null}),[]);let k=(0,re.useCallback)(()=>{C.current++,h.current?.cancel(),h.current=null,p.current&&c(!1)},[]),R=(0,re.useCallback)(async d=>{let b=d===void 0,m=(b?v.current:d)??"";if(!m.trim())return;h.current?.cancel();let P=++C.current,x=()=>p.current&&C.current===P,A=l.current,M=A?.parseChunk??Yo,L={id:br("msg"),role:"user",content:m},E={id:br("msg"),role:"assistant",content:""},O=[...g.current,L].map(F=>({role:F.role,content:F.content})),J=[...g.current,L,E];g.current=J,n(J),b&&i(""),f(null),c(!0);let X=A?.buildPayload??(F=>({messages:F})),{initialMessages:z,parseChunk:Z,buildPayload:ne,onFinish:Q,onError:T,...W}=A??{},S=F=>{n(U=>U.map(oe=>oe.id===E.id?{...oe,content:F}:oe))},N="",V;try{V=r.requestStream(X(O),W),h.current=V}catch(F){let U=hn(F);x()&&(f(U),c(!1),A?.onError?.(U));return}try{for await(let F of V){if(C.current!==P)break;N+=M(F),x()&&S(N)}x()&&(c(!1),A?.onFinish?.({...E,content:N}))}catch(F){let U=hn(F);x()&&(f(U),c(!1),A?.onError?.(U))}finally{h.current===V&&(h.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:R,stop:k,isStreaming:a,error:u}}var te=require("react"),at=require("@urun-sh/core"),Tr=[];function kn(e,t={}){let{field:r=at.INPUT_PRESENCE_FIELD,hz:o=at.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,te.useMemo)(()=>s?(0,at.createInputPresencePublisher)({awareness:{setLocalStateField:(m,w)=>s.setField(m,w)},field:r,hz:o}):null,[s,r,o]),a=(0,te.useRef)(null);a.current=i;let[c,u]=(0,te.useState)(!1),[f,l]=(0,te.useState)(Tr),g=(0,te.useRef)(!1);(0,te.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let v=(0,te.useCallback)(()=>{let m=a.current;l(m?m.heldKeys():Tr)},[]),C=(0,te.useCallback)(()=>{a.current?.clear(),l(Tr)},[]);(0,te.useEffect)(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,w=()=>{if(m()){g.current=!1,u(!0);return}g.current||(u(!1),C())},P=E=>{m()&&(a.current?.keyDown(E.key),v())},x=E=>{a.current?.keyUp(E.key),v()},A=E=>{m()&&a.current?.movePointer(E.movementX,E.movementY)},M=E=>{m()&&a.current?.setButtons(E.buttons)},L=()=>{C()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",P),n.addEventListener("keyup",x),n.addEventListener("mousemove",A),n.addEventListener("mousedown",M),n.addEventListener("mouseup",M),n.defaultView?.addEventListener("blur",L),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",P),n.removeEventListener("keyup",x),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",M),n.removeEventListener("mouseup",M),n.defaultView?.removeEventListener("blur",L)}},[n,C,v]);let h=(0,te.useCallback)(m=>{m.requestPointerLock?.()},[]),p=(0,te.useCallback)(()=>{g.current=!0,u(!0)},[]),k=(0,te.useCallback)(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),C()},[n,C]),R=(0,te.useCallback)(m=>{a.current?.keyDown(m),v()},[v]),d=(0,te.useCallback)(m=>{a.current?.keyUp(m),v()},[v]),b=(0,te.useCallback)((m,w)=>{a.current?.movePointer(m,w)},[]);return{engage:h,engageTouch:p,release:k,engaged:c,heldKeys:f,pressKey:R,releaseKey:d,movePointer:b}}var me=require("react"),Un=require("@urun-sh/core");var H=require("react"),wn=require("@urun-sh/core");var Wt=null;function Zo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function Rt(){if(Wt)return Wt;let e=Zo();return e?(Wt=new e,Wt):null}function Je(){let e=Rt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Pt=require("react"),Cn=require("react/jsx-runtime"),Cr=(0,Pt.createContext)(null);function bn({session:e,children:t}){return(0,Cn.jsx)(Cr.Provider,{value:e,children:t})}function Ue(){return(0,Pt.useContext)(Cr)}function Tn(){let e=(0,Pt.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 Qo(e,t){return e-t>>>0<2147483648}var Rn=1e3;function Pn(...e){console.debug("[video]",...e)}function xn(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 En(e,t,r){return r?[r,t]:[e,t]}var Ye=(0,H.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:C,children:h,onTrack:p,onFirstFrame:k,frameMarker:R,onFrameMarkerReached:d,onFrameMarkerUnsupported:b,onUnlockChange:m}=t,w=Ue(),P=o??w,x=(0,H.useRef)(null),A=(0,H.useRef)(null),[M,L]=(0,H.useState)(!1),[E,O]=(0,H.useState)(!1),J=(0,H.useRef)(!1),X=(0,H.useRef)(null),z=(0,H.useRef)(p);z.current=p;let Z=(0,H.useRef)(m);Z.current=m;let ne=(0,H.useRef)(k);ne.current=k;let Q=(0,H.useRef)(d);Q.current=d;let T=(0,H.useRef)(b);T.current=b;let W=(0,H.useRef)(R??null);W.current=R??null;let S=(0,H.useCallback)(y=>{X.current!==y&&(X.current=y,Z.current?.(y))},[]),N=(0,H.useRef)(null),V=(0,H.useRef)(null),F=(0,H.useCallback)((y,q=!1)=>{if(!q&&y===N.current||(N.current=y,V.current?.(),V.current=null,J.current=!1,O(!1),!y))return;let _=x.current;if(!_)return;let $=W.current,ee=$?.rtpTimestamp??null,ve=!1,D=()=>{ve||(ve=!0,T.current?.())};$&&ee==null&&D();let Ae=$!=null&&ee!=null,rt=_e=>{V.current?.(),V.current=null,J.current=!0,O(!0),ne.current?.(),_e&&Q.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let _e=!1,B=0,K=(ye,ke)=>{if(!_e){if(Ae){let Re=ke?.rtpTimestamp;if(typeof Re!="number"){D(),rt(!1);return}if(!Qo(Re,ee)){B=_.requestVideoFrameCallback(K);return}rt(!0);return}rt(!1)}};B=_.requestVideoFrameCallback(K),V.current=()=>{_e=!0,_.cancelVideoFrameCallback?.(B)};return}Ae&&D();let Me=()=>{let _e=_.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&rt(!1)};_.addEventListener("loadeddata",Me),_.addEventListener("timeupdate",Me),_.addEventListener("playing",Me),V.current=()=>{_.removeEventListener("loadeddata",Me),_.removeEventListener("timeupdate",Me),_.removeEventListener("playing",Me)},Me()},[]);(0,H.useEffect)(()=>()=>{V.current?.(),V.current=null},[]);let U=R==null?null:`${R.rtpTimestamp??""}|${R.ptsMs??""}`,oe=(0,H.useRef)(U);(0,H.useEffect)(()=>{if(oe.current===U||(oe.current=U,U==null))return;let y=N.current;y&&F(y,!0)},[U,F]);let se=(0,H.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let y=x.current;return y&&y.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(y.srcObject=A.current),A.current},[]),de=(0,H.useCallback)(y=>{let q=x.current;if(!q)return;let _=q.play();!_||typeof _.then!="function"||_.then(()=>{q.muted||S(!0)}).catch($=>{if(($ instanceof Error?$.name:String($))==="NotAllowedError"&&!q.muted){Pn(`play() blocked pending a user gesture (${y})`),S(!1);return}Pn(`play() failed (${y})`,$)})},[S]),we=(0,H.useCallback)(()=>{let y=x.current;y&&(se(),!y.muted&&(de("gesture"),Je(),S(!0)))},[se,de,S]),he=(0,H.useCallback)(y=>{let q=se();if(q){for(let _ of q.getVideoTracks())_!==y&&q.removeTrack(_);if(y&&!q.getVideoTracks().includes(y)){q.addTrack(y);let _=x.current;_&&(_.srcObject=q)}y&&de("track-attach"),L(y!==null),F(y),z.current?.(y)}},[se,de,F]),qe=(0,H.useCallback)(y=>{let q=se();if(q){for(let _ of q.getAudioTracks())_!==y&&q.removeTrack(_);if(y&&!q.getAudioTracks().includes(y)){q.addTrack(y);let _=x.current;_&&_.srcObject!==q&&(_.srcObject=q)}y&&de("audio-attach")}},[se,de]),fe=(0,H.useCallback)(y=>{x.current=y,y&&(a?(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted",""),X.current=null):(y.muted=!1,y.defaultMuted=!1,y.removeAttribute("muted")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),se())},[se,a]);(0,H.useImperativeHandle)(r,()=>({get element(){return x.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return J.current},unlock:we,get unlocked(){return X.current===!0}}),[we]);let pe=(0,wn.derivedLegRole)(n)!==void 0;(0,H.useEffect)(()=>{pe&&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.`)},[pe,n]);let ae=i!==void 0;return(0,H.useEffect)(()=>{if(ae){he(i??null);return}if(pe){he(null);return}if(!P)return;let y=xn(P,En(n,"video")),q=()=>{let D=A.current;return D?D.getVideoTracks()[0]??null:null},_=D=>{if(D!==q()&&(he(D),D)){let Ae=()=>{q()===D&&he(null)};D.addEventListener("ended",Ae)}},$=y.track;$&&$.readyState==="live"&&_($);let ee=y.on("track",D=>{D&&D.readyState!=="live"||_(D)}),ve=setInterval(()=>{let D=y.track;D&&D.readyState==="live"&&_(D)},Rn);return()=>{ee(),clearInterval(ve)}},[P,n,pe,ae,i,he]),(0,H.useEffect)(()=>{if(ae||!P||s===!1||pe)return;let y=xn(P,En(n,"audio",s)),q=()=>{let D=A.current;return D?D.getAudioTracks()[0]??null:null},_=D=>{if(D!==q()&&(qe(D),D)){let Ae=()=>{q()===D&&qe(null)};D.addEventListener("ended",Ae)}},$=y.track;$&&$.readyState==="live"&&_($);let ee=y.on("track",D=>{D&&D.readyState!=="live"||_(D)}),ve=setInterval(()=>{let D=y.track;D&&D.readyState==="live"&&_(D)},Rn);return()=>{ee(),clearInterval(ve)}},[P,n,pe,s,ae,qe]),(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":E?"true":"false",children:[(0,xt.jsx)("video",{ref:fe,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),M?null:v,C===void 0?null:(0,xt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":E||void 0,style:{position:"absolute",inset:0,...E?{opacity:0,pointerEvents:"none"}:null},children:C}),h]})});var Et=require("react/jsx-runtime"),es={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},An=(0,me.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,me.useRef)(null),v=(0,me.useRef)(null),C=(0,me.useRef)(0),h=(0,me.useRef)(f);h.current=f;let p=(0,me.useMemo)(()=>(0,Un.createCameraWarp)(h.current),[]);return(0,me.useImperativeHandle)(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:p,get lastDrawTs(){return C.current}}),[p]),(0,me.useEffect)(()=>{if(!i)return;let k=0,R=0,d=null,b=w=>{typeof w.requestVideoFrameCallback=="function"&&(d=w,R=w.requestVideoFrameCallback(function P(){p.frameArrived(),R=w.requestVideoFrameCallback(P)}))},m=w=>{k=requestAnimationFrame(m);let P=v.current,x=g.current?.element??null;if(!P||!x||(x!==d&&(d&&R&&d.cancelVideoFrameCallback?.(R),b(x)),x.readyState<2))return;p.tick(w);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,M=Math.max(1,Math.round(P.clientWidth*A)),L=Math.max(1,Math.round(P.clientHeight*A));(P.width!==M||P.height!==L)&&(P.width=M,P.height=L);let E=P.getContext("2d");if(!E)return;let O=p.transform(),J=x.videoWidth||M,X=x.videoHeight||L,Z=Math.max(M/J,L/X)*(1+a)*O.scale;E.setTransform(Z,0,0,Z,M/2+O.translateX*M,L/2+O.translateY*L),E.drawImage(x,-J/2,-X/2),C.current=w};return k=requestAnimationFrame(m),()=>{cancelAnimationFrame(k),d&&R&&d.cancelVideoFrameCallback?.(R)}},[i,a,p]),(0,me.useEffect)(()=>{if(!i||!c||!l)return;let k=()=>!!l.pointerLockElement,R=P=>{k()&&p.keyDown(P.key)},d=P=>p.keyUp(P.key),b=P=>{k()&&p.pointerDelta(P.movementX,P.movementY)},m=()=>{k()||p.clearKeys()},w=()=>p.clearKeys();return l.addEventListener("keydown",R),l.addEventListener("keyup",d),l.addEventListener("mousemove",b),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",w),()=>{l.removeEventListener("keydown",R),l.removeEventListener("keyup",d),l.removeEventListener("mousemove",b),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",w)}},[i,c,l,p]),i?(0,Et.jsxs)(Ye,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Et.jsx)("canvas",{ref:v,style:es,"data-urun-warp":""}),n]}):(0,Et.jsx)(Ye,{ref:g,...s,children:n})});var Mn=new Map;function _n(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Mn.set(e,{component:t,schema:r})}function Nn(e,t){let r=Mn.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 Ze=require("react/jsx-runtime");function On({name:e,props:t,fallback:r}){let o=Nn(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ze.jsx)(Ze.Fragment,{children:r}):(0,Ze.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ze.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ze.jsx)(n,{...o.validatedProps})}var ut=require("zod"),Qe=require("react/jsx-runtime"),In=ut.z.object({step:ut.z.number().min(0),total:ut.z.number().min(1),label:ut.z.string().optional(),variant:ut.z.enum(["default","success","error"]).default("default")});function Rr(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 Ln(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Rr(e);return(0,Qe.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Qe.jsx)("div",{className:"urun-progress-label",children:o}),(0,Qe.jsx)("div",{className:"urun-progress-bar",children:(0,Qe.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Qe.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Bt=require("zod"),wt=require("react/jsx-runtime"),Dn=Bt.z.object({state:Bt.z.enum(["thinking","generating","idle","error"]),message:Bt.z.string().optional()}),ts={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Pr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??ts[t]??t;return{state:t,message:n,isActive:o}}function Vn(e){let{state:t,message:r,isActive:o}=Pr(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"),Fn=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 qn(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"),Hn=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 Wn(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 Ie=require("zod"),ct=require("react/jsx-runtime"),Bn=Ie.z.object({metrics:Ie.z.array(Ie.z.object({label:Ie.z.string(),value:Ie.z.union([Ie.z.string(),Ie.z.number()]),unit:Ie.z.string().optional()}))});function wr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function jn(e){let{metrics:t}=wr(e);return(0,ct.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ct.jsxs)("div",{className:"urun-metric-card",children:[(0,ct.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ct.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var Y=require("react"),zn=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 rs(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 ns(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function os(e){let t=We(e),r=t?.body;return ns(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 lt=class extends Error{name="TextStreamError"},ss=4,Ar=3,Mr=240,Kn=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function $n(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function is(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,Y.useRef)(e);(0,Y.useEffect)(()=>{o.current=e});let n=(0,Y.useRef)(null),s=(0,Y.useRef)(()=>{}),i=(0,Y.useRef)(null),a=(0,Y.useRef)(""),c=(0,Y.useRef)(""),u=(0,Y.useRef)(null),f=(0,Y.useRef)(!1),l=(0,Y.useRef)(!1),g=(0,Y.useRef)(!1),v=(0,Y.useRef)(null),C=(0,Y.useRef)($n()),h=(0,Y.useCallback)(d=>{if(n.current=d,!d){i.current=null;return}let b=i.current;if(b&&b.parentNode===d)return;let m=d.ownerDocument.createTextNode(c.current);d.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),p=(0,Y.useCallback)(()=>{u.current=null;let d=i.current,b=a.current;if(b.length>0){let A=o.current,M=A.smoothCharsPerFrame??Ar,L=A.smoothThreshold??Mr,E=A.smooth&&b.length<=L?b.slice(0,M):b;a.current=b.slice(E.length),c.current+=E,d?.appendData(E)}let m=C.current,w=c.current.length,P=v.current===null?0:Math.max(0,Kn()-v.current),x=Math.round(w/ss);if(m.chars=w,m.tokens=x,m.elapsedMs=P,m.tokensPerSecond=P>0?x*1e3/P:0,a.current.length>0){k(),o.current.onMeter?.(m);return}if(!f.current&&!g.current){g.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(m)},[]),k=(0,Y.useCallback)(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>p()))},[p]);s.current=k,(0,Y.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,is(C.current),i.current&&(i.current.data="");let d=!1,b=null;return(async()=>{try{for(b=t.stream(r).messages()[Symbol.asyncIterator]();;){let w=await b.next();if(d)return;if(w.done)break;let P=w.value,x=rs(P);if(x==="error")throw new lt(os(P));if(x==="done")break;if(x==="ignore")continue;let A=Ur(P);A&&(v.current===null&&(v.current=Kn()),a.current+=A,k())}if(d)return;b.return?.(void 0),f.current=!1,k()}catch(m){if(d)return;b?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(m instanceof Error?m:new lt(String(m))),k()}})(),()=>{d=!0,f.current=!1,b?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,k]);let R=(0,Y.useCallback)(()=>c.current,[]);return{ref:h,meterRef:C,getText:R}}function Gn(e,t=250){let[r,o]=(0,Y.useState)($n);return(0,Y.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 Xn(e){let{className:t,style:r,...o}=e,{ref:n}=_r(o);return(0,zn.jsx)("span",{ref:n,className:t,style:r})}var Jn=require("react");var Zn=require("react/jsx-runtime"),Yn=(0,Jn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Zn.jsx)(Ye,{ref:r,stream:o,...n})});var j=require("react"),Qn=require("@urun-sh/core");var to=require("react/jsx-runtime"),as=1e3;function us(e){return e!==null&&Or.has(e)}var Or=new WeakSet,cs=1e3;function Nr(...e){console.debug("[audio]",...e)}var Nt=(0,j.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f,directOut:l}=t,g=Ue(),v=o??g,C=(0,j.useRef)(null),h=(0,j.useRef)(null),p=(0,j.useRef)(null),k=(0,j.useRef)(null),R=(0,j.useRef)(null),d=(0,j.useRef)(0),b=(0,j.useRef)(!1),m=(0,j.useRef)(c);m.current=c;let w=(0,j.useRef)(u);w.current=u;let P=(0,j.useRef)(l);P.current=l;let x=(0,j.useCallback)(T=>{p.current!==T&&(p.current=T,w.current?.(T))},[]),A=(0,j.useCallback)(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let T=C.current;return T&&T.srcObject!==h.current&&h.current.getAudioTracks().length>0&&(T.srcObject=h.current),h.current},[]),M=(0,j.useCallback)(()=>{d.current=0,R.current!==null&&cancelAnimationFrame(R.current),R.current=null,k.current!==null&&clearTimeout(k.current),k.current=null},[]),L=(0,j.useCallback)(T=>{R.current=null,k.current=null,A(),C.current&&(C.current.muted=b.current),J.current(`${T}:retry`)},[A]),E=(0,j.useCallback)(T=>{if(!C.current||R.current!==null||k.current!==null)return;let S=h.current;if(!(!!S&&S.getAudioTracks().some(F=>F.readyState==="live"))){M();return}let V=d.current;if(d.current=V+1,V===0&&typeof requestAnimationFrame=="function"){R.current=requestAnimationFrame(()=>L(T));return}k.current=setTimeout(()=>L(T),cs)},[M,L]),O=(0,j.useCallback)(T=>{let W=C.current;if(!W)return;let S=W.play();!S||typeof S.then!="function"||S.then(()=>{W.muted=b.current,W.muted||x(!0),M()}).catch(N=>{let V=N instanceof Error?N.name:String(N);if(V==="AbortError"){Nr(`play() aborted (${T}); retrying on the ladder`),E(`${T}:abort`);return}if(V==="NotAllowedError"){Nr(`play() blocked pending a user gesture (${T})`),x(!1),E(`${T}:blocked`);return}Nr(`play() failed (${T})`,N)})},[x]),J=(0,j.useRef)(()=>{});J.current=O;let X=(0,j.useCallback)(T=>{let W=A();if(!W)return;for(let N of W.getAudioTracks())N!==T&&W.removeTrack(N);T&&!W.getAudioTracks().includes(T)&&W.addTrack(T),A();let S=P.current??us(T);b.current=!!T&&S,C.current&&(C.current.muted=b.current),T&&O("track-attach"),m.current?.(T)},[A,O]),z=(0,j.useCallback)(()=>{let T=C.current;T&&(A(),T.muted=b.current,O("gesture"),Je(),x(!0))},[A,O,x]);(0,j.useImperativeHandle)(r,()=>({unlock:z,get unlocked(){return p.current===!0},get element(){return C.current}}),[z]);let Z=(0,j.useCallback)(()=>{E("pause-event")},[E]),ne=(0,j.useCallback)(T=>{let W=C.current;W&&W!==T&&W.removeEventListener("pause",Z),C.current=T,T&&(T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),A(),T.addEventListener("pause",Z)),f?.(T)},[A,f,Z]),Q=s!==void 0;return(0,j.useEffect)(()=>{if(Q){X(s??null);return}if(!v)return;let T=v.stream(n);if(T.directOut){let U=T.track;U&&Or.add(U)}let W=()=>{let U=h.current;return U?U.getAudioTracks()[0]??null:null},S=U=>{if(U!==W()&&(T.directOut&&U&&Or.add(U),X(U),U)){let oe=()=>{W()===U&&X(null)};U.addEventListener("ended",oe)}},N=T.track;N&&N.readyState==="live"&&S(N);let V=T.on("track",U=>{U&&U.readyState!=="live"||S(U)}),F=setInterval(()=>{let U=T.track;U&&U.readyState==="live"&&S(U)},as);return()=>{V(),clearInterval(F)}},[v,n,Q,s,X]),(0,j.useEffect)(()=>(0,Qn.observePageLifecycle)(()=>{Je(),p.current===!0&&O("foreground")}),[O]),(0,j.useEffect)(()=>()=>{k.current&&clearTimeout(k.current),R.current!==null&&cancelAnimationFrame(R.current),R.current=null},[]),(0,to.jsx)("audio",{ref:ne,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),eo=Nt;var G=require("react"),Be=require("@urun-sh/core");var no=require("react/jsx-runtime"),Ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Kt(...e){console.debug("[voice]",...e)}function ls(e){return e instanceof Be.SessionFailedError&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var Ot=(0,G.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:C,onUnlockChange:h,capture:p,directOut:k}=t,R=Ue(),d=o??R,b=(0,G.useRef)(null),m=(0,G.useRef)(null),w=(0,G.useRef)(null),P=(0,G.useRef)([]),x=(0,G.useRef)(!1),A=(0,G.useRef)(l);A.current=l;let M=(0,G.useRef)(g);M.current=g;let L=(0,G.useRef)(v);L.current=v;let E=(0,G.useCallback)(S=>{x.current!==S&&(x.current=S,A.current?.(S))},[]),O=(0,G.useCallback)(()=>{for(let S of P.current)S();P.current=[],w.current?.release(),w.current=null,m.current&&(m.current=null,L.current?.(null))},[]),J=(0,G.useCallback)(async()=>{let S=w.current;if(S){let U=await S.update(a);return m.current=S.stream,L.current?.(S.stream),U}let V=await(p??(0,Be.sharedCaptureController)()).claim("audio",a);w.current=V,P.current=[V.onTrack((U,oe)=>{m.current=oe,L.current?.(oe),x.current&&d?.stream(n).attach(U).catch(se=>Kt("mic re-attach after one-capture re-acquire failed",se))}),V.onLost(U=>{w.current=null,P.current=[],m.current=null,L.current?.(null),E(!1),M.current?.(U)})],m.current=V.stream,L.current?.(V.stream);let F=V.track;if(!F)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return F},[p,a,d,n,E]),X=(0,G.useCallback)(async()=>{O(),E(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,O,E]),z=(0,G.useCallback)(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");b.current?.unlock();let S;try{S=await J()}catch(F){O();let U=(0,Be.sessionFailureFromMediaError)(F,d.status);throw M.current?.(U),U}let N;for(let F=1;F<=u;F++)try{await d.whenLive(c!==void 0?{timeout:c}:void 0),await d.stream(n).attach(S),E(!0);return}catch(U){if(N=U,Kt(`start attempt ${F}/${u} failed`,U),ls(U))break;d.connect?.(),F<u&&await new Promise(oe=>setTimeout(oe,f))}O(),E(!1);let V=N instanceof Error?N:new Error(String(N??"voice start failed"));throw M.current?.(V),V},[d,n,c,u,f,J,O,E]);(0,G.useImperativeHandle)(r,()=>({start:z,stop:X,unlock:()=>b.current?.unlock(),get active(){return x.current},get micStream(){return m.current},get audio(){return b.current}}),[z,X]);let Z=(0,G.useRef)(z);Z.current=z;let ne=(0,G.useRef)(null),Q=(0,G.useCallback)((S,N)=>{S.promise.then(()=>{N&&(O(),E(!1)),S.session.stream(S.streamName).detach().catch(()=>{})})},[O,E]);(0,G.useEffect)(()=>{if(!i||!d)return;let S=ne.current;S&&(S.session!==d||S.streamName!==n)&&(S.disposeTimer&&clearTimeout(S.disposeTimer),Q(S,!1),S=null),S?S.disposeTimer&&(clearTimeout(S.disposeTimer),S.disposeTimer=null):(S={session:d,streamName:n,promise:Z.current().catch(()=>{}),refCount:0,disposeTimer:null},ne.current=S),S.refCount+=1;let N=S;return()=>{N.refCount-=1,!(N.refCount>0)&&(N.disposeTimer=setTimeout(()=>{ne.current===N&&(ne.current=null),Q(N,!0)},0))}},[i,d,n,Q]);let T=(0,G.useRef)(!1),W=(0,G.useCallback)(async()=>{if(!d||!x.current||T.current)return;let S=m.current?.getAudioTracks()[0]??null;if(S&&S.readyState==="live"){try{await d.stream(n).attach(S)}catch(N){Kt("foreground mic re-assert failed (will retry on next pass)",N)}return}T.current=!0;try{let N=await J();await d.stream(n).attach(N)}catch(N){let V=N instanceof Error?N:new Error(String(N));Kt("foreground mic re-acquire failed",V),M.current?.(V)}finally{T.current=!1}},[d,n,J]);return(0,G.useEffect)(()=>{let S=()=>{W()};return d&&typeof d.onRecovery=="function"?d.onRecovery(S):(0,Be.observePageLifecycle)(S)},[d,W]),(0,G.useEffect)(()=>O,[O]),s?(0,no.jsx)(Nt,{ref:b,session:d,stream:n,onTrack:C,onUnlockChange:h,directOut:k}):null}),ro=Ot;var De=require("react");var $t=require("react");var Lr={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,$t.useState)(Lr);return(0,$t.useEffect)(()=>{if(!e){i(Lr);return}let a=Rt();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 C=0;for(let p=0;p<l.length;p++){let k=(l[p]-128)/128;C+=k*k}let h=Math.sqrt(C/l.length);i(p=>{let k=h>n;return Math.abs(p.level-h)<.005&&p.speaking===k?p:{level:h,speaking:k}})},o);return()=>{clearInterval(v),u.disconnect(),i(Lr)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),ds={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ps={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},oo=(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(),C=o??v,h=(0,De.useRef)(null),[p,k]=(0,De.useState)(null),R=(0,De.useRef)(l);R.current=l;let{level:d,speaking:b}=Gt(a?p:null);return(0,De.useImperativeHandle)(r,()=>({start:()=>{let m=h.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>h.current?.stop()??Promise.resolve(),get active(){return h.current?.active??!1},get micStream(){return h.current?.micStream??null}}),[]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(Ot,{ref:h,session:C,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:m=>{k(m),R.current?.(m)}}),a?(0,Le.jsx)("span",{className:c,style:ds,"data-urun-mic":"","data-urun-mic-active":p?"true":"false","data-urun-mic-speaking":b?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(d*100)/100,children:(0,Le.jsx)("span",{style:ps,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(d*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var dt=require("@urun-sh/core"),I=require("react");var be=require("react/jsx-runtime"),Vr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Dr(...e){console.debug("[camera]",...e)}function ms(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function fs(){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 Fr=(0,I.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:C,onActiveChange:h,onError:p,onStream:k,onTrack:R,children:d,capture:b,flipControl:m="auto",flipControlClassName:w,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let x=i?"user":a?"environment":c??"environment",A=Ue(),M=o??A,L=(0,I.useRef)(null),E=(0,I.useRef)(null),O=(0,I.useRef)(null),J=(0,I.useRef)([]),X=(0,I.useRef)(null),z=(0,I.useRef)(!1),Z=(0,I.useRef)(!1),ne=(0,I.useRef)(x),[Q,T]=(0,I.useState)(x),[W,S]=(0,I.useState)(!1),[N,V]=(0,I.useState)(null),[F,U]=(0,I.useState)(!1),[oe]=(0,I.useState)(ms),se=(0,I.useRef)(h);se.current=h;let de=(0,I.useRef)(p);de.current=p;let we=(0,I.useRef)(k);we.current=k;let he=(0,I.useRef)(R);he.current=R;let qe=(0,I.useRef)(P);qe.current=P;let fe=(0,I.useCallback)(B=>{z.current!==B&&(z.current=B,S(B),se.current?.(B))},[]);(0,I.useEffect)(()=>{if(!W){V(null);return}let B=!1,K=()=>{fs().then(ke=>{B||(V(ke),ke&&qe.current?.(ke))})};K();let ye=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ye?.addEventListener=="function"?(ye.addEventListener("devicechange",K),()=>{B=!0,ye.removeEventListener?.("devicechange",K)}):()=>{B=!0}},[W]);let pe=(0,I.useCallback)(B=>{let K=L.current;K&&(K.muted=!0,K.defaultMuted=!0,K.setAttribute("muted",""),K.setAttribute("playsinline",""),K.setAttribute("webkit-playsinline",""),K.srcObject=B,B&&K.play()?.catch?.(ye=>Dr("preview play() failed",ye)))},[]),ae=(0,I.useCallback)(()=>{Z.current=!1,X.current?.(),X.current=null;for(let B of J.current)B();J.current=[],O.current?.release(),O.current=null,E.current&&(E.current=null,we.current?.(null),he.current?.(null)),pe(null)},[pe]),y=(0,I.useCallback)((B,K)=>{X.current?.(),E.current=K,pe(K),we.current?.(K);let ye=()=>{E.current===K&&(Dr("camera track ended (device removed or permission revoked)"),ae(),fe(!1))};B.addEventListener("ended",ye),X.current=()=>B.removeEventListener("ended",ye)},[pe,ae,fe]),q=(0,I.useCallback)(async B=>{let K=n!==!1;if(K&&!M)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ye={...Vr,...s,facingMode:B},ke;try{let Re=O.current;if(Re)ke=await Re.update(ye);else{let yt=await(b??(0,dt.sharedCaptureController)()).claim("video",ye);if(O.current=yt,J.current=[yt.onTrack((kt,_o)=>{y(kt,_o),z.current&&(!K||!M||M.stream(n).attachVideo(kt).then(()=>he.current?.(kt)).catch(No=>Dr("camera re-publish after one-capture re-acquire failed",No)))}),yt.onLost(kt=>{O.current=null,J.current=[],ae(),fe(!1),de.current?.(kt)})],!yt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ke=yt.track}}catch(Re){let nt=(0,dt.sessionFailureFromMediaError)(Re,M?.status);throw de.current?.(nt),nt}ne.current=B,T(B),y(ke,O.current?.stream??new MediaStream([ke]));try{K&&M&&(M.connect?.(),await M.whenLive(l!==void 0?{timeout:l}:void 0),await M.stream(n).attachVideo(ke)),Z.current=K?n:!1}catch(Re){ae(),fe(!1);let nt=Re instanceof Error?Re:new Error(String(Re));throw de.current?.(nt),nt}he.current?.(ke),fe(!0)},[M,n,s,l,b,y,ae,fe]),_=(0,I.useCallback)(B=>q(B?.facingMode??ne.current),[q]),$=(0,I.useCallback)(async B=>{let K=Z.current===n;z.current&&ne.current===B&&K||await q(B)},[q,n]),ee=(0,I.useCallback)(()=>q(ne.current==="environment"?"user":"environment"),[q]),ve=(0,I.useCallback)(async()=>{ae(),fe(!1),n!==!1&&await M?.stream(n).detachVideo().catch(()=>{})},[M,n,ae,fe]),D=(0,I.useCallback)(async B=>{let K=L.current;if(!K)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,dt.captureStillFromVideo)(K,B)},[]);(0,I.useImperativeHandle)(r,()=>({start:_,stop:ve,flip:ee,setFacingMode:$,capturePhoto:D,get active(){return z.current},get facingMode(){return ne.current},get stream(){return E.current},get element(){return L.current}}),[_,ve,ee,$,D]);let Ae=(0,I.useRef)($);if(Ae.current=$,(0,I.useEffect)(()=>{u&&(n!==!1&&!M||Ae.current(x).catch(()=>{}))},[u,M,x,n]),(0,I.useEffect)(()=>ae,[ae]),!g)return null;let rt=f==="auto"?Q==="user":f,Me=W&&(m===!0||m==="auto"&&oe&&(N?.length??0)>1),_e=()=>{F||(U(!0),ee().catch(()=>{}).finally(()=>U(!1)))};return(0,be.jsxs)("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":Q,children:[(0,be.jsx)("video",{ref:L,className:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...rt?{transform:"scaleX(-1)"}:{}}}),Me?(0,be.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:F,className:w,style:w?{opacity:F?.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:F?.6:1},children:(0,be.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,be.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,be.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,be.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,be.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,be.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,d]})}),so=(0,I.forwardRef)(function({preview:t=!0,...r},o){return(0,be.jsx)(Fr,{ref:o,...r,visible:t,autoStart:!1})});var pt=require("@urun-sh/core"),ie=require("react");function io(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,ie.useState)(null),[a,c]=(0,ie.useState)(null),[u,f]=(0,ie.useState)(!1),[l,g]=(0,ie.useState)(null),[v]=(0,ie.useState)(pt.cameraCaptureAvailable),C=(0,ie.useRef)(n);C.current=n;let h=(0,ie.useRef)(null),p=(0,ie.useRef)(0),k=(0,ie.useCallback)(w=>{h.current&&URL.revokeObjectURL(h.current),h.current=w?URL.createObjectURL(new Blob([w.bytes],{type:w.type})):null,c(h.current),i(w),C.current?.(w)},[]);(0,ie.useEffect)(()=>()=>{p.current++,h.current&&URL.revokeObjectURL(h.current),h.current=null},[]);let R=(0,ie.useCallback)(async w=>{let P=++p.current;f(!0),g(null);try{let x=await w();if(p.current!==P)return;k(x)}catch(x){if(p.current!==P)return;g((0,pt.referenceImageErrorMessage)(x))}finally{p.current===P&&f(!1)}},[k]),d=(0,ie.useCallback)(w=>R(()=>(0,pt.normalizeReferenceImage)(w,{maxSize:t,type:r,quality:o,source:"file"})),[R,t,r,o]),b=(0,ie.useCallback)(w=>R(()=>w.capturePhoto({maxSize:t,type:r,quality:o})),[R,t,r,o]),m=(0,ie.useCallback)(()=>{p.current++,g(null),f(!1),k(null)},[k]);return{reference:s,previewUrl:a,pick:d,capture:b,clear:m,busy:u,error:l,cameraAvailable:v}}var Xt=require("react");function ao(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 lo=require("react");var Jt=require("react");var uo=require("zustand/vanilla"),co=require("zustand"),gs=()=>{};function zt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=(0,uo.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):gs,c=(u=>(0,co.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 po(e,t,r){let n=mt(e,t)(r??(a=>a)),s=(0,lo.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 mo(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 je=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 fo({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 It=require("react");var Se=require("react/jsx-runtime");function Lt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,It.useState)(""),[i,a]=(0,It.useState)(null),c=(0,It.useCallback)(()=>{let u=Zt(n);if(!u.ok){a(u.error);return}a(null),o(u.value,n.trim()),s("")},[n,o]);return(0,Se.jsxs)("div",{className:"urun-doc-patch",children:[(0,Se.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:e,rows:3}),(0,Se.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,Se.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?(0,Se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function go({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,Se.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,Se.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,Se.jsx)("code",{children:t}),(0,Se.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,Se.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,Se.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 So(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ho({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:So(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:So(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 et=require("react/jsx-runtime");function vo({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,et.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,et.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,et.jsxs)("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[(0,et.jsx)("span",{className:"urun-event-spine-kind",children:u.kind})," ",(0,et.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 Te(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 ko=require("@urun-sh/core");var gt=require("react"),yo=require("@urun-sh/core");function or(e){let t=Te(e),r=(0,yo.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 Ke=require("react/jsx-runtime");function sr({session:e,render:t,className:r}){let o=or(e);return!o.waking||!o.phase?null:(0,Ke.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,Ke.jsxs)(Ke.Fragment,{children:[(0,Ke.jsx)("span",{className:"urun-session-waking-label",children:(0,ko.describeSessionPhase)(o.phase)})," ",(0,Ke.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var ar=require("react");var $e=require("react"),Ss={event:null,elapsedMs:0};function ir(e,t){let[r,o]=(0,$e.useState)(null),n=(0,$e.useRef)(0);(0,$e.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,$e.useState)(0);return(0,$e.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}:Ss}var St=require("react/jsx-runtime"),hs={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 vs(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=vs(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??hs[c]})," ",(0,St.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var Ce=require("react/jsx-runtime"),ys={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",degraded:"degraded",paused:"paused",error:"error",unknown:"unrecognized state"};function bo({session:e,className:t}){let r=Te(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,Ce.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,Ce.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,Ce.jsx)("span",{className:"urun-session-status-label",children:ys[o]}),n?(0,Ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function To({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Te(e);if(s?.name==="live")return(0,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,Ce.jsx)(ur,{session:e})]});let i=r?r(s):(0,Ce.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&(0,cr.isWakingPhase)(s.name)?(0,Ce.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,Ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,Ce.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var lr=require("react");var Ro=require("react/jsx-runtime");function qr(e){return Te(e)?.endsAt??null}function ks(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 Co({session:e,urgentMs:t=6e4,className:r}){let n=qr(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=ks(s);return(0,Ro.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 Po=require("@urun-sh/core");var ht=require("react/jsx-runtime"),bs=new Set(["paused","error"]);function Hr({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=Te(e);if(!s||!bs.has(s.name))return null;let i=o?o(s):(0,ht.jsx)("span",{className:"urun-session-paused-copy",children:(0,Po.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 xo=Hr;var Ge=require("react"),tt=require("react/jsx-runtime");function Wr(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 Br(e){let t=(0,Ge.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Ge.useState)(()=>t?Wr(t.get("idle")):null);return(0,Ge.useEffect)(()=>{if(!t){o(null);return}return o(Wr(t.get("idle"))),t.on("change",()=>o(Wr(t.get("idle"))))},[t]),r}function Ts(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Eo({session:e,onStillHere:t,className:r}){let o=Br(e),n=o?.deadlineEpochS??null,[s,i]=(0,Ge.useState)(null);if((0,Ge.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,tt.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,tt.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,tt.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,tt.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Ts(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,tt.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var Ee=require("react");function Cs(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:Cs(o),loading:s,error:a,refresh:l}}var pr=require("react/jsx-runtime");function wo({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 Xe=require("@urun-sh/core");var vt=require("react"),Uo=require("@urun-sh/core");function Ao(e){let t=(0,vt.useContext)(He),[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,Uo.prewake)({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(h=>{g||o(h)}).catch(()=>{})};v();let C=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(C)}},[n,s,i,a,c,u,f,l]),r}var mr=require("react");function Mo(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 kt,b as Un,c as Tt}from"./chunk-WF2OBDSX.mjs";import{useCallback as gr,useEffect as Hn,useMemo as kr,useRef as Sr,useState as Pt}from"react";import{computeBackoffDelay as Wn}from"@urun-sh/core/internal";import{Component as An}from"react";import{jsx as lr,jsxs as Mn}from"react/jsx-runtime";var Ke=class extends An{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||Mn("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:[lr("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),lr("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as _n}from"react";var Ce=_n(null);function Te(e){return e&&e.trim()?e.trim():void 0}function ge(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Te(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Te(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=ge("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ge("VERCEL_ENV")==="production"?"workos":ge("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Nn(){return rt()==="workos"}import{useEffect as On,useRef as In}from"react";var Ln="urun.operator_token",pr=null,dr="op",Dn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function mr(){return typeof window<"u"}function fr(){return pr}function Vn(){if(!mr())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(dr);if(!r)return null;pr=r,t.delete(dr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Fn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Rt(e){let t=In(e);t.current=e,On(()=>{if(!mr())return;Vn();let r=o=>{if(!Fn(o))return;let n=fr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as qn}from"react";function Ct(e=!0){qn(()=>{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 Ve,jsxs as zn}from"react/jsx-runtime";var Bn="/api/urun-token",jn=1e4;function Kn(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}}var hr=3,$n=new Set([502,503,504]);function vr(e){return new Promise(t=>setTimeout(t,Wn(e)))}async function yr(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=hr-1)throw a;await vr(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!$n.has(o.status)||r>=hr-1)throw a;await vr(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function br(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 kr(()=>e,[t])}function Gn(e,t){return typeof e=="function"?e(t):e!==void 0?e:zn("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:[Ve("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ve("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Xn({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:R,confirmOnLeave:h=!1,fallback:p,errorFallback:b,children:C}){let d=n===void 0&&t===void 0;if(!d&&(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(!d&&(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 k=r??o;if(d&&(typeof k!="string"||k.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Ct(h);let[m,w]=Pt(),[P,E]=Pt(null),A=Sr(void 0),M=Sr(null),[I,x]=Pt(null);Rt(_=>x({jwt:_}));let O=Tt(),$=ge("NEXT_PUBLIC_SESSION_TOKEN")??ge("NEXT_PUBLIC_URUN_JWT"),j=rt(),K=I!==null,G=j==="workos"&&!n&&!K&&!d,J=n??(j==="jwt"?$:void 0)??m?.token,X=K?I.jwt:J,T=s??ge("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),q=G&&!X&&!O?.getAccessToken,S=t??m?.orgId,N=e??m?.gatewayUrl,D=d&&m===void 0,V=d&&m!==void 0&&!N?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,U=q?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,Y=P??V??U,Z=br("NEXT_PUBLIC_URUN_TOKEN_URL",ge("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Bn,ee=br("NEXT_PUBLIC_URUN_EVENTS_URL",ge("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,fe=gr(async _=>{if(!_?.forceRefresh){let z=A.current;if(!z)return z;let ie=Kn(z);if(ie===null||ie-Date.now()>jn)return z}return(await(M.current??(M.current=(async()=>{try{let z=await yr(Z);return A.current=z.token,w(z),z}finally{M.current=null}})()))).token},[Z]),se=gr(async()=>X,[X]),Re=typeof X=="string"&&X.trim().length>0,ne=G?O?.getAccessToken:d&&!K?fe:Re?se:void 0,te=Et(g),Q=Et(v),y=Et(R),F=kr(()=>({appId:k,baseUrl:N??"",orgId:S??"",jwt:X,getAccessToken:G?O?.getAccessToken:d&&!K?fe:void 0,authProvider:T,eventsUrl:ee,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:te,videoPlayout:Q,sessionStats:y,priority:K?"preempt":void 0}),[k,O,N,T,X,ee,S,a,u,f,l,te,Q,y,G,K,d,fe]);return Hn(()=>{if(!d)return;let _=new AbortController;return E(null),(async()=>{try{let B=await yr(Z,_.signal);A.current=B.token,w(B)}catch(B){if(_.signal.aborted)return;E(B instanceof Error?B:new Error(String(B)))}})(),()=>_.abort()},[d,Z]),Ve(Ke,{fallback:p,children:Y?Gn(b,Y):D?Ve("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ve(Ce.Provider,{value:F,children:ne?Ve(kt,{getAccessToken:ne,children:C}):C})})}import{useContext as Jn,useEffect as Yn,useMemo as Tr,useReducer as Zn,useRef as xt}from"react";import{App as Qn}from"@urun-sh/core";function Rr(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function eo(e,t,r){let o=Rr(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function to(e,t,r,o){let n=Rr(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 Me=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}get directOut(){return this._stream.directOut}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 mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}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 ro(){let e=Jn(Ce);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Zn(i=>i+1,0),r=xt(new Map),o=xt(new Map),n=xt(null),s=Tr(()=>Qn(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 Yn(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Me.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=Me.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=Me.get(c);!l||l.refCount!==0||(Me.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),Tr(()=>{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=eo(c,l,g),R=r.current.get(v);if(R&&!R.disposed)return R;let h=to(e,c,l,g),p=Me.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),Me.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new At(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Me.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(c,f),f}})},[e,s])}import{useContext as no,useMemo as oo}from"react";import{sessionDirectory as so}from"@urun-sh/core";function io(){let e=no(Ce);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 oo(()=>so(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}import{useCallback as Mt,useEffect as ao,useMemo as uo,useRef as nt,useState as _t}from"react";function Fe(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 co(e){return e instanceof Error?e:new Error(String(e))}function lo(e,t){let r=uo(()=>Fe(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);ao(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=Mt(async p=>{l.current?.abort();let b=new AbortController;l.current=b;let C=++f.current,d=()=>g.current&&f.current===C;d()&&(c(!0),i(null));try{let k=await r.request(p,{...u.current,signal:b.signal});return d()&&(n(k),c(!1),u.current?.onSuccess?.(k)),k}catch(k){let m=co(k);throw d()&&(i(m),c(!1),u.current?.onError?.(m)),m}},[r]),R=Mt(p=>{v(p).catch(()=>{})},[v]),h=Mt(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:R,mutateAsync:v,data:o,error:s,isPending:a,reset:h}}import{useCallback as Cr,useEffect as po,useMemo as mo,useRef as ot,useState as Nt}from"react";function Pr(e){return e instanceof Error?e:new Error(String(e))}var fo=e=>typeof e=="string"?e:String(e);function go(e,t){let r=mo(()=>Fe(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);po(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=Cr(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),R=Cr(async h=>{l.current?.cancel();let p=++f.current,b=()=>g.current&&f.current===p,C=u.current,d=C?.parseChunk??fo,k=C?.buildPayload??(x=>({prompt:x}));b()&&(n(""),c(null),i(!0));let{parseChunk:m,buildPayload:w,onFinish:P,onError:E,...A}=C??{},M="",I;try{I=r.requestStream(k(h),A),l.current=I}catch(x){let O=Pr(x);b()&&(c(O),i(!1),C?.onError?.(O));return}try{for await(let x of I){if(f.current!==p)break;M+=d(x),b()&&n(M)}b()&&(i(!1),C?.onFinish?.(M))}catch(x){let O=Pr(x);b()&&(c(O),i(!1),C?.onError?.(O))}finally{l.current===I&&(l.current=null)}},[r]);return{completion:o,complete:R,stop:v,isStreaming:s,error:a}}import{useCallback as Er,useEffect as So,useMemo as ho,useRef as qe,useState as st}from"react";function xr(e){return e instanceof Error?e:new Error(String(e))}var vo=e=>typeof e=="string"?e:String(e),wr=0;function Ot(e){return wr+=1,`${e}-${wr}`}function yo(e,t){let r=ho(()=>Fe(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(d=>({id:d.id??Ot("msg"),role:d.role,content:d.content}))),[s,i]=st(""),[a,c]=st(!1),[u,f]=st(null),l=qe(t);l.current=t;let g=qe(o);g.current=o;let v=qe(s);v.current=s;let R=qe(0),h=qe(null),p=qe(!0);So(()=>(p.current=!0,()=>{p.current=!1,h.current?.cancel(),h.current=null}),[]);let b=Er(()=>{R.current++,h.current?.cancel(),h.current=null,p.current&&c(!1)},[]),C=Er(async d=>{let k=d===void 0,m=(k?v.current:d)??"";if(!m.trim())return;h.current?.cancel();let P=++R.current,E=()=>p.current&&R.current===P,A=l.current,M=A?.parseChunk??vo,I={id:Ot("msg"),role:"user",content:m},x={id:Ot("msg"),role:"assistant",content:""},O=[...g.current,I].map(V=>({role:V.role,content:V.content})),$=[...g.current,I,x];g.current=$,n($),k&&i(""),f(null),c(!0);let j=A?.buildPayload??(V=>({messages:V})),{initialMessages:K,parseChunk:G,buildPayload:J,onFinish:X,onError:T,...q}=A??{},S=V=>{n(U=>U.map(Y=>Y.id===x.id?{...Y,content:V}:Y))},N="",D;try{D=r.requestStream(j(O),q),h.current=D}catch(V){let U=xr(V);E()&&(f(U),c(!1),A?.onError?.(U));return}try{for await(let V of D){if(R.current!==P)break;N+=M(V),E()&&S(N)}E()&&(c(!1),A?.onFinish?.({...x,content:N}))}catch(V){let U=xr(V);E()&&(f(U),c(!1),A?.onError?.(U))}finally{h.current===D&&(h.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:C,stop:b,isStreaming:a,error:u}}import{useCallback as Pe,useEffect as Ur,useMemo as bo,useRef as Ar,useState as Mr}from"react";import{createInputPresencePublisher as ko,INPUT_PRESENCE_DEFAULT_HZ as To,INPUT_PRESENCE_FIELD as Ro}from"@urun-sh/core";var It=[];function Co(e,t={}){let{field:r=Ro,hz:o=To}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=bo(()=>s?ko({awareness:{setLocalStateField:(m,w)=>s.setField(m,w)},field:r,hz:o}):null,[s,r,o]),a=Ar(null);a.current=i;let[c,u]=Mr(!1),[f,l]=Mr(It),g=Ar(!1);Ur(()=>{if(i)return()=>i.dispose()},[i]);let v=Pe(()=>{let m=a.current;l(m?m.heldKeys():It)},[]),R=Pe(()=>{a.current?.clear(),l(It)},[]);Ur(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,w=()=>{if(m()){g.current=!1,u(!0);return}g.current||(u(!1),R())},P=x=>{m()&&(a.current?.keyDown(x.key),v())},E=x=>{a.current?.keyUp(x.key),v()},A=x=>{m()&&a.current?.movePointer(x.movementX,x.movementY)},M=x=>{m()&&a.current?.setButtons(x.buttons)},I=()=>{R()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",P),n.addEventListener("keyup",E),n.addEventListener("mousemove",A),n.addEventListener("mousedown",M),n.addEventListener("mouseup",M),n.defaultView?.addEventListener("blur",I),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",P),n.removeEventListener("keyup",E),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",M),n.removeEventListener("mouseup",M),n.defaultView?.removeEventListener("blur",I)}},[n,R,v]);let h=Pe(m=>{m.requestPointerLock?.()},[]),p=Pe(()=>{g.current=!0,u(!0)},[]),b=Pe(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),R()},[n,R]),C=Pe(m=>{a.current?.keyDown(m),v()},[v]),d=Pe(m=>{a.current?.keyUp(m),v()},[v]),k=Pe((m,w)=>{a.current?.movePointer(m,w)},[]);return{engage:h,engageTouch:p,release:b,engaged:c,heldKeys:f,pressKey:C,releaseKey:d,movePointer:k}}import{forwardRef as Io,useEffect as Fr,useImperativeHandle as Lo,useMemo as Do,useRef as ut}from"react";import{createCameraWarp as Vo}from"@urun-sh/core";import{forwardRef as Ao,useCallback as Ee,useEffect as $e,useImperativeHandle as Mo,useRef as oe,useState as Nr}from"react";import{derivedLegRole as _o}from"@urun-sh/core";var it=null;function Po(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=Po();return e?(it=new e,it):null}function He(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as Eo,useContext as _r}from"react";import{jsx as Uo}from"react/jsx-runtime";var Lt=Eo(null);function xo({session:e,children:t}){return Uo(Lt.Provider,{value:e,children:t})}function Se(){return _r(Lt)}function wo(){let e=_r(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 Vr,jsxs as Oo}from"react/jsx-runtime";function No(e,t){return e-t>>>0<2147483648}var Or=1e3;function Ir(...e){console.debug("[video]",...e)}function Lr(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 Dr(e,t,r){return r?[r,t]:[e,t]}var We=Ao(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:R,children:h,onTrack:p,onFirstFrame:b,frameMarker:C,onFrameMarkerReached:d,onFrameMarkerUnsupported:k,onUnlockChange:m}=t,w=Se(),P=o??w,E=oe(null),A=oe(null),[M,I]=Nr(!1),[x,O]=Nr(!1),$=oe(!1),j=oe(null),K=oe(p);K.current=p;let G=oe(m);G.current=m;let J=oe(b);J.current=b;let X=oe(d);X.current=d;let T=oe(k);T.current=k;let q=oe(C??null);q.current=C??null;let S=Ee(y=>{j.current!==y&&(j.current=y,G.current?.(y))},[]),N=oe(null),D=oe(null),V=Ee((y,F=!1)=>{if(!F&&y===N.current||(N.current=y,D.current?.(),D.current=null,$.current=!1,O(!1),!y))return;let _=E.current;if(!_)return;let B=q.current,z=B?.rtpTimestamp??null,ie=!1,L=()=>{ie||(ie=!0,T.current?.())};B&&z==null&&L();let ye=B!=null&&z!=null,Le=ke=>{D.current?.(),D.current=null,$.current=!0,O(!0),J.current?.(),ke&&X.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let ke=!1,H=0,W=(ae,ue)=>{if(!ke){if(ye){let le=ue?.rtpTimestamp;if(typeof le!="number"){L(),Le(!1);return}if(!No(le,z)){H=_.requestVideoFrameCallback(W);return}Le(!0);return}Le(!1)}};H=_.requestVideoFrameCallback(W),D.current=()=>{ke=!0,_.cancelVideoFrameCallback?.(H)};return}ye&&L();let be=()=>{let ke=_.getVideoPlaybackQuality?.();(ke?ke.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&Le(!1)};_.addEventListener("loadeddata",be),_.addEventListener("timeupdate",be),_.addEventListener("playing",be),D.current=()=>{_.removeEventListener("loadeddata",be),_.removeEventListener("timeupdate",be),_.removeEventListener("playing",be)},be()},[]);$e(()=>()=>{D.current?.(),D.current=null},[]);let U=C==null?null:`${C.rtpTimestamp??""}|${C.ptsMs??""}`,Y=oe(U);$e(()=>{if(Y.current===U||(Y.current=U,U==null))return;let y=N.current;y&&V(y,!0)},[U,V]);let Z=Ee(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let y=E.current;return y&&y.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(y.srcObject=A.current),A.current},[]),ee=Ee(y=>{let F=E.current;if(!F)return;let _=F.play();!_||typeof _.then!="function"||_.then(()=>{F.muted||S(!0)}).catch(B=>{if((B instanceof Error?B.name:String(B))==="NotAllowedError"&&!F.muted){Ir(`play() blocked pending a user gesture (${y})`),S(!1);return}Ir(`play() failed (${y})`,B)})},[S]),fe=Ee(()=>{let y=E.current;y&&(Z(),!y.muted&&(ee("gesture"),He(),S(!0)))},[Z,ee,S]),se=Ee(y=>{let F=Z();if(F){for(let _ of F.getVideoTracks())_!==y&&F.removeTrack(_);if(y&&!F.getVideoTracks().includes(y)){F.addTrack(y);let _=E.current;_&&(_.srcObject=F)}y&&ee("track-attach"),I(y!==null),V(y),K.current?.(y)}},[Z,ee,V]),Re=Ee(y=>{let F=Z();if(F){for(let _ of F.getAudioTracks())_!==y&&F.removeTrack(_);if(y&&!F.getAudioTracks().includes(y)){F.addTrack(y);let _=E.current;_&&_.srcObject!==F&&(_.srcObject=F)}y&&ee("audio-attach")}},[Z,ee]),ne=Ee(y=>{E.current=y,y&&(a?(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted",""),j.current=null):(y.muted=!1,y.defaultMuted=!1,y.removeAttribute("muted")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),Z())},[Z,a]);Mo(r,()=>({get element(){return E.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return $.current},unlock:fe,get unlocked(){return j.current===!0}}),[fe]);let te=_o(n)!==void 0;$e(()=>{te&&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.`)},[te,n]);let Q=i!==void 0;return $e(()=>{if(Q){se(i??null);return}if(te){se(null);return}if(!P)return;let y=Lr(P,Dr(n,"video")),F=()=>{let L=A.current;return L?L.getVideoTracks()[0]??null:null},_=L=>{if(L!==F()&&(se(L),L)){let ye=()=>{F()===L&&se(null)};L.addEventListener("ended",ye)}},B=y.track;B&&B.readyState==="live"&&_(B);let z=y.on("track",L=>{L&&L.readyState!=="live"||_(L)}),ie=setInterval(()=>{let L=y.track;L&&L.readyState==="live"&&_(L)},Or);return()=>{z(),clearInterval(ie)}},[P,n,te,Q,i,se]),$e(()=>{if(Q||!P||s===!1||te)return;let y=Lr(P,Dr(n,"audio",s)),F=()=>{let L=A.current;return L?L.getAudioTracks()[0]??null:null},_=L=>{if(L!==F()&&(Re(L),L)){let ye=()=>{F()===L&&Re(null)};L.addEventListener("ended",ye)}},B=y.track;B&&B.readyState==="live"&&_(B);let z=y.on("track",L=>{L&&L.readyState!=="live"||_(L)}),ie=setInterval(()=>{let L=y.track;L&&L.readyState==="live"&&_(L)},Or);return()=>{z(),clearInterval(ie)}},[P,n,te,s,Q,Re]),Oo("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":x?"true":"false",children:[Vr("video",{ref:ne,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),M?null:v,R===void 0?null:Vr("div",{"data-urun-video-poster":"","aria-hidden":x||void 0,style:{position:"absolute",inset:0,...x?{opacity:0,pointerEvents:"none"}:null},children:R}),h]})});import{jsx as qr,jsxs as Ho}from"react/jsx-runtime";var Fo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},qo=Io(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),R=ut(0),h=ut(f);h.current=f;let p=Do(()=>Vo(h.current),[]);return Lo(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:p,get lastDrawTs(){return R.current}}),[p]),Fr(()=>{if(!i)return;let b=0,C=0,d=null,k=w=>{typeof w.requestVideoFrameCallback=="function"&&(d=w,C=w.requestVideoFrameCallback(function P(){p.frameArrived(),C=w.requestVideoFrameCallback(P)}))},m=w=>{b=requestAnimationFrame(m);let P=v.current,E=g.current?.element??null;if(!P||!E||(E!==d&&(d&&C&&d.cancelVideoFrameCallback?.(C),k(E)),E.readyState<2))return;p.tick(w);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,M=Math.max(1,Math.round(P.clientWidth*A)),I=Math.max(1,Math.round(P.clientHeight*A));(P.width!==M||P.height!==I)&&(P.width=M,P.height=I);let x=P.getContext("2d");if(!x)return;let O=p.transform(),$=E.videoWidth||M,j=E.videoHeight||I,G=Math.max(M/$,I/j)*(1+a)*O.scale;x.setTransform(G,0,0,G,M/2+O.translateX*M,I/2+O.translateY*I),x.drawImage(E,-$/2,-j/2),R.current=w};return b=requestAnimationFrame(m),()=>{cancelAnimationFrame(b),d&&C&&d.cancelVideoFrameCallback?.(C)}},[i,a,p]),Fr(()=>{if(!i||!c||!l)return;let b=()=>!!l.pointerLockElement,C=P=>{b()&&p.keyDown(P.key)},d=P=>p.keyUp(P.key),k=P=>{b()&&p.pointerDelta(P.movementX,P.movementY)},m=()=>{b()||p.clearKeys()},w=()=>p.clearKeys();return l.addEventListener("keydown",C),l.addEventListener("keyup",d),l.addEventListener("mousemove",k),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",w),()=>{l.removeEventListener("keydown",C),l.removeEventListener("keyup",d),l.removeEventListener("mousemove",k),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",w)}},[i,c,l,p]),i?Ho(We,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[qr("canvas",{ref:v,style:Fo,"data-urun-warp":""}),n]}):qr(We,{ref:g,...s,children:n})});var Hr=new Map;function Wo(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Hr.set(e,{component:t,schema:r})}function Wr(e,t){let r=Hr.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 jo,jsx as ct}from"react/jsx-runtime";function Bo({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(jo,{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 Br}from"react/jsx-runtime";var Ko=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 jr(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 $o(e){let{step:t,total:r,label:o,variant:n,percentage:s}=jr(e);return Br("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}%`}})}),Br("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as Kr,jsxs as Jo}from"react/jsx-runtime";var Go=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),Xo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function $r(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Xo[t]??t;return{state:t,message:n,isActive:o}}function zo(e){let{state:t,message:r,isActive:o}=$r(e);return Jo("span",{className:"urun-status-badge","data-state":t,children:[Kr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Kr("span",{className:"urun-status-message",children:r})]})}import{useRef as Gr,useEffect as Yo}from"react";import{z as Ft}from"zod";import{jsx as Xr,jsxs as es}from"react/jsx-runtime";var Zo=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function zr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Qo(e){let{text:t,streaming:r}=zr(e),o=Gr(null),n=Gr(0);return Yo(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),es("div",{className:"urun-text-stream",children:[Xr("span",{ref:o,className:"urun-text-content"}),r&&Xr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as Jr,jsxs as ns}from"react/jsx-runtime";var ts=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Yr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function rs(e){let{src:t,alt:r,caption:o}=Yr(e);return ns("figure",{className:"urun-image-frame",children:[Jr("img",{className:"urun-image",src:t,alt:r}),o&&Jr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as xe}from"zod";import{jsx as qt,jsxs as is}from"react/jsx-runtime";var os=xe.object({metrics:xe.array(xe.object({label:xe.string(),value:xe.union([xe.string(),xe.number()]),unit:xe.string().optional()}))});function Zr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function ss(e){let{metrics:t}=Zr(e);return qt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>is("div",{className:"urun-metric-card",children:[qt("div",{className:"urun-metric-label",children:r.label}),qt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as Ht,useRef as ce,useState as as}from"react";import{jsx as gs}from"react/jsx-runtime";function we(e){return e&&typeof e=="object"?e:null}function en(e){if(typeof e=="string")return e;let t=we(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function us(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 cs(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function ls(e){let t=we(e),r=t?.body;return cs(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 Xe=class extends Error{name="TextStreamError"},ds=4,tn=3,rn=240,Qr=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function nn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function ps(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function on(e){let{session:t,stream:r}=e,o=ce(e);Ht(()=>{o.current=e});let n=ce(null),s=ce(()=>{}),i=ce(null),a=ce(""),c=ce(""),u=ce(null),f=ce(!1),l=ce(!1),g=ce(!1),v=ce(null),R=ce(nn()),h=dt(d=>{if(n.current=d,!d){i.current=null;return}let k=i.current;if(k&&k.parentNode===d)return;let m=d.ownerDocument.createTextNode(c.current);d.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),p=dt(()=>{u.current=null;let d=i.current,k=a.current;if(k.length>0){let A=o.current,M=A.smoothCharsPerFrame??tn,I=A.smoothThreshold??rn,x=A.smooth&&k.length<=I?k.slice(0,M):k;a.current=k.slice(x.length),c.current+=x,d?.appendData(x)}let m=R.current,w=c.current.length,P=v.current===null?0:Math.max(0,Qr()-v.current),E=Math.round(w/ds);if(m.chars=w,m.tokens=E,m.elapsedMs=P,m.tokensPerSecond=P>0?E*1e3/P:0,a.current.length>0){b(),o.current.onMeter?.(m);return}if(!f.current&&!g.current){g.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(m)},[]),b=dt(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>p()))},[p]);s.current=b,Ht(()=>{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,ps(R.current),i.current&&(i.current.data="");let d=!1,k=null;return(async()=>{try{for(k=t.stream(r).messages()[Symbol.asyncIterator]();;){let w=await k.next();if(d)return;if(w.done)break;let P=w.value,E=us(P);if(E==="error")throw new Xe(ls(P));if(E==="done")break;if(E==="ignore")continue;let A=en(P);A&&(v.current===null&&(v.current=Qr()),a.current+=A,b())}if(d)return;k.return?.(void 0),f.current=!1,b()}catch(m){if(d)return;k?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(m instanceof Error?m:new Xe(String(m))),b()}})(),()=>{d=!0,f.current=!1,k?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,b]);let C=dt(()=>c.current,[]);return{ref:h,meterRef:R,getText:C}}function ms(e,t=250){let[r,o]=as(nn);return Ht(()=>{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 fs(e){let{className:t,style:r,...o}=e,{ref:n}=on(o);return gs("span",{ref:n,className:t,style:r})}import{forwardRef as Ss}from"react";import{jsx as vs}from"react/jsx-runtime";var hs=Ss(function(t,r){let{stream:o="image",...n}=t;return vs(We,{ref:r,stream:o,...n})});import{forwardRef as ys,useCallback as he,useEffect as Wt,useImperativeHandle as bs,useRef as de}from"react";import{observePageLifecycle as ks}from"@urun-sh/core";import{jsx as Es}from"react/jsx-runtime";var Ts=1e3;function Rs(e){return e!==null&&jt.has(e)}var jt=new WeakSet,Cs=1e3;function Bt(...e){console.debug("[audio]",...e)}var pt=ys(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f,directOut:l}=t,g=Se(),v=o??g,R=de(null),h=de(null),p=de(null),b=de(null),C=de(null),d=de(0),k=de(!1),m=de(c);m.current=c;let w=de(u);w.current=u;let P=de(l);P.current=l;let E=he(T=>{p.current!==T&&(p.current=T,w.current?.(T))},[]),A=he(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let T=R.current;return T&&T.srcObject!==h.current&&h.current.getAudioTracks().length>0&&(T.srcObject=h.current),h.current},[]),M=he(()=>{d.current=0,C.current!==null&&cancelAnimationFrame(C.current),C.current=null,b.current!==null&&clearTimeout(b.current),b.current=null},[]),I=he(T=>{C.current=null,b.current=null,A(),R.current&&(R.current.muted=k.current),$.current(`${T}:retry`)},[A]),x=he(T=>{if(!R.current||C.current!==null||b.current!==null)return;let S=h.current;if(!(!!S&&S.getAudioTracks().some(V=>V.readyState==="live"))){M();return}let D=d.current;if(d.current=D+1,D===0&&typeof requestAnimationFrame=="function"){C.current=requestAnimationFrame(()=>I(T));return}b.current=setTimeout(()=>I(T),Cs)},[M,I]),O=he(T=>{let q=R.current;if(!q)return;let S=q.play();!S||typeof S.then!="function"||S.then(()=>{q.muted=k.current,q.muted||E(!0),M()}).catch(N=>{let D=N instanceof Error?N.name:String(N);if(D==="AbortError"){Bt(`play() aborted (${T}); retrying on the ladder`),x(`${T}:abort`);return}if(D==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${T})`),E(!1),x(`${T}:blocked`);return}Bt(`play() failed (${T})`,N)})},[E]),$=de(()=>{});$.current=O;let j=he(T=>{let q=A();if(!q)return;for(let N of q.getAudioTracks())N!==T&&q.removeTrack(N);T&&!q.getAudioTracks().includes(T)&&q.addTrack(T),A();let S=P.current??Rs(T);k.current=!!T&&S,R.current&&(R.current.muted=k.current),T&&O("track-attach"),m.current?.(T)},[A,O]),K=he(()=>{let T=R.current;T&&(A(),T.muted=k.current,O("gesture"),He(),E(!0))},[A,O,E]);bs(r,()=>({unlock:K,get unlocked(){return p.current===!0},get element(){return R.current}}),[K]);let G=he(()=>{x("pause-event")},[x]),J=he(T=>{let q=R.current;q&&q!==T&&q.removeEventListener("pause",G),R.current=T,T&&(T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),A(),T.addEventListener("pause",G)),f?.(T)},[A,f,G]),X=s!==void 0;return Wt(()=>{if(X){j(s??null);return}if(!v)return;let T=v.stream(n);if(T.directOut){let U=T.track;U&&jt.add(U)}let q=()=>{let U=h.current;return U?U.getAudioTracks()[0]??null:null},S=U=>{if(U!==q()&&(T.directOut&&U&&jt.add(U),j(U),U)){let Y=()=>{q()===U&&j(null)};U.addEventListener("ended",Y)}},N=T.track;N&&N.readyState==="live"&&S(N);let D=T.on("track",U=>{U&&U.readyState!=="live"||S(U)}),V=setInterval(()=>{let U=T.track;U&&U.readyState==="live"&&S(U)},Ts);return()=>{D(),clearInterval(V)}},[v,n,X,s,j]),Wt(()=>ks(()=>{He(),p.current===!0&&O("foreground")}),[O]),Wt(()=>()=>{b.current&&clearTimeout(b.current),C.current!==null&&cancelAnimationFrame(C.current),C.current=null},[]),Es("audio",{ref:J,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Ps=pt;import{forwardRef as xs,useCallback as _e,useEffect as Kt,useImperativeHandle as ws,useRef as pe}from"react";import{observePageLifecycle as Us,SessionFailedError as As,sessionFailureFromMediaError as Ms,sharedCaptureController as _s}from"@urun-sh/core";import{jsx as Is}from"react/jsx-runtime";var sn={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}function Ns(e){return e instanceof As&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var ft=xs(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=sn,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:R,onUnlockChange:h,capture:p,directOut:b}=t,C=Se(),d=o??C,k=pe(null),m=pe(null),w=pe(null),P=pe([]),E=pe(!1),A=pe(l);A.current=l;let M=pe(g);M.current=g;let I=pe(v);I.current=v;let x=_e(S=>{E.current!==S&&(E.current=S,A.current?.(S))},[]),O=_e(()=>{for(let S of P.current)S();P.current=[],w.current?.release(),w.current=null,m.current&&(m.current=null,I.current?.(null))},[]),$=_e(async()=>{let S=w.current;if(S){let U=await S.update(a);return m.current=S.stream,I.current?.(S.stream),U}let D=await(p??_s()).claim("audio",a);w.current=D,P.current=[D.onTrack((U,Y)=>{m.current=Y,I.current?.(Y),E.current&&d?.stream(n).attach(U).catch(Z=>mt("mic re-attach after one-capture re-acquire failed",Z))}),D.onLost(U=>{w.current=null,P.current=[],m.current=null,I.current?.(null),x(!1),M.current?.(U)})],m.current=D.stream,I.current?.(D.stream);let V=D.track;if(!V)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return V},[p,a,d,n,x]),j=_e(async()=>{O(),x(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,O,x]),K=_e(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");k.current?.unlock();let S;try{S=await $()}catch(V){O();let U=Ms(V,d.status);throw M.current?.(U),U}let N;for(let V=1;V<=u;V++)try{await d.whenLive(c!==void 0?{timeout:c}:void 0),await d.stream(n).attach(S),x(!0);return}catch(U){if(N=U,mt(`start attempt ${V}/${u} failed`,U),Ns(U))break;d.connect?.(),V<u&&await new Promise(Y=>setTimeout(Y,f))}O(),x(!1);let D=N instanceof Error?N:new Error(String(N??"voice start failed"));throw M.current?.(D),D},[d,n,c,u,f,$,O,x]);ws(r,()=>({start:K,stop:j,unlock:()=>k.current?.unlock(),get active(){return E.current},get micStream(){return m.current},get audio(){return k.current}}),[K,j]);let G=pe(K);G.current=K;let J=pe(null),X=_e((S,N)=>{S.promise.then(()=>{N&&(O(),x(!1)),S.session.stream(S.streamName).detach().catch(()=>{})})},[O,x]);Kt(()=>{if(!i||!d)return;let S=J.current;S&&(S.session!==d||S.streamName!==n)&&(S.disposeTimer&&clearTimeout(S.disposeTimer),X(S,!1),S=null),S?S.disposeTimer&&(clearTimeout(S.disposeTimer),S.disposeTimer=null):(S={session:d,streamName:n,promise:G.current().catch(()=>{}),refCount:0,disposeTimer:null},J.current=S),S.refCount+=1;let N=S;return()=>{N.refCount-=1,!(N.refCount>0)&&(N.disposeTimer=setTimeout(()=>{J.current===N&&(J.current=null),X(N,!0)},0))}},[i,d,n,X]);let T=pe(!1),q=_e(async()=>{if(!d||!E.current||T.current)return;let S=m.current?.getAudioTracks()[0]??null;if(S&&S.readyState==="live"){try{await d.stream(n).attach(S)}catch(N){mt("foreground mic re-assert failed (will retry on next pass)",N)}return}T.current=!0;try{let N=await $();await d.stream(n).attach(N)}catch(N){let D=N instanceof Error?N:new Error(String(N));mt("foreground mic re-acquire failed",D),M.current?.(D)}finally{T.current=!1}},[d,n,$]);return Kt(()=>{let S=()=>{q()};return d&&typeof d.onRecovery=="function"?d.onRecovery(S):Us(S)},[d,q]),Kt(()=>O,[O]),s?Is(pt,{ref:k,session:d,stream:n,onTrack:R,onUnlockChange:h,directOut:b}):null}),Os=ft;import{forwardRef as Vs,useImperativeHandle as Fs,useRef as an,useState as qs}from"react";import{useEffect as Ls,useState as Ds}from"react";var $t={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Ds($t);return Ls(()=>{if(!e){i($t);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 R=0;for(let p=0;p<l.length;p++){let b=(l[p]-128)/128;R+=b*b}let h=Math.sqrt(R/l.length);i(p=>{let b=h>n;return Math.abs(p.level-h)<.005&&p.speaking===b?p:{level:h,speaking:b}})},o);return()=>{clearInterval(v),u.disconnect(),i($t)}},[e,r,o,n]),s}import{Fragment as js,jsx as gt,jsxs as Ks}from"react/jsx-runtime";var Hs={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Ws={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Bs=Vs(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=Se(),R=o??v,h=an(null),[p,b]=qs(null),C=an(l);C.current=l;let{level:d,speaking:k}=Gt(a?p:null);return Fs(r,()=>({start:()=>{let m=h.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>h.current?.stop()??Promise.resolve(),get active(){return h.current?.active??!1},get micStream(){return h.current?.micStream??null}}),[]),Ks(js,{children:[gt(ft,{ref:h,session:R,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:m=>{b(m),C.current?.(m)}}),a?gt("span",{className:c,style:Hs,"data-urun-mic":"","data-urun-mic-active":p?"true":"false","data-urun-mic-speaking":k?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(d*100)/100,children:gt("span",{style:Ws,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(d*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as $s,sessionFailureFromMediaError as Gs,sharedCaptureController as Xs}from"@urun-sh/core";import{forwardRef as cn,useCallback as ve,useEffect as Xt,useImperativeHandle as zs,useRef as re,useState as ze}from"react";import{jsx as Ue,jsxs as un}from"react/jsx-runtime";var ln={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function zt(...e){console.debug("[camera]",...e)}function Js(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Ys(){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 dn=cn(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:R,onActiveChange:h,onError:p,onStream:b,onTrack:C,children:d,capture:k,flipControl:m="auto",flipControlClassName:w,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let E=i?"user":a?"environment":c??"environment",A=Se(),M=o??A,I=re(null),x=re(null),O=re(null),$=re([]),j=re(null),K=re(!1),G=re(!1),J=re(E),[X,T]=ze(E),[q,S]=ze(!1),[N,D]=ze(null),[V,U]=ze(!1),[Y]=ze(Js),Z=re(h);Z.current=h;let ee=re(p);ee.current=p;let fe=re(b);fe.current=b;let se=re(C);se.current=C;let Re=re(P);Re.current=P;let ne=ve(H=>{K.current!==H&&(K.current=H,S(H),Z.current?.(H))},[]);Xt(()=>{if(!q){D(null);return}let H=!1,W=()=>{Ys().then(ue=>{H||(D(ue),ue&&Re.current?.(ue))})};W();let ae=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ae?.addEventListener=="function"?(ae.addEventListener("devicechange",W),()=>{H=!0,ae.removeEventListener?.("devicechange",W)}):()=>{H=!0}},[q]);let te=ve(H=>{let W=I.current;W&&(W.muted=!0,W.defaultMuted=!0,W.setAttribute("muted",""),W.setAttribute("playsinline",""),W.setAttribute("webkit-playsinline",""),W.srcObject=H,H&&W.play()?.catch?.(ae=>zt("preview play() failed",ae)))},[]),Q=ve(()=>{G.current=!1,j.current?.(),j.current=null;for(let H of $.current)H();$.current=[],O.current?.release(),O.current=null,x.current&&(x.current=null,fe.current?.(null),se.current?.(null)),te(null)},[te]),y=ve((H,W)=>{j.current?.(),x.current=W,te(W),fe.current?.(W);let ae=()=>{x.current===W&&(zt("camera track ended (device removed or permission revoked)"),Q(),ne(!1))};H.addEventListener("ended",ae),j.current=()=>H.removeEventListener("ended",ae)},[te,Q,ne]),F=ve(async H=>{let W=n!==!1;if(W&&!M)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ae={...ln,...s,facingMode:H},ue;try{let le=O.current;if(le)ue=await le.update(ae);else{let Be=await(k??Xs()).claim("video",ae);if(O.current=Be,$.current=[Be.onTrack((je,xn)=>{y(je,xn),K.current&&(!W||!M||M.stream(n).attachVideo(je).then(()=>se.current?.(je)).catch(wn=>zt("camera re-publish after one-capture re-acquire failed",wn)))}),Be.onLost(je=>{O.current=null,$.current=[],Q(),ne(!1),ee.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ue=Be.track}}catch(le){let De=Gs(le,M?.status);throw ee.current?.(De),De}J.current=H,T(H),y(ue,O.current?.stream??new MediaStream([ue]));try{W&&M&&(M.connect?.(),await M.whenLive(l!==void 0?{timeout:l}:void 0),await M.stream(n).attachVideo(ue)),G.current=W?n:!1}catch(le){Q(),ne(!1);let De=le instanceof Error?le:new Error(String(le));throw ee.current?.(De),De}se.current?.(ue),ne(!0)},[M,n,s,l,k,y,Q,ne]),_=ve(H=>F(H?.facingMode??J.current),[F]),B=ve(async H=>{let W=G.current===n;K.current&&J.current===H&&W||await F(H)},[F,n]),z=ve(()=>F(J.current==="environment"?"user":"environment"),[F]),ie=ve(async()=>{Q(),ne(!1),n!==!1&&await M?.stream(n).detachVideo().catch(()=>{})},[M,n,Q,ne]),L=ve(async H=>{let W=I.current;if(!W)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await $s(W,H)},[]);zs(r,()=>({start:_,stop:ie,flip:z,setFacingMode:B,capturePhoto:L,get active(){return K.current},get facingMode(){return J.current},get stream(){return x.current},get element(){return I.current}}),[_,ie,z,B,L]);let ye=re(B);if(ye.current=B,Xt(()=>{u&&(n!==!1&&!M||ye.current(E).catch(()=>{}))},[u,M,E,n]),Xt(()=>Q,[Q]),!g)return null;let Le=f==="auto"?X==="user":f,be=q&&(m===!0||m==="auto"&&Y&&(N?.length??0)>1),ke=()=>{V||(U(!0),z().catch(()=>{}).finally(()=>U(!1)))};return un("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":X,children:[Ue("video",{ref:I,className:R,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Le?{transform:"scaleX(-1)"}:{}}}),be?Ue("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ke,disabled:V,className:w,style:w?{opacity:V?.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:V?.6:1},children:un("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:[Ue("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),Ue("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),Ue("path",{d:"M14.5 10.5v1.6h-1.6"}),Ue("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),Ue("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,d]})}),Zs=cn(function({preview:t=!0,...r},o){return Ue(dn,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Qs,normalizeReferenceImage as ei,referenceImageErrorMessage as ti}from"@urun-sh/core";import{useCallback as Je,useEffect as ri,useRef as Jt,useState as Ye}from"react";function ni(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(Qs),R=Jt(n);R.current=n;let h=Jt(null),p=Jt(0),b=Je(w=>{h.current&&URL.revokeObjectURL(h.current),h.current=w?URL.createObjectURL(new Blob([w.bytes],{type:w.type})):null,c(h.current),i(w),R.current?.(w)},[]);ri(()=>()=>{p.current++,h.current&&URL.revokeObjectURL(h.current),h.current=null},[]);let C=Je(async w=>{let P=++p.current;f(!0),g(null);try{let E=await w();if(p.current!==P)return;b(E)}catch(E){if(p.current!==P)return;g(ti(E))}finally{p.current===P&&f(!1)}},[b]),d=Je(w=>C(()=>ei(w,{maxSize:t,type:r,quality:o,source:"file"})),[C,t,r,o]),k=Je(w=>C(()=>w.capturePhoto({maxSize:t,type:r,quality:o})),[C,t,r,o]),m=Je(()=>{p.current++,g(null),f(!1),b(null)},[b]);return{reference:s,previewUrl:a,pick:d,capture:k,clear:m,busy:u,error:l,cameraAvailable:v}}import{useEffect as oi,useState as si}from"react";function ii(e,t){let[r,o]=si(null);return oi(()=>{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 pi}from"react";import{useEffect as li,useMemo as di}from"react";import{createStore as ai}from"zustand/vanilla";import{useStore as ui}from"zustand";var ci=()=>{};function Yt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=ai(()=>({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):ci,c=(u=>ui(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=di(()=>Yt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return li(()=>r.bind(),[r]),r}function mi(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=pi(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 fi,useState as gi}from"react";function Si(e){let[t,r]=gi(null);return fi(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}import{useEffect as hi,useState as vi}from"react";var Ne=200;function Ae(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 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 Qt(e,t,r={}){let o=r.cap??200,[n,s]=vi([]);return hi(()=>{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=>Ae(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 yi({session:e,name:t,cap:r,className:o}){let n=Qt(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 bi,useState as pn}from"react";import{jsx as Oe,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=pn(""),[i,a]=pn(null),c=bi(()=>{let u=Zt(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:[Oe("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:[Oe("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?Oe("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function ki({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:[Oe("code",{children:t}),Oe("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),Oe("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?Oe(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as Ti,useState as Ri}from"react";import{jsx as tt,jsxs as fn}from"react/jsx-runtime";function mn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ci({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=Ri([]);return Ti(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ae(c,{at:Date.now(),direction:"in",text:mn(Qe(a))},r))}):void 0),[e,t,r]),fn("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=>Ae(c,{at:Date.now(),direction:"out",text:mn(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)=>fn("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 Pi,useState as Ei}from"react";import{jsx as yt,jsxs as wi}from"react/jsx-runtime";function xi({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=Ei([]),a=t.join(","),c=r.join(",");return Pi(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>Ae(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)=>wi("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 Bi,isWakingPhase as ji}from"@urun-sh/core";import{useEffect as Ui,useState as Ai}from"react";function me(e){let[t,r]=Ai(e?.phase??null);return Ui(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as Ii}from"@urun-sh/core";import{useEffect as Mi,useRef as _i,useState as Ni}from"react";import{isWakingPhase as Oi}from"@urun-sh/core";function er(e){let t=me(e),r=Oi(t?.name),o=_i(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]=Ni(s);return Mi(()=>{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 Li,jsx as gn,jsxs as Sn}from"react/jsx-runtime";function tr({session:e,render:t,className:r}){let o=er(e);return!o.waking||!o.phase?null:gn("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Sn(Li,{children:[gn("span",{className:"urun-session-waking-label",children:Ii(o.phase)})," ",Sn("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Fi,useState as qi}from"react";import{useEffect as hn,useRef as Di,useState as vn}from"react";var Vi={event:null,elapsedMs:0};function rr(e,t){let[r,o]=vn(null),n=Di(0);hn(()=>{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]=vn(0);return hn(()=>{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}:Vi}import{jsx as yn,jsxs as bn}from"react/jsx-runtime";var Hi={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 Wi(e){let[t,r]=qi(!1);return Fi(()=>{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 nr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=rr(e,t),i=Wi(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return yn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):bn("div",{className:"urun-activation-overlay-card",children:[yn("span",{className:"urun-activation-overlay-copy",children:a.hint??Hi[c]})," ",bn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ie,jsxs as or}from"react/jsx-runtime";var Ki={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 $i({session:e,className:t}){let r=me(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 or("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ie("span",{className:"urun-session-status-dot","data-phase":o}),Ie("span",{className:"urun-session-status-label",children:Ki[o]}),n?Ie("span",{className:"urun-session-status-detail",children:n}):null]})}function Gi({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=me(e);if(s?.name==="live")return or("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ie(nr,{session:e})]});let i=r?r(s):Ie("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&ji(s.name)?Ie(tr,{session:e}):s&&s.name!=="idle"?Bi(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return or("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ie("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Xi,useState as zi}from"react";import{jsx as Zi}from"react/jsx-runtime";function kn(e){return me(e)?.endsAt??null}function Ji(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 Yi({session:e,urgentMs:t=6e4,className:r}){let n=kn(e)?.getTime()??null,[s,i]=zi(()=>n===null?null:Math.max(0,n-Date.now()));if(Xi(()=>{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=Ji(s);return Zi("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 Qi}from"@urun-sh/core";import{jsx as sr,jsxs as ra}from"react/jsx-runtime";var ea=new Set(["paused","error"]);function Tn({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=me(e);if(!s||!ea.has(s.name))return null;let i=o?o(s):sr("span",{className:"urun-session-paused-copy",children:Qi(s)});return ra("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?sr("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?sr("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var ta=Tn;import{useEffect as Rn,useMemo as na,useState as Cn}from"react";import{jsx as bt,jsxs as ia}from"react/jsx-runtime";function ir(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 Pn(e){let t=na(()=>e?e.doc("control"):null,[e]),[r,o]=Cn(()=>t?ir(t.get("idle")):null);return Rn(()=>{if(!t){o(null);return}return o(ir(t.get("idle"))),t.on("change",()=>o(ir(t.get("idle"))))},[t]),r}function oa(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function sa({session:e,onStillHere:t,className:r}){let o=Pn(e),n=o?.deadlineEpochS??null,[s,i]=Cn(null);if(Rn(()=>{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 bt("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:ia("div",{className:"urun-idle-warning-card",children:[bt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),bt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${oa(s)} due to inactivity.`:"This session will end soon due to inactivity."}),bt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useCallback as En,useEffect as aa,useRef as ua,useState as ar}from"react";function ca(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function ur(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=ar(null),[s,i]=ar(e!==null),[a,c]=ar(null),u=ua(e),f=En(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)}},[]);aa(()=>{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=En(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:ca(o),loading:s,error:a,refresh:l}}import{jsx as cr}from"react/jsx-runtime";function la({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=ur(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return cr("div",{className:i,children:t});let a=r?r(n):cr("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return cr("div",{className:i,children:a})}import{CreditsClient as zd,createCreditsClient as Jd,CreditsError as Yd,CreditsUnauthorizedError as Zd}from"@urun-sh/core";import{useContext as da,useEffect as pa,useState as ma}from"react";import{prewake as fa}from"@urun-sh/core";function ga(e){let t=da(Ce),[r,o]=ma(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 pa(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{fa({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(h=>{g||o(h)}).catch(()=>{})};v();let R=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(R)}},[n,s,i,a,c,u,f,l]),r}import{useEffect as Sa,useState as ha}from"react";function va(e){let[t,r]=ha(null);return Sa(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as ip,isWakingPhase as ap}from"@urun-sh/core";export{pt as Audio,dn as Camera,Bo as ComponentRenderer,zd as CreditsClient,Yd as CreditsError,Zd as CreditsUnauthorizedError,ln as DEFAULT_CAMERA_CONSTRAINTS,Ne as DEFAULT_LOG_CAP,tn as DEFAULT_SMOOTH_CHARS_PER_FRAME,rn as DEFAULT_SMOOTH_THRESHOLD,sn as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,hs as Image,rs as ImageFrame,ts as ImageFrameSchema,ss as MetricsPanel,os as MetricsPanelSchema,Bs as Mic,Dn as OPERATOR_CHORD_LABEL,Ln as OPERATOR_TOKEN_STORAGE_KEY,$o as ProgressCard,Ko as ProgressCardSchema,qo as ReprojectedVideo,xo as Session,zo as StatusBadge,Go as StatusBadgeSchema,fs as Text,Qo as TextStream,Xe as TextStreamError,Zo as TextStreamSchema,nr as UrunActivationOverlay,Ps as UrunAudio,kt as UrunAuthProvider,Zs as UrunCamera,Ci as UrunControlSender,la as UrunCreditsGate,ki as UrunDocPanel,Ke as UrunErrorBoundary,xi as UrunEventSpine,sa as UrunIdleWarning,Un as UrunJwtProvider,Xn as UrunProvider,Yi as UrunSessionClock,ta as UrunSessionEnded,Gi as UrunSessionGate,Tn as UrunSessionPaused,$i as UrunSessionStatus,tr as UrunSessionWaking,yi as UrunStreamTail,Os as UrunVoice,We as Video,ft as Voice,rt as authMode,Jd as createCreditsClient,Yt as createDocStore,ip as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,ap as isWakingPhase,Zt as parseJsonObject,Ae as pushCapped,fr as readOperatorToken,Wo as registerComponent,He as resumeUrunAudioContext,en as textDelta,ge as urunPublicEnv,rr as useActivation,ro as useApp,yo as useChat,go as useCompletion,Ct as useConfirmOnLeave,ur as useCredits,Ze as useDocStore,Si as useGenerationTick,Yr as useImageFrame,Co as useInputPresence,Zr as useMetricsPanel,Rt as useOperatorOverride,jr as useProgressCard,ni as useReferenceImage,lo as useRequest,wo as useSession,io as useSessionDirectory,mi as useSessionDoc,kn as useSessionEndsAt,Pn as useSessionIdle,me as useSessionPhase,va as useSessionStats,ii as useSessionTrack,er as useSessionWake,$r as useStatusBadge,Qt as useStreamMessages,on as useText,ms as useTextMeter,zr as useTextStream,Gt as useUrunAudioLevel,Tt as useUrunAuth,ga as useUrunPrewake,Nn as usesWorkOSAuth};
|
|
2
|
+
import{a as kt,b as Un,c as Tt}from"./chunk-WF2OBDSX.mjs";import{useCallback as gr,useEffect as Hn,useMemo as kr,useRef as Sr,useState as Pt}from"react";import{computeBackoffDelay as Wn}from"@urun-sh/core/internal";import{Component as An}from"react";import{jsx as lr,jsxs as Mn}from"react/jsx-runtime";var Ke=class extends An{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||Mn("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:[lr("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),lr("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as _n}from"react";var Ce=_n(null);function Te(e){return e&&e.trim()?e.trim():void 0}function ge(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Te(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Te(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Te(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=ge("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ge("VERCEL_ENV")==="production"?"workos":ge("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Nn(){return rt()==="workos"}import{useEffect as On,useRef as In}from"react";var Ln="urun.operator_token",pr=null,dr="op",Dn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function mr(){return typeof window<"u"}function fr(){return pr}function Vn(){if(!mr())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(dr);if(!r)return null;pr=r,t.delete(dr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Fn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Rt(e){let t=In(e);t.current=e,On(()=>{if(!mr())return;Vn();let r=o=>{if(!Fn(o))return;let n=fr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as qn}from"react";function Ct(e=!0){qn(()=>{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 Ve,jsxs as zn}from"react/jsx-runtime";var Bn="/api/urun-token",jn=1e4;function Kn(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}}var hr=3,$n=new Set([502,503,504]);function vr(e){return new Promise(t=>setTimeout(t,Wn(e)))}async function yr(e,t){for(let r=0;;r++){let o;try{o=await fetch(e,{method:"POST",signal:t})}catch(a){if(t?.aborted||r>=hr-1)throw a;await vr(r);continue}if(!o.ok){let a=new Error(`[urun] token endpoint ${e} answered ${o.status}`);if(!$n.has(o.status)||r>=hr-1)throw a;await vr(r);continue}let n=await o.json(),s=typeof n.token=="string"?n.token:"",i=typeof n.orgId=="string"?n.orgId:"";if(!s||!i)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:s,orgId:i,gatewayUrl:typeof n.gatewayUrl=="string"?n.gatewayUrl:void 0}}}function br(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 kr(()=>e,[t])}function Gn(e,t){return typeof e=="function"?e(t):e!==void 0?e:zn("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:[Ve("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ve("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Xn({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:R,confirmOnLeave:h=!1,fallback:p,errorFallback:b,children:C}){let d=n===void 0&&t===void 0;if(!d&&(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(!d&&(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 k=r??o;if(d&&(typeof k!="string"||k.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Ct(h);let[m,w]=Pt(),[P,E]=Pt(null),A=Sr(void 0),M=Sr(null),[I,x]=Pt(null);Rt(_=>x({jwt:_}));let O=Tt(),$=ge("NEXT_PUBLIC_SESSION_TOKEN")??ge("NEXT_PUBLIC_URUN_JWT"),j=rt(),K=I!==null,G=j==="workos"&&!n&&!K&&!d,J=n??(j==="jwt"?$:void 0)??m?.token,X=K?I.jwt:J,T=s??ge("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),q=G&&!X&&!O?.getAccessToken,S=t??m?.orgId,N=e??m?.gatewayUrl,D=d&&m===void 0,V=d&&m!==void 0&&!N?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,U=q?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,Y=P??V??U,Z=br("NEXT_PUBLIC_URUN_TOKEN_URL",ge("NEXT_PUBLIC_URUN_TOKEN_URL"))??c??Bn,ee=br("NEXT_PUBLIC_URUN_EVENTS_URL",ge("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,fe=gr(async _=>{if(!_?.forceRefresh){let z=A.current;if(!z)return z;let ie=Kn(z);if(ie===null||ie-Date.now()>jn)return z}return(await(M.current??(M.current=(async()=>{try{let z=await yr(Z);return A.current=z.token,w(z),z}finally{M.current=null}})()))).token},[Z]),se=gr(async()=>X,[X]),Re=typeof X=="string"&&X.trim().length>0,ne=G?O?.getAccessToken:d&&!K?fe:Re?se:void 0,te=Et(g),Q=Et(v),y=Et(R),F=kr(()=>({appId:k,baseUrl:N??"",orgId:S??"",jwt:X,getAccessToken:G?O?.getAccessToken:d&&!K?fe:void 0,authProvider:T,eventsUrl:ee,sessionKey:a,releaseOnLeave:u,allowWebTransport:f,allowWebRtcFallback:l,audioPlayout:te,videoPlayout:Q,sessionStats:y,priority:K?"preempt":void 0}),[k,O,N,T,X,ee,S,a,u,f,l,te,Q,y,G,K,d,fe]);return Hn(()=>{if(!d)return;let _=new AbortController;return E(null),(async()=>{try{let B=await yr(Z,_.signal);A.current=B.token,w(B)}catch(B){if(_.signal.aborted)return;E(B instanceof Error?B:new Error(String(B)))}})(),()=>_.abort()},[d,Z]),Ve(Ke,{fallback:p,children:Y?Gn(b,Y):D?Ve("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ve(Ce.Provider,{value:F,children:ne?Ve(kt,{getAccessToken:ne,children:C}):C})})}import{useContext as Jn,useEffect as Yn,useMemo as Tr,useReducer as Zn,useRef as xt}from"react";import{App as Qn}from"@urun-sh/core";function Rr(e){return e?.sessionId?{sessionId:e.sessionId}:e?.label?{label:e.label}:{}}function eo(e,t,r){let o=Rr(r),n=r?.activity??"auto";return`${e}:${JSON.stringify(t??{})}:${o.sessionId??""}:${o.label??""}:${n}`}function to(e,t,r,o){let n=Rr(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 Me=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}get directOut(){return this._stream.directOut}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 mediaTransportAttempted(){return this._session.mediaTransportAttempted??!0}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 ro(){let e=Jn(Ce);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Zn(i=>i+1,0),r=xt(new Map),o=xt(new Map),n=xt(null),s=Tr(()=>Qn(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 Yn(()=>{let i=n.current;if(i){n.current=null;for(let[a,c]of i){let u=Me.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=Me.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=Me.get(c);!l||l.refCount!==0||(Me.delete(c),l.handle.disconnect())},0)))}n.current=a}},[]),Tr(()=>{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=eo(c,l,g),R=r.current.get(v);if(R&&!R.disposed)return R;let h=to(e,c,l,g),p=Me.get(h);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),Me.delete(h),o.current.get(h)===p&&o.current.delete(h),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new At(s[c](l,g),t,e.eventsUrl),refCount:0,disposeTimer:null},Me.set(h,p)),o.current.get(h)!==p&&(o.current.set(h,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(v,p.handle),p.handle};return i.set(c,f),f}})},[e,s])}import{useContext as no,useMemo as oo}from"react";import{sessionDirectory as so}from"@urun-sh/core";function io(){let e=no(Ce);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 oo(()=>so(t,{baseUrl:r,orgId:o,jwt:n,getAccessToken:s,authProvider:i}),[t,r,o,n,s,i])}import{useCallback as Mt,useEffect as ao,useMemo as uo,useRef as nt,useState as _t}from"react";function Fe(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 co(e){return e instanceof Error?e:new Error(String(e))}function lo(e,t){let r=uo(()=>Fe(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);ao(()=>(g.current=!0,()=>{g.current=!1,l.current?.abort()}),[]);let v=Mt(async p=>{l.current?.abort();let b=new AbortController;l.current=b;let C=++f.current,d=()=>g.current&&f.current===C;d()&&(c(!0),i(null));try{let k=await r.request(p,{...u.current,signal:b.signal});return d()&&(n(k),c(!1),u.current?.onSuccess?.(k)),k}catch(k){let m=co(k);throw d()&&(i(m),c(!1),u.current?.onError?.(m)),m}},[r]),R=Mt(p=>{v(p).catch(()=>{})},[v]),h=Mt(()=>{f.current++,l.current?.abort(),l.current=null,n(void 0),i(null),c(!1)},[]);return{mutate:R,mutateAsync:v,data:o,error:s,isPending:a,reset:h}}import{useCallback as Cr,useEffect as po,useMemo as mo,useRef as ot,useState as Nt}from"react";function Pr(e){return e instanceof Error?e:new Error(String(e))}var fo=e=>typeof e=="string"?e:String(e);function go(e,t){let r=mo(()=>Fe(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);po(()=>(g.current=!0,()=>{g.current=!1,l.current?.cancel(),l.current=null}),[]);let v=Cr(()=>{f.current++,l.current?.cancel(),l.current=null,g.current&&i(!1)},[]),R=Cr(async h=>{l.current?.cancel();let p=++f.current,b=()=>g.current&&f.current===p,C=u.current,d=C?.parseChunk??fo,k=C?.buildPayload??(x=>({prompt:x}));b()&&(n(""),c(null),i(!0));let{parseChunk:m,buildPayload:w,onFinish:P,onError:E,...A}=C??{},M="",I;try{I=r.requestStream(k(h),A),l.current=I}catch(x){let O=Pr(x);b()&&(c(O),i(!1),C?.onError?.(O));return}try{for await(let x of I){if(f.current!==p)break;M+=d(x),b()&&n(M)}b()&&(i(!1),C?.onFinish?.(M))}catch(x){let O=Pr(x);b()&&(c(O),i(!1),C?.onError?.(O))}finally{l.current===I&&(l.current=null)}},[r]);return{completion:o,complete:R,stop:v,isStreaming:s,error:a}}import{useCallback as Er,useEffect as So,useMemo as ho,useRef as qe,useState as st}from"react";function xr(e){return e instanceof Error?e:new Error(String(e))}var vo=e=>typeof e=="string"?e:String(e),wr=0;function Ot(e){return wr+=1,`${e}-${wr}`}function yo(e,t){let r=ho(()=>Fe(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(d=>({id:d.id??Ot("msg"),role:d.role,content:d.content}))),[s,i]=st(""),[a,c]=st(!1),[u,f]=st(null),l=qe(t);l.current=t;let g=qe(o);g.current=o;let v=qe(s);v.current=s;let R=qe(0),h=qe(null),p=qe(!0);So(()=>(p.current=!0,()=>{p.current=!1,h.current?.cancel(),h.current=null}),[]);let b=Er(()=>{R.current++,h.current?.cancel(),h.current=null,p.current&&c(!1)},[]),C=Er(async d=>{let k=d===void 0,m=(k?v.current:d)??"";if(!m.trim())return;h.current?.cancel();let P=++R.current,E=()=>p.current&&R.current===P,A=l.current,M=A?.parseChunk??vo,I={id:Ot("msg"),role:"user",content:m},x={id:Ot("msg"),role:"assistant",content:""},O=[...g.current,I].map(V=>({role:V.role,content:V.content})),$=[...g.current,I,x];g.current=$,n($),k&&i(""),f(null),c(!0);let j=A?.buildPayload??(V=>({messages:V})),{initialMessages:K,parseChunk:G,buildPayload:J,onFinish:X,onError:T,...q}=A??{},S=V=>{n(U=>U.map(Y=>Y.id===x.id?{...Y,content:V}:Y))},N="",D;try{D=r.requestStream(j(O),q),h.current=D}catch(V){let U=xr(V);E()&&(f(U),c(!1),A?.onError?.(U));return}try{for await(let V of D){if(R.current!==P)break;N+=M(V),E()&&S(N)}E()&&(c(!1),A?.onFinish?.({...x,content:N}))}catch(V){let U=xr(V);E()&&(f(U),c(!1),A?.onError?.(U))}finally{h.current===D&&(h.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:C,stop:b,isStreaming:a,error:u}}import{useCallback as Pe,useEffect as Ur,useMemo as bo,useRef as Ar,useState as Mr}from"react";import{createInputPresencePublisher as ko,INPUT_PRESENCE_DEFAULT_HZ as To,INPUT_PRESENCE_FIELD as Ro}from"@urun-sh/core";var It=[];function Co(e,t={}){let{field:r=Ro,hz:o=To}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=bo(()=>s?ko({awareness:{setLocalStateField:(m,w)=>s.setField(m,w)},field:r,hz:o}):null,[s,r,o]),a=Ar(null);a.current=i;let[c,u]=Mr(!1),[f,l]=Mr(It),g=Ar(!1);Ur(()=>{if(i)return()=>i.dispose()},[i]);let v=Pe(()=>{let m=a.current;l(m?m.heldKeys():It)},[]),R=Pe(()=>{a.current?.clear(),l(It)},[]);Ur(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,w=()=>{if(m()){g.current=!1,u(!0);return}g.current||(u(!1),R())},P=x=>{m()&&(a.current?.keyDown(x.key),v())},E=x=>{a.current?.keyUp(x.key),v()},A=x=>{m()&&a.current?.movePointer(x.movementX,x.movementY)},M=x=>{m()&&a.current?.setButtons(x.buttons)},I=()=>{R()};return n.addEventListener("pointerlockchange",w),n.addEventListener("keydown",P),n.addEventListener("keyup",E),n.addEventListener("mousemove",A),n.addEventListener("mousedown",M),n.addEventListener("mouseup",M),n.defaultView?.addEventListener("blur",I),()=>{n.removeEventListener("pointerlockchange",w),n.removeEventListener("keydown",P),n.removeEventListener("keyup",E),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",M),n.removeEventListener("mouseup",M),n.defaultView?.removeEventListener("blur",I)}},[n,R,v]);let h=Pe(m=>{m.requestPointerLock?.()},[]),p=Pe(()=>{g.current=!0,u(!0)},[]),b=Pe(()=>{g.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),R()},[n,R]),C=Pe(m=>{a.current?.keyDown(m),v()},[v]),d=Pe(m=>{a.current?.keyUp(m),v()},[v]),k=Pe((m,w)=>{a.current?.movePointer(m,w)},[]);return{engage:h,engageTouch:p,release:b,engaged:c,heldKeys:f,pressKey:C,releaseKey:d,movePointer:k}}import{forwardRef as Io,useEffect as Fr,useImperativeHandle as Lo,useMemo as Do,useRef as ut}from"react";import{createCameraWarp as Vo}from"@urun-sh/core";import{forwardRef as Ao,useCallback as Ee,useEffect as $e,useImperativeHandle as Mo,useRef as oe,useState as Nr}from"react";import{derivedLegRole as _o}from"@urun-sh/core";var it=null;function Po(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=Po();return e?(it=new e,it):null}function He(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as Eo,useContext as _r}from"react";import{jsx as Uo}from"react/jsx-runtime";var Lt=Eo(null);function xo({session:e,children:t}){return Uo(Lt.Provider,{value:e,children:t})}function Se(){return _r(Lt)}function wo(){let e=_r(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 Vr,jsxs as Oo}from"react/jsx-runtime";function No(e,t){return e-t>>>0<2147483648}var Or=1e3;function Ir(...e){console.debug("[video]",...e)}function Lr(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 Dr(e,t,r){return r?[r,t]:[e,t]}var We=Ao(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:R,children:h,onTrack:p,onFirstFrame:b,frameMarker:C,onFrameMarkerReached:d,onFrameMarkerUnsupported:k,onUnlockChange:m}=t,w=Se(),P=o??w,E=oe(null),A=oe(null),[M,I]=Nr(!1),[x,O]=Nr(!1),$=oe(!1),j=oe(null),K=oe(p);K.current=p;let G=oe(m);G.current=m;let J=oe(b);J.current=b;let X=oe(d);X.current=d;let T=oe(k);T.current=k;let q=oe(C??null);q.current=C??null;let S=Ee(y=>{j.current!==y&&(j.current=y,G.current?.(y))},[]),N=oe(null),D=oe(null),V=Ee((y,F=!1)=>{if(!F&&y===N.current||(N.current=y,D.current?.(),D.current=null,$.current=!1,O(!1),!y))return;let _=E.current;if(!_)return;let B=q.current,z=B?.rtpTimestamp??null,ie=!1,L=()=>{ie||(ie=!0,T.current?.())};B&&z==null&&L();let ye=B!=null&&z!=null,Le=ke=>{D.current?.(),D.current=null,$.current=!0,O(!0),J.current?.(),ke&&X.current?.()};if(typeof _.requestVideoFrameCallback=="function"){let ke=!1,H=0,W=(ae,ue)=>{if(!ke){if(ye){let le=ue?.rtpTimestamp;if(typeof le!="number"){L(),Le(!1);return}if(!No(le,z)){H=_.requestVideoFrameCallback(W);return}Le(!0);return}Le(!1)}};H=_.requestVideoFrameCallback(W),D.current=()=>{ke=!0,_.cancelVideoFrameCallback?.(H)};return}ye&&L();let be=()=>{let ke=_.getVideoPlaybackQuality?.();(ke?ke.totalVideoFrames>0:_.readyState>=2&&_.videoWidth>0)&&Le(!1)};_.addEventListener("loadeddata",be),_.addEventListener("timeupdate",be),_.addEventListener("playing",be),D.current=()=>{_.removeEventListener("loadeddata",be),_.removeEventListener("timeupdate",be),_.removeEventListener("playing",be)},be()},[]);$e(()=>()=>{D.current?.(),D.current=null},[]);let U=C==null?null:`${C.rtpTimestamp??""}|${C.ptsMs??""}`,Y=oe(U);$e(()=>{if(Y.current===U||(Y.current=U,U==null))return;let y=N.current;y&&V(y,!0)},[U,V]);let Z=Ee(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let y=E.current;return y&&y.srcObject!==A.current&&A.current.getVideoTracks().length+A.current.getAudioTracks().length>0&&(y.srcObject=A.current),A.current},[]),ee=Ee(y=>{let F=E.current;if(!F)return;let _=F.play();!_||typeof _.then!="function"||_.then(()=>{F.muted||S(!0)}).catch(B=>{if((B instanceof Error?B.name:String(B))==="NotAllowedError"&&!F.muted){Ir(`play() blocked pending a user gesture (${y})`),S(!1);return}Ir(`play() failed (${y})`,B)})},[S]),fe=Ee(()=>{let y=E.current;y&&(Z(),!y.muted&&(ee("gesture"),He(),S(!0)))},[Z,ee,S]),se=Ee(y=>{let F=Z();if(F){for(let _ of F.getVideoTracks())_!==y&&F.removeTrack(_);if(y&&!F.getVideoTracks().includes(y)){F.addTrack(y);let _=E.current;_&&(_.srcObject=F)}y&&ee("track-attach"),I(y!==null),V(y),K.current?.(y)}},[Z,ee,V]),Re=Ee(y=>{let F=Z();if(F){for(let _ of F.getAudioTracks())_!==y&&F.removeTrack(_);if(y&&!F.getAudioTracks().includes(y)){F.addTrack(y);let _=E.current;_&&_.srcObject!==F&&(_.srcObject=F)}y&&ee("audio-attach")}},[Z,ee]),ne=Ee(y=>{E.current=y,y&&(a?(y.muted=!0,y.defaultMuted=!0,y.setAttribute("muted",""),j.current=null):(y.muted=!1,y.defaultMuted=!1,y.removeAttribute("muted")),y.setAttribute("playsinline",""),y.setAttribute("webkit-playsinline",""),Z())},[Z,a]);Mo(r,()=>({get element(){return E.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return $.current},unlock:fe,get unlocked(){return j.current===!0}}),[fe]);let te=_o(n)!==void 0;$e(()=>{te&&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.`)},[te,n]);let Q=i!==void 0;return $e(()=>{if(Q){se(i??null);return}if(te){se(null);return}if(!P)return;let y=Lr(P,Dr(n,"video")),F=()=>{let L=A.current;return L?L.getVideoTracks()[0]??null:null},_=L=>{if(L!==F()&&(se(L),L)){let ye=()=>{F()===L&&se(null)};L.addEventListener("ended",ye)}},B=y.track;B&&B.readyState==="live"&&_(B);let z=y.on("track",L=>{L&&L.readyState!=="live"||_(L)}),ie=setInterval(()=>{let L=y.track;L&&L.readyState==="live"&&_(L)},Or);return()=>{z(),clearInterval(ie)}},[P,n,te,Q,i,se]),$e(()=>{if(Q||!P||s===!1||te)return;let y=Lr(P,Dr(n,"audio",s)),F=()=>{let L=A.current;return L?L.getAudioTracks()[0]??null:null},_=L=>{if(L!==F()&&(Re(L),L)){let ye=()=>{F()===L&&Re(null)};L.addEventListener("ended",ye)}},B=y.track;B&&B.readyState==="live"&&_(B);let z=y.on("track",L=>{L&&L.readyState!=="live"||_(L)}),ie=setInterval(()=>{let L=y.track;L&&L.readyState==="live"&&_(L)},Or);return()=>{z(),clearInterval(ie)}},[P,n,te,s,Q,Re]),Oo("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":x?"true":"false",children:[Vr("video",{ref:ne,className:g,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...c?{transform:"scaleX(-1)"}:{}}}),M?null:v,R===void 0?null:Vr("div",{"data-urun-video-poster":"","aria-hidden":x||void 0,style:{position:"absolute",inset:0,...x?{opacity:0,pointerEvents:"none"}:null},children:R}),h]})});import{jsx as qr,jsxs as Ho}from"react/jsx-runtime";var Fo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},qo=Io(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),R=ut(0),h=ut(f);h.current=f;let p=Do(()=>Vo(h.current),[]);return Lo(r,()=>({get video(){return g.current},get canvas(){return v.current},warp:p,get lastDrawTs(){return R.current}}),[p]),Fr(()=>{if(!i)return;let b=0,C=0,d=null,k=w=>{typeof w.requestVideoFrameCallback=="function"&&(d=w,C=w.requestVideoFrameCallback(function P(){p.frameArrived(),C=w.requestVideoFrameCallback(P)}))},m=w=>{b=requestAnimationFrame(m);let P=v.current,E=g.current?.element??null;if(!P||!E||(E!==d&&(d&&C&&d.cancelVideoFrameCallback?.(C),k(E)),E.readyState<2))return;p.tick(w);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,M=Math.max(1,Math.round(P.clientWidth*A)),I=Math.max(1,Math.round(P.clientHeight*A));(P.width!==M||P.height!==I)&&(P.width=M,P.height=I);let x=P.getContext("2d");if(!x)return;let O=p.transform(),$=E.videoWidth||M,j=E.videoHeight||I,G=Math.max(M/$,I/j)*(1+a)*O.scale;x.setTransform(G,0,0,G,M/2+O.translateX*M,I/2+O.translateY*I),x.drawImage(E,-$/2,-j/2),R.current=w};return b=requestAnimationFrame(m),()=>{cancelAnimationFrame(b),d&&C&&d.cancelVideoFrameCallback?.(C)}},[i,a,p]),Fr(()=>{if(!i||!c||!l)return;let b=()=>!!l.pointerLockElement,C=P=>{b()&&p.keyDown(P.key)},d=P=>p.keyUp(P.key),k=P=>{b()&&p.pointerDelta(P.movementX,P.movementY)},m=()=>{b()||p.clearKeys()},w=()=>p.clearKeys();return l.addEventListener("keydown",C),l.addEventListener("keyup",d),l.addEventListener("mousemove",k),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",w),()=>{l.removeEventListener("keydown",C),l.removeEventListener("keyup",d),l.removeEventListener("mousemove",k),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",w)}},[i,c,l,p]),i?Ho(We,{ref:g,...s,videoClassName:s.videoClassName,style:{...s.style},children:[qr("canvas",{ref:v,style:Fo,"data-urun-warp":""}),n]}):qr(We,{ref:g,...s,children:n})});var Hr=new Map;function Wo(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Hr.set(e,{component:t,schema:r})}function Wr(e,t){let r=Hr.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 jo,jsx as ct}from"react/jsx-runtime";function Bo({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(jo,{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 Br}from"react/jsx-runtime";var Ko=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 jr(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 $o(e){let{step:t,total:r,label:o,variant:n,percentage:s}=jr(e);return Br("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}%`}})}),Br("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as Kr,jsxs as Jo}from"react/jsx-runtime";var Go=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),Xo={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function $r(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Xo[t]??t;return{state:t,message:n,isActive:o}}function zo(e){let{state:t,message:r,isActive:o}=$r(e);return Jo("span",{className:"urun-status-badge","data-state":t,children:[Kr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Kr("span",{className:"urun-status-message",children:r})]})}import{useRef as Gr,useEffect as Yo}from"react";import{z as Ft}from"zod";import{jsx as Xr,jsxs as es}from"react/jsx-runtime";var Zo=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function zr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Qo(e){let{text:t,streaming:r}=zr(e),o=Gr(null),n=Gr(0);return Yo(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),es("div",{className:"urun-text-stream",children:[Xr("span",{ref:o,className:"urun-text-content"}),r&&Xr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as Jr,jsxs as ns}from"react/jsx-runtime";var ts=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Yr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function rs(e){let{src:t,alt:r,caption:o}=Yr(e);return ns("figure",{className:"urun-image-frame",children:[Jr("img",{className:"urun-image",src:t,alt:r}),o&&Jr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as xe}from"zod";import{jsx as qt,jsxs as is}from"react/jsx-runtime";var os=xe.object({metrics:xe.array(xe.object({label:xe.string(),value:xe.union([xe.string(),xe.number()]),unit:xe.string().optional()}))});function Zr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function ss(e){let{metrics:t}=Zr(e);return qt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>is("div",{className:"urun-metric-card",children:[qt("div",{className:"urun-metric-label",children:r.label}),qt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as Ht,useRef as ce,useState as as}from"react";import{jsx as gs}from"react/jsx-runtime";function we(e){return e&&typeof e=="object"?e:null}function en(e){if(typeof e=="string")return e;let t=we(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function us(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 cs(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function ls(e){let t=we(e),r=t?.body;return cs(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 Xe=class extends Error{name="TextStreamError"},ds=4,tn=3,rn=240,Qr=typeof performance<"u"&&typeof performance.now=="function"?()=>performance.now():()=>Date.now();function nn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function ps(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function on(e){let{session:t,stream:r}=e,o=ce(e);Ht(()=>{o.current=e});let n=ce(null),s=ce(()=>{}),i=ce(null),a=ce(""),c=ce(""),u=ce(null),f=ce(!1),l=ce(!1),g=ce(!1),v=ce(null),R=ce(nn()),h=dt(d=>{if(n.current=d,!d){i.current=null;return}let k=i.current;if(k&&k.parentNode===d)return;let m=d.ownerDocument.createTextNode(c.current);d.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),p=dt(()=>{u.current=null;let d=i.current,k=a.current;if(k.length>0){let A=o.current,M=A.smoothCharsPerFrame??tn,I=A.smoothThreshold??rn,x=A.smooth&&k.length<=I?k.slice(0,M):k;a.current=k.slice(x.length),c.current+=x,d?.appendData(x)}let m=R.current,w=c.current.length,P=v.current===null?0:Math.max(0,Qr()-v.current),E=Math.round(w/ds);if(m.chars=w,m.tokens=E,m.elapsedMs=P,m.tokensPerSecond=P>0?E*1e3/P:0,a.current.length>0){b(),o.current.onMeter?.(m);return}if(!f.current&&!g.current){g.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(c.current);return}o.current.onMeter?.(m)},[]),b=dt(()=>{u.current===null&&(u.current=globalThis.requestAnimationFrame(()=>p()))},[p]);s.current=b,Ht(()=>{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,ps(R.current),i.current&&(i.current.data="");let d=!1,k=null;return(async()=>{try{for(k=t.stream(r).messages()[Symbol.asyncIterator]();;){let w=await k.next();if(d)return;if(w.done)break;let P=w.value,E=us(P);if(E==="error")throw new Xe(ls(P));if(E==="done")break;if(E==="ignore")continue;let A=en(P);A&&(v.current===null&&(v.current=Qr()),a.current+=A,b())}if(d)return;k.return?.(void 0),f.current=!1,b()}catch(m){if(d)return;k?.return?.(void 0),l.current=!0,f.current=!1,o.current.onError?.(m instanceof Error?m:new Xe(String(m))),b()}})(),()=>{d=!0,f.current=!1,k?.return?.(void 0),u.current!==null&&(globalThis.cancelAnimationFrame?.(u.current),u.current=null)}},[t,r,b]);let C=dt(()=>c.current,[]);return{ref:h,meterRef:R,getText:C}}function ms(e,t=250){let[r,o]=as(nn);return Ht(()=>{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 fs(e){let{className:t,style:r,...o}=e,{ref:n}=on(o);return gs("span",{ref:n,className:t,style:r})}import{forwardRef as Ss}from"react";import{jsx as vs}from"react/jsx-runtime";var hs=Ss(function(t,r){let{stream:o="image",...n}=t;return vs(We,{ref:r,stream:o,...n})});import{forwardRef as ys,useCallback as he,useEffect as Wt,useImperativeHandle as bs,useRef as de}from"react";import{observePageLifecycle as ks}from"@urun-sh/core";import{jsx as Es}from"react/jsx-runtime";var Ts=1e3;function Rs(e){return e!==null&&jt.has(e)}var jt=new WeakSet,Cs=1e3;function Bt(...e){console.debug("[audio]",...e)}var pt=ys(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:c,onUnlockChange:u,onAudioElement:f,directOut:l}=t,g=Se(),v=o??g,R=de(null),h=de(null),p=de(null),b=de(null),C=de(null),d=de(0),k=de(!1),m=de(c);m.current=c;let w=de(u);w.current=u;let P=de(l);P.current=l;let E=he(T=>{p.current!==T&&(p.current=T,w.current?.(T))},[]),A=he(()=>{if(typeof MediaStream>"u")return null;h.current||(h.current=new MediaStream);let T=R.current;return T&&T.srcObject!==h.current&&h.current.getAudioTracks().length>0&&(T.srcObject=h.current),h.current},[]),M=he(()=>{d.current=0,C.current!==null&&cancelAnimationFrame(C.current),C.current=null,b.current!==null&&clearTimeout(b.current),b.current=null},[]),I=he(T=>{C.current=null,b.current=null,A(),R.current&&(R.current.muted=k.current),$.current(`${T}:retry`)},[A]),x=he(T=>{if(!R.current||C.current!==null||b.current!==null)return;let S=h.current;if(!(!!S&&S.getAudioTracks().some(V=>V.readyState==="live"))){M();return}let D=d.current;if(d.current=D+1,D===0&&typeof requestAnimationFrame=="function"){C.current=requestAnimationFrame(()=>I(T));return}b.current=setTimeout(()=>I(T),Cs)},[M,I]),O=he(T=>{let q=R.current;if(!q)return;let S=q.play();!S||typeof S.then!="function"||S.then(()=>{q.muted=k.current,q.muted||E(!0),M()}).catch(N=>{let D=N instanceof Error?N.name:String(N);if(D==="AbortError"){Bt(`play() aborted (${T}); retrying on the ladder`),x(`${T}:abort`);return}if(D==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${T})`),E(!1),x(`${T}:blocked`);return}Bt(`play() failed (${T})`,N)})},[E]),$=de(()=>{});$.current=O;let j=he(T=>{let q=A();if(!q)return;for(let N of q.getAudioTracks())N!==T&&q.removeTrack(N);T&&!q.getAudioTracks().includes(T)&&q.addTrack(T),A();let S=P.current??Rs(T);k.current=!!T&&S,R.current&&(R.current.muted=k.current),T&&O("track-attach"),m.current?.(T)},[A,O]),K=he(()=>{let T=R.current;T&&(A(),T.muted=k.current,O("gesture"),He(),E(!0))},[A,O,E]);bs(r,()=>({unlock:K,get unlocked(){return p.current===!0},get element(){return R.current}}),[K]);let G=he(()=>{x("pause-event")},[x]),J=he(T=>{let q=R.current;q&&q!==T&&q.removeEventListener("pause",G),R.current=T,T&&(T.setAttribute("playsinline",""),T.setAttribute("webkit-playsinline",""),A(),T.addEventListener("pause",G)),f?.(T)},[A,f,G]),X=s!==void 0;return Wt(()=>{if(X){j(s??null);return}if(!v)return;let T=v.stream(n);if(T.directOut){let U=T.track;U&&jt.add(U)}let q=()=>{let U=h.current;return U?U.getAudioTracks()[0]??null:null},S=U=>{if(U!==q()&&(T.directOut&&U&&jt.add(U),j(U),U)){let Y=()=>{q()===U&&j(null)};U.addEventListener("ended",Y)}},N=T.track;N&&N.readyState==="live"&&S(N);let D=T.on("track",U=>{U&&U.readyState!=="live"||S(U)}),V=setInterval(()=>{let U=T.track;U&&U.readyState==="live"&&S(U)},Ts);return()=>{D(),clearInterval(V)}},[v,n,X,s,j]),Wt(()=>ks(()=>{He(),p.current===!0&&O("foreground")}),[O]),Wt(()=>()=>{b.current&&clearTimeout(b.current),C.current!==null&&cancelAnimationFrame(C.current),C.current=null},[]),Es("audio",{ref:J,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Ps=pt;import{forwardRef as xs,useCallback as _e,useEffect as Kt,useImperativeHandle as ws,useRef as pe}from"react";import{observePageLifecycle as Us,SessionFailedError as As,sessionFailureFromMediaError as Ms,sharedCaptureController as _s}from"@urun-sh/core";import{jsx as Is}from"react/jsx-runtime";var sn={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}function Ns(e){return e instanceof As&&e.kind==="create-failed"&&(e.status.error?.code==="client_release"||e.status.error?.httpStatus===410)}var ft=xs(function(t,r){let{session:o,stream:n="audio",playback:s=!0,autoStart:i=!s,constraints:a=sn,connectTimeoutMs:c,attempts:u=3,retryDelayMs:f=1500,onActiveChange:l,onError:g,onMicStream:v,onTrack:R,onUnlockChange:h,capture:p,directOut:b}=t,C=Se(),d=o??C,k=pe(null),m=pe(null),w=pe(null),P=pe([]),E=pe(!1),A=pe(l);A.current=l;let M=pe(g);M.current=g;let I=pe(v);I.current=v;let x=_e(S=>{E.current!==S&&(E.current=S,A.current?.(S))},[]),O=_e(()=>{for(let S of P.current)S();P.current=[],w.current?.release(),w.current=null,m.current&&(m.current=null,I.current?.(null))},[]),$=_e(async()=>{let S=w.current;if(S){let U=await S.update(a);return m.current=S.stream,I.current?.(S.stream),U}let D=await(p??_s()).claim("audio",a);w.current=D,P.current=[D.onTrack((U,Y)=>{m.current=Y,I.current?.(Y),E.current&&d?.stream(n).attach(U).catch(Z=>mt("mic re-attach after one-capture re-acquire failed",Z))}),D.onLost(U=>{w.current=null,P.current=[],m.current=null,I.current?.(null),x(!1),M.current?.(U)})],m.current=D.stream,I.current?.(D.stream);let V=D.track;if(!V)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return V},[p,a,d,n,x]),j=_e(async()=>{O(),x(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,O,x]),K=_e(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");k.current?.unlock();let S;try{S=await $()}catch(V){O();let U=Ms(V,d.status);throw M.current?.(U),U}let N;for(let V=1;V<=u;V++)try{await d.whenLive(c!==void 0?{timeout:c}:void 0),await d.stream(n).attach(S),x(!0);return}catch(U){if(N=U,mt(`start attempt ${V}/${u} failed`,U),Ns(U))break;d.connect?.(),V<u&&await new Promise(Y=>setTimeout(Y,f))}O(),x(!1);let D=N instanceof Error?N:new Error(String(N??"voice start failed"));throw M.current?.(D),D},[d,n,c,u,f,$,O,x]);ws(r,()=>({start:K,stop:j,unlock:()=>k.current?.unlock(),get active(){return E.current},get micStream(){return m.current},get audio(){return k.current}}),[K,j]);let G=pe(K);G.current=K;let J=pe(null),X=_e((S,N)=>{S.promise.then(()=>{N&&(O(),x(!1)),S.session.stream(S.streamName).detach().catch(()=>{})})},[O,x]);Kt(()=>{if(!i||!d)return;let S=J.current;S&&(S.session!==d||S.streamName!==n)&&(S.disposeTimer&&clearTimeout(S.disposeTimer),X(S,!1),S=null),S?S.disposeTimer&&(clearTimeout(S.disposeTimer),S.disposeTimer=null):(S={session:d,streamName:n,promise:G.current().catch(()=>{}),refCount:0,disposeTimer:null},J.current=S),S.refCount+=1;let N=S;return()=>{N.refCount-=1,!(N.refCount>0)&&(N.disposeTimer=setTimeout(()=>{J.current===N&&(J.current=null),X(N,!0)},0))}},[i,d,n,X]);let T=pe(!1),q=_e(async()=>{if(!d||!E.current||T.current)return;let S=m.current?.getAudioTracks()[0]??null;if(S&&S.readyState==="live"){try{await d.stream(n).attach(S)}catch(N){mt("foreground mic re-assert failed (will retry on next pass)",N)}return}T.current=!0;try{let N=await $();await d.stream(n).attach(N)}catch(N){let D=N instanceof Error?N:new Error(String(N));mt("foreground mic re-acquire failed",D),M.current?.(D)}finally{T.current=!1}},[d,n,$]);return Kt(()=>{let S=()=>{q()};return d&&typeof d.onRecovery=="function"?d.onRecovery(S):Us(S)},[d,q]),Kt(()=>O,[O]),s?Is(pt,{ref:k,session:d,stream:n,onTrack:R,onUnlockChange:h,directOut:b}):null}),Os=ft;import{forwardRef as Vs,useImperativeHandle as Fs,useRef as an,useState as qs}from"react";import{useEffect as Ls,useState as Ds}from"react";var $t={level:0,speaking:!1};function Gt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Ds($t);return Ls(()=>{if(!e){i($t);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 R=0;for(let p=0;p<l.length;p++){let b=(l[p]-128)/128;R+=b*b}let h=Math.sqrt(R/l.length);i(p=>{let b=h>n;return Math.abs(p.level-h)<.005&&p.speaking===b?p:{level:h,speaking:b}})},o);return()=>{clearInterval(v),u.disconnect(),i($t)}},[e,r,o,n]),s}import{Fragment as js,jsx as gt,jsxs as Ks}from"react/jsx-runtime";var Hs={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Ws={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Bs=Vs(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=Se(),R=o??v,h=an(null),[p,b]=qs(null),C=an(l);C.current=l;let{level:d,speaking:k}=Gt(a?p:null);return Fs(r,()=>({start:()=>{let m=h.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>h.current?.stop()??Promise.resolve(),get active(){return h.current?.active??!1},get micStream(){return h.current?.micStream??null}}),[]),Ks(js,{children:[gt(ft,{ref:h,session:R,stream:n,playback:!1,autoStart:i,...s!==void 0?{constraints:s}:{},...g!==void 0?{capture:g}:{},onActiveChange:u,onError:f,onMicStream:m=>{b(m),C.current?.(m)}}),a?gt("span",{className:c,style:Hs,"data-urun-mic":"","data-urun-mic-active":p?"true":"false","data-urun-mic-speaking":k?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(d*100)/100,children:gt("span",{style:Ws,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(d*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as $s,sessionFailureFromMediaError as Gs,sharedCaptureController as Xs}from"@urun-sh/core";import{forwardRef as cn,useCallback as ve,useEffect as Xt,useImperativeHandle as zs,useRef as re,useState as ze}from"react";import{jsx as Ue,jsxs as un}from"react/jsx-runtime";var ln={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function zt(...e){console.debug("[camera]",...e)}function Js(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Ys(){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 dn=cn(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:R,onActiveChange:h,onError:p,onStream:b,onTrack:C,children:d,capture:k,flipControl:m="auto",flipControlClassName:w,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let E=i?"user":a?"environment":c??"environment",A=Se(),M=o??A,I=re(null),x=re(null),O=re(null),$=re([]),j=re(null),K=re(!1),G=re(!1),J=re(E),[X,T]=ze(E),[q,S]=ze(!1),[N,D]=ze(null),[V,U]=ze(!1),[Y]=ze(Js),Z=re(h);Z.current=h;let ee=re(p);ee.current=p;let fe=re(b);fe.current=b;let se=re(C);se.current=C;let Re=re(P);Re.current=P;let ne=ve(H=>{K.current!==H&&(K.current=H,S(H),Z.current?.(H))},[]);Xt(()=>{if(!q){D(null);return}let H=!1,W=()=>{Ys().then(ue=>{H||(D(ue),ue&&Re.current?.(ue))})};W();let ae=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof ae?.addEventListener=="function"?(ae.addEventListener("devicechange",W),()=>{H=!0,ae.removeEventListener?.("devicechange",W)}):()=>{H=!0}},[q]);let te=ve(H=>{let W=I.current;W&&(W.muted=!0,W.defaultMuted=!0,W.setAttribute("muted",""),W.setAttribute("playsinline",""),W.setAttribute("webkit-playsinline",""),W.srcObject=H,H&&W.play()?.catch?.(ae=>zt("preview play() failed",ae)))},[]),Q=ve(()=>{G.current=!1,j.current?.(),j.current=null;for(let H of $.current)H();$.current=[],O.current?.release(),O.current=null,x.current&&(x.current=null,fe.current?.(null),se.current?.(null)),te(null)},[te]),y=ve((H,W)=>{j.current?.(),x.current=W,te(W),fe.current?.(W);let ae=()=>{x.current===W&&(zt("camera track ended (device removed or permission revoked)"),Q(),ne(!1))};H.addEventListener("ended",ae),j.current=()=>H.removeEventListener("ended",ae)},[te,Q,ne]),F=ve(async H=>{let W=n!==!1;if(W&&!M)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let ae={...ln,...s,facingMode:H},ue;try{let le=O.current;if(le)ue=await le.update(ae);else{let Be=await(k??Xs()).claim("video",ae);if(O.current=Be,$.current=[Be.onTrack((je,xn)=>{y(je,xn),K.current&&(!W||!M||M.stream(n).attachVideo(je).then(()=>se.current?.(je)).catch(wn=>zt("camera re-publish after one-capture re-acquire failed",wn)))}),Be.onLost(je=>{O.current=null,$.current=[],Q(),ne(!1),ee.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ue=Be.track}}catch(le){let De=Gs(le,M?.status);throw ee.current?.(De),De}J.current=H,T(H),y(ue,O.current?.stream??new MediaStream([ue]));try{W&&M&&(M.connect?.(),await M.whenLive(l!==void 0?{timeout:l}:void 0),await M.stream(n).attachVideo(ue)),G.current=W?n:!1}catch(le){Q(),ne(!1);let De=le instanceof Error?le:new Error(String(le));throw ee.current?.(De),De}se.current?.(ue),ne(!0)},[M,n,s,l,k,y,Q,ne]),_=ve(H=>F(H?.facingMode??J.current),[F]),B=ve(async H=>{let W=G.current===n;K.current&&J.current===H&&W||await F(H)},[F,n]),z=ve(()=>F(J.current==="environment"?"user":"environment"),[F]),ie=ve(async()=>{Q(),ne(!1),n!==!1&&await M?.stream(n).detachVideo().catch(()=>{})},[M,n,Q,ne]),L=ve(async H=>{let W=I.current;if(!W)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await $s(W,H)},[]);zs(r,()=>({start:_,stop:ie,flip:z,setFacingMode:B,capturePhoto:L,get active(){return K.current},get facingMode(){return J.current},get stream(){return x.current},get element(){return I.current}}),[_,ie,z,B,L]);let ye=re(B);if(ye.current=B,Xt(()=>{u&&(n!==!1&&!M||ye.current(E).catch(()=>{}))},[u,M,E,n]),Xt(()=>Q,[Q]),!g)return null;let Le=f==="auto"?X==="user":f,be=q&&(m===!0||m==="auto"&&Y&&(N?.length??0)>1),ke=()=>{V||(U(!0),z().catch(()=>{}).finally(()=>U(!1)))};return un("div",{className:v,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":X,children:[Ue("video",{ref:I,className:R,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Le?{transform:"scaleX(-1)"}:{}}}),be?Ue("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ke,disabled:V,className:w,style:w?{opacity:V?.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:V?.6:1},children:un("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:[Ue("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),Ue("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),Ue("path",{d:"M14.5 10.5v1.6h-1.6"}),Ue("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),Ue("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,d]})}),Zs=cn(function({preview:t=!0,...r},o){return Ue(dn,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Qs,normalizeReferenceImage as ei,referenceImageErrorMessage as ti}from"@urun-sh/core";import{useCallback as Je,useEffect as ri,useRef as Jt,useState as Ye}from"react";function ni(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(Qs),R=Jt(n);R.current=n;let h=Jt(null),p=Jt(0),b=Je(w=>{h.current&&URL.revokeObjectURL(h.current),h.current=w?URL.createObjectURL(new Blob([w.bytes],{type:w.type})):null,c(h.current),i(w),R.current?.(w)},[]);ri(()=>()=>{p.current++,h.current&&URL.revokeObjectURL(h.current),h.current=null},[]);let C=Je(async w=>{let P=++p.current;f(!0),g(null);try{let E=await w();if(p.current!==P)return;b(E)}catch(E){if(p.current!==P)return;g(ti(E))}finally{p.current===P&&f(!1)}},[b]),d=Je(w=>C(()=>ei(w,{maxSize:t,type:r,quality:o,source:"file"})),[C,t,r,o]),k=Je(w=>C(()=>w.capturePhoto({maxSize:t,type:r,quality:o})),[C,t,r,o]),m=Je(()=>{p.current++,g(null),f(!1),b(null)},[b]);return{reference:s,previewUrl:a,pick:d,capture:k,clear:m,busy:u,error:l,cameraAvailable:v}}import{useEffect as oi,useState as si}from"react";function ii(e,t){let[r,o]=si(null);return oi(()=>{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 pi}from"react";import{useEffect as li,useMemo as di}from"react";import{createStore as ai}from"zustand/vanilla";import{useStore as ui}from"zustand";var ci=()=>{};function Yt(e,t={}){let r=u=>{e?.set(u)},o=()=>e?e.get()??{}:{},n=ai(()=>({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):ci,c=(u=>ui(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=di(()=>Yt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return li(()=>r.bind(),[r]),r}function mi(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=pi(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 fi,useState as gi}from"react";function Si(e){let[t,r]=gi(null);return fi(()=>{if(r(null),!!e)return e.on("generationTick",r)},[e]),t}import{useEffect as hi,useState as vi}from"react";var Ne=200;function Ae(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 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 Qt(e,t,r={}){let o=r.cap??200,[n,s]=vi([]);return hi(()=>{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=>Ae(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 yi({session:e,name:t,cap:r,className:o}){let n=Qt(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 bi,useState as pn}from"react";import{jsx as Oe,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=pn(""),[i,a]=pn(null),c=bi(()=>{let u=Zt(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:[Oe("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:[Oe("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:t}),i?Oe("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function ki({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:[Oe("code",{children:t}),Oe("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),Oe("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?Oe(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:u=>c(u)}):null]})}import{useEffect as Ti,useState as Ri}from"react";import{jsx as tt,jsxs as fn}from"react/jsx-runtime";function mn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ci({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=Ri([]);return Ti(()=>(s([]),e?e.doc(t).on("change",a=>{s(c=>Ae(c,{at:Date.now(),direction:"in",text:mn(Qe(a))},r))}):void 0),[e,t,r]),fn("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=>Ae(c,{at:Date.now(),direction:"out",text:mn(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)=>fn("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 Pi,useState as Ei}from"react";import{jsx as yt,jsxs as wi}from"react/jsx-runtime";function xi({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=Ei([]),a=t.join(","),c=r.join(",");return Pi(()=>{if(i([]),!e)return;let u=(l,g)=>i(v=>Ae(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)=>wi("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 Bi,isWakingPhase as ji}from"@urun-sh/core";import{useEffect as Ui,useState as Ai}from"react";function me(e){let[t,r]=Ai(e?.phase??null);return Ui(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as Ii}from"@urun-sh/core";import{useEffect as Mi,useRef as _i,useState as Ni}from"react";import{isWakingPhase as Oi}from"@urun-sh/core";function er(e){let t=me(e),r=Oi(t?.name),o=_i(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]=Ni(s);return Mi(()=>{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 Li,jsx as gn,jsxs as Sn}from"react/jsx-runtime";function tr({session:e,render:t,className:r}){let o=er(e);return!o.waking||!o.phase?null:gn("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Sn(Li,{children:[gn("span",{className:"urun-session-waking-label",children:Ii(o.phase)})," ",Sn("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Fi,useState as qi}from"react";import{useEffect as hn,useRef as Di,useState as vn}from"react";var Vi={event:null,elapsedMs:0};function rr(e,t){let[r,o]=vn(null),n=Di(0);hn(()=>{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]=vn(0);return hn(()=>{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}:Vi}import{jsx as yn,jsxs as bn}from"react/jsx-runtime";var Hi={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 Wi(e){let[t,r]=qi(!1);return Fi(()=>{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 nr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=rr(e,t),i=Wi(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let c=a.state;return yn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):bn("div",{className:"urun-activation-overlay-card",children:[yn("span",{className:"urun-activation-overlay-copy",children:a.hint??Hi[c]})," ",bn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ie,jsxs as or}from"react/jsx-runtime";var Ki={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",waiting_for_capacity:"waiting for GPU capacity",connecting:"connecting",live:"live",degraded:"degraded",paused:"paused",error:"error",unknown:"unrecognized state"};function $i({session:e,className:t}){let r=me(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 or("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ie("span",{className:"urun-session-status-dot","data-phase":o}),Ie("span",{className:"urun-session-status-label",children:Ki[o]}),n?Ie("span",{className:"urun-session-status-detail",children:n}):null]})}function Gi({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=me(e);if(s?.name==="live")return or("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ie(nr,{session:e})]});let i=r?r(s):Ie("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s&&ji(s.name)?Ie(tr,{session:e}):s&&s.name!=="idle"?Bi(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="paused");return or("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ie("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Xi,useState as zi}from"react";import{jsx as Zi}from"react/jsx-runtime";function kn(e){return me(e)?.endsAt??null}function Ji(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 Yi({session:e,urgentMs:t=6e4,className:r}){let n=kn(e)?.getTime()??null,[s,i]=zi(()=>n===null?null:Math.max(0,n-Date.now()));if(Xi(()=>{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=Ji(s);return Zi("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 Qi}from"@urun-sh/core";import{jsx as sr,jsxs as ra}from"react/jsx-runtime";var ea=new Set(["paused","error"]);function Tn({session:e,onResume:t,onNewSession:r,children:o,className:n}){let s=me(e);if(!s||!ea.has(s.name))return null;let i=o?o(s):sr("span",{className:"urun-session-paused-copy",children:Qi(s)});return ra("div",{className:["urun-session-paused",n].filter(Boolean).join(" "),"data-phase":s.name,children:[i,t?sr("button",{type:"button",className:"urun-session-paused-resume",onClick:t,children:"Resume"}):null,r?sr("button",{type:"button",className:"urun-session-paused-new",onClick:r,children:"New session"}):null]})}var ta=Tn;import{useEffect as Rn,useMemo as na,useState as Cn}from"react";import{jsx as bt,jsxs as ia}from"react/jsx-runtime";function ir(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 Pn(e){let t=na(()=>e?e.doc("control"):null,[e]),[r,o]=Cn(()=>t?ir(t.get("idle")):null);return Rn(()=>{if(!t){o(null);return}return o(ir(t.get("idle"))),t.on("change",()=>o(ir(t.get("idle"))))},[t]),r}function oa(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function sa({session:e,onStillHere:t,className:r}){let o=Pn(e),n=o?.deadlineEpochS??null,[s,i]=Cn(null);if(Rn(()=>{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 bt("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:ia("div",{className:"urun-idle-warning-card",children:[bt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),bt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${oa(s)} due to inactivity.`:"This session will end soon due to inactivity."}),bt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useCallback as En,useEffect as aa,useRef as ua,useState as ar}from"react";function ca(e){return e?e.activated&&!e.exempt&&e.available_credits<=0:!1}function ur(e,t={}){let{refreshIntervalMs:r}=t,[o,n]=ar(null),[s,i]=ar(e!==null),[a,c]=ar(null),u=ua(e),f=En(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)}},[]);aa(()=>{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=En(async()=>{let g=u.current;g&&await f(g)},[f]);return{balance:o,isExhausted:ca(o),loading:s,error:a,refresh:l}}import{jsx as cr}from"react/jsx-runtime";function la({client:e,children:t,fallback:r,className:o}){let{balance:n,isExhausted:s}=ur(e),i=["urun-credits-gate",o].filter(Boolean).join(" ");if(!s)return cr("div",{className:i,children:t});let a=r?r(n):cr("span",{className:"urun-credits-gate-fallback",children:"Out of credits \u2014 add credits to keep running sessions."});return cr("div",{className:i,children:a})}import{CreditsClient as zd,createCreditsClient as Jd,CreditsError as Yd,CreditsUnauthorizedError as Zd}from"@urun-sh/core";import{useContext as da,useEffect as pa,useState as ma}from"react";import{prewake as fa}from"@urun-sh/core";function ga(e){let t=da(Ce),[r,o]=ma(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 pa(()=>{if(!a||!c||!n||!s)return;let g=!1,v=()=>{fa({baseUrl:a,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:f,authProvider:l}).then(h=>{g||o(h)}).catch(()=>{})};v();let R=setInterval(v,Math.max(1,i)*1e3);return()=>{g=!0,clearInterval(R)}},[n,s,i,a,c,u,f,l]),r}import{useEffect as Sa,useState as ha}from"react";function va(e){let[t,r]=ha(null);return Sa(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as ip,isWakingPhase as ap}from"@urun-sh/core";export{pt as Audio,dn as Camera,Bo as ComponentRenderer,zd as CreditsClient,Yd as CreditsError,Zd as CreditsUnauthorizedError,ln as DEFAULT_CAMERA_CONSTRAINTS,Ne as DEFAULT_LOG_CAP,tn as DEFAULT_SMOOTH_CHARS_PER_FRAME,rn as DEFAULT_SMOOTH_THRESHOLD,sn as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,hs as Image,rs as ImageFrame,ts as ImageFrameSchema,ss as MetricsPanel,os as MetricsPanelSchema,Bs as Mic,Dn as OPERATOR_CHORD_LABEL,Ln as OPERATOR_TOKEN_STORAGE_KEY,$o as ProgressCard,Ko as ProgressCardSchema,qo as ReprojectedVideo,xo as Session,zo as StatusBadge,Go as StatusBadgeSchema,fs as Text,Qo as TextStream,Xe as TextStreamError,Zo as TextStreamSchema,nr as UrunActivationOverlay,Ps as UrunAudio,kt as UrunAuthProvider,Zs as UrunCamera,Ci as UrunControlSender,la as UrunCreditsGate,ki as UrunDocPanel,Ke as UrunErrorBoundary,xi as UrunEventSpine,sa as UrunIdleWarning,Un as UrunJwtProvider,Xn as UrunProvider,Yi as UrunSessionClock,ta as UrunSessionEnded,Gi as UrunSessionGate,Tn as UrunSessionPaused,$i as UrunSessionStatus,tr as UrunSessionWaking,yi as UrunStreamTail,Os as UrunVoice,We as Video,ft as Voice,rt as authMode,Jd as createCreditsClient,Yt as createDocStore,ip as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,ap as isWakingPhase,Zt as parseJsonObject,Ae as pushCapped,fr as readOperatorToken,Wo as registerComponent,He as resumeUrunAudioContext,en as textDelta,ge as urunPublicEnv,rr as useActivation,ro as useApp,yo as useChat,go as useCompletion,Ct as useConfirmOnLeave,ur as useCredits,Ze as useDocStore,Si as useGenerationTick,Yr as useImageFrame,Co as useInputPresence,Zr as useMetricsPanel,Rt as useOperatorOverride,jr as useProgressCard,ni as useReferenceImage,lo as useRequest,wo as useSession,io as useSessionDirectory,mi as useSessionDoc,kn as useSessionEndsAt,Pn as useSessionIdle,me as useSessionPhase,va as useSessionStats,ii as useSessionTrack,er as useSessionWake,$r as useStatusBadge,Qt as useStreamMessages,on as useText,ms as useTextMeter,zr as useTextStream,Gt as useUrunAudioLevel,Tt as useUrunAuth,ga as useUrunPrewake,Nn as usesWorkOSAuth};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/react",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.36",
|
|
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.
|
|
56
|
+
"@urun-sh/core": "^0.6.36",
|
|
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",
|