@urun-sh/react 0.2.34 → 0.2.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/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -455,6 +455,8 @@ interface VideoHandle {
|
|
|
455
455
|
readonly element: HTMLVideoElement | null;
|
|
456
456
|
|
|
457
457
|
readonly live: boolean;
|
|
458
|
+
|
|
459
|
+
readonly framed: boolean;
|
|
458
460
|
}
|
|
459
461
|
|
|
460
462
|
interface VideoProps {
|
|
@@ -479,9 +481,13 @@ interface VideoProps {
|
|
|
479
481
|
|
|
480
482
|
placeholder?: ReactNode;
|
|
481
483
|
|
|
484
|
+
poster?: ReactNode;
|
|
485
|
+
|
|
482
486
|
children?: ReactNode;
|
|
483
487
|
|
|
484
488
|
onTrack?: (track: MediaStreamTrack | null) => void;
|
|
489
|
+
|
|
490
|
+
onFirstFrame?: () => void;
|
|
485
491
|
}
|
|
486
492
|
|
|
487
493
|
declare const Video: react.ForwardRefExoticComponent<VideoProps & react.RefAttributes<VideoHandle>>;
|
package/dist/index.d.ts
CHANGED
|
@@ -455,6 +455,8 @@ interface VideoHandle {
|
|
|
455
455
|
readonly element: HTMLVideoElement | null;
|
|
456
456
|
|
|
457
457
|
readonly live: boolean;
|
|
458
|
+
|
|
459
|
+
readonly framed: boolean;
|
|
458
460
|
}
|
|
459
461
|
|
|
460
462
|
interface VideoProps {
|
|
@@ -479,9 +481,13 @@ interface VideoProps {
|
|
|
479
481
|
|
|
480
482
|
placeholder?: ReactNode;
|
|
481
483
|
|
|
484
|
+
poster?: ReactNode;
|
|
485
|
+
|
|
482
486
|
children?: ReactNode;
|
|
483
487
|
|
|
484
488
|
onTrack?: (track: MediaStreamTrack | null) => void;
|
|
489
|
+
|
|
490
|
+
onFirstFrame?: () => void;
|
|
485
491
|
}
|
|
486
492
|
|
|
487
493
|
declare const Video: react.ForwardRefExoticComponent<VideoProps & react.RefAttributes<VideoHandle>>;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
"use strict";var Kt=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var Wn=Object.prototype.hasOwnProperty;var Bn=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},$n=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Hn(t))!Wn.call(e,n)&&n!==r&&Kt(e,n,{get:()=>t[n],enumerable:!(o=Fn(t,n))||o.enumerable});return e};var Kn=e=>$n(Kt({},"__esModule",{value:!0}),e);var yo={};Bn(yo,{Audio:()=>st,Camera:()=>lr,ComponentRenderer:()=>Br,DEFAULT_CAMERA_CONSTRAINTS:()=>cr,DEFAULT_LOG_CAP:()=>be,DEFAULT_VOICE_CONSTRAINTS:()=>ir,DocPatchForm:()=>ut,Image:()=>on,ImageFrame:()=>Yr,ImageFrameSchema:()=>Gr,MetricsPanel:()=>Qr,MetricsPanelSchema:()=>Zr,Mic:()=>mn,OPERATOR_CHORD_LABEL:()=>wr,OPERATOR_TOKEN_STORAGE_KEY:()=>xr,ProgressCard:()=>Kr,ProgressCardSchema:()=>$r,Session:()=>en,StatusBadge:()=>Jr,StatusBadgeSchema:()=>jr,TextStream:()=>Xr,TextStreamSchema:()=>zr,UrunActivationOverlay:()=>qt,UrunAudio:()=>cn,UrunAuthProvider:()=>jt,UrunCamera:()=>fn,UrunControlSender:()=>Cn,UrunDocPanel:()=>bn,UrunErrorBoundary:()=>Ie,UrunEventSpine:()=>xn,UrunIdleWarning:()=>_n,UrunJwtProvider:()=>br,UrunProvider:()=>Ur,UrunSessionClock:()=>An,UrunSessionEnded:()=>Mn,UrunSessionGate:()=>Rn,UrunSessionStatus:()=>En,UrunSessionWaking:()=>Ot,UrunStreamTail:()=>kn,UrunVoice:()=>dn,Video:()=>yt,Voice:()=>it,authMode:()=>Ge,createDocStore:()=>Et,describeSessionPhase:()=>Wt.describeSessionPhase,formatPayload:()=>Be,getUrunAudioContext:()=>nt,isWakingPhase:()=>Wt.isWakingPhase,parseJsonObject:()=>At,pushCapped:()=>he,readOperatorToken:()=>Jt,registerComponent:()=>Hr,resumeUrunAudioContext:()=>ot,urunPublicEnv:()=>fe,useActivation:()=>Dt,useApp:()=>_r,useChat:()=>Vr,useCompletion:()=>Lr,useConfirmOnLeave:()=>St,useDocStore:()=>We,useImageFrame:()=>rr,useInputPresence:()=>qr,useMetricsPanel:()=>nr,useOperatorOverride:()=>gt,useProgressCard:()=>Qt,useRequest:()=>Nr,useSession:()=>tn,useSessionDoc:()=>yn,useSessionEndsAt:()=>dr,useSessionIdle:()=>mr,useSessionPhase:()=>oe,useSessionTrack:()=>gn,useSessionWake:()=>Lt,useStatusBadge:()=>er,useStreamMessages:()=>Mt,useTextStream:()=>tr,useUrunAudioLevel:()=>xt,useUrunAuth:()=>mt,useUrunPrewake:()=>In,usesWorkOSAuth:()=>yr});module.exports=Kn(yo);var Y=require("react");var hr=require("react"),Xe=require("react/jsx-runtime"),Ie=class extends hr.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,Xe.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,Xe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,Xe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var vr=require("react"),Le=(0,vr.createContext)(null);function Te(e){return e&&e.trim()?e.trim():void 0}function fe(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"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 Ge(){let e=fe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||fe("VERCEL_ENV")==="production"?"workos":fe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function yr(){return Ge()==="workos"}var Oe=require("react"),Pr=require("react/jsx-runtime"),kr=(0,Oe.createContext)(null);function jt({getAccessToken:e,children:t}){let r=(0,Oe.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Pr.jsx)(kr.Provider,{value:r,children:t})}var br=jt;function mt(){return(0,Oe.useContext)(kr)}var ft=require("react"),xr="urun.operator_token",Tr=null,Cr="op",wr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Er(){return typeof window<"u"}function Jt(){return Tr}function jn(){if(!Er())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(Cr);if(!r)return null;Tr=r,t.delete(Cr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Jn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function gt(e){let t=(0,ft.useRef)(e);t.current=e,(0,ft.useEffect)(()=>{if(!Er())return;jn();let r=o=>{if(!Jn(o))return;let n=Jt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Rr=require("react");function St(e=!0){(0,Rr.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 ke=require("react/jsx-runtime"),zn="/api/urun-token";async function Ar(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function Xn(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,ke.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,ke.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,ke.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Ur({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:g=!1,fallback:d,errorFallback:k,children:P}){let S=n===void 0&&t===void 0;if(!S&&(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(!S&&(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 p=r??o;if(S&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);St(g);let[C,h]=(0,Y.useState)(),[x,T]=(0,Y.useState)(),[E,v]=(0,Y.useState)(null),A=(0,Y.useRef)(void 0),L=(0,Y.useRef)(null),[U,M]=(0,Y.useState)(null);gt($=>M({jwt:$}));let l=mt(),m=fe("NEXT_PUBLIC_SESSION_TOKEN")??fe("NEXT_PUBLIC_URUN_JWT"),f=Ge(),b=U!==null,_=f==="workos"&&!n&&!b&&!S,z=n??(f==="jwt"?m:void 0)??C??x?.token,R=b?U.jwt:z,y=s??fe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),D=_&&!R,H=t??x?.orgId,W=e??x?.gatewayUrl,K=S&&x===void 0,le=S&&x!==void 0&&!W?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,ie=E??le,Z=u??zn,B=(0,Y.useCallback)(async $=>$?.forceRefresh?(await(L.current??(L.current=(async()=>{try{let de=await Ar(Z);return A.current=de.token,T(de),de}finally{L.current=null}})()))).token:A.current,[Z]),ae=(0,Y.useMemo)(()=>({appId:p,baseUrl:W??"",orgId:H??"",jwt:R,getAccessToken:_?l?.getAccessToken:S&&!b?B:void 0,authProvider:y,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:b?"preempt":void 0}),[p,l,W,y,R,i,H,a,c,_,b,S,B]);return(0,Y.useEffect)(()=>{if(!S)return;let $=new AbortController;return v(null),(async()=>{try{let Q=await Ar(Z,$.signal);A.current=Q.token,T(Q)}catch(Q){if($.signal.aborted)return;v(Q instanceof Error?Q:new Error(String(Q)))}})(),()=>$.abort()},[S,Z]),(0,Y.useEffect)(()=>{if(!_||!l)return;let $=!1,Q=l;async function de(){try{let lt=await Q.getAccessToken();$||h(lt??void 0)}catch{$||h(void 0)}}de();let Me=window.setInterval(()=>{de()},6e4);return()=>{$=!0,window.clearInterval(Me)}},[l,_]),(0,ke.jsx)(Ie,{fallback:d,children:ie?Xn(k,ie):D||K?(0,ke.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,ke.jsx)(Le.Provider,{value:ae,children:P})})}var ee=require("react"),Mr=require("@urun-sh/core");function Gn(e,t){return`${e}:${JSON.stringify(t??{})}`}function Yn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var we=new Map;var zt=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()})}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()}},Xt=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},Gt=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"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}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()}doc(t){let r=this._docs.get(t);return r||(r=new zt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Xt(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_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 _r(){let e=(0,ee.useContext)(Le);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,ee.useReducer)(i=>i+1,0),r=(0,ee.useRef)(new Map),o=(0,ee.useRef)(new Map),n=(0,ee.useRef)(null),s=(0,ee.useMemo)(()=>(0,Mr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return(0,ee.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=we.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=we.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let d=we.get(u);!d||d.refCount!==0||(we.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),(0,ee.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=d=>{let k=Gn(u,d),P=r.current.get(k);if(P&&!P.disposed)return P;let S=Yn(e,u,d),p=we.get(S);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),we.delete(S),o.current.get(S)===p&&o.current.delete(S),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new Gt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},we.set(S,p)),o.current.get(S)!==p&&(o.current.set(S,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(k,p.handle),p.handle};return i.set(u,g),g}})},[e,s])}var j=require("react");function De(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Zn(e){return e instanceof Error?e:new Error(String(e))}function Nr(e,t){let r=(0,j.useMemo)(()=>De(e),[e]),[o,n]=(0,j.useState)(void 0),[s,i]=(0,j.useState)(null),[a,u]=(0,j.useState)(!1),c=(0,j.useRef)(t);c.current=t;let g=(0,j.useRef)(0),d=(0,j.useRef)(null),k=(0,j.useRef)(!0);(0,j.useEffect)(()=>(k.current=!0,()=>{k.current=!1,d.current?.abort()}),[]);let P=(0,j.useCallback)(async C=>{d.current?.abort();let h=new AbortController;d.current=h;let x=++g.current,T=()=>k.current&&g.current===x;T()&&(u(!0),i(null));try{let E=await r.request(C,{...c.current,signal:h.signal});return T()&&(n(E),u(!1),c.current?.onSuccess?.(E)),E}catch(E){let v=Zn(E);throw T()&&(i(v),u(!1),c.current?.onError?.(v)),v}},[r]),S=(0,j.useCallback)(C=>{P(C).catch(()=>{})},[P]),p=(0,j.useCallback)(()=>{g.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:S,mutateAsync:P,data:o,error:s,isPending:a,reset:p}}var X=require("react");function Ir(e){return e instanceof Error?e:new Error(String(e))}var Qn=e=>typeof e=="string"?e:String(e);function Lr(e,t){let r=(0,X.useMemo)(()=>De(e),[e]),[o,n]=(0,X.useState)(""),[s,i]=(0,X.useState)(!1),[a,u]=(0,X.useState)(null),c=(0,X.useRef)(t);c.current=t;let g=(0,X.useRef)(0),d=(0,X.useRef)(null),k=(0,X.useRef)(!0);(0,X.useEffect)(()=>(k.current=!0,()=>{k.current=!1,d.current?.cancel(),d.current=null}),[]);let P=(0,X.useCallback)(()=>{g.current++,d.current?.cancel(),d.current=null,k.current&&i(!1)},[]),S=(0,X.useCallback)(async p=>{d.current?.cancel();let C=++g.current,h=()=>k.current&&g.current===C,x=c.current,T=x?.parseChunk??Qn,E=x?.buildPayload??(f=>({prompt:f}));h()&&(n(""),u(null),i(!0));let{parseChunk:v,buildPayload:A,onFinish:L,onError:U,...M}=x??{},l="",m;try{m=r.requestStream(E(p),M),d.current=m}catch(f){let b=Ir(f);h()&&(u(b),i(!1),x?.onError?.(b));return}try{for await(let f of m){if(g.current!==C)break;l+=T(f),h()&&n(l)}h()&&(i(!1),x?.onFinish?.(l))}catch(f){let b=Ir(f);h()&&(u(b),i(!1),x?.onError?.(b))}finally{d.current===m&&(d.current=null)}},[r]);return{completion:o,complete:S,stop:P,isStreaming:s,error:a}}var F=require("react");function Or(e){return e instanceof Error?e:new Error(String(e))}var eo=e=>typeof e=="string"?e:String(e),Dr=0;function Yt(e){return Dr+=1,`${e}-${Dr}`}function Vr(e,t){let r=(0,F.useMemo)(()=>De(e),[e]),[o,n]=(0,F.useState)(()=>(t?.initialMessages??[]).map(T=>({id:T.id??Yt("msg"),role:T.role,content:T.content}))),[s,i]=(0,F.useState)(""),[a,u]=(0,F.useState)(!1),[c,g]=(0,F.useState)(null),d=(0,F.useRef)(t);d.current=t;let k=(0,F.useRef)(o);k.current=o;let P=(0,F.useRef)(s);P.current=s;let S=(0,F.useRef)(0),p=(0,F.useRef)(null),C=(0,F.useRef)(!0);(0,F.useEffect)(()=>(C.current=!0,()=>{C.current=!1,p.current?.cancel(),p.current=null}),[]);let h=(0,F.useCallback)(()=>{S.current++,p.current?.cancel(),p.current=null,C.current&&u(!1)},[]),x=(0,F.useCallback)(async T=>{let E=T===void 0,v=(E?P.current:T)??"";if(!v.trim())return;p.current?.cancel();let L=++S.current,U=()=>C.current&&S.current===L,M=d.current,l=M?.parseChunk??eo,m={id:Yt("msg"),role:"user",content:v},f={id:Yt("msg"),role:"assistant",content:""},b=[...k.current,m].map(B=>({role:B.role,content:B.content})),_=[...k.current,m,f];k.current=_,n(_),E&&i(""),g(null),u(!0);let z=M?.buildPayload??(B=>({messages:B})),{initialMessages:R,parseChunk:y,buildPayload:D,onFinish:H,onError:W,...K}=M??{},le=B=>{n(ae=>ae.map($=>$.id===f.id?{...$,content:B}:$))},ie="",Z;try{Z=r.requestStream(z(b),K),p.current=Z}catch(B){let ae=Or(B);U()&&(g(ae),u(!1),M?.onError?.(ae));return}try{for await(let B of Z){if(S.current!==L)break;ie+=l(B),U()&&le(ie)}U()&&(u(!1),M?.onFinish?.({...f,content:ie}))}catch(B){let ae=Or(B);U()&&(g(ae),u(!1),M?.onError?.(ae))}finally{p.current===Z&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:x,stop:h,isStreaming:a,error:c}}var q=require("react"),Ve=require("@urun-sh/core"),Zt=[];function qr(e,t={}){let{field:r=Ve.INPUT_PRESENCE_FIELD,hz:o=Ve.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,q.useMemo)(()=>s?(0,Ve.createInputPresencePublisher)({awareness:{setLocalStateField:(v,A)=>s.setField(v,A)},field:r,hz:o}):null,[s,r,o]),a=(0,q.useRef)(null);a.current=i;let[u,c]=(0,q.useState)(!1),[g,d]=(0,q.useState)(Zt),k=(0,q.useRef)(!1);(0,q.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let P=(0,q.useCallback)(()=>{let v=a.current;d(v?v.heldKeys():Zt)},[]),S=(0,q.useCallback)(()=>{a.current?.clear(),d(Zt)},[]);(0,q.useEffect)(()=>{if(!n)return;let v=()=>!!n.pointerLockElement,A=()=>{if(v()){k.current=!1,c(!0);return}k.current||(c(!1),S())},L=f=>{v()&&(a.current?.keyDown(f.key),P())},U=f=>{a.current?.keyUp(f.key),P()},M=f=>{v()&&a.current?.movePointer(f.movementX,f.movementY)},l=f=>{v()&&a.current?.setButtons(f.buttons)},m=()=>{S()};return n.addEventListener("pointerlockchange",A),n.addEventListener("keydown",L),n.addEventListener("keyup",U),n.addEventListener("mousemove",M),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",m),()=>{n.removeEventListener("pointerlockchange",A),n.removeEventListener("keydown",L),n.removeEventListener("keyup",U),n.removeEventListener("mousemove",M),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",m)}},[n,S,P]);let p=(0,q.useCallback)(v=>{v.requestPointerLock?.()},[]),C=(0,q.useCallback)(()=>{k.current=!0,c(!0)},[]),h=(0,q.useCallback)(()=>{k.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),S()},[n,S]),x=(0,q.useCallback)(v=>{a.current?.keyDown(v),P()},[P]),T=(0,q.useCallback)(v=>{a.current?.keyUp(v),P()},[P]),E=(0,q.useCallback)((v,A)=>{a.current?.movePointer(v,A)},[]);return{engage:p,engageTouch:C,release:h,engaged:u,heldKeys:g,pressKey:x,releaseKey:T,movePointer:E}}var Fr=new Map;function Hr(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);Fr.set(e,{component:t,schema:r})}function Wr(e,t){let r=Fr.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 Ee=require("react/jsx-runtime");function Br({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Ee.jsx)(Ee.Fragment,{children:r}):(0,Ee.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Ee.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Ee.jsx)(n,{...o.validatedProps})}var qe=require("zod"),Re=require("react/jsx-runtime"),$r=qe.z.object({step:qe.z.number().min(0),total:qe.z.number().min(1),label:qe.z.string().optional(),variant:qe.z.enum(["default","success","error"]).default("default")});function Qt(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 Kr(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Qt(e);return(0,Re.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Re.jsx)("div",{className:"urun-progress-label",children:o}),(0,Re.jsx)("div",{className:"urun-progress-bar",children:(0,Re.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Re.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var ht=require("zod"),Ye=require("react/jsx-runtime"),jr=ht.z.object({state:ht.z.enum(["thinking","generating","idle","error"]),message:ht.z.string().optional()}),to={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function er(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??to[t]??t;return{state:t,message:n,isActive:o}}function Jr(e){let{state:t,message:r,isActive:o}=er(e);return(0,Ye.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,Ye.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Ye.jsx)("span",{className:"urun-status-message",children:r})]})}var Ze=require("react"),vt=require("zod"),Qe=require("react/jsx-runtime"),zr=vt.z.object({text:vt.z.string(),streaming:vt.z.boolean().default(!1)});function tr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Xr(e){let{text:t,streaming:r}=tr(e),o=(0,Ze.useRef)(null),n=(0,Ze.useRef)(0);return(0,Ze.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Qe.jsxs)("div",{className:"urun-text-stream",children:[(0,Qe.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Qe.jsx)("span",{className:"urun-text-cursor"})]})}var et=require("zod"),tt=require("react/jsx-runtime"),Gr=et.z.object({src:et.z.string().url(),alt:et.z.string().optional(),caption:et.z.string().optional()});function rr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Yr(e){let{src:t,alt:r,caption:o}=rr(e);return(0,tt.jsxs)("figure",{className:"urun-image-frame",children:[(0,tt.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,tt.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var ge=require("zod"),Fe=require("react/jsx-runtime"),Zr=ge.z.object({metrics:ge.z.array(ge.z.object({label:ge.z.string(),value:ge.z.union([ge.z.string(),ge.z.number()]),unit:ge.z.string().optional()}))});function nr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Qr(e){let{metrics:t}=nr(e);return(0,Fe.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,Fe.jsxs)("div",{className:"urun-metric-card",children:[(0,Fe.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,Fe.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var rt=require("react"),rn=require("react/jsx-runtime"),or=(0,rt.createContext)(null);function en({session:e,children:t}){return(0,rn.jsx)(or.Provider,{value:e,children:t})}function pe(){return(0,rt.useContext)(or)}function tn(){let e=(0,rt.useContext)(or);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 J=require("react");var kt=require("react/jsx-runtime"),ro=1e3;function no(...e){console.debug("[video]",...e)}var yt=(0,J.forwardRef)(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:g,videoClassName:d,placeholder:k,children:P,onTrack:S}=t,p=pe(),C=o??p,h=(0,J.useRef)(null),x=(0,J.useRef)(null),[T,E]=(0,J.useState)(!1),v=(0,J.useRef)(S);v.current=S;let A=(0,J.useCallback)(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let m=h.current;return m&&m.srcObject!==x.current&&(m.srcObject=x.current),x.current},[]),L=(0,J.useCallback)(m=>{let f=h.current;if(!f)return;let b=f.play();!b||typeof b.catch!="function"||b.catch(_=>no(`play() failed (${m})`,_))},[]),U=(0,J.useCallback)(m=>{let f=A();if(f){for(let b of f.getVideoTracks())b!==m&&f.removeTrack(b);if(m&&!f.getVideoTracks().includes(m)){f.addTrack(m);let b=h.current;b&&(b.srcObject=f)}m&&L("track-attach"),E(m!==null),v.current?.(m)}},[A,L]),M=(0,J.useCallback)(m=>{h.current=m,m&&(i&&(m.muted=!0,m.defaultMuted=!0,m.setAttribute("muted","")),m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),A())},[A,i]);(0,J.useImperativeHandle)(r,()=>({get element(){return h.current},get live(){return x.current?x.current.getVideoTracks().length>0:!1}}),[]);let l=s!==void 0;return(0,J.useEffect)(()=>{if(l){U(s??null);return}if(!C)return;let m=C.stream(n),f=()=>{let y=x.current;return y?y.getVideoTracks()[0]??null:null},b=y=>{if(y!==f()&&(U(y),y)){let D=()=>{f()===y&&U(null)};y.addEventListener("ended",D)}},_=m.track;_&&_.readyState==="live"&&b(_);let z=m.on("track",y=>{y&&y.readyState!=="live"||b(y)}),R=setInterval(()=>{let y=m.track;y&&y.readyState==="live"&&b(y)},ro);return()=>{z(),clearInterval(R)}},[C,n,l,s,U]),(0,kt.jsxs)("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...g},"data-urun-video":"","data-urun-video-live":T?"true":"false",children:[(0,kt.jsx)("video",{ref:M,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),T?null:k,P]})});var nn=require("react");var sn=require("react/jsx-runtime"),on=(0,nn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,sn.jsx)(yt,{ref:r,stream:o,...n})});var O=require("react"),un=require("@urun-sh/core");var bt=null;function oo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function nt(){if(bt)return bt;let e=oo();return e?(bt=new e,bt):null}function ot(){let e=nt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var ln=require("react/jsx-runtime"),so=1e3,an=200;function sr(...e){console.debug("[audio]",...e)}var st=(0,O.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,d=pe(),k=o??d,P=(0,O.useRef)(null),S=(0,O.useRef)(null),p=(0,O.useRef)(null),C=(0,O.useRef)(null),h=(0,O.useRef)(u);h.current=u;let x=(0,O.useRef)(c);x.current=c;let T=(0,O.useCallback)(l=>{p.current!==l&&(p.current=l,x.current?.(l))},[]),E=(0,O.useCallback)(()=>{if(typeof MediaStream>"u")return null;S.current||(S.current=new MediaStream);let l=P.current;return l&&l.srcObject!==S.current&&(l.srcObject=S.current),S.current},[]),v=(0,O.useCallback)(l=>{let m=P.current;if(!m)return;let f=m.play();!f||typeof f.then!="function"||f.then(()=>{m.muted||T(!0)}).catch(b=>{let _=b instanceof Error?b.name:String(b);if(_==="AbortError"){sr(`play() aborted (${l}); retrying in ${an}ms`),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,v(`${l}:retry`)},an);return}if(_==="NotAllowedError"){sr(`play() blocked pending a user gesture (${l})`),T(!1);return}sr(`play() failed (${l})`,b)})},[T]),A=(0,O.useCallback)(l=>{let m=E();if(m){for(let f of m.getAudioTracks())f!==l&&m.removeTrack(f);l&&!m.getAudioTracks().includes(l)&&m.addTrack(l),l&&v("track-attach"),h.current?.(l)}},[E,v]),L=(0,O.useCallback)(()=>{let l=P.current;l&&(E(),l.muted=!1,v("gesture"),ot(),T(!0))},[E,v,T]);(0,O.useImperativeHandle)(r,()=>({unlock:L,get unlocked(){return p.current===!0},get element(){return P.current}}),[L]);let U=(0,O.useCallback)(l=>{P.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),E()),g?.(l)},[E,g]),M=s!==void 0;return(0,O.useEffect)(()=>{if(M){A(s??null);return}if(!k)return;let l=k.stream(n),m=()=>{let R=S.current;return R?R.getAudioTracks()[0]??null:null},f=R=>{if(R!==m()&&(A(R),R)){let y=()=>{m()===R&&A(null)};R.addEventListener("ended",y)}},b=l.track;b&&b.readyState==="live"&&f(b);let _=l.on("track",R=>{R&&R.readyState!=="live"||f(R)}),z=setInterval(()=>{let R=l.track;R&&R.readyState==="live"&&f(R)},so);return()=>{_(),clearInterval(z)}},[k,n,M,s,A]),(0,O.useEffect)(()=>(0,un.observePageLifecycle)(()=>{ot(),p.current===!0&&v("foreground")}),[v]),(0,O.useEffect)(()=>()=>{C.current&&clearTimeout(C.current)},[]),(0,ln.jsx)("audio",{ref:U,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),cn=st;var I=require("react"),He=require("@urun-sh/core");var pn=require("react/jsx-runtime"),ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Pt(...e){console.debug("[voice]",...e)}var it=(0,I.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=ir,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:d,onMicStream:k,onTrack:P,onUnlockChange:S,capture:p}=t,C=pe(),h=o??C,x=(0,I.useRef)(null),T=(0,I.useRef)(null),E=(0,I.useRef)(null),v=(0,I.useRef)([]),A=(0,I.useRef)(!1),L=(0,I.useRef)(g);L.current=g;let U=(0,I.useRef)(d);U.current=d;let M=(0,I.useRef)(k);M.current=k;let l=(0,I.useCallback)(y=>{A.current!==y&&(A.current=y,L.current?.(y))},[]),m=(0,I.useCallback)(()=>{for(let y of v.current)y();v.current=[],E.current?.release(),E.current=null,T.current&&(T.current=null,M.current?.(null))},[]),f=(0,I.useCallback)(async()=>{let y=E.current;if(y){let K=await y.update(i);return T.current=y.stream,M.current?.(y.stream),K}let H=await(p??(0,He.sharedCaptureController)()).claim("audio",i);E.current=H,v.current=[H.onTrack((K,le)=>{T.current=le,M.current?.(le),A.current&&h?.stream(n).attach(K).catch(ie=>Pt("mic re-attach after one-capture re-acquire failed",ie))}),H.onLost(K=>{E.current=null,v.current=[],T.current=null,M.current?.(null),l(!1),U.current?.(K)})],T.current=H.stream,M.current?.(H.stream);let W=H.track;if(!W)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return W},[p,i,h,n,l]),b=(0,I.useCallback)(async()=>{m(),l(!1),await h?.stream(n).detach().catch(()=>{})},[h,n,m,l]),_=(0,I.useCallback)(async()=>{if(!h)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");x.current?.unlock();let y;try{y=await f()}catch(W){m();let K=(0,He.sessionFailureFromMediaError)(W,h.status);throw U.current?.(K),K}h.connect?.();let D;for(let W=1;W<=u;W++)try{await h.whenLive(a!==void 0?{timeout:a}:void 0),await h.stream(n).attach(y),l(!0);return}catch(K){D=K,Pt(`start attempt ${W}/${u} failed`,K),W<u&&await new Promise(le=>setTimeout(le,c))}m(),l(!1);let H=D instanceof Error?D:new Error(String(D??"voice start failed"));throw U.current?.(H),H},[h,n,a,u,c,f,m,l]);(0,I.useImperativeHandle)(r,()=>({start:_,stop:b,unlock:()=>x.current?.unlock(),get active(){return A.current},get micStream(){return T.current},get audio(){return x.current}}),[_,b]);let z=(0,I.useRef)(!1),R=(0,I.useCallback)(async()=>{if(!h||!A.current||z.current)return;let y=T.current?.getAudioTracks()[0]??null;if(y&&y.readyState==="live"){try{await h.stream(n).attach(y)}catch(D){Pt("foreground mic re-assert failed (will retry on next pass)",D)}return}z.current=!0;try{let D=await f();await h.stream(n).attach(D)}catch(D){let H=D instanceof Error?D:new Error(String(D));Pt("foreground mic re-acquire failed",H),U.current?.(H)}finally{z.current=!1}},[h,n,f]);return(0,I.useEffect)(()=>{let y=()=>{R()};return h&&typeof h.onRecovery=="function"?h.onRecovery(y):(0,He.observePageLifecycle)(y)},[h,R]),(0,I.useEffect)(()=>m,[m]),s?(0,pn.jsx)(st,{ref:x,session:h,stream:n,onTrack:P,onUnlockChange:S}):null}),dn=it;var ue=require("react");var Ct=require("react");var ar={level:0,speaking:!1};function xt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,Ct.useState)(ar);return(0,Ct.useEffect)(()=>{if(!e){i(ar);return}let a=nt();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let d=new Uint8Array(g.fftSize),P=setInterval(()=>{g.getByteTimeDomainData(d);let S=0;for(let C=0;C<d.length;C++){let h=(d[C]-128)/128;S+=h*h}let p=Math.sqrt(S/d.length);i(C=>{let h=p>n;return Math.abs(C.level-p)<.005&&C.speaking===h?C:{level:p,speaking:h}})},o);return()=>{clearInterval(P),c.disconnect(),i(ar)}},[e,r,o,n]),s}var Se=require("react/jsx-runtime"),io={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ao={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},mn=(0,ue.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:d,capture:k}=t,P=pe(),S=o??P,p=(0,ue.useRef)(null),[C,h]=(0,ue.useState)(null),x=(0,ue.useRef)(d);x.current=d;let{level:T,speaking:E}=xt(a?C:null);return(0,ue.useImperativeHandle)(r,()=>({start:()=>{let v=p.current;return v?v.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),(0,ue.useEffect)(()=>{!i||!S||p.current?.start().catch(()=>{})},[i,S]),(0,Se.jsxs)(Se.Fragment,{children:[(0,Se.jsx)(it,{ref:p,session:S,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...k!==void 0?{capture:k}:{},onActiveChange:c,onError:g,onMicStream:v=>{h(v),x.current?.(v)}}),a?(0,Se.jsx)("span",{className:u,style:io,"data-urun-mic":"","data-urun-mic-active":C?"true":"false","data-urun-mic-speaking":E?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(T*100)/100,children:(0,Se.jsx)("span",{style:ao,children:(0,Se.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(T*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var Tt=require("@urun-sh/core"),w=require("react");var ne=require("react/jsx-runtime"),cr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function ur(...e){console.debug("[camera]",...e)}function uo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function co(){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 lr=(0,w.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:d,visible:k=!1,className:P,videoClassName:S,onActiveChange:p,onError:C,onStream:h,onTrack:x,children:T,capture:E,flipControl:v="auto",flipControlClassName:A,onDevices:L}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let U=i?"user":a?"environment":u??"environment",M=pe(),l=o??M,m=(0,w.useRef)(null),f=(0,w.useRef)(null),b=(0,w.useRef)(null),_=(0,w.useRef)([]),z=(0,w.useRef)(null),R=(0,w.useRef)(!1),y=(0,w.useRef)(U),[D,H]=(0,w.useState)(U),[W,K]=(0,w.useState)(!1),[le,ie]=(0,w.useState)(null),[Z,B]=(0,w.useState)(!1),[ae]=(0,w.useState)(uo),$=(0,w.useRef)(p);$.current=p;let Q=(0,w.useRef)(C);Q.current=C;let de=(0,w.useRef)(h);de.current=h;let Me=(0,w.useRef)(x);Me.current=x;let lt=(0,w.useRef)(L);lt.current=L;let ye=(0,w.useCallback)(N=>{R.current!==N&&(R.current=N,K(N),$.current?.(N))},[]);(0,w.useEffect)(()=>{if(!W){ie(null);return}let N=!1,V=()=>{co().then(re=>{N||(ie(re),re&<.current?.(re))})};V();let G=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof G?.addEventListener=="function"?(G.addEventListener("devicechange",V),()=>{N=!0,G.removeEventListener?.("devicechange",V)}):()=>{N=!0}},[W]);let dt=(0,w.useCallback)(N=>{let V=m.current;V&&(V.muted=!0,V.defaultMuted=!0,V.setAttribute("muted",""),V.setAttribute("playsinline",""),V.setAttribute("webkit-playsinline",""),V.srcObject=N,N&&V.play()?.catch?.(G=>ur("preview play() failed",G)))},[]),me=(0,w.useCallback)(()=>{z.current?.(),z.current=null;for(let N of _.current)N();_.current=[],b.current?.release(),b.current=null,f.current&&(f.current=null,de.current?.(null),Me.current?.(null)),dt(null)},[dt]),Bt=(0,w.useCallback)((N,V)=>{z.current?.(),f.current=V,dt(V),de.current?.(V);let G=()=>{f.current===V&&(ur("camera track ended (device removed or permission revoked)"),me(),ye(!1))};N.addEventListener("ended",G),z.current=()=>N.removeEventListener("ended",G)},[dt,me,ye]),_e=(0,w.useCallback)(async N=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let V={...cr,...s,facingMode:N},G;try{let re=b.current;if(re)G=await re.update(V);else{let Je=await(E??(0,Tt.sharedCaptureController)()).claim("video",V);if(b.current=Je,_.current=[Je.onTrack((ze,Vn)=>{Bt(ze,Vn),R.current&&l.stream(n).attachVideo(ze).then(()=>Me.current?.(ze)).catch(qn=>ur("camera re-publish after one-capture re-acquire failed",qn))}),Je.onLost(ze=>{b.current=null,_.current=[],me(),ye(!1),Q.current?.(ze)})],!Je.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});G=Je.track}}catch(re){let Ne=(0,Tt.sessionFailureFromMediaError)(re,l.status);throw Q.current?.(Ne),Ne}y.current=N,H(N),Bt(G,b.current?.stream??new MediaStream([G]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(G)}catch(re){me(),ye(!1);let Ne=re instanceof Error?re:new Error(String(re));throw Q.current?.(Ne),Ne}Me.current?.(G),ye(!0)},[l,n,s,d,E,Bt,me,ye]),fr=(0,w.useCallback)(N=>_e(N?.facingMode??y.current),[_e]),pt=(0,w.useCallback)(async N=>{R.current&&y.current===N||await _e(N)},[_e]),$t=(0,w.useCallback)(()=>_e(y.current==="environment"?"user":"environment"),[_e]),gr=(0,w.useCallback)(async()=>{me(),ye(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,me,ye]);(0,w.useImperativeHandle)(r,()=>({start:fr,stop:gr,flip:$t,setFacingMode:pt,get active(){return R.current},get facingMode(){return y.current},get stream(){return f.current},get element(){return m.current}}),[fr,gr,$t,pt]);let Sr=(0,w.useRef)(pt);if(Sr.current=pt,(0,w.useEffect)(()=>{!c||!l||Sr.current(U).catch(()=>{})},[c,l,U]),(0,w.useEffect)(()=>me,[me]),!k)return null;let Ln=g==="auto"?D==="user":g,On=W&&(v===!0||v==="auto"&&ae&&(le?.length??0)>1),Dn=()=>{Z||(B(!0),$t().catch(()=>{}).finally(()=>B(!1)))};return(0,ne.jsxs)("div",{className:P,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":D,children:[(0,ne.jsx)("video",{ref:m,className:S,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ln?{transform:"scaleX(-1)"}:{}}}),On?(0,ne.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Dn,disabled:Z,className:A,style:A?{opacity:Z?.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:Z?.6:1},children:(0,ne.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,ne.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ne.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ne.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ne.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ne.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,T]})}),fn=(0,w.forwardRef)(function({preview:t=!0,...r},o){return(0,ne.jsx)(lr,{ref:o,...r,visible:t,autoStart:!1})});var wt=require("react");function gn(e,t){let[r,o]=(0,wt.useState)(null);return(0,wt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var vn=require("react");var Rt=require("react");var Sn=require("zustand/vanilla"),hn=require("zustand"),lo=()=>{};function Et(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,Sn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):lo,u=(c=>(0,hn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function We(e,t){let r=(0,Rt.useMemo)(()=>Et(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Rt.useEffect)(()=>r.bind(),[r]),r}function yn(e,t,r){let n=We(e,t)(r??(a=>a)),s=(0,vn.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 Ut=require("react");var be=200;function he(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Be(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(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 Mt(e,t,r={}){let o=r.cap??200,[n,s]=(0,Ut.useState)([]);return(0,Ut.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>he(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var ce=require("react/jsx-runtime");function kn({session:e,name:t,cap:r,className:o}){let n=Mt(e,t,{cap:r});return(0,ce.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,ce.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,ce.jsx)("code",{children:t}),(0,ce.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,ce.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,ce.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,ce.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,ce.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,ce.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Be(s.payload)]},`${s.at}-${i}`))})]})}var at=require("react");var te=require("react/jsx-runtime");function ut({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,at.useState)(""),[i,a]=(0,at.useState)(null),u=(0,at.useCallback)(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,te.jsxs)("div",{className:"urun-doc-patch",children:[(0,te.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,te.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,te.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,te.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function bn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=We(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,te.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,te.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,te.jsx)("code",{children:t}),(0,te.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,te.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,te.jsx)(ut,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var _t=require("react");var ve=require("react/jsx-runtime");function Pn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Cn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,_t.useState)([]);return(0,_t.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>he(u,{at:Date.now(),direction:"in",text:Pn(Be(a))},r))}):void 0),[e,t,r]),(0,ve.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,ve.jsx)(ut,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>he(u,{at:Date.now(),direction:"out",text:Pn(a)},r))}}),(0,ve.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,ve.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,ve.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,ve.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,ve.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Nt=require("react");var Ae=require("react/jsx-runtime");function xn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Nt.useState)([]),a=t.join(","),u=r.join(",");return(0,Nt.useEffect)(()=>{if(i([]),!e)return;let c=(d,k)=>i(P=>he(P,{at:Date.now(),kind:d,text:k},o)),g=[];g.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let k=e.stream(d);g.push(k.on("track",P=>c("track",`${d}: ${P?"track arrived":"track ended"}`)))}for(let d of r){let k=e.doc(d);g.push(k.on("change",()=>c("doc",`${d} changed`)))}return()=>g.forEach(d=>d())},[e,a,u,o]),(0,Ae.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Ae.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((c,g)=>(0,Ae.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Ae.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Ae.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}var Ft=require("@urun-sh/core");var It=require("react");function oe(e){let[t,r]=(0,It.useState)(e?.phase??null);return(0,It.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var wn=require("@urun-sh/core");var $e=require("react"),Tn=require("@urun-sh/core");function Lt(e){let t=oe(e),r=(0,Tn.isWakingPhase)(t?.name),o=(0,$e.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,$e.useState)(s);return(0,$e.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[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 Pe=require("react/jsx-runtime");function Ot({session:e,render:t,className:r}){let o=Lt(e);return!o.waking||!o.phase?null:(0,Pe.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,Pe.jsxs)(Pe.Fragment,{children:[(0,Pe.jsx)("span",{className:"urun-session-waking-label",children:(0,wn.describeSessionPhase)(o.phase)})," ",(0,Pe.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Vt=require("react");var Ce=require("react"),po={event:null,elapsedMs:0};function Dt(e,t){let[r,o]=(0,Ce.useState)(null),n=(0,Ce.useRef)(0);(0,Ce.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,Ce.useState)(0);return(0,Ce.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:po}var Ke=require("react/jsx-runtime"),mo={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 fo(e){let[t,r]=(0,Vt.useState)(!1);return(0,Vt.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 qt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Dt(e,t),i=fo(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,Ke.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,Ke.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,Ke.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??mo[u]})," ",(0,Ke.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var se=require("react/jsx-runtime"),go={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function En({session:e,className:t}){let r=oe(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,se.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,se.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,se.jsx)("span",{className:"urun-session-status-label",children:go[o]}),n?(0,se.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function Rn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=oe(e);if(s?.name==="live")return(0,se.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,se.jsx)(qt,{session:e})]});let i=r?r(s):(0,se.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,Ft.isWakingPhase)(s.name)?(0,se.jsx)(Ot,{session:e}):s&&s.name!=="idle"?(0,Ft.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,se.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,se.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var Ht=require("react");var Un=require("react/jsx-runtime");function dr(e){return oe(e)?.endsAt??null}function So(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 An({session:e,urgentMs:t=6e4,className:r}){let n=dr(e)?.getTime()??null,[s,i]=(0,Ht.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Ht.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=So(s);return(0,Un.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 ct=require("react/jsx-runtime"),ho=new Set(["expired","ended","error"]);function Mn({session:e,onNewSession:t,children:r,className:o}){let n=oe(e);if(!n||!ho.has(n.name))return null;let s=r?r(n):(0,ct.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,ct.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,ct.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var xe=require("react"),Ue=require("react/jsx-runtime");function pr(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 mr(e){let t=(0,xe.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,xe.useState)(()=>t?pr(t.get("idle")):null);return(0,xe.useEffect)(()=>{if(!t){o(null);return}return o(pr(t.get("idle"))),t.on("change",()=>o(pr(t.get("idle"))))},[t]),r}function vo(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function _n({session:e,onStillHere:t,className:r}){let o=mr(e),n=o?.deadlineEpochS??null,[s,i]=(0,xe.useState)(null);if((0,xe.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,Ue.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,Ue.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Ue.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Ue.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${vo(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Ue.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var je=require("react"),Nn=require("@urun-sh/core");function In(e){let t=(0,je.useContext)(Le),[r,o]=(0,je.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,d=t?.authProvider;return(0,je.useEffect)(()=>{if(!a||!u||!n||!s)return;let k=!1,P=()=>{(0,Nn.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:d}).then(p=>{k||o(p)}).catch(()=>{})};P();let S=setInterval(P,Math.max(1,i)*1e3);return()=>{k=!0,clearInterval(S)}},[n,s,i,a,u,c,g,d]),r}var Wt=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,Session,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
|
2
|
+
"use strict";var Kt=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var Wn=Object.prototype.hasOwnProperty;var Bn=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},$n=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Hn(t))!Wn.call(e,n)&&n!==r&&Kt(e,n,{get:()=>t[n],enumerable:!(o=qn(t,n))||o.enumerable});return e};var Kn=e=>$n(Kt({},"__esModule",{value:!0}),e);var bo={};Bn(bo,{Audio:()=>it,Camera:()=>lr,ComponentRenderer:()=>Br,DEFAULT_CAMERA_CONSTRAINTS:()=>cr,DEFAULT_LOG_CAP:()=>Pe,DEFAULT_VOICE_CONSTRAINTS:()=>ir,DocPatchForm:()=>ct,Image:()=>on,ImageFrame:()=>Yr,ImageFrameSchema:()=>Gr,MetricsPanel:()=>Qr,MetricsPanelSchema:()=>Zr,Mic:()=>mn,OPERATOR_CHORD_LABEL:()=>Er,OPERATOR_TOKEN_STORAGE_KEY:()=>xr,ProgressCard:()=>Kr,ProgressCardSchema:()=>$r,Session:()=>en,StatusBadge:()=>Jr,StatusBadgeSchema:()=>jr,TextStream:()=>Xr,TextStreamSchema:()=>zr,UrunActivationOverlay:()=>Ft,UrunAudio:()=>cn,UrunAuthProvider:()=>jt,UrunCamera:()=>fn,UrunControlSender:()=>Cn,UrunDocPanel:()=>bn,UrunErrorBoundary:()=>Ie,UrunEventSpine:()=>xn,UrunIdleWarning:()=>_n,UrunJwtProvider:()=>br,UrunProvider:()=>Ur,UrunSessionClock:()=>An,UrunSessionEnded:()=>Mn,UrunSessionGate:()=>Rn,UrunSessionStatus:()=>wn,UrunSessionWaking:()=>Ot,UrunStreamTail:()=>kn,UrunVoice:()=>dn,Video:()=>kt,Voice:()=>at,authMode:()=>Ge,createDocStore:()=>wt,describeSessionPhase:()=>Wt.describeSessionPhase,formatPayload:()=>Be,getUrunAudioContext:()=>ot,isWakingPhase:()=>Wt.isWakingPhase,parseJsonObject:()=>At,pushCapped:()=>ve,readOperatorToken:()=>Jt,registerComponent:()=>Hr,resumeUrunAudioContext:()=>st,urunPublicEnv:()=>ge,useActivation:()=>Dt,useApp:()=>_r,useChat:()=>Vr,useCompletion:()=>Lr,useConfirmOnLeave:()=>ht,useDocStore:()=>We,useImageFrame:()=>rr,useInputPresence:()=>Fr,useMetricsPanel:()=>nr,useOperatorOverride:()=>St,useProgressCard:()=>Qt,useRequest:()=>Nr,useSession:()=>tn,useSessionDoc:()=>yn,useSessionEndsAt:()=>dr,useSessionIdle:()=>mr,useSessionPhase:()=>ue,useSessionTrack:()=>gn,useSessionWake:()=>Lt,useStatusBadge:()=>er,useStreamMessages:()=>Mt,useTextStream:()=>tr,useUrunAudioLevel:()=>xt,useUrunAuth:()=>ft,useUrunPrewake:()=>In,usesWorkOSAuth:()=>yr});module.exports=Kn(bo);var re=require("react");var hr=require("react"),Xe=require("react/jsx-runtime"),Ie=class extends hr.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,Xe.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,Xe.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,Xe.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var vr=require("react"),Le=(0,vr.createContext)(null);function Ee(e){return e&&e.trim()?e.trim():void 0}function ge(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ee(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return Ee(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ee(typeof process<"u"?process.env?.[e]:void 0)}}function Ge(){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 yr(){return Ge()==="workos"}var Oe=require("react"),Pr=require("react/jsx-runtime"),kr=(0,Oe.createContext)(null);function jt({getAccessToken:e,children:t}){let r=(0,Oe.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Pr.jsx)(kr.Provider,{value:r,children:t})}var br=jt;function ft(){return(0,Oe.useContext)(kr)}var gt=require("react"),xr="urun.operator_token",Tr=null,Cr="op",Er="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function wr(){return typeof window<"u"}function Jt(){return Tr}function jn(){if(!wr())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(Cr);if(!r)return null;Tr=r,t.delete(Cr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Jn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function St(e){let t=(0,gt.useRef)(e);t.current=e,(0,gt.useEffect)(()=>{if(!wr())return;jn();let r=o=>{if(!Jn(o))return;let n=Jt();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Rr=require("react");function ht(e=!0){(0,Rr.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 be=require("react/jsx-runtime"),zn="/api/urun-token",Xn=1e4;function Gn(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Ar(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function Yn(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,be.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,be.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,be.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Ur({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:m=!1,fallback:d,errorFallback:y,children:k}){let f=n===void 0&&t===void 0;if(!f&&(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(!f&&(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 p=r??o;if(f&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);ht(m);let[C,S]=(0,re.useState)(),[A,b]=(0,re.useState)(),[x,g]=(0,re.useState)(null),_=(0,re.useRef)(void 0),H=(0,re.useRef)(null),[I,M]=(0,re.useState)(null);St(J=>M({jwt:J}));let l=ft(),E=ge("NEXT_PUBLIC_SESSION_TOKEN")??ge("NEXT_PUBLIC_URUN_JWT"),v=Ge(),T=I!==null,V=v==="workos"&&!n&&!T&&!f,G=n??(v==="jwt"?E:void 0)??C??A?.token,U=T?I.jwt:G,R=s??ge("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),B=V&&!U,$=t??A?.orgId,h=e??A?.gatewayUrl,P=f&&A===void 0,L=f&&A!==void 0&&!h?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,O=x??L,K=u??zn,j=(0,re.useCallback)(async J=>{if(!J?.forceRefresh){let ee=_.current;if(!ee)return ee;let me=Gn(ee);if(me===null||me-Date.now()>Xn)return ee}return(await(H.current??(H.current=(async()=>{try{let ee=await Ar(K);return _.current=ee.token,b(ee),ee}finally{H.current=null}})()))).token},[K]),N=(0,re.useMemo)(()=>({appId:p,baseUrl:h??"",orgId:$??"",jwt:U,getAccessToken:V?l?.getAccessToken:f&&!T?j:void 0,authProvider:R,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:T?"preempt":void 0}),[p,l,h,R,U,i,$,a,c,V,T,f,j]);return(0,re.useEffect)(()=>{if(!f)return;let J=new AbortController;return g(null),(async()=>{try{let ne=await Ar(K,J.signal);_.current=ne.token,b(ne)}catch(ne){if(J.signal.aborted)return;g(ne instanceof Error?ne:new Error(String(ne)))}})(),()=>J.abort()},[f,K]),(0,re.useEffect)(()=>{if(!V||!l)return;let J=!1,ne=l;async function ee(){try{let dt=await ne.getAccessToken();J||S(dt??void 0)}catch{J||S(void 0)}}ee();let me=window.setInterval(()=>{ee()},6e4);return()=>{J=!0,window.clearInterval(me)}},[l,V]),(0,be.jsx)(Ie,{fallback:d,children:O?Yn(y,O):B||P?(0,be.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,be.jsx)(Le.Provider,{value:N,children:k})})}var oe=require("react"),Mr=require("@urun-sh/core");function Zn(e,t){return`${e}:${JSON.stringify(t??{})}`}function Qn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var we=new Map;var zt=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()})}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()}},Xt=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},Gt=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"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}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()}doc(t){let r=this._docs.get(t);return r||(r=new zt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Xt(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_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 _r(){let e=(0,oe.useContext)(Le);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,oe.useReducer)(i=>i+1,0),r=(0,oe.useRef)(new Map),o=(0,oe.useRef)(new Map),n=(0,oe.useRef)(null),s=(0,oe.useMemo)(()=>(0,Mr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return(0,oe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=we.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let m=we.get(u);m===c&&(m.handle.removeNotifier(t),m.refCount=Math.max(0,m.refCount-1),a.set(u,m),m.refCount===0&&(m.disposeTimer=setTimeout(()=>{let d=we.get(u);!d||d.refCount!==0||(we.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),(0,oe.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let m=d=>{let y=Zn(u,d),k=r.current.get(y);if(k&&!k.disposed)return k;let f=Qn(e,u,d),p=we.get(f);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),we.delete(f),o.current.get(f)===p&&o.current.delete(f),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new Gt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},we.set(f,p)),o.current.get(f)!==p&&(o.current.set(f,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(y,p.handle),p.handle};return i.set(u,m),m}})},[e,s])}var Z=require("react");function De(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function eo(e){return e instanceof Error?e:new Error(String(e))}function Nr(e,t){let r=(0,Z.useMemo)(()=>De(e),[e]),[o,n]=(0,Z.useState)(void 0),[s,i]=(0,Z.useState)(null),[a,u]=(0,Z.useState)(!1),c=(0,Z.useRef)(t);c.current=t;let m=(0,Z.useRef)(0),d=(0,Z.useRef)(null),y=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(y.current=!0,()=>{y.current=!1,d.current?.abort()}),[]);let k=(0,Z.useCallback)(async C=>{d.current?.abort();let S=new AbortController;d.current=S;let A=++m.current,b=()=>y.current&&m.current===A;b()&&(u(!0),i(null));try{let x=await r.request(C,{...c.current,signal:S.signal});return b()&&(n(x),u(!1),c.current?.onSuccess?.(x)),x}catch(x){let g=eo(x);throw b()&&(i(g),u(!1),c.current?.onError?.(g)),g}},[r]),f=(0,Z.useCallback)(C=>{k(C).catch(()=>{})},[k]),p=(0,Z.useCallback)(()=>{m.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:f,mutateAsync:k,data:o,error:s,isPending:a,reset:p}}var Q=require("react");function Ir(e){return e instanceof Error?e:new Error(String(e))}var to=e=>typeof e=="string"?e:String(e);function Lr(e,t){let r=(0,Q.useMemo)(()=>De(e),[e]),[o,n]=(0,Q.useState)(""),[s,i]=(0,Q.useState)(!1),[a,u]=(0,Q.useState)(null),c=(0,Q.useRef)(t);c.current=t;let m=(0,Q.useRef)(0),d=(0,Q.useRef)(null),y=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(y.current=!0,()=>{y.current=!1,d.current?.cancel(),d.current=null}),[]);let k=(0,Q.useCallback)(()=>{m.current++,d.current?.cancel(),d.current=null,y.current&&i(!1)},[]),f=(0,Q.useCallback)(async p=>{d.current?.cancel();let C=++m.current,S=()=>y.current&&m.current===C,A=c.current,b=A?.parseChunk??to,x=A?.buildPayload??(v=>({prompt:v}));S()&&(n(""),u(null),i(!0));let{parseChunk:g,buildPayload:_,onFinish:H,onError:I,...M}=A??{},l="",E;try{E=r.requestStream(x(p),M),d.current=E}catch(v){let T=Ir(v);S()&&(u(T),i(!1),A?.onError?.(T));return}try{for await(let v of E){if(m.current!==C)break;l+=b(v),S()&&n(l)}S()&&(i(!1),A?.onFinish?.(l))}catch(v){let T=Ir(v);S()&&(u(T),i(!1),A?.onError?.(T))}finally{d.current===E&&(d.current=null)}},[r]);return{completion:o,complete:f,stop:k,isStreaming:s,error:a}}var Y=require("react");function Or(e){return e instanceof Error?e:new Error(String(e))}var ro=e=>typeof e=="string"?e:String(e),Dr=0;function Yt(e){return Dr+=1,`${e}-${Dr}`}function Vr(e,t){let r=(0,Y.useMemo)(()=>De(e),[e]),[o,n]=(0,Y.useState)(()=>(t?.initialMessages??[]).map(b=>({id:b.id??Yt("msg"),role:b.role,content:b.content}))),[s,i]=(0,Y.useState)(""),[a,u]=(0,Y.useState)(!1),[c,m]=(0,Y.useState)(null),d=(0,Y.useRef)(t);d.current=t;let y=(0,Y.useRef)(o);y.current=o;let k=(0,Y.useRef)(s);k.current=s;let f=(0,Y.useRef)(0),p=(0,Y.useRef)(null),C=(0,Y.useRef)(!0);(0,Y.useEffect)(()=>(C.current=!0,()=>{C.current=!1,p.current?.cancel(),p.current=null}),[]);let S=(0,Y.useCallback)(()=>{f.current++,p.current?.cancel(),p.current=null,C.current&&u(!1)},[]),A=(0,Y.useCallback)(async b=>{let x=b===void 0,g=(x?k.current:b)??"";if(!g.trim())return;p.current?.cancel();let H=++f.current,I=()=>C.current&&f.current===H,M=d.current,l=M?.parseChunk??ro,E={id:Yt("msg"),role:"user",content:g},v={id:Yt("msg"),role:"assistant",content:""},T=[...y.current,E].map(j=>({role:j.role,content:j.content})),V=[...y.current,E,v];y.current=V,n(V),x&&i(""),m(null),u(!0);let G=M?.buildPayload??(j=>({messages:j})),{initialMessages:U,parseChunk:R,buildPayload:B,onFinish:$,onError:h,...P}=M??{},L=j=>{n(N=>N.map(J=>J.id===v.id?{...J,content:j}:J))},O="",K;try{K=r.requestStream(G(T),P),p.current=K}catch(j){let N=Or(j);I()&&(m(N),u(!1),M?.onError?.(N));return}try{for await(let j of K){if(f.current!==H)break;O+=l(j),I()&&L(O)}I()&&(u(!1),M?.onFinish?.({...v,content:O}))}catch(j){let N=Or(j);I()&&(m(N),u(!1),M?.onError?.(N))}finally{p.current===K&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:A,stop:S,isStreaming:a,error:c}}var X=require("react"),Ve=require("@urun-sh/core"),Zt=[];function Fr(e,t={}){let{field:r=Ve.INPUT_PRESENCE_FIELD,hz:o=Ve.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,X.useMemo)(()=>s?(0,Ve.createInputPresencePublisher)({awareness:{setLocalStateField:(g,_)=>s.setField(g,_)},field:r,hz:o}):null,[s,r,o]),a=(0,X.useRef)(null);a.current=i;let[u,c]=(0,X.useState)(!1),[m,d]=(0,X.useState)(Zt),y=(0,X.useRef)(!1);(0,X.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let k=(0,X.useCallback)(()=>{let g=a.current;d(g?g.heldKeys():Zt)},[]),f=(0,X.useCallback)(()=>{a.current?.clear(),d(Zt)},[]);(0,X.useEffect)(()=>{if(!n)return;let g=()=>!!n.pointerLockElement,_=()=>{if(g()){y.current=!1,c(!0);return}y.current||(c(!1),f())},H=v=>{g()&&(a.current?.keyDown(v.key),k())},I=v=>{a.current?.keyUp(v.key),k()},M=v=>{g()&&a.current?.movePointer(v.movementX,v.movementY)},l=v=>{g()&&a.current?.setButtons(v.buttons)},E=()=>{f()};return n.addEventListener("pointerlockchange",_),n.addEventListener("keydown",H),n.addEventListener("keyup",I),n.addEventListener("mousemove",M),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",_),n.removeEventListener("keydown",H),n.removeEventListener("keyup",I),n.removeEventListener("mousemove",M),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",E)}},[n,f,k]);let p=(0,X.useCallback)(g=>{g.requestPointerLock?.()},[]),C=(0,X.useCallback)(()=>{y.current=!0,c(!0)},[]),S=(0,X.useCallback)(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),f()},[n,f]),A=(0,X.useCallback)(g=>{a.current?.keyDown(g),k()},[k]),b=(0,X.useCallback)(g=>{a.current?.keyUp(g),k()},[k]),x=(0,X.useCallback)((g,_)=>{a.current?.movePointer(g,_)},[]);return{engage:p,engageTouch:C,release:S,engaged:u,heldKeys:m,pressKey:A,releaseKey:b,movePointer:x}}var qr=new Map;function Hr(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);qr.set(e,{component:t,schema:r})}function Wr(e,t){let r=qr.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 Re=require("react/jsx-runtime");function Br({name:e,props:t,fallback:r}){let o=Wr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Re.jsx)(Re.Fragment,{children:r}):(0,Re.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Re.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Re.jsx)(n,{...o.validatedProps})}var Fe=require("zod"),Ae=require("react/jsx-runtime"),$r=Fe.z.object({step:Fe.z.number().min(0),total:Fe.z.number().min(1),label:Fe.z.string().optional(),variant:Fe.z.enum(["default","success","error"]).default("default")});function Qt(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 Kr(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Qt(e);return(0,Ae.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Ae.jsx)("div",{className:"urun-progress-label",children:o}),(0,Ae.jsx)("div",{className:"urun-progress-bar",children:(0,Ae.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Ae.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var vt=require("zod"),Ye=require("react/jsx-runtime"),jr=vt.z.object({state:vt.z.enum(["thinking","generating","idle","error"]),message:vt.z.string().optional()}),no={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function er(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??no[t]??t;return{state:t,message:n,isActive:o}}function Jr(e){let{state:t,message:r,isActive:o}=er(e);return(0,Ye.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,Ye.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Ye.jsx)("span",{className:"urun-status-message",children:r})]})}var Ze=require("react"),yt=require("zod"),Qe=require("react/jsx-runtime"),zr=yt.z.object({text:yt.z.string(),streaming:yt.z.boolean().default(!1)});function tr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Xr(e){let{text:t,streaming:r}=tr(e),o=(0,Ze.useRef)(null),n=(0,Ze.useRef)(0);return(0,Ze.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Qe.jsxs)("div",{className:"urun-text-stream",children:[(0,Qe.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Qe.jsx)("span",{className:"urun-text-cursor"})]})}var et=require("zod"),tt=require("react/jsx-runtime"),Gr=et.z.object({src:et.z.string().url(),alt:et.z.string().optional(),caption:et.z.string().optional()});function rr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Yr(e){let{src:t,alt:r,caption:o}=rr(e);return(0,tt.jsxs)("figure",{className:"urun-image-frame",children:[(0,tt.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,tt.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Se=require("zod"),qe=require("react/jsx-runtime"),Zr=Se.z.object({metrics:Se.z.array(Se.z.object({label:Se.z.string(),value:Se.z.union([Se.z.string(),Se.z.number()]),unit:Se.z.string().optional()}))});function nr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Qr(e){let{metrics:t}=nr(e);return(0,qe.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,qe.jsxs)("div",{className:"urun-metric-card",children:[(0,qe.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,qe.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var rt=require("react"),rn=require("react/jsx-runtime"),or=(0,rt.createContext)(null);function en({session:e,children:t}){return(0,rn.jsx)(or.Provider,{value:e,children:t})}function pe(){return(0,rt.useContext)(or)}function tn(){let e=(0,rt.useContext)(or);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 F=require("react");var nt=require("react/jsx-runtime"),oo=1e3;function so(...e){console.debug("[video]",...e)}var kt=(0,F.forwardRef)(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:m,videoClassName:d,placeholder:y,poster:k,children:f,onTrack:p,onFirstFrame:C}=t,S=pe(),A=o??S,b=(0,F.useRef)(null),x=(0,F.useRef)(null),[g,_]=(0,F.useState)(!1),[H,I]=(0,F.useState)(!1),M=(0,F.useRef)(!1),l=(0,F.useRef)(p);l.current=p;let E=(0,F.useRef)(C);E.current=C;let v=(0,F.useRef)(null),T=(0,F.useRef)(null),V=(0,F.useCallback)(h=>{if(h===v.current||(v.current=h,T.current?.(),T.current=null,M.current=!1,I(!1),!h))return;let P=b.current;if(!P)return;let L=()=>{T.current?.(),T.current=null,M.current=!0,I(!0),E.current?.()};if(typeof P.requestVideoFrameCallback=="function"){let K=P.requestVideoFrameCallback(L);T.current=()=>P.cancelVideoFrameCallback?.(K);return}let O=()=>{let K=P.getVideoPlaybackQuality?.();(K?K.totalVideoFrames>0:P.readyState>=2&&P.videoWidth>0)&&L()};P.addEventListener("loadeddata",O),P.addEventListener("timeupdate",O),P.addEventListener("playing",O),T.current=()=>{P.removeEventListener("loadeddata",O),P.removeEventListener("timeupdate",O),P.removeEventListener("playing",O)},O()},[]);(0,F.useEffect)(()=>()=>{T.current?.(),T.current=null},[]);let G=(0,F.useCallback)(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let h=b.current;return h&&h.srcObject!==x.current&&(h.srcObject=x.current),x.current},[]),U=(0,F.useCallback)(h=>{let P=b.current;if(!P)return;let L=P.play();!L||typeof L.catch!="function"||L.catch(O=>so(`play() failed (${h})`,O))},[]),R=(0,F.useCallback)(h=>{let P=G();if(P){for(let L of P.getVideoTracks())L!==h&&P.removeTrack(L);if(h&&!P.getVideoTracks().includes(h)){P.addTrack(h);let L=b.current;L&&(L.srcObject=P)}h&&U("track-attach"),_(h!==null),V(h),l.current?.(h)}},[G,U,V]),B=(0,F.useCallback)(h=>{b.current=h,h&&(i&&(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted","")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),G())},[G,i]);(0,F.useImperativeHandle)(r,()=>({get element(){return b.current},get live(){return x.current?x.current.getVideoTracks().length>0:!1},get framed(){return M.current}}),[]);let $=s!==void 0;return(0,F.useEffect)(()=>{if($){R(s??null);return}if(!A)return;let h=A.stream(n),P=()=>{let N=x.current;return N?N.getVideoTracks()[0]??null:null},L=N=>{if(N!==P()&&(R(N),N)){let J=()=>{P()===N&&R(null)};N.addEventListener("ended",J)}},O=h.track;O&&O.readyState==="live"&&L(O);let K=h.on("track",N=>{N&&N.readyState!=="live"||L(N)}),j=setInterval(()=>{let N=h.track;N&&N.readyState==="live"&&L(N)},oo);return()=>{K(),clearInterval(j)}},[A,n,$,s,R]),(0,nt.jsxs)("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...m},"data-urun-video":"","data-urun-video-live":g?"true":"false","data-urun-video-framed":H?"true":"false",children:[(0,nt.jsx)("video",{ref:B,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),g?null:y,k===void 0?null:(0,nt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":H||void 0,style:{position:"absolute",inset:0,...H?{opacity:0,pointerEvents:"none"}:null},children:k}),f]})});var nn=require("react");var sn=require("react/jsx-runtime"),on=(0,nn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,sn.jsx)(kt,{ref:r,stream:o,...n})});var W=require("react"),un=require("@urun-sh/core");var bt=null;function io(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function ot(){if(bt)return bt;let e=io();return e?(bt=new e,bt):null}function st(){let e=ot();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var ln=require("react/jsx-runtime"),ao=1e3,an=200;function sr(...e){console.debug("[audio]",...e)}var it=(0,W.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:m}=t,d=pe(),y=o??d,k=(0,W.useRef)(null),f=(0,W.useRef)(null),p=(0,W.useRef)(null),C=(0,W.useRef)(null),S=(0,W.useRef)(u);S.current=u;let A=(0,W.useRef)(c);A.current=c;let b=(0,W.useCallback)(l=>{p.current!==l&&(p.current=l,A.current?.(l))},[]),x=(0,W.useCallback)(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let l=k.current;return l&&l.srcObject!==f.current&&(l.srcObject=f.current),f.current},[]),g=(0,W.useCallback)(l=>{let E=k.current;if(!E)return;let v=E.play();!v||typeof v.then!="function"||v.then(()=>{E.muted||b(!0)}).catch(T=>{let V=T instanceof Error?T.name:String(T);if(V==="AbortError"){sr(`play() aborted (${l}); retrying in ${an}ms`),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,g(`${l}:retry`)},an);return}if(V==="NotAllowedError"){sr(`play() blocked pending a user gesture (${l})`),b(!1);return}sr(`play() failed (${l})`,T)})},[b]),_=(0,W.useCallback)(l=>{let E=x();if(E){for(let v of E.getAudioTracks())v!==l&&E.removeTrack(v);l&&!E.getAudioTracks().includes(l)&&E.addTrack(l),l&&g("track-attach"),S.current?.(l)}},[x,g]),H=(0,W.useCallback)(()=>{let l=k.current;l&&(x(),l.muted=!1,g("gesture"),st(),b(!0))},[x,g,b]);(0,W.useImperativeHandle)(r,()=>({unlock:H,get unlocked(){return p.current===!0},get element(){return k.current}}),[H]);let I=(0,W.useCallback)(l=>{k.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),x()),m?.(l)},[x,m]),M=s!==void 0;return(0,W.useEffect)(()=>{if(M){_(s??null);return}if(!y)return;let l=y.stream(n),E=()=>{let U=f.current;return U?U.getAudioTracks()[0]??null:null},v=U=>{if(U!==E()&&(_(U),U)){let R=()=>{E()===U&&_(null)};U.addEventListener("ended",R)}},T=l.track;T&&T.readyState==="live"&&v(T);let V=l.on("track",U=>{U&&U.readyState!=="live"||v(U)}),G=setInterval(()=>{let U=l.track;U&&U.readyState==="live"&&v(U)},ao);return()=>{V(),clearInterval(G)}},[y,n,M,s,_]),(0,W.useEffect)(()=>(0,un.observePageLifecycle)(()=>{st(),p.current===!0&&g("foreground")}),[g]),(0,W.useEffect)(()=>()=>{C.current&&clearTimeout(C.current)},[]),(0,ln.jsx)("audio",{ref:I,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),cn=it;var q=require("react"),He=require("@urun-sh/core");var pn=require("react/jsx-runtime"),ir={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Pt(...e){console.debug("[voice]",...e)}var at=(0,q.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=ir,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:m,onError:d,onMicStream:y,onTrack:k,onUnlockChange:f,capture:p}=t,C=pe(),S=o??C,A=(0,q.useRef)(null),b=(0,q.useRef)(null),x=(0,q.useRef)(null),g=(0,q.useRef)([]),_=(0,q.useRef)(!1),H=(0,q.useRef)(m);H.current=m;let I=(0,q.useRef)(d);I.current=d;let M=(0,q.useRef)(y);M.current=y;let l=(0,q.useCallback)(R=>{_.current!==R&&(_.current=R,H.current?.(R))},[]),E=(0,q.useCallback)(()=>{for(let R of g.current)R();g.current=[],x.current?.release(),x.current=null,b.current&&(b.current=null,M.current?.(null))},[]),v=(0,q.useCallback)(async()=>{let R=x.current;if(R){let P=await R.update(i);return b.current=R.stream,M.current?.(R.stream),P}let $=await(p??(0,He.sharedCaptureController)()).claim("audio",i);x.current=$,g.current=[$.onTrack((P,L)=>{b.current=L,M.current?.(L),_.current&&S?.stream(n).attach(P).catch(O=>Pt("mic re-attach after one-capture re-acquire failed",O))}),$.onLost(P=>{x.current=null,g.current=[],b.current=null,M.current?.(null),l(!1),I.current?.(P)})],b.current=$.stream,M.current?.($.stream);let h=$.track;if(!h)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return h},[p,i,S,n,l]),T=(0,q.useCallback)(async()=>{E(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,E,l]),V=(0,q.useCallback)(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");A.current?.unlock();let R;try{R=await v()}catch(h){E();let P=(0,He.sessionFailureFromMediaError)(h,S.status);throw I.current?.(P),P}S.connect?.();let B;for(let h=1;h<=u;h++)try{await S.whenLive(a!==void 0?{timeout:a}:void 0),await S.stream(n).attach(R),l(!0);return}catch(P){B=P,Pt(`start attempt ${h}/${u} failed`,P),h<u&&await new Promise(L=>setTimeout(L,c))}E(),l(!1);let $=B instanceof Error?B:new Error(String(B??"voice start failed"));throw I.current?.($),$},[S,n,a,u,c,v,E,l]);(0,q.useImperativeHandle)(r,()=>({start:V,stop:T,unlock:()=>A.current?.unlock(),get active(){return _.current},get micStream(){return b.current},get audio(){return A.current}}),[V,T]);let G=(0,q.useRef)(!1),U=(0,q.useCallback)(async()=>{if(!S||!_.current||G.current)return;let R=b.current?.getAudioTracks()[0]??null;if(R&&R.readyState==="live"){try{await S.stream(n).attach(R)}catch(B){Pt("foreground mic re-assert failed (will retry on next pass)",B)}return}G.current=!0;try{let B=await v();await S.stream(n).attach(B)}catch(B){let $=B instanceof Error?B:new Error(String(B));Pt("foreground mic re-acquire failed",$),I.current?.($)}finally{G.current=!1}},[S,n,v]);return(0,q.useEffect)(()=>{let R=()=>{U()};return S&&typeof S.onRecovery=="function"?S.onRecovery(R):(0,He.observePageLifecycle)(R)},[S,U]),(0,q.useEffect)(()=>E,[E]),s?(0,pn.jsx)(it,{ref:A,session:S,stream:n,onTrack:k,onUnlockChange:f}):null}),dn=at;var le=require("react");var Ct=require("react");var ar={level:0,speaking:!1};function xt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,Ct.useState)(ar);return(0,Ct.useEffect)(()=>{if(!e){i(ar);return}let a=ot();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,m;try{c=a.createMediaStreamSource(u),m=a.createAnalyser(),m.fftSize=r,c.connect(m)}catch{return}let d=new Uint8Array(m.fftSize),k=setInterval(()=>{m.getByteTimeDomainData(d);let f=0;for(let C=0;C<d.length;C++){let S=(d[C]-128)/128;f+=S*S}let p=Math.sqrt(f/d.length);i(C=>{let S=p>n;return Math.abs(C.level-p)<.005&&C.speaking===S?C:{level:p,speaking:S}})},o);return()=>{clearInterval(k),c.disconnect(),i(ar)}},[e,r,o,n]),s}var he=require("react/jsx-runtime"),uo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},co={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},mn=(0,le.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:m,onMicStream:d,capture:y}=t,k=pe(),f=o??k,p=(0,le.useRef)(null),[C,S]=(0,le.useState)(null),A=(0,le.useRef)(d);A.current=d;let{level:b,speaking:x}=xt(a?C:null);return(0,le.useImperativeHandle)(r,()=>({start:()=>{let g=p.current;return g?g.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),(0,le.useEffect)(()=>{!i||!f||p.current?.start().catch(()=>{})},[i,f]),(0,he.jsxs)(he.Fragment,{children:[(0,he.jsx)(at,{ref:p,session:f,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:m,onMicStream:g=>{S(g),A.current?.(g)}}),a?(0,he.jsx)("span",{className:u,style:uo,"data-urun-mic":"","data-urun-mic-active":C?"true":"false","data-urun-mic-speaking":x?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(b*100)/100,children:(0,he.jsx)("span",{style:co,children:(0,he.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(b*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var Tt=require("@urun-sh/core"),w=require("react");var ae=require("react/jsx-runtime"),cr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function ur(...e){console.debug("[camera]",...e)}function lo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function po(){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 lr=(0,w.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:m="auto",connectTimeoutMs:d,visible:y=!1,className:k,videoClassName:f,onActiveChange:p,onError:C,onStream:S,onTrack:A,children:b,capture:x,flipControl:g="auto",flipControlClassName:_,onDevices:H}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let I=i?"user":a?"environment":u??"environment",M=pe(),l=o??M,E=(0,w.useRef)(null),v=(0,w.useRef)(null),T=(0,w.useRef)(null),V=(0,w.useRef)([]),G=(0,w.useRef)(null),U=(0,w.useRef)(!1),R=(0,w.useRef)(I),[B,$]=(0,w.useState)(I),[h,P]=(0,w.useState)(!1),[L,O]=(0,w.useState)(null),[K,j]=(0,w.useState)(!1),[N]=(0,w.useState)(lo),J=(0,w.useRef)(p);J.current=p;let ne=(0,w.useRef)(C);ne.current=C;let ee=(0,w.useRef)(S);ee.current=S;let me=(0,w.useRef)(A);me.current=A;let dt=(0,w.useRef)(H);dt.current=H;let ke=(0,w.useCallback)(D=>{U.current!==D&&(U.current=D,P(D),J.current?.(D))},[]);(0,w.useEffect)(()=>{if(!h){O(null);return}let D=!1,z=()=>{po().then(ie=>{D||(O(ie),ie&&dt.current?.(ie))})};z();let te=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof te?.addEventListener=="function"?(te.addEventListener("devicechange",z),()=>{D=!0,te.removeEventListener?.("devicechange",z)}):()=>{D=!0}},[h]);let pt=(0,w.useCallback)(D=>{let z=E.current;z&&(z.muted=!0,z.defaultMuted=!0,z.setAttribute("muted",""),z.setAttribute("playsinline",""),z.setAttribute("webkit-playsinline",""),z.srcObject=D,D&&z.play()?.catch?.(te=>ur("preview play() failed",te)))},[]),fe=(0,w.useCallback)(()=>{G.current?.(),G.current=null;for(let D of V.current)D();V.current=[],T.current?.release(),T.current=null,v.current&&(v.current=null,ee.current?.(null),me.current?.(null)),pt(null)},[pt]),Bt=(0,w.useCallback)((D,z)=>{G.current?.(),v.current=z,pt(z),ee.current?.(z);let te=()=>{v.current===z&&(ur("camera track ended (device removed or permission revoked)"),fe(),ke(!1))};D.addEventListener("ended",te),G.current=()=>D.removeEventListener("ended",te)},[pt,fe,ke]),_e=(0,w.useCallback)(async D=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let z={...cr,...s,facingMode:D},te;try{let ie=T.current;if(ie)te=await ie.update(z);else{let Je=await(x??(0,Tt.sharedCaptureController)()).claim("video",z);if(T.current=Je,V.current=[Je.onTrack((ze,Vn)=>{Bt(ze,Vn),U.current&&l.stream(n).attachVideo(ze).then(()=>me.current?.(ze)).catch(Fn=>ur("camera re-publish after one-capture re-acquire failed",Fn))}),Je.onLost(ze=>{T.current=null,V.current=[],fe(),ke(!1),ne.current?.(ze)})],!Je.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});te=Je.track}}catch(ie){let Ne=(0,Tt.sessionFailureFromMediaError)(ie,l.status);throw ne.current?.(Ne),Ne}R.current=D,$(D),Bt(te,T.current?.stream??new MediaStream([te]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(te)}catch(ie){fe(),ke(!1);let Ne=ie instanceof Error?ie:new Error(String(ie));throw ne.current?.(Ne),Ne}me.current?.(te),ke(!0)},[l,n,s,d,x,Bt,fe,ke]),fr=(0,w.useCallback)(D=>_e(D?.facingMode??R.current),[_e]),mt=(0,w.useCallback)(async D=>{U.current&&R.current===D||await _e(D)},[_e]),$t=(0,w.useCallback)(()=>_e(R.current==="environment"?"user":"environment"),[_e]),gr=(0,w.useCallback)(async()=>{fe(),ke(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,fe,ke]);(0,w.useImperativeHandle)(r,()=>({start:fr,stop:gr,flip:$t,setFacingMode:mt,get active(){return U.current},get facingMode(){return R.current},get stream(){return v.current},get element(){return E.current}}),[fr,gr,$t,mt]);let Sr=(0,w.useRef)(mt);if(Sr.current=mt,(0,w.useEffect)(()=>{!c||!l||Sr.current(I).catch(()=>{})},[c,l,I]),(0,w.useEffect)(()=>fe,[fe]),!y)return null;let Ln=m==="auto"?B==="user":m,On=h&&(g===!0||g==="auto"&&N&&(L?.length??0)>1),Dn=()=>{K||(j(!0),$t().catch(()=>{}).finally(()=>j(!1)))};return(0,ae.jsxs)("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":B,children:[(0,ae.jsx)("video",{ref:E,className:f,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ln?{transform:"scaleX(-1)"}:{}}}),On?(0,ae.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Dn,disabled:K,className:_,style:_?{opacity:K?.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:K?.6:1},children:(0,ae.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,ae.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ae.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ae.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ae.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ae.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,b]})}),fn=(0,w.forwardRef)(function({preview:t=!0,...r},o){return(0,ae.jsx)(lr,{ref:o,...r,visible:t,autoStart:!1})});var Et=require("react");function gn(e,t){let[r,o]=(0,Et.useState)(null);return(0,Et.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var vn=require("react");var Rt=require("react");var Sn=require("zustand/vanilla"),hn=require("zustand"),mo=()=>{};function wt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,Sn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):mo,u=(c=>(0,hn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function We(e,t){let r=(0,Rt.useMemo)(()=>wt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Rt.useEffect)(()=>r.bind(),[r]),r}function yn(e,t,r){let n=We(e,t)(r??(a=>a)),s=(0,vn.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 Ut=require("react");var Pe=200;function ve(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Be(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(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 Mt(e,t,r={}){let o=r.cap??200,[n,s]=(0,Ut.useState)([]);return(0,Ut.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ve(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var de=require("react/jsx-runtime");function kn({session:e,name:t,cap:r,className:o}){let n=Mt(e,t,{cap:r});return(0,de.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,de.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,de.jsx)("code",{children:t}),(0,de.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,de.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,de.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,de.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,de.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,de.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Be(s.payload)]},`${s.at}-${i}`))})]})}var ut=require("react");var se=require("react/jsx-runtime");function ct({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,ut.useState)(""),[i,a]=(0,ut.useState)(null),u=(0,ut.useCallback)(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.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:c=>s(c.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:u,children:t}),i?(0,se.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function bn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=We(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.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)(ct,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var _t=require("react");var ye=require("react/jsx-runtime");function Pn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Cn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,_t.useState)([]);return(0,_t.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ve(u,{at:Date.now(),direction:"in",text:Pn(Be(a))},r))}):void 0),[e,t,r]),(0,ye.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,ye.jsx)(ct,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ve(u,{at:Date.now(),direction:"out",text:Pn(a)},r))}}),(0,ye.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,ye.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,ye.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,ye.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,ye.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Nt=require("react");var Ue=require("react/jsx-runtime");function xn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Nt.useState)([]),a=t.join(","),u=r.join(",");return(0,Nt.useEffect)(()=>{if(i([]),!e)return;let c=(d,y)=>i(k=>ve(k,{at:Date.now(),kind:d,text:y},o)),m=[];m.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let y=e.stream(d);m.push(y.on("track",k=>c("track",`${d}: ${k?"track arrived":"track ended"}`)))}for(let d of r){let y=e.doc(d);m.push(y.on("change",()=>c("doc",`${d} changed`)))}return()=>m.forEach(d=>d())},[e,a,u,o]),(0,Ue.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Ue.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((c,m)=>(0,Ue.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Ue.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Ue.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${m}`))})}var qt=require("@urun-sh/core");var It=require("react");function ue(e){let[t,r]=(0,It.useState)(e?.phase??null);return(0,It.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var En=require("@urun-sh/core");var $e=require("react"),Tn=require("@urun-sh/core");function Lt(e){let t=ue(e),r=(0,Tn.isWakingPhase)(t?.name),o=(0,$e.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,$e.useState)(s);return(0,$e.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[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 Ce=require("react/jsx-runtime");function Ot({session:e,render:t,className:r}){let o=Lt(e);return!o.waking||!o.phase?null:(0,Ce.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,Ce.jsxs)(Ce.Fragment,{children:[(0,Ce.jsx)("span",{className:"urun-session-waking-label",children:(0,En.describeSessionPhase)(o.phase)})," ",(0,Ce.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var Vt=require("react");var xe=require("react"),fo={event:null,elapsedMs:0};function Dt(e,t){let[r,o]=(0,xe.useState)(null),n=(0,xe.useRef)(0);(0,xe.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,xe.useState)(0);return(0,xe.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:fo}var Ke=require("react/jsx-runtime"),go={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 So(e){let[t,r]=(0,Vt.useState)(!1);return(0,Vt.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 Ft({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Dt(e,t),i=So(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,Ke.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,Ke.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,Ke.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??go[u]})," ",(0,Ke.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var ce=require("react/jsx-runtime"),ho={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function wn({session:e,className:t}){let r=ue(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.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:ho[o]}),n?(0,ce.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function Rn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ue(e);if(s?.name==="live")return(0,ce.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,ce.jsx)(Ft,{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?.name==="ended"?"Session ended.":s&&(0,qt.isWakingPhase)(s.name)?(0,ce.jsx)(Ot,{session:e}):s&&s.name!=="idle"?(0,qt.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");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 Ht=require("react");var Un=require("react/jsx-runtime");function dr(e){return ue(e)?.endsAt??null}function vo(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 An({session:e,urgentMs:t=6e4,className:r}){let n=dr(e)?.getTime()??null,[s,i]=(0,Ht.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,Ht.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=vo(s);return(0,Un.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 lt=require("react/jsx-runtime"),yo=new Set(["expired","ended","error"]);function Mn({session:e,onNewSession:t,children:r,className:o}){let n=ue(e);if(!n||!yo.has(n.name))return null;let s=r?r(n):(0,lt.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,lt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,lt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var Te=require("react"),Me=require("react/jsx-runtime");function pr(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 mr(e){let t=(0,Te.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,Te.useState)(()=>t?pr(t.get("idle")):null);return(0,Te.useEffect)(()=>{if(!t){o(null);return}return o(pr(t.get("idle"))),t.on("change",()=>o(pr(t.get("idle"))))},[t]),r}function ko(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function _n({session:e,onStillHere:t,className:r}){let o=mr(e),n=o?.deadlineEpochS??null,[s,i]=(0,Te.useState)(null);if((0,Te.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,Me.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,Me.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Me.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Me.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${ko(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Me.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var je=require("react"),Nn=require("@urun-sh/core");function In(e){let t=(0,je.useContext)(Le),[r,o]=(0,je.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,m=t?.getAccessToken,d=t?.authProvider;return(0,je.useEffect)(()=>{if(!a||!u||!n||!s)return;let y=!1,k=()=>{(0,Nn.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:m,authProvider:d}).then(p=>{y||o(p)}).catch(()=>{})};k();let f=setInterval(k,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(f)}},[n,s,i,a,u,c,m,d]),r}var Wt=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,Session,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
import{a as Br,b as $r,c as nt}from"./chunk-WF2OBDSX.mjs";import{useCallback as rn,useEffect as jt,useMemo as nn,useRef as Kt,useState as Oe}from"react";import{Component as jr}from"react";import{jsx as Ft,jsxs as Kr}from"react/jsx-runtime";var we=class extends jr{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||Kr("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:[Ft("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Ft("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Jr}from"react";var Se=Jr(null);function ue(e){return e&&e.trim()?e.trim():void 0}function ne(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ue(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ue(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ue(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ue(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ue(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ue(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ue(typeof process<"u"?process.env?.[e]:void 0)}}function Le(){let e=ne("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||ne("VERCEL_ENV")==="production"?"workos":ne("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function zr(){return Le()==="workos"}import{useEffect as Xr,useRef as Gr}from"react";var Yr="urun.operator_token",Wt=null,Ht="op",Zr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Bt(){return typeof window<"u"}function $t(){return Wt}function Qr(){if(!Bt())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(Ht);if(!r)return null;Wt=r,t.delete(Ht);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function en(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function ot(e){let t=Gr(e);t.current=e,Xr(()=>{if(!Bt())return;Qr();let r=o=>{if(!en(o))return;let n=$t();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as tn}from"react";function st(e=!0){tn(()=>{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 xe,jsxs as un}from"react/jsx-runtime";var on="/api/urun-token";async function Jt(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function sn(e,t){return typeof e=="function"?e(t):e!==void 0?e:un("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[xe("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),xe("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function an({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:g=!1,fallback:d,errorFallback:k,children:P}){let S=n===void 0&&t===void 0;if(!S&&(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(!S&&(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 p=r??o;if(S&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);st(g);let[C,h]=Oe(),[w,x]=Oe(),[T,v]=Oe(null),R=Kt(void 0),N=Kt(null),[A,U]=Oe(null);ot(q=>U({jwt:q}));let l=nt(),m=ne("NEXT_PUBLIC_SESSION_TOKEN")??ne("NEXT_PUBLIC_URUN_JWT"),f=Le(),b=A!==null,M=f==="workos"&&!n&&!b&&!S,H=n??(f==="jwt"?m:void 0)??C??w?.token,E=b?A.jwt:H,y=s??ne("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),I=M&&!E,O=t??w?.orgId,D=e??w?.gatewayUrl,F=S&&w===void 0,G=S&&w!==void 0&&!D?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,J=T??G,B=u??on,V=rn(async q=>q?.forceRefresh?(await(N.current??(N.current=(async()=>{try{let Y=await Jt(B);return R.current=Y.token,x(Y),Y}finally{N.current=null}})()))).token:R.current,[B]),z=nn(()=>({appId:p,baseUrl:D??"",orgId:O??"",jwt:E,getAccessToken:M?l?.getAccessToken:S&&!b?V:void 0,authProvider:y,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:b?"preempt":void 0}),[p,l,D,y,E,i,O,a,c,M,b,S,V]);return jt(()=>{if(!S)return;let q=new AbortController;return v(null),(async()=>{try{let $=await Jt(B,q.signal);R.current=$.token,x($)}catch($){if(q.signal.aborted)return;v($ instanceof Error?$:new Error(String($)))}})(),()=>q.abort()},[S,B]),jt(()=>{if(!M||!l)return;let q=!1,$=l;async function Y(){try{let _e=await $.getAccessToken();q||h(_e??void 0)}catch{q||h(void 0)}}Y();let me=window.setInterval(()=>{Y()},6e4);return()=>{q=!0,window.clearInterval(me)}},[l,M]),xe(we,{fallback:d,children:J?sn(k,J):I||F?xe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):xe(Se.Provider,{value:z,children:P})})}import{useContext as cn,useEffect as ln,useMemo as zt,useReducer as dn,useRef as it}from"react";import{App as pn}from"@urun-sh/core";function mn(e,t){return`${e}:${JSON.stringify(t??{})}`}function fn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var ce=new Map;var at=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()})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},ut=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},ct=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"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}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()}doc(t){let r=this._docs.get(t);return r||(r=new at(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}disconnect(){this._disposeHandle(),this._session.disconnect()}_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 gn(){let e=cn(Se);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=dn(i=>i+1,0),r=it(new Map),o=it(new Map),n=it(null),s=zt(()=>pn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return ln(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=ce.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=ce.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let d=ce.get(u);!d||d.refCount!==0||(ce.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),zt(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=d=>{let k=mn(u,d),P=r.current.get(k);if(P&&!P.disposed)return P;let S=fn(e,u,d),p=ce.get(S);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),ce.delete(S),o.current.get(S)===p&&o.current.delete(S),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new ct(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},ce.set(S,p)),o.current.get(S)!==p&&(o.current.set(S,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(k,p.handle),p.handle};return i.set(u,g),g}})},[e,s])}import{useCallback as lt,useEffect as Sn,useMemo as hn,useRef as De,useState as dt}from"react";function he(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 vn(e){return e instanceof Error?e:new Error(String(e))}function yn(e,t){let r=hn(()=>he(e),[e]),[o,n]=dt(void 0),[s,i]=dt(null),[a,u]=dt(!1),c=De(t);c.current=t;let g=De(0),d=De(null),k=De(!0);Sn(()=>(k.current=!0,()=>{k.current=!1,d.current?.abort()}),[]);let P=lt(async C=>{d.current?.abort();let h=new AbortController;d.current=h;let w=++g.current,x=()=>k.current&&g.current===w;x()&&(u(!0),i(null));try{let T=await r.request(C,{...c.current,signal:h.signal});return x()&&(n(T),u(!1),c.current?.onSuccess?.(T)),T}catch(T){let v=vn(T);throw x()&&(i(v),u(!1),c.current?.onError?.(v)),v}},[r]),S=lt(C=>{P(C).catch(()=>{})},[P]),p=lt(()=>{g.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:S,mutateAsync:P,data:o,error:s,isPending:a,reset:p}}import{useCallback as Xt,useEffect as kn,useMemo as bn,useRef as Ve,useState as pt}from"react";function Gt(e){return e instanceof Error?e:new Error(String(e))}var Pn=e=>typeof e=="string"?e:String(e);function Cn(e,t){let r=bn(()=>he(e),[e]),[o,n]=pt(""),[s,i]=pt(!1),[a,u]=pt(null),c=Ve(t);c.current=t;let g=Ve(0),d=Ve(null),k=Ve(!0);kn(()=>(k.current=!0,()=>{k.current=!1,d.current?.cancel(),d.current=null}),[]);let P=Xt(()=>{g.current++,d.current?.cancel(),d.current=null,k.current&&i(!1)},[]),S=Xt(async p=>{d.current?.cancel();let C=++g.current,h=()=>k.current&&g.current===C,w=c.current,x=w?.parseChunk??Pn,T=w?.buildPayload??(f=>({prompt:f}));h()&&(n(""),u(null),i(!0));let{parseChunk:v,buildPayload:R,onFinish:N,onError:A,...U}=w??{},l="",m;try{m=r.requestStream(T(p),U),d.current=m}catch(f){let b=Gt(f);h()&&(u(b),i(!1),w?.onError?.(b));return}try{for await(let f of m){if(g.current!==C)break;l+=x(f),h()&&n(l)}h()&&(i(!1),w?.onFinish?.(l))}catch(f){let b=Gt(f);h()&&(u(b),i(!1),w?.onError?.(b))}finally{d.current===m&&(d.current=null)}},[r]);return{completion:o,complete:S,stop:P,isStreaming:s,error:a}}import{useCallback as Yt,useEffect as wn,useMemo as xn,useRef as ve,useState as qe}from"react";function Zt(e){return e instanceof Error?e:new Error(String(e))}var Tn=e=>typeof e=="string"?e:String(e),Qt=0;function mt(e){return Qt+=1,`${e}-${Qt}`}function En(e,t){let r=xn(()=>he(e),[e]),[o,n]=qe(()=>(t?.initialMessages??[]).map(x=>({id:x.id??mt("msg"),role:x.role,content:x.content}))),[s,i]=qe(""),[a,u]=qe(!1),[c,g]=qe(null),d=ve(t);d.current=t;let k=ve(o);k.current=o;let P=ve(s);P.current=s;let S=ve(0),p=ve(null),C=ve(!0);wn(()=>(C.current=!0,()=>{C.current=!1,p.current?.cancel(),p.current=null}),[]);let h=Yt(()=>{S.current++,p.current?.cancel(),p.current=null,C.current&&u(!1)},[]),w=Yt(async x=>{let T=x===void 0,v=(T?P.current:x)??"";if(!v.trim())return;p.current?.cancel();let N=++S.current,A=()=>C.current&&S.current===N,U=d.current,l=U?.parseChunk??Tn,m={id:mt("msg"),role:"user",content:v},f={id:mt("msg"),role:"assistant",content:""},b=[...k.current,m].map(V=>({role:V.role,content:V.content})),M=[...k.current,m,f];k.current=M,n(M),T&&i(""),g(null),u(!0);let H=U?.buildPayload??(V=>({messages:V})),{initialMessages:E,parseChunk:y,buildPayload:I,onFinish:O,onError:D,...F}=U??{},G=V=>{n(z=>z.map(q=>q.id===f.id?{...q,content:V}:q))},J="",B;try{B=r.requestStream(H(b),F),p.current=B}catch(V){let z=Zt(V);A()&&(g(z),u(!1),U?.onError?.(z));return}try{for await(let V of B){if(S.current!==N)break;J+=l(V),A()&&G(J)}A()&&(u(!1),U?.onFinish?.({...f,content:J}))}catch(V){let z=Zt(V);A()&&(g(z),u(!1),U?.onError?.(z))}finally{p.current===B&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:w,stop:h,isStreaming:a,error:c}}import{useCallback as oe,useEffect as er,useMemo as Rn,useRef as tr,useState as rr}from"react";import{createInputPresencePublisher as An,INPUT_PRESENCE_DEFAULT_HZ as Un,INPUT_PRESENCE_FIELD as Mn}from"@urun-sh/core";var ft=[];function _n(e,t={}){let{field:r=Mn,hz:o=Un}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=Rn(()=>s?An({awareness:{setLocalStateField:(v,R)=>s.setField(v,R)},field:r,hz:o}):null,[s,r,o]),a=tr(null);a.current=i;let[u,c]=rr(!1),[g,d]=rr(ft),k=tr(!1);er(()=>{if(i)return()=>i.dispose()},[i]);let P=oe(()=>{let v=a.current;d(v?v.heldKeys():ft)},[]),S=oe(()=>{a.current?.clear(),d(ft)},[]);er(()=>{if(!n)return;let v=()=>!!n.pointerLockElement,R=()=>{if(v()){k.current=!1,c(!0);return}k.current||(c(!1),S())},N=f=>{v()&&(a.current?.keyDown(f.key),P())},A=f=>{a.current?.keyUp(f.key),P()},U=f=>{v()&&a.current?.movePointer(f.movementX,f.movementY)},l=f=>{v()&&a.current?.setButtons(f.buttons)},m=()=>{S()};return n.addEventListener("pointerlockchange",R),n.addEventListener("keydown",N),n.addEventListener("keyup",A),n.addEventListener("mousemove",U),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",m),()=>{n.removeEventListener("pointerlockchange",R),n.removeEventListener("keydown",N),n.removeEventListener("keyup",A),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",m)}},[n,S,P]);let p=oe(v=>{v.requestPointerLock?.()},[]),C=oe(()=>{k.current=!0,c(!0)},[]),h=oe(()=>{k.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),S()},[n,S]),w=oe(v=>{a.current?.keyDown(v),P()},[P]),x=oe(v=>{a.current?.keyUp(v),P()},[P]),T=oe((v,R)=>{a.current?.movePointer(v,R)},[]);return{engage:p,engageTouch:C,release:h,engaged:u,heldKeys:g,pressKey:w,releaseKey:x,movePointer:T}}var nr=new Map;function Nn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);nr.set(e,{component:t,schema:r})}function or(e,t){let r=nr.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 Ln,jsx as Fe}from"react/jsx-runtime";function In({name:e,props:t,fallback:r}){let o=or(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?Fe(Ln,{children:r}):Fe("div",{className:"urun-component-error",role:"alert",children:Fe("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return Fe(n,{...o.validatedProps})}import{z as Te}from"zod";import{jsx as gt,jsxs as sr}from"react/jsx-runtime";var On=Te.object({step:Te.number().min(0),total:Te.number().min(1),label:Te.string().optional(),variant:Te.enum(["default","success","error"]).default("default")});function ir(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 Dn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=ir(e);return sr("div",{className:"urun-progress-card","data-variant":n,children:[o&>("div",{className:"urun-progress-label",children:o}),gt("div",{className:"urun-progress-bar",children:gt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),sr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as St}from"zod";import{jsx as ar,jsxs as Hn}from"react/jsx-runtime";var Vn=St.object({state:St.enum(["thinking","generating","idle","error"]),message:St.string().optional()}),qn={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function ur(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??qn[t]??t;return{state:t,message:n,isActive:o}}function Fn(e){let{state:t,message:r,isActive:o}=ur(e);return Hn("span",{className:"urun-status-badge","data-state":t,children:[ar("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),ar("span",{className:"urun-status-message",children:r})]})}import{useRef as cr,useEffect as Wn}from"react";import{z as ht}from"zod";import{jsx as lr,jsxs as jn}from"react/jsx-runtime";var Bn=ht.object({text:ht.string(),streaming:ht.boolean().default(!1)});function dr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function $n(e){let{text:t,streaming:r}=dr(e),o=cr(null),n=cr(0);return Wn(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),jn("div",{className:"urun-text-stream",children:[lr("span",{ref:o,className:"urun-text-content"}),r&&lr("span",{className:"urun-text-cursor"})]})}import{z as He}from"zod";import{jsx as pr,jsxs as zn}from"react/jsx-runtime";var Kn=He.object({src:He.string().url(),alt:He.string().optional(),caption:He.string().optional()});function mr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Jn(e){let{src:t,alt:r,caption:o}=mr(e);return zn("figure",{className:"urun-image-frame",children:[pr("img",{className:"urun-image",src:t,alt:r}),o&&pr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as se}from"zod";import{jsx as vt,jsxs as Yn}from"react/jsx-runtime";var Xn=se.object({metrics:se.array(se.object({label:se.string(),value:se.union([se.string(),se.number()]),unit:se.string().optional()}))});function fr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Gn(e){let{metrics:t}=fr(e);return vt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>Yn("div",{className:"urun-metric-card",children:[vt("div",{className:"urun-metric-label",children:r.label}),vt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as Zn,useContext as gr}from"react";import{jsx as to}from"react/jsx-runtime";var yt=Zn(null);function Qn({session:e,children:t}){return to(yt.Provider,{value:e,children:t})}function Z(){return gr(yt)}function eo(){let e=gr(yt);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{forwardRef as ro,useCallback as We,useEffect as no,useImperativeHandle as oo,useRef as kt,useState as so}from"react";import{jsx as uo,jsxs as co}from"react/jsx-runtime";var io=1e3;function ao(...e){console.debug("[video]",...e)}var bt=ro(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:g,videoClassName:d,placeholder:k,children:P,onTrack:S}=t,p=Z(),C=o??p,h=kt(null),w=kt(null),[x,T]=so(!1),v=kt(S);v.current=S;let R=We(()=>{if(typeof MediaStream>"u")return null;w.current||(w.current=new MediaStream);let m=h.current;return m&&m.srcObject!==w.current&&(m.srcObject=w.current),w.current},[]),N=We(m=>{let f=h.current;if(!f)return;let b=f.play();!b||typeof b.catch!="function"||b.catch(M=>ao(`play() failed (${m})`,M))},[]),A=We(m=>{let f=R();if(f){for(let b of f.getVideoTracks())b!==m&&f.removeTrack(b);if(m&&!f.getVideoTracks().includes(m)){f.addTrack(m);let b=h.current;b&&(b.srcObject=f)}m&&N("track-attach"),T(m!==null),v.current?.(m)}},[R,N]),U=We(m=>{h.current=m,m&&(i&&(m.muted=!0,m.defaultMuted=!0,m.setAttribute("muted","")),m.setAttribute("playsinline",""),m.setAttribute("webkit-playsinline",""),R())},[R,i]);oo(r,()=>({get element(){return h.current},get live(){return w.current?w.current.getVideoTracks().length>0:!1}}),[]);let l=s!==void 0;return no(()=>{if(l){A(s??null);return}if(!C)return;let m=C.stream(n),f=()=>{let y=w.current;return y?y.getVideoTracks()[0]??null:null},b=y=>{if(y!==f()&&(A(y),y)){let I=()=>{f()===y&&A(null)};y.addEventListener("ended",I)}},M=m.track;M&&M.readyState==="live"&&b(M);let H=m.on("track",y=>{y&&y.readyState!=="live"||b(y)}),E=setInterval(()=>{let y=m.track;y&&y.readyState==="live"&&b(y)},io);return()=>{H(),clearInterval(E)}},[C,n,l,s,A]),co("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...g},"data-urun-video":"","data-urun-video-live":x?"true":"false",children:[uo("video",{ref:U,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),x?null:k,P]})});import{forwardRef as lo}from"react";import{jsx as mo}from"react/jsx-runtime";var po=lo(function(t,r){let{stream:o="image",...n}=t;return mo(bt,{ref:r,stream:o,...n})});import{forwardRef as go,useCallback as ye,useEffect as Pt,useImperativeHandle as So,useRef as ke}from"react";import{observePageLifecycle as ho}from"@urun-sh/core";var Be=null;function fo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function $e(){if(Be)return Be;let e=fo();return e?(Be=new e,Be):null}function je(){let e=$e();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as ko}from"react/jsx-runtime";var vo=1e3,Sr=200;function Ct(...e){console.debug("[audio]",...e)}var Ke=go(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,d=Z(),k=o??d,P=ke(null),S=ke(null),p=ke(null),C=ke(null),h=ke(u);h.current=u;let w=ke(c);w.current=c;let x=ye(l=>{p.current!==l&&(p.current=l,w.current?.(l))},[]),T=ye(()=>{if(typeof MediaStream>"u")return null;S.current||(S.current=new MediaStream);let l=P.current;return l&&l.srcObject!==S.current&&(l.srcObject=S.current),S.current},[]),v=ye(l=>{let m=P.current;if(!m)return;let f=m.play();!f||typeof f.then!="function"||f.then(()=>{m.muted||x(!0)}).catch(b=>{let M=b instanceof Error?b.name:String(b);if(M==="AbortError"){Ct(`play() aborted (${l}); retrying in ${Sr}ms`),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,v(`${l}:retry`)},Sr);return}if(M==="NotAllowedError"){Ct(`play() blocked pending a user gesture (${l})`),x(!1);return}Ct(`play() failed (${l})`,b)})},[x]),R=ye(l=>{let m=T();if(m){for(let f of m.getAudioTracks())f!==l&&m.removeTrack(f);l&&!m.getAudioTracks().includes(l)&&m.addTrack(l),l&&v("track-attach"),h.current?.(l)}},[T,v]),N=ye(()=>{let l=P.current;l&&(T(),l.muted=!1,v("gesture"),je(),x(!0))},[T,v,x]);So(r,()=>({unlock:N,get unlocked(){return p.current===!0},get element(){return P.current}}),[N]);let A=ye(l=>{P.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),T()),g?.(l)},[T,g]),U=s!==void 0;return Pt(()=>{if(U){R(s??null);return}if(!k)return;let l=k.stream(n),m=()=>{let E=S.current;return E?E.getAudioTracks()[0]??null:null},f=E=>{if(E!==m()&&(R(E),E)){let y=()=>{m()===E&&R(null)};E.addEventListener("ended",y)}},b=l.track;b&&b.readyState==="live"&&f(b);let M=l.on("track",E=>{E&&E.readyState!=="live"||f(E)}),H=setInterval(()=>{let E=l.track;E&&E.readyState==="live"&&f(E)},vo);return()=>{M(),clearInterval(H)}},[k,n,U,s,R]),Pt(()=>ho(()=>{je(),p.current===!0&&v("foreground")}),[v]),Pt(()=>()=>{C.current&&clearTimeout(C.current)},[]),ko("audio",{ref:A,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),yo=Ke;import{forwardRef as bo,useCallback as be,useEffect as hr,useImperativeHandle as Po,useRef as ee}from"react";import{observePageLifecycle as Co,sessionFailureFromMediaError as wo,sharedCaptureController as xo}from"@urun-sh/core";import{jsx as Eo}from"react/jsx-runtime";var vr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Je(...e){console.debug("[voice]",...e)}var ze=bo(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=vr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:d,onMicStream:k,onTrack:P,onUnlockChange:S,capture:p}=t,C=Z(),h=o??C,w=ee(null),x=ee(null),T=ee(null),v=ee([]),R=ee(!1),N=ee(g);N.current=g;let A=ee(d);A.current=d;let U=ee(k);U.current=k;let l=be(y=>{R.current!==y&&(R.current=y,N.current?.(y))},[]),m=be(()=>{for(let y of v.current)y();v.current=[],T.current?.release(),T.current=null,x.current&&(x.current=null,U.current?.(null))},[]),f=be(async()=>{let y=T.current;if(y){let F=await y.update(i);return x.current=y.stream,U.current?.(y.stream),F}let O=await(p??xo()).claim("audio",i);T.current=O,v.current=[O.onTrack((F,G)=>{x.current=G,U.current?.(G),R.current&&h?.stream(n).attach(F).catch(J=>Je("mic re-attach after one-capture re-acquire failed",J))}),O.onLost(F=>{T.current=null,v.current=[],x.current=null,U.current?.(null),l(!1),A.current?.(F)})],x.current=O.stream,U.current?.(O.stream);let D=O.track;if(!D)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return D},[p,i,h,n,l]),b=be(async()=>{m(),l(!1),await h?.stream(n).detach().catch(()=>{})},[h,n,m,l]),M=be(async()=>{if(!h)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");w.current?.unlock();let y;try{y=await f()}catch(D){m();let F=wo(D,h.status);throw A.current?.(F),F}h.connect?.();let I;for(let D=1;D<=u;D++)try{await h.whenLive(a!==void 0?{timeout:a}:void 0),await h.stream(n).attach(y),l(!0);return}catch(F){I=F,Je(`start attempt ${D}/${u} failed`,F),D<u&&await new Promise(G=>setTimeout(G,c))}m(),l(!1);let O=I instanceof Error?I:new Error(String(I??"voice start failed"));throw A.current?.(O),O},[h,n,a,u,c,f,m,l]);Po(r,()=>({start:M,stop:b,unlock:()=>w.current?.unlock(),get active(){return R.current},get micStream(){return x.current},get audio(){return w.current}}),[M,b]);let H=ee(!1),E=be(async()=>{if(!h||!R.current||H.current)return;let y=x.current?.getAudioTracks()[0]??null;if(y&&y.readyState==="live"){try{await h.stream(n).attach(y)}catch(I){Je("foreground mic re-assert failed (will retry on next pass)",I)}return}H.current=!0;try{let I=await f();await h.stream(n).attach(I)}catch(I){let O=I instanceof Error?I:new Error(String(I));Je("foreground mic re-acquire failed",O),A.current?.(O)}finally{H.current=!1}},[h,n,f]);return hr(()=>{let y=()=>{E()};return h&&typeof h.onRecovery=="function"?h.onRecovery(y):Co(y)},[h,E]),hr(()=>m,[m]),s?Eo(Ke,{ref:w,session:h,stream:n,onTrack:P,onUnlockChange:S}):null}),To=ze;import{forwardRef as Uo,useEffect as Mo,useImperativeHandle as _o,useRef as yr,useState as No}from"react";import{useEffect as Ro,useState as Ao}from"react";var wt={level:0,speaking:!1};function xt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Ao(wt);return Ro(()=>{if(!e){i(wt);return}let a=$e();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let d=new Uint8Array(g.fftSize),P=setInterval(()=>{g.getByteTimeDomainData(d);let S=0;for(let C=0;C<d.length;C++){let h=(d[C]-128)/128;S+=h*h}let p=Math.sqrt(S/d.length);i(C=>{let h=p>n;return Math.abs(C.level-p)<.005&&C.speaking===h?C:{level:p,speaking:h}})},o);return()=>{clearInterval(P),c.disconnect(),i(wt)}},[e,r,o,n]),s}import{Fragment as Do,jsx as Xe,jsxs as Vo}from"react/jsx-runtime";var Io={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Lo={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Oo=Uo(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:d,capture:k}=t,P=Z(),S=o??P,p=yr(null),[C,h]=No(null),w=yr(d);w.current=d;let{level:x,speaking:T}=xt(a?C:null);return _o(r,()=>({start:()=>{let v=p.current;return v?v.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),Mo(()=>{!i||!S||p.current?.start().catch(()=>{})},[i,S]),Vo(Do,{children:[Xe(ze,{ref:p,session:S,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...k!==void 0?{capture:k}:{},onActiveChange:c,onError:g,onMicStream:v=>{h(v),w.current?.(v)}}),a?Xe("span",{className:u,style:Io,"data-urun-mic":"","data-urun-mic-active":C?"true":"false","data-urun-mic-speaking":T?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(x*100)/100,children:Xe("span",{style:Lo,children:Xe("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(x*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{sessionFailureFromMediaError as qo,sharedCaptureController as Fo}from"@urun-sh/core";import{forwardRef as br,useCallback as te,useEffect as Tt,useImperativeHandle as Ho,useRef as j,useState as Ee}from"react";import{jsx as ie,jsxs as kr}from"react/jsx-runtime";var Pr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Et(...e){console.debug("[camera]",...e)}function Wo(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Bo(){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 Cr=br(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:d,visible:k=!1,className:P,videoClassName:S,onActiveChange:p,onError:C,onStream:h,onTrack:w,children:x,capture:T,flipControl:v="auto",flipControlClassName:R,onDevices:N}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let A=i?"user":a?"environment":u??"environment",U=Z(),l=o??U,m=j(null),f=j(null),b=j(null),M=j([]),H=j(null),E=j(!1),y=j(A),[I,O]=Ee(A),[D,F]=Ee(!1),[G,J]=Ee(null),[B,V]=Ee(!1),[z]=Ee(Wo),q=j(p);q.current=p;let $=j(C);$.current=C;let Y=j(h);Y.current=h;let me=j(w);me.current=w;let _e=j(N);_e.current=N;let re=te(_=>{E.current!==_&&(E.current=_,F(_),q.current?.(_))},[]);Tt(()=>{if(!D){J(null);return}let _=!1,L=()=>{Bo().then(K=>{_||(J(K),K&&_e.current?.(K))})};L();let W=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof W?.addEventListener=="function"?(W.addEventListener("devicechange",L),()=>{_=!0,W.removeEventListener?.("devicechange",L)}):()=>{_=!0}},[D]);let Ne=te(_=>{let L=m.current;L&&(L.muted=!0,L.defaultMuted=!0,L.setAttribute("muted",""),L.setAttribute("playsinline",""),L.setAttribute("webkit-playsinline",""),L.srcObject=_,_&&L.play()?.catch?.(W=>Et("preview play() failed",W)))},[]),Q=te(()=>{H.current?.(),H.current=null;for(let _ of M.current)_();M.current=[],b.current?.release(),b.current=null,f.current&&(f.current=null,Y.current?.(null),me.current?.(null)),Ne(null)},[Ne]),tt=te((_,L)=>{H.current?.(),f.current=L,Ne(L),Y.current?.(L);let W=()=>{f.current===L&&(Et("camera track ended (device removed or permission revoked)"),Q(),re(!1))};_.addEventListener("ended",W),H.current=()=>_.removeEventListener("ended",W)},[Ne,Q,re]),fe=te(async _=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let L={...Pr,...s,facingMode:_},W;try{let K=b.current;if(K)W=await K.update(L);else{let Pe=await(T??Fo()).claim("video",L);if(b.current=Pe,M.current=[Pe.onTrack((Ce,Hr)=>{tt(Ce,Hr),E.current&&l.stream(n).attachVideo(Ce).then(()=>me.current?.(Ce)).catch(Wr=>Et("camera re-publish after one-capture re-acquire failed",Wr))}),Pe.onLost(Ce=>{b.current=null,M.current=[],Q(),re(!1),$.current?.(Ce)})],!Pe.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});W=Pe.track}}catch(K){let ge=qo(K,l.status);throw $.current?.(ge),ge}y.current=_,O(_),tt(W,b.current?.stream??new MediaStream([W]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(W)}catch(K){Q(),re(!1);let ge=K instanceof Error?K:new Error(String(K));throw $.current?.(ge),ge}me.current?.(W),re(!0)},[l,n,s,d,T,tt,Q,re]),Dt=te(_=>fe(_?.facingMode??y.current),[fe]),Ie=te(async _=>{E.current&&y.current===_||await fe(_)},[fe]),rt=te(()=>fe(y.current==="environment"?"user":"environment"),[fe]),Vt=te(async()=>{Q(),re(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,Q,re]);Ho(r,()=>({start:Dt,stop:Vt,flip:rt,setFacingMode:Ie,get active(){return E.current},get facingMode(){return y.current},get stream(){return f.current},get element(){return m.current}}),[Dt,Vt,rt,Ie]);let qt=j(Ie);if(qt.current=Ie,Tt(()=>{!c||!l||qt.current(A).catch(()=>{})},[c,l,A]),Tt(()=>Q,[Q]),!k)return null;let Vr=g==="auto"?I==="user":g,qr=D&&(v===!0||v==="auto"&&z&&(G?.length??0)>1),Fr=()=>{B||(V(!0),rt().catch(()=>{}).finally(()=>V(!1)))};return kr("div",{className:P,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":I,children:[ie("video",{ref:m,className:S,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Vr?{transform:"scaleX(-1)"}:{}}}),qr?ie("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Fr,disabled:B,className:R,style:R?{opacity:B?.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:B?.6:1},children:kr("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:[ie("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ie("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ie("path",{d:"M14.5 10.5v1.6h-1.6"}),ie("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ie("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,x]})}),$o=br(function({preview:t=!0,...r},o){return ie(Cr,{ref:o,...r,visible:t,autoStart:!1})});import{useEffect as jo,useState as Ko}from"react";function Jo(e,t){let[r,o]=Ko(null);return jo(()=>{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 Qo}from"react";import{useEffect as Yo,useMemo as Zo}from"react";import{createStore as zo}from"zustand/vanilla";import{useStore as Xo}from"zustand";var Go=()=>{};function Rt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=zo(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Go,u=(c=>Xo(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function Re(e,t){let r=Zo(()=>Rt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Yo(()=>r.bind(),[r]),r}function es(e,t,r){let n=Re(e,t)(r??(a=>a)),s=Qo(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 ts,useState as rs}from"react";var le=200;function ae(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Ae(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(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 Ut(e,t,r={}){let o=r.cap??200,[n,s]=rs([]);return ts(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ae(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as Ge,jsxs as Ue}from"react/jsx-runtime";function ns({session:e,name:t,cap:r,className:o}){let n=Ut(e,t,{cap:r});return Ue("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[Ue("div",{className:"urun-stream-tail-meta",children:[Ge("code",{children:t}),Ue("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),Ge("div",{className:"urun-stream-tail-log",children:n.length===0?Ue("span",{className:"urun-stream-tail-empty",children:["Waiting for ",Ge("code",{children:t})," messages\u2026"]}):n.map((s,i)=>Ue("div",{className:"urun-stream-tail-line",children:[Ge("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Ae(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as os,useState as wr}from"react";import{jsx as de,jsxs as Ye}from"react/jsx-runtime";function Ze({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=wr(""),[i,a]=wr(null),u=os(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return Ye("div",{className:"urun-doc-patch",children:[de("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),Ye("div",{className:"urun-doc-patch-actions",children:[de("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?de("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function ss({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Re(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return Ye("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Ye("div",{className:"urun-doc-panel-meta",children:[de("code",{children:t}),de("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),de("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?de(Ze,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as is,useState as as}from"react";import{jsx as Me,jsxs as Tr}from"react/jsx-runtime";function xr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function us({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=as([]);return is(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ae(u,{at:Date.now(),direction:"in",text:xr(Ae(a))},r))}):void 0),[e,t,r]),Tr("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Me(Ze,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ae(u,{at:Date.now(),direction:"out",text:xr(a)},r))}}),Me("div",{className:"urun-control-sender-log",children:n.length===0?Me("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>Tr("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Me("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Me("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as cs,useState as ls}from"react";import{jsx as Qe,jsxs as ps}from"react/jsx-runtime";function ds({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=ls([]),a=t.join(","),u=r.join(",");return cs(()=>{if(i([]),!e)return;let c=(d,k)=>i(P=>ae(P,{at:Date.now(),kind:d,text:k},o)),g=[];g.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let k=e.stream(d);g.push(k.on("track",P=>c("track",`${d}: ${P?"track arrived":"track ended"}`)))}for(let d of r){let k=e.doc(d);g.push(k.on("change",()=>c("doc",`${d} changed`)))}return()=>g.forEach(d=>d())},[e,a,u,o]),Qe("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?Qe("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,g)=>ps("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[Qe("span",{className:"urun-event-spine-kind",children:c.kind})," ",Qe("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}import{describeSessionPhase as Es,isWakingPhase as Rs}from"@urun-sh/core";import{useEffect as ms,useState as fs}from"react";function X(e){let[t,r]=fs(e?.phase??null);return ms(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as ys}from"@urun-sh/core";import{useEffect as gs,useRef as Ss,useState as hs}from"react";import{isWakingPhase as vs}from"@urun-sh/core";function Mt(e){let t=X(e),r=vs(t?.name),o=Ss(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]=hs(s);return gs(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[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 ks,jsx as Er,jsxs as Rr}from"react/jsx-runtime";function _t({session:e,render:t,className:r}){let o=Mt(e);return!o.waking||!o.phase?null:Er("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Rr(ks,{children:[Er("span",{className:"urun-session-waking-label",children:ys(o.phase)})," ",Rr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Cs,useState as ws}from"react";import{useEffect as Ar,useRef as bs,useState as Ur}from"react";var Ps={event:null,elapsedMs:0};function Nt(e,t){let[r,o]=Ur(null),n=bs(0);Ar(()=>{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]=Ur(0);return Ar(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:Ps}import{jsx as Mr,jsxs as _r}from"react/jsx-runtime";var xs={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 Ts(e){let[t,r]=ws(!1);return Cs(()=>{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 It({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Nt(e,t),i=Ts(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Mr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):_r("div",{className:"urun-activation-overlay-card",children:[Mr("span",{className:"urun-activation-overlay-copy",children:a.hint??xs[u]})," ",_r("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as pe,jsxs as Lt}from"react/jsx-runtime";var As={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Us({session:e,className:t}){let r=X(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return Lt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[pe("span",{className:"urun-session-status-dot","data-phase":o}),pe("span",{className:"urun-session-status-label",children:As[o]}),n?pe("span",{className:"urun-session-status-detail",children:n}):null]})}function Ms({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=X(e);if(s?.name==="live")return Lt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,pe(It,{session:e})]});let i=r?r(s):pe("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Rs(s.name)?pe(_t,{session:e}):s&&s.name!=="idle"?Es(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Lt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?pe("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as _s,useState as Ns}from"react";import{jsx as Os}from"react/jsx-runtime";function Nr(e){return X(e)?.endsAt??null}function Is(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 Ls({session:e,urgentMs:t=6e4,className:r}){let n=Nr(e)?.getTime()??null,[s,i]=Ns(()=>n===null?null:Math.max(0,n-Date.now()));if(_s(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Is(s);return Os("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{jsx as Ir,jsxs as qs}from"react/jsx-runtime";var Ds=new Set(["expired","ended","error"]);function Vs({session:e,onNewSession:t,children:r,className:o}){let n=X(e);if(!n||!Ds.has(n.name))return null;let s=r?r(n):Ir("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return qs("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?Ir("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as Lr,useMemo as Fs,useState as Or}from"react";import{jsx as et,jsxs as Bs}from"react/jsx-runtime";function Ot(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 Dr(e){let t=Fs(()=>e?e.doc("control"):null,[e]),[r,o]=Or(()=>t?Ot(t.get("idle")):null);return Lr(()=>{if(!t){o(null);return}return o(Ot(t.get("idle"))),t.on("change",()=>o(Ot(t.get("idle"))))},[t]),r}function Hs(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Ws({session:e,onStillHere:t,className:r}){let o=Dr(e),n=o?.deadlineEpochS??null,[s,i]=Or(null);if(Lr(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return et("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:Bs("div",{className:"urun-idle-warning-card",children:[et("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),et("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Hs(s)} due to inactivity.`:"This session will end soon due to inactivity."}),et("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as $s,useEffect as js,useState as Ks}from"react";import{prewake as Js}from"@urun-sh/core";function zs(e){let t=$s(Se),[r,o]=Ks(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,d=t?.authProvider;return js(()=>{if(!a||!u||!n||!s)return;let k=!1,P=()=>{Js({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:d}).then(p=>{k||o(p)}).catch(()=>{})};P();let S=setInterval(P,Math.max(1,i)*1e3);return()=>{k=!0,clearInterval(S)}},[n,s,i,a,u,c,g,d]),r}import{describeSessionPhase as zc,isWakingPhase as Xc}from"@urun-sh/core";export{Ke as Audio,Cr as Camera,In as ComponentRenderer,Pr as DEFAULT_CAMERA_CONSTRAINTS,le as DEFAULT_LOG_CAP,vr as DEFAULT_VOICE_CONSTRAINTS,Ze as DocPatchForm,po as Image,Jn as ImageFrame,Kn as ImageFrameSchema,Gn as MetricsPanel,Xn as MetricsPanelSchema,Oo as Mic,Zr as OPERATOR_CHORD_LABEL,Yr as OPERATOR_TOKEN_STORAGE_KEY,Dn as ProgressCard,On as ProgressCardSchema,Qn as Session,Fn as StatusBadge,Vn as StatusBadgeSchema,$n as TextStream,Bn as TextStreamSchema,It as UrunActivationOverlay,yo as UrunAudio,Br as UrunAuthProvider,$o as UrunCamera,us as UrunControlSender,ss as UrunDocPanel,we as UrunErrorBoundary,ds as UrunEventSpine,Ws as UrunIdleWarning,$r as UrunJwtProvider,an as UrunProvider,Ls as UrunSessionClock,Vs as UrunSessionEnded,Ms as UrunSessionGate,Us as UrunSessionStatus,_t as UrunSessionWaking,ns as UrunStreamTail,To as UrunVoice,bt as Video,ze as Voice,Le as authMode,Rt as createDocStore,zc as describeSessionPhase,Ae as formatPayload,$e as getUrunAudioContext,Xc as isWakingPhase,At as parseJsonObject,ae as pushCapped,$t as readOperatorToken,Nn as registerComponent,je as resumeUrunAudioContext,ne as urunPublicEnv,Nt as useActivation,gn as useApp,En as useChat,Cn as useCompletion,st as useConfirmOnLeave,Re as useDocStore,mr as useImageFrame,_n as useInputPresence,fr as useMetricsPanel,ot as useOperatorOverride,ir as useProgressCard,yn as useRequest,eo as useSession,es as useSessionDoc,Nr as useSessionEndsAt,Dr as useSessionIdle,X as useSessionPhase,Jo as useSessionTrack,Mt as useSessionWake,ur as useStatusBadge,Ut as useStreamMessages,dr as useTextStream,xt as useUrunAudioLevel,nt as useUrunAuth,zs as useUrunPrewake,zr as usesWorkOSAuth};
|
|
2
|
+
import{a as Kr,b as Jr,c as ot}from"./chunk-WF2OBDSX.mjs";import{useCallback as sn,useEffect as jt,useMemo as an,useRef as Kt,useState as Ve}from"react";import{Component as zr}from"react";import{jsx as qt,jsxs as Xr}from"react/jsx-runtime";var we=class extends zr{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||Xr("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:[qt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),qt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Gr}from"react";var he=Gr(null);function ce(e){return e&&e.trim()?e.trim():void 0}function oe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ce(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return ce(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ce(typeof process<"u"?process.env?.[e]:void 0)}}function De(){let e=oe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||oe("VERCEL_ENV")==="production"?"workos":oe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Yr(){return De()==="workos"}import{useEffect as Zr,useRef as Qr}from"react";var en="urun.operator_token",Wt=null,Ht="op",tn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Bt(){return typeof window<"u"}function $t(){return Wt}function rn(){if(!Bt())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(Ht);if(!r)return null;Wt=r,t.delete(Ht);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function nn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function st(e){let t=Qr(e);t.current=e,Zr(()=>{if(!Bt())return;rn();let r=o=>{if(!nn(o))return;let n=$t();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as on}from"react";function it(e=!0){on(()=>{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 xe,jsxs as mn}from"react/jsx-runtime";var un="/api/urun-token",cn=1e4;function ln(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Jt(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function dn(e,t){return typeof e=="function"?e(t):e!==void 0?e: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:[xe("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),xe("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function pn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,confirmOnLeave:m=!1,fallback:d,errorFallback:y,children:k}){let f=n===void 0&&t===void 0;if(!f&&(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(!f&&(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 p=r??o;if(f&&(typeof p!="string"||p.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);it(m);let[P,S]=Ve(),[R,b]=Ve(),[E,g]=Ve(null),M=Kt(void 0),V=Kt(null),[N,U]=Ve(null);st(B=>U({jwt:B}));let l=ot(),x=oe("NEXT_PUBLIC_SESSION_TOKEN")??oe("NEXT_PUBLIC_URUN_JWT"),v=De(),w=N!==null,D=v==="workos"&&!n&&!w&&!f,j=n??(v==="jwt"?x:void 0)??P??R?.token,A=w?N.jwt:j,T=s??oe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),F=D&&!A,q=t??R?.orgId,h=e??R?.gatewayUrl,C=f&&R===void 0,I=f&&R!==void 0&&!h?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,L=E??I,H=u??un,W=sn(async B=>{if(!B?.forceRefresh){let K=M.current;if(!K)return K;let Q=ln(K);if(Q===null||Q-Date.now()>cn)return K}return(await(V.current??(V.current=(async()=>{try{let K=await Jt(H);return M.current=K.token,b(K),K}finally{V.current=null}})()))).token},[H]),_=an(()=>({appId:p,baseUrl:h??"",orgId:q??"",jwt:A,getAccessToken:D?l?.getAccessToken:f&&!w?W:void 0,authProvider:T,eventsUrl:i,sessionKey:a,releaseOnLeave:c,priority:w?"preempt":void 0}),[p,l,h,T,A,i,q,a,c,D,w,f,W]);return jt(()=>{if(!f)return;let B=new AbortController;return g(null),(async()=>{try{let z=await Jt(H,B.signal);M.current=z.token,b(z)}catch(z){if(B.signal.aborted)return;g(z instanceof Error?z:new Error(String(z)))}})(),()=>B.abort()},[f,H]),jt(()=>{if(!D||!l)return;let B=!1,z=l;async function K(){try{let Ie=await z.getAccessToken();B||S(Ie??void 0)}catch{B||S(void 0)}}K();let Q=window.setInterval(()=>{K()},6e4);return()=>{B=!0,window.clearInterval(Q)}},[l,D]),xe(we,{fallback:d,children:L?dn(y,L):F||C?xe("div",{role:"status","aria-live":"polite",children:"Signing in..."}):xe(he.Provider,{value:_,children:k})})}import{useContext as fn,useEffect as gn,useMemo as zt,useReducer as Sn,useRef as at}from"react";import{App as hn}from"@urun-sh/core";function vn(e,t){return`${e}:${JSON.stringify(t??{})}`}function yn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var le=new Map;var ut=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()})}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()}},ct=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},lt=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"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}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()}doc(t){let r=this._docs.get(t);return r||(r=new ut(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new ct(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_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 kn(){let e=fn(he);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Sn(i=>i+1,0),r=at(new Map),o=at(new Map),n=at(null),s=zt(()=>hn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority]);return gn(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=le.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let m=le.get(u);m===c&&(m.handle.removeNotifier(t),m.refCount=Math.max(0,m.refCount-1),a.set(u,m),m.refCount===0&&(m.disposeTimer=setTimeout(()=>{let d=le.get(u);!d||d.refCount!==0||(le.delete(u),d.handle.disconnect())},0)))}n.current=a}},[]),zt(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let m=d=>{let y=vn(u,d),k=r.current.get(y);if(k&&!k.disposed)return k;let f=yn(e,u,d),p=le.get(f);return p?.handle.disposed&&(p.disposeTimer&&clearTimeout(p.disposeTimer),le.delete(f),o.current.get(f)===p&&o.current.delete(f),p=void 0),p?p.disposeTimer&&(clearTimeout(p.disposeTimer),p.disposeTimer=null):(p={handle:new lt(s[u](d),t,e.eventsUrl),refCount:0,disposeTimer:null},le.set(f,p)),o.current.get(f)!==p&&(o.current.set(f,p),p.handle.addNotifier(t),p.refCount+=1),r.current.set(y,p.handle),p.handle};return i.set(u,m),m}})},[e,s])}import{useCallback as dt,useEffect as bn,useMemo as Cn,useRef as Fe,useState as pt}from"react";function ve(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 Pn(e){return e instanceof Error?e:new Error(String(e))}function En(e,t){let r=Cn(()=>ve(e),[e]),[o,n]=pt(void 0),[s,i]=pt(null),[a,u]=pt(!1),c=Fe(t);c.current=t;let m=Fe(0),d=Fe(null),y=Fe(!0);bn(()=>(y.current=!0,()=>{y.current=!1,d.current?.abort()}),[]);let k=dt(async P=>{d.current?.abort();let S=new AbortController;d.current=S;let R=++m.current,b=()=>y.current&&m.current===R;b()&&(u(!0),i(null));try{let E=await r.request(P,{...c.current,signal:S.signal});return b()&&(n(E),u(!1),c.current?.onSuccess?.(E)),E}catch(E){let g=Pn(E);throw b()&&(i(g),u(!1),c.current?.onError?.(g)),g}},[r]),f=dt(P=>{k(P).catch(()=>{})},[k]),p=dt(()=>{m.current++,d.current?.abort(),d.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:f,mutateAsync:k,data:o,error:s,isPending:a,reset:p}}import{useCallback as Xt,useEffect as wn,useMemo as xn,useRef as qe,useState as mt}from"react";function Gt(e){return e instanceof Error?e:new Error(String(e))}var Tn=e=>typeof e=="string"?e:String(e);function Rn(e,t){let r=xn(()=>ve(e),[e]),[o,n]=mt(""),[s,i]=mt(!1),[a,u]=mt(null),c=qe(t);c.current=t;let m=qe(0),d=qe(null),y=qe(!0);wn(()=>(y.current=!0,()=>{y.current=!1,d.current?.cancel(),d.current=null}),[]);let k=Xt(()=>{m.current++,d.current?.cancel(),d.current=null,y.current&&i(!1)},[]),f=Xt(async p=>{d.current?.cancel();let P=++m.current,S=()=>y.current&&m.current===P,R=c.current,b=R?.parseChunk??Tn,E=R?.buildPayload??(v=>({prompt:v}));S()&&(n(""),u(null),i(!0));let{parseChunk:g,buildPayload:M,onFinish:V,onError:N,...U}=R??{},l="",x;try{x=r.requestStream(E(p),U),d.current=x}catch(v){let w=Gt(v);S()&&(u(w),i(!1),R?.onError?.(w));return}try{for await(let v of x){if(m.current!==P)break;l+=b(v),S()&&n(l)}S()&&(i(!1),R?.onFinish?.(l))}catch(v){let w=Gt(v);S()&&(u(w),i(!1),R?.onError?.(w))}finally{d.current===x&&(d.current=null)}},[r]);return{completion:o,complete:f,stop:k,isStreaming:s,error:a}}import{useCallback as Yt,useEffect as An,useMemo as Un,useRef as ye,useState as He}from"react";function Zt(e){return e instanceof Error?e:new Error(String(e))}var Mn=e=>typeof e=="string"?e:String(e),Qt=0;function ft(e){return Qt+=1,`${e}-${Qt}`}function _n(e,t){let r=Un(()=>ve(e),[e]),[o,n]=He(()=>(t?.initialMessages??[]).map(b=>({id:b.id??ft("msg"),role:b.role,content:b.content}))),[s,i]=He(""),[a,u]=He(!1),[c,m]=He(null),d=ye(t);d.current=t;let y=ye(o);y.current=o;let k=ye(s);k.current=s;let f=ye(0),p=ye(null),P=ye(!0);An(()=>(P.current=!0,()=>{P.current=!1,p.current?.cancel(),p.current=null}),[]);let S=Yt(()=>{f.current++,p.current?.cancel(),p.current=null,P.current&&u(!1)},[]),R=Yt(async b=>{let E=b===void 0,g=(E?k.current:b)??"";if(!g.trim())return;p.current?.cancel();let V=++f.current,N=()=>P.current&&f.current===V,U=d.current,l=U?.parseChunk??Mn,x={id:ft("msg"),role:"user",content:g},v={id:ft("msg"),role:"assistant",content:""},w=[...y.current,x].map(W=>({role:W.role,content:W.content})),D=[...y.current,x,v];y.current=D,n(D),E&&i(""),m(null),u(!0);let j=U?.buildPayload??(W=>({messages:W})),{initialMessages:A,parseChunk:T,buildPayload:F,onFinish:q,onError:h,...C}=U??{},I=W=>{n(_=>_.map(B=>B.id===v.id?{...B,content:W}:B))},L="",H;try{H=r.requestStream(j(w),C),p.current=H}catch(W){let _=Zt(W);N()&&(m(_),u(!1),U?.onError?.(_));return}try{for await(let W of H){if(f.current!==V)break;L+=l(W),N()&&I(L)}N()&&(u(!1),U?.onFinish?.({...v,content:L}))}catch(W){let _=Zt(W);N()&&(m(_),u(!1),U?.onError?.(_))}finally{p.current===H&&(p.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:R,stop:S,isStreaming:a,error:c}}import{useCallback as se,useEffect as er,useMemo as Nn,useRef as tr,useState as rr}from"react";import{createInputPresencePublisher as In,INPUT_PRESENCE_DEFAULT_HZ as Ln,INPUT_PRESENCE_FIELD as On}from"@urun-sh/core";var gt=[];function Dn(e,t={}){let{field:r=On,hz:o=Ln}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=Nn(()=>s?In({awareness:{setLocalStateField:(g,M)=>s.setField(g,M)},field:r,hz:o}):null,[s,r,o]),a=tr(null);a.current=i;let[u,c]=rr(!1),[m,d]=rr(gt),y=tr(!1);er(()=>{if(i)return()=>i.dispose()},[i]);let k=se(()=>{let g=a.current;d(g?g.heldKeys():gt)},[]),f=se(()=>{a.current?.clear(),d(gt)},[]);er(()=>{if(!n)return;let g=()=>!!n.pointerLockElement,M=()=>{if(g()){y.current=!1,c(!0);return}y.current||(c(!1),f())},V=v=>{g()&&(a.current?.keyDown(v.key),k())},N=v=>{a.current?.keyUp(v.key),k()},U=v=>{g()&&a.current?.movePointer(v.movementX,v.movementY)},l=v=>{g()&&a.current?.setButtons(v.buttons)},x=()=>{f()};return n.addEventListener("pointerlockchange",M),n.addEventListener("keydown",V),n.addEventListener("keyup",N),n.addEventListener("mousemove",U),n.addEventListener("mousedown",l),n.addEventListener("mouseup",l),n.defaultView?.addEventListener("blur",x),()=>{n.removeEventListener("pointerlockchange",M),n.removeEventListener("keydown",V),n.removeEventListener("keyup",N),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",l),n.removeEventListener("mouseup",l),n.defaultView?.removeEventListener("blur",x)}},[n,f,k]);let p=se(g=>{g.requestPointerLock?.()},[]),P=se(()=>{y.current=!0,c(!0)},[]),S=se(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),f()},[n,f]),R=se(g=>{a.current?.keyDown(g),k()},[k]),b=se(g=>{a.current?.keyUp(g),k()},[k]),E=se((g,M)=>{a.current?.movePointer(g,M)},[]);return{engage:p,engageTouch:P,release:S,engaged:u,heldKeys:m,pressKey:R,releaseKey:b,movePointer:E}}var nr=new Map;function Vn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);nr.set(e,{component:t,schema:r})}function or(e,t){let r=nr.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 qn,jsx as We}from"react/jsx-runtime";function Fn({name:e,props:t,fallback:r}){let o=or(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?We(qn,{children:r}):We("div",{className:"urun-component-error",role:"alert",children:We("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return We(n,{...o.validatedProps})}import{z as Te}from"zod";import{jsx as St,jsxs as sr}from"react/jsx-runtime";var Hn=Te.object({step:Te.number().min(0),total:Te.number().min(1),label:Te.string().optional(),variant:Te.enum(["default","success","error"]).default("default")});function ir(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 Wn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=ir(e);return sr("div",{className:"urun-progress-card","data-variant":n,children:[o&&St("div",{className:"urun-progress-label",children:o}),St("div",{className:"urun-progress-bar",children:St("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),sr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as ht}from"zod";import{jsx as ar,jsxs as Kn}from"react/jsx-runtime";var Bn=ht.object({state:ht.enum(["thinking","generating","idle","error"]),message:ht.string().optional()}),$n={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function ur(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??$n[t]??t;return{state:t,message:n,isActive:o}}function jn(e){let{state:t,message:r,isActive:o}=ur(e);return Kn("span",{className:"urun-status-badge","data-state":t,children:[ar("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),ar("span",{className:"urun-status-message",children:r})]})}import{useRef as cr,useEffect as Jn}from"react";import{z as vt}from"zod";import{jsx as lr,jsxs as Gn}from"react/jsx-runtime";var zn=vt.object({text:vt.string(),streaming:vt.boolean().default(!1)});function dr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Xn(e){let{text:t,streaming:r}=dr(e),o=cr(null),n=cr(0);return Jn(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Gn("div",{className:"urun-text-stream",children:[lr("span",{ref:o,className:"urun-text-content"}),r&&lr("span",{className:"urun-text-cursor"})]})}import{z as Be}from"zod";import{jsx as pr,jsxs as Qn}from"react/jsx-runtime";var Yn=Be.object({src:Be.string().url(),alt:Be.string().optional(),caption:Be.string().optional()});function mr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Zn(e){let{src:t,alt:r,caption:o}=mr(e);return Qn("figure",{className:"urun-image-frame",children:[pr("img",{className:"urun-image",src:t,alt:r}),o&&pr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as ie}from"zod";import{jsx as yt,jsxs as ro}from"react/jsx-runtime";var eo=ie.object({metrics:ie.array(ie.object({label:ie.string(),value:ie.union([ie.string(),ie.number()]),unit:ie.string().optional()}))});function fr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function to(e){let{metrics:t}=fr(e);return yt("div",{className:"urun-metrics-panel",children:t.map((r,o)=>ro("div",{className:"urun-metric-card",children:[yt("div",{className:"urun-metric-label",children:r.label}),yt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as no,useContext as gr}from"react";import{jsx as io}from"react/jsx-runtime";var kt=no(null);function oo({session:e,children:t}){return io(kt.Provider,{value:e,children:t})}function Z(){return gr(kt)}function so(){let e=gr(kt);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{forwardRef as ao,useCallback as Re,useEffect as Sr,useImperativeHandle as uo,useRef as de,useState as hr}from"react";import{jsx as vr,jsxs as po}from"react/jsx-runtime";var co=1e3;function lo(...e){console.debug("[video]",...e)}var bt=ao(function(t,r){let{session:o,stream:n="video",track:s,muted:i=!0,mirror:a=!1,objectFit:u="contain",className:c,style:m,videoClassName:d,placeholder:y,poster:k,children:f,onTrack:p,onFirstFrame:P}=t,S=Z(),R=o??S,b=de(null),E=de(null),[g,M]=hr(!1),[V,N]=hr(!1),U=de(!1),l=de(p);l.current=p;let x=de(P);x.current=P;let v=de(null),w=de(null),D=Re(h=>{if(h===v.current||(v.current=h,w.current?.(),w.current=null,U.current=!1,N(!1),!h))return;let C=b.current;if(!C)return;let I=()=>{w.current?.(),w.current=null,U.current=!0,N(!0),x.current?.()};if(typeof C.requestVideoFrameCallback=="function"){let H=C.requestVideoFrameCallback(I);w.current=()=>C.cancelVideoFrameCallback?.(H);return}let L=()=>{let H=C.getVideoPlaybackQuality?.();(H?H.totalVideoFrames>0:C.readyState>=2&&C.videoWidth>0)&&I()};C.addEventListener("loadeddata",L),C.addEventListener("timeupdate",L),C.addEventListener("playing",L),w.current=()=>{C.removeEventListener("loadeddata",L),C.removeEventListener("timeupdate",L),C.removeEventListener("playing",L)},L()},[]);Sr(()=>()=>{w.current?.(),w.current=null},[]);let j=Re(()=>{if(typeof MediaStream>"u")return null;E.current||(E.current=new MediaStream);let h=b.current;return h&&h.srcObject!==E.current&&(h.srcObject=E.current),E.current},[]),A=Re(h=>{let C=b.current;if(!C)return;let I=C.play();!I||typeof I.catch!="function"||I.catch(L=>lo(`play() failed (${h})`,L))},[]),T=Re(h=>{let C=j();if(C){for(let I of C.getVideoTracks())I!==h&&C.removeTrack(I);if(h&&!C.getVideoTracks().includes(h)){C.addTrack(h);let I=b.current;I&&(I.srcObject=C)}h&&A("track-attach"),M(h!==null),D(h),l.current?.(h)}},[j,A,D]),F=Re(h=>{b.current=h,h&&(i&&(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted","")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),j())},[j,i]);uo(r,()=>({get element(){return b.current},get live(){return E.current?E.current.getVideoTracks().length>0:!1},get framed(){return U.current}}),[]);let q=s!==void 0;return Sr(()=>{if(q){T(s??null);return}if(!R)return;let h=R.stream(n),C=()=>{let _=E.current;return _?_.getVideoTracks()[0]??null:null},I=_=>{if(_!==C()&&(T(_),_)){let B=()=>{C()===_&&T(null)};_.addEventListener("ended",B)}},L=h.track;L&&L.readyState==="live"&&I(L);let H=h.on("track",_=>{_&&_.readyState!=="live"||I(_)}),W=setInterval(()=>{let _=h.track;_&&_.readyState==="live"&&I(_)},co);return()=>{H(),clearInterval(W)}},[R,n,q,s,T]),po("div",{className:c,style:{position:"relative",width:"100%",height:"100%",...m},"data-urun-video":"","data-urun-video-live":g?"true":"false","data-urun-video-framed":V?"true":"false",children:[vr("video",{ref:F,className:d,autoPlay:!0,muted:i,playsInline:!0,style:{width:"100%",height:"100%",objectFit:u,...a?{transform:"scaleX(-1)"}:{}}}),g?null:y,k===void 0?null:vr("div",{"data-urun-video-poster":"","aria-hidden":V||void 0,style:{position:"absolute",inset:0,...V?{opacity:0,pointerEvents:"none"}:null},children:k}),f]})});import{forwardRef as mo}from"react";import{jsx as go}from"react/jsx-runtime";var fo=mo(function(t,r){let{stream:o="image",...n}=t;return go(bt,{ref:r,stream:o,...n})});import{forwardRef as ho,useCallback as ke,useEffect as Ct,useImperativeHandle as vo,useRef as be}from"react";import{observePageLifecycle as yo}from"@urun-sh/core";var $e=null;function So(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function je(){if($e)return $e;let e=So();return e?($e=new e,$e):null}function Ke(){let e=je();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{jsx as Co}from"react/jsx-runtime";var ko=1e3,yr=200;function Pt(...e){console.debug("[audio]",...e)}var Je=ho(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:m}=t,d=Z(),y=o??d,k=be(null),f=be(null),p=be(null),P=be(null),S=be(u);S.current=u;let R=be(c);R.current=c;let b=ke(l=>{p.current!==l&&(p.current=l,R.current?.(l))},[]),E=ke(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let l=k.current;return l&&l.srcObject!==f.current&&(l.srcObject=f.current),f.current},[]),g=ke(l=>{let x=k.current;if(!x)return;let v=x.play();!v||typeof v.then!="function"||v.then(()=>{x.muted||b(!0)}).catch(w=>{let D=w instanceof Error?w.name:String(w);if(D==="AbortError"){Pt(`play() aborted (${l}); retrying in ${yr}ms`),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null,g(`${l}:retry`)},yr);return}if(D==="NotAllowedError"){Pt(`play() blocked pending a user gesture (${l})`),b(!1);return}Pt(`play() failed (${l})`,w)})},[b]),M=ke(l=>{let x=E();if(x){for(let v of x.getAudioTracks())v!==l&&x.removeTrack(v);l&&!x.getAudioTracks().includes(l)&&x.addTrack(l),l&&g("track-attach"),S.current?.(l)}},[E,g]),V=ke(()=>{let l=k.current;l&&(E(),l.muted=!1,g("gesture"),Ke(),b(!0))},[E,g,b]);vo(r,()=>({unlock:V,get unlocked(){return p.current===!0},get element(){return k.current}}),[V]);let N=ke(l=>{k.current=l,l&&(l.setAttribute("playsinline",""),l.setAttribute("webkit-playsinline",""),E()),m?.(l)},[E,m]),U=s!==void 0;return Ct(()=>{if(U){M(s??null);return}if(!y)return;let l=y.stream(n),x=()=>{let A=f.current;return A?A.getAudioTracks()[0]??null:null},v=A=>{if(A!==x()&&(M(A),A)){let T=()=>{x()===A&&M(null)};A.addEventListener("ended",T)}},w=l.track;w&&w.readyState==="live"&&v(w);let D=l.on("track",A=>{A&&A.readyState!=="live"||v(A)}),j=setInterval(()=>{let A=l.track;A&&A.readyState==="live"&&v(A)},ko);return()=>{D(),clearInterval(j)}},[y,n,U,s,M]),Ct(()=>yo(()=>{Ke(),p.current===!0&&g("foreground")}),[g]),Ct(()=>()=>{P.current&&clearTimeout(P.current)},[]),Co("audio",{ref:N,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),bo=Je;import{forwardRef as Po,useCallback as Ce,useEffect as kr,useImperativeHandle as Eo,useRef as te}from"react";import{observePageLifecycle as wo,sessionFailureFromMediaError as xo,sharedCaptureController as To}from"@urun-sh/core";import{jsx as Ao}from"react/jsx-runtime";var br={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ze(...e){console.debug("[voice]",...e)}var Xe=Po(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=br,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:m,onError:d,onMicStream:y,onTrack:k,onUnlockChange:f,capture:p}=t,P=Z(),S=o??P,R=te(null),b=te(null),E=te(null),g=te([]),M=te(!1),V=te(m);V.current=m;let N=te(d);N.current=d;let U=te(y);U.current=y;let l=Ce(T=>{M.current!==T&&(M.current=T,V.current?.(T))},[]),x=Ce(()=>{for(let T of g.current)T();g.current=[],E.current?.release(),E.current=null,b.current&&(b.current=null,U.current?.(null))},[]),v=Ce(async()=>{let T=E.current;if(T){let C=await T.update(i);return b.current=T.stream,U.current?.(T.stream),C}let q=await(p??To()).claim("audio",i);E.current=q,g.current=[q.onTrack((C,I)=>{b.current=I,U.current?.(I),M.current&&S?.stream(n).attach(C).catch(L=>ze("mic re-attach after one-capture re-acquire failed",L))}),q.onLost(C=>{E.current=null,g.current=[],b.current=null,U.current?.(null),l(!1),N.current?.(C)})],b.current=q.stream,U.current?.(q.stream);let h=q.track;if(!h)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return h},[p,i,S,n,l]),w=Ce(async()=>{x(),l(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,x,l]),D=Ce(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");R.current?.unlock();let T;try{T=await v()}catch(h){x();let C=xo(h,S.status);throw N.current?.(C),C}S.connect?.();let F;for(let h=1;h<=u;h++)try{await S.whenLive(a!==void 0?{timeout:a}:void 0),await S.stream(n).attach(T),l(!0);return}catch(C){F=C,ze(`start attempt ${h}/${u} failed`,C),h<u&&await new Promise(I=>setTimeout(I,c))}x(),l(!1);let q=F instanceof Error?F:new Error(String(F??"voice start failed"));throw N.current?.(q),q},[S,n,a,u,c,v,x,l]);Eo(r,()=>({start:D,stop:w,unlock:()=>R.current?.unlock(),get active(){return M.current},get micStream(){return b.current},get audio(){return R.current}}),[D,w]);let j=te(!1),A=Ce(async()=>{if(!S||!M.current||j.current)return;let T=b.current?.getAudioTracks()[0]??null;if(T&&T.readyState==="live"){try{await S.stream(n).attach(T)}catch(F){ze("foreground mic re-assert failed (will retry on next pass)",F)}return}j.current=!0;try{let F=await v();await S.stream(n).attach(F)}catch(F){let q=F instanceof Error?F:new Error(String(F));ze("foreground mic re-acquire failed",q),N.current?.(q)}finally{j.current=!1}},[S,n,v]);return kr(()=>{let T=()=>{A()};return S&&typeof S.onRecovery=="function"?S.onRecovery(T):wo(T)},[S,A]),kr(()=>x,[x]),s?Ao(Je,{ref:R,session:S,stream:n,onTrack:k,onUnlockChange:f}):null}),Ro=Xe;import{forwardRef as _o,useEffect as No,useImperativeHandle as Io,useRef as Cr,useState as Lo}from"react";import{useEffect as Uo,useState as Mo}from"react";var Et={level:0,speaking:!1};function wt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Mo(Et);return Uo(()=>{if(!e){i(Et);return}let a=je();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,m;try{c=a.createMediaStreamSource(u),m=a.createAnalyser(),m.fftSize=r,c.connect(m)}catch{return}let d=new Uint8Array(m.fftSize),k=setInterval(()=>{m.getByteTimeDomainData(d);let f=0;for(let P=0;P<d.length;P++){let S=(d[P]-128)/128;f+=S*S}let p=Math.sqrt(f/d.length);i(P=>{let S=p>n;return Math.abs(P.level-p)<.005&&P.speaking===S?P:{level:p,speaking:S}})},o);return()=>{clearInterval(k),c.disconnect(),i(Et)}},[e,r,o,n]),s}import{Fragment as Fo,jsx as Ge,jsxs as qo}from"react/jsx-runtime";var Oo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Do={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Vo=_o(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:m,onMicStream:d,capture:y}=t,k=Z(),f=o??k,p=Cr(null),[P,S]=Lo(null),R=Cr(d);R.current=d;let{level:b,speaking:E}=wt(a?P:null);return Io(r,()=>({start:()=>{let g=p.current;return g?g.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>p.current?.stop()??Promise.resolve(),get active(){return p.current?.active??!1},get micStream(){return p.current?.micStream??null}}),[]),No(()=>{!i||!f||p.current?.start().catch(()=>{})},[i,f]),qo(Fo,{children:[Ge(Xe,{ref:p,session:f,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:m,onMicStream:g=>{S(g),R.current?.(g)}}),a?Ge("span",{className:u,style:Oo,"data-urun-mic":"","data-urun-mic-active":P?"true":"false","data-urun-mic-speaking":E?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(b*100)/100,children:Ge("span",{style:Do,children:Ge("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(b*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{sessionFailureFromMediaError as Ho,sharedCaptureController as Wo}from"@urun-sh/core";import{forwardRef as Er,useCallback as re,useEffect as xt,useImperativeHandle as Bo,useRef as X,useState as Ae}from"react";import{jsx as ae,jsxs as Pr}from"react/jsx-runtime";var wr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Tt(...e){console.debug("[camera]",...e)}function $o(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function jo(){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 xr=Er(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:m="auto",connectTimeoutMs:d,visible:y=!1,className:k,videoClassName:f,onActiveChange:p,onError:P,onStream:S,onTrack:R,children:b,capture:E,flipControl:g="auto",flipControlClassName:M,onDevices:V}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let N=i?"user":a?"environment":u??"environment",U=Z(),l=o??U,x=X(null),v=X(null),w=X(null),D=X([]),j=X(null),A=X(!1),T=X(N),[F,q]=Ae(N),[h,C]=Ae(!1),[I,L]=Ae(null),[H,W]=Ae(!1),[_]=Ae($o),B=X(p);B.current=p;let z=X(P);z.current=P;let K=X(S);K.current=S;let Q=X(R);Q.current=R;let Ie=X(V);Ie.current=V;let ne=re(O=>{A.current!==O&&(A.current=O,C(O),B.current?.(O))},[]);xt(()=>{if(!h){L(null);return}let O=!1,$=()=>{jo().then(G=>{O||(L(G),G&&Ie.current?.(G))})};$();let J=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof J?.addEventListener=="function"?(J.addEventListener("devicechange",$),()=>{O=!0,J.removeEventListener?.("devicechange",$)}):()=>{O=!0}},[h]);let Le=re(O=>{let $=x.current;$&&($.muted=!0,$.defaultMuted=!0,$.setAttribute("muted",""),$.setAttribute("playsinline",""),$.setAttribute("webkit-playsinline",""),$.srcObject=O,O&&$.play()?.catch?.(J=>Tt("preview play() failed",J)))},[]),ee=re(()=>{j.current?.(),j.current=null;for(let O of D.current)O();D.current=[],w.current?.release(),w.current=null,v.current&&(v.current=null,K.current?.(null),Q.current?.(null)),Le(null)},[Le]),rt=re((O,$)=>{j.current?.(),v.current=$,Le($),K.current?.($);let J=()=>{v.current===$&&(Tt("camera track ended (device removed or permission revoked)"),ee(),ne(!1))};O.addEventListener("ended",J),j.current=()=>O.removeEventListener("ended",J)},[Le,ee,ne]),ge=re(async O=>{if(!l)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let $={...wr,...s,facingMode:O},J;try{let G=w.current;if(G)J=await G.update($);else{let Pe=await(E??Wo()).claim("video",$);if(w.current=Pe,D.current=[Pe.onTrack((Ee,$r)=>{rt(Ee,$r),A.current&&l.stream(n).attachVideo(Ee).then(()=>Q.current?.(Ee)).catch(jr=>Tt("camera re-publish after one-capture re-acquire failed",jr))}),Pe.onLost(Ee=>{w.current=null,D.current=[],ee(),ne(!1),z.current?.(Ee)})],!Pe.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});J=Pe.track}}catch(G){let Se=Ho(G,l.status);throw z.current?.(Se),Se}T.current=O,q(O),rt(J,w.current?.stream??new MediaStream([J]));try{l.connect?.(),await l.whenLive(d!==void 0?{timeout:d}:void 0),await l.stream(n).attachVideo(J)}catch(G){ee(),ne(!1);let Se=G instanceof Error?G:new Error(String(G));throw z.current?.(Se),Se}Q.current?.(J),ne(!0)},[l,n,s,d,E,rt,ee,ne]),Dt=re(O=>ge(O?.facingMode??T.current),[ge]),Oe=re(async O=>{A.current&&T.current===O||await ge(O)},[ge]),nt=re(()=>ge(T.current==="environment"?"user":"environment"),[ge]),Vt=re(async()=>{ee(),ne(!1),await l?.stream(n).detachVideo().catch(()=>{})},[l,n,ee,ne]);Bo(r,()=>({start:Dt,stop:Vt,flip:nt,setFacingMode:Oe,get active(){return A.current},get facingMode(){return T.current},get stream(){return v.current},get element(){return x.current}}),[Dt,Vt,nt,Oe]);let Ft=X(Oe);if(Ft.current=Oe,xt(()=>{!c||!l||Ft.current(N).catch(()=>{})},[c,l,N]),xt(()=>ee,[ee]),!y)return null;let Hr=m==="auto"?F==="user":m,Wr=h&&(g===!0||g==="auto"&&_&&(I?.length??0)>1),Br=()=>{H||(W(!0),nt().catch(()=>{}).finally(()=>W(!1)))};return Pr("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":F,children:[ae("video",{ref:x,className:f,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Hr?{transform:"scaleX(-1)"}:{}}}),Wr?ae("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Br,disabled:H,className:M,style:M?{opacity:H?.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:H?.6:1},children:Pr("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:[ae("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ae("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ae("path",{d:"M14.5 10.5v1.6h-1.6"}),ae("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ae("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,b]})}),Ko=Er(function({preview:t=!0,...r},o){return ae(xr,{ref:o,...r,visible:t,autoStart:!1})});import{useEffect as Jo,useState as zo}from"react";function Xo(e,t){let[r,o]=zo(null);return Jo(()=>{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 ts}from"react";import{useEffect as Qo,useMemo as es}from"react";import{createStore as Go}from"zustand/vanilla";import{useStore as Yo}from"zustand";var Zo=()=>{};function Rt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Go(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Zo,u=(c=>Yo(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function Ue(e,t){let r=es(()=>Rt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return Qo(()=>r.bind(),[r]),r}function rs(e,t,r){let n=Ue(e,t)(r??(a=>a)),s=ts(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 ns,useState as os}from"react";var pe=200;function ue(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Me(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function At(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 Ut(e,t,r={}){let o=r.cap??200,[n,s]=os([]);return ns(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>ue(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as Ye,jsxs as _e}from"react/jsx-runtime";function ss({session:e,name:t,cap:r,className:o}){let n=Ut(e,t,{cap:r});return _e("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[_e("div",{className:"urun-stream-tail-meta",children:[Ye("code",{children:t}),_e("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),Ye("div",{className:"urun-stream-tail-log",children:n.length===0?_e("span",{className:"urun-stream-tail-empty",children:["Waiting for ",Ye("code",{children:t})," messages\u2026"]}):n.map((s,i)=>_e("div",{className:"urun-stream-tail-line",children:[Ye("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Me(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as is,useState as Tr}from"react";import{jsx as me,jsxs as Ze}from"react/jsx-runtime";function Qe({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=Tr(""),[i,a]=Tr(null),u=is(()=>{let c=At(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return Ze("div",{className:"urun-doc-patch",children:[me("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),Ze("div",{className:"urun-doc-patch-actions",children:[me("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?me("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function as({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ue(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return Ze("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Ze("div",{className:"urun-doc-panel-meta",children:[me("code",{children:t}),me("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),me("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?me(Qe,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as us,useState as cs}from"react";import{jsx as Ne,jsxs as Ar}from"react/jsx-runtime";function Rr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ls({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=cs([]);return us(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>ue(u,{at:Date.now(),direction:"in",text:Rr(Me(a))},r))}):void 0),[e,t,r]),Ar("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Ne(Qe,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>ue(u,{at:Date.now(),direction:"out",text:Rr(a)},r))}}),Ne("div",{className:"urun-control-sender-log",children:n.length===0?Ne("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>Ar("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Ne("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Ne("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as ds,useState as ps}from"react";import{jsx as et,jsxs as fs}from"react/jsx-runtime";function ms({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=ps([]),a=t.join(","),u=r.join(",");return ds(()=>{if(i([]),!e)return;let c=(d,y)=>i(k=>ue(k,{at:Date.now(),kind:d,text:y},o)),m=[];m.push(e.onPhase(d=>c("phase",`phase \u2192 ${d.name}`)));for(let d of t){let y=e.stream(d);m.push(y.on("track",k=>c("track",`${d}: ${k?"track arrived":"track ended"}`)))}for(let d of r){let y=e.doc(d);m.push(y.on("change",()=>c("doc",`${d} changed`)))}return()=>m.forEach(d=>d())},[e,a,u,o]),et("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?et("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,m)=>fs("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[et("span",{className:"urun-event-spine-kind",children:c.kind})," ",et("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${m}`))})}import{describeSessionPhase as As,isWakingPhase as Us}from"@urun-sh/core";import{useEffect as gs,useState as Ss}from"react";function Y(e){let[t,r]=Ss(e?.phase??null);return gs(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as bs}from"@urun-sh/core";import{useEffect as hs,useRef as vs,useState as ys}from"react";import{isWakingPhase as ks}from"@urun-sh/core";function Mt(e){let t=Y(e),r=ks(t?.name),o=vs(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]=ys(s);return hs(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[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 Cs,jsx as Ur,jsxs as Mr}from"react/jsx-runtime";function _t({session:e,render:t,className:r}){let o=Mt(e);return!o.waking||!o.phase?null:Ur("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):Mr(Cs,{children:[Ur("span",{className:"urun-session-waking-label",children:bs(o.phase)})," ",Mr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as ws,useState as xs}from"react";import{useEffect as _r,useRef as Ps,useState as Nr}from"react";var Es={event:null,elapsedMs:0};function Nt(e,t){let[r,o]=Nr(null),n=Ps(0);_r(()=>{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]=Nr(0);return _r(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:Es}import{jsx as Ir,jsxs as Lr}from"react/jsx-runtime";var Ts={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 Rs(e){let[t,r]=xs(!1);return ws(()=>{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 It({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Nt(e,t),i=Rs(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return Ir("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):Lr("div",{className:"urun-activation-overlay-card",children:[Ir("span",{className:"urun-activation-overlay-copy",children:a.hint??Ts[u]})," ",Lr("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as fe,jsxs as Lt}from"react/jsx-runtime";var Ms={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function _s({session:e,className:t}){let r=Y(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return Lt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[fe("span",{className:"urun-session-status-dot","data-phase":o}),fe("span",{className:"urun-session-status-label",children:Ms[o]}),n?fe("span",{className:"urun-session-status-detail",children:n}):null]})}function Ns({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=Y(e);if(s?.name==="live")return Lt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,fe(It,{session:e})]});let i=r?r(s):fe("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Us(s.name)?fe(_t,{session:e}):s&&s.name!=="idle"?As(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Lt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?fe("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Is,useState as Ls}from"react";import{jsx as Vs}from"react/jsx-runtime";function Or(e){return Y(e)?.endsAt??null}function Os(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 Ds({session:e,urgentMs:t=6e4,className:r}){let n=Or(e)?.getTime()??null,[s,i]=Ls(()=>n===null?null:Math.max(0,n-Date.now()));if(Is(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Os(s);return Vs("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{jsx as Dr,jsxs as Hs}from"react/jsx-runtime";var Fs=new Set(["expired","ended","error"]);function qs({session:e,onNewSession:t,children:r,className:o}){let n=Y(e);if(!n||!Fs.has(n.name))return null;let s=r?r(n):Dr("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return Hs("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?Dr("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as Vr,useMemo as Ws,useState as Fr}from"react";import{jsx as tt,jsxs as js}from"react/jsx-runtime";function Ot(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 qr(e){let t=Ws(()=>e?e.doc("control"):null,[e]),[r,o]=Fr(()=>t?Ot(t.get("idle")):null);return Vr(()=>{if(!t){o(null);return}return o(Ot(t.get("idle"))),t.on("change",()=>o(Ot(t.get("idle"))))},[t]),r}function Bs(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function $s({session:e,onStillHere:t,className:r}){let o=qr(e),n=o?.deadlineEpochS??null,[s,i]=Fr(null);if(Vr(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return tt("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:js("div",{className:"urun-idle-warning-card",children:[tt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),tt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Bs(s)} due to inactivity.`:"This session will end soon due to inactivity."}),tt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as Ks,useEffect as Js,useState as zs}from"react";import{prewake as Xs}from"@urun-sh/core";function Gs(e){let t=Ks(he),[r,o]=zs(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,m=t?.getAccessToken,d=t?.authProvider;return Js(()=>{if(!a||!u||!n||!s)return;let y=!1,k=()=>{Xs({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:m,authProvider:d}).then(p=>{y||o(p)}).catch(()=>{})};k();let f=setInterval(k,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(f)}},[n,s,i,a,u,c,m,d]),r}import{describeSessionPhase as Gc,isWakingPhase as Yc}from"@urun-sh/core";export{Je as Audio,xr as Camera,Fn as ComponentRenderer,wr as DEFAULT_CAMERA_CONSTRAINTS,pe as DEFAULT_LOG_CAP,br as DEFAULT_VOICE_CONSTRAINTS,Qe as DocPatchForm,fo as Image,Zn as ImageFrame,Yn as ImageFrameSchema,to as MetricsPanel,eo as MetricsPanelSchema,Vo as Mic,tn as OPERATOR_CHORD_LABEL,en as OPERATOR_TOKEN_STORAGE_KEY,Wn as ProgressCard,Hn as ProgressCardSchema,oo as Session,jn as StatusBadge,Bn as StatusBadgeSchema,Xn as TextStream,zn as TextStreamSchema,It as UrunActivationOverlay,bo as UrunAudio,Kr as UrunAuthProvider,Ko as UrunCamera,ls as UrunControlSender,as as UrunDocPanel,we as UrunErrorBoundary,ms as UrunEventSpine,$s as UrunIdleWarning,Jr as UrunJwtProvider,pn as UrunProvider,Ds as UrunSessionClock,qs as UrunSessionEnded,Ns as UrunSessionGate,_s as UrunSessionStatus,_t as UrunSessionWaking,ss as UrunStreamTail,Ro as UrunVoice,bt as Video,Xe as Voice,De as authMode,Rt as createDocStore,Gc as describeSessionPhase,Me as formatPayload,je as getUrunAudioContext,Yc as isWakingPhase,At as parseJsonObject,ue as pushCapped,$t as readOperatorToken,Vn as registerComponent,Ke as resumeUrunAudioContext,oe as urunPublicEnv,Nt as useActivation,kn as useApp,_n as useChat,Rn as useCompletion,it as useConfirmOnLeave,Ue as useDocStore,mr as useImageFrame,Dn as useInputPresence,fr as useMetricsPanel,st as useOperatorOverride,ir as useProgressCard,En as useRequest,so as useSession,rs as useSessionDoc,Or as useSessionEndsAt,qr as useSessionIdle,Y as useSessionPhase,Xo as useSessionTrack,Mt as useSessionWake,ur as useStatusBadge,Ut as useStreamMessages,dr as useTextStream,wt as useUrunAudioLevel,ot as useUrunAuth,Gs as useUrunPrewake,Yr as usesWorkOSAuth};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/react",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.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.2.
|
|
56
|
+
"@urun-sh/core": "^0.2.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",
|