@urun-sh/react 0.2.22 → 0.2.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -1
- package/dist/index.d.mts +207 -30
- package/dist/index.d.ts +207 -30
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/video.d.mts +7 -3
- package/dist/video.d.ts +7 -3
- package/dist/video.js +2 -2
- package/dist/video.mjs +2 -2
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
import{a as gn,b as hn,c as He}from"./chunk-WF2OBDSX.mjs";import{useEffect as bn,useMemo as Cn,useState as Pn}from"react";import{Component as Sn}from"react";import{jsx as kt,jsxs as vn}from"react/jsx-runtime";var Se=class extends Sn{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,n){console.error("[urun] Error caught by UrunErrorBoundary:",e,n)}render(){if(this.state.error){let{fallback:e}=this.props;return typeof e=="function"?e(this.state.error):e||vn("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:[kt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),kt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as yn}from"react";var ue=yn(null);function ee(t){return t&&t.trim()?t.trim():void 0}function X(t){switch(t){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?.[t]:void 0)}}function Re(){let t=X("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return t==="jwt"||t==="customer-jwt"||t==="test-jwt"?"jwt":t==="workos"||X("VERCEL_ENV")==="production"?"workos":X("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function kn(){return Re()==="workos"}import{jsx as $e}from"react/jsx-runtime";function Tn({baseUrl:t,orgId:e,appId:n,jwt:r,authProvider:o,eventsUrl:s,fallback:a,children:i}){let[u,c]=Pn(),p=He(),l=X("NEXT_PUBLIC_SESSION_TOKEN")??X("NEXT_PUBLIC_URUN_JWT"),f=Re(),g=f==="workos"&&!r,v=r??(f==="jwt"?l:void 0)??u,k=o??X("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),S=g&&!v,y=Cn(()=>({appId:n,baseUrl:t,orgId:e,jwt:v,getAccessToken:g?p?.getAccessToken:void 0,authProvider:k,eventsUrl:s}),[n,p,t,k,v,s,e,g]);return bn(()=>{if(!g||!p)return;let T=!1,C=p;async function U(){try{let E=await C.getAccessToken();T||c(E??void 0)}catch{T||c(void 0)}}U();let h=window.setInterval(()=>{U()},6e4);return()=>{T=!0,window.clearInterval(h)}},[p,g]),$e(Se,{fallback:a,children:S?$e("div",{role:"status","aria-live":"polite",children:"Signing in..."}):$e(ue.Provider,{value:y,children:i})})}import{useContext as xn,useEffect as Rn,useMemo as bt,useReducer as Un,useRef as Ct}from"react";import{App as En}from"@urun-sh/core";function wn(t,e){return`${t}:${JSON.stringify(e??{})}`}function An(t,e,n){return JSON.stringify({appId:t.appId,baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,fnName:e,args:n??{}})}var ce=new Map;var je=class{constructor(e,n){this._doc=e;this._notify=n;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(e,n){return this._doc.get(e,n)}set(e){this._doc.set(e),this._notify()}on(e,n){return this._doc.on(e,r=>n(r))}get synced(){return this._doc.synced}onSynced(e){return this._doc.onSynced(()=>{e(),this._notify()})}text(e){let n=this._doc.text(e),r=this._notify;return{append(o){n.append(o),r()},toString:()=>n.toString(),get length(){return n.length},on:(o,s)=>n.on(o,a=>{s(a),r()})}}dispose(){this._unsubscribeChange()}},Ke=class{constructor(e,n){this._stream=e;this._notify=n;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(e){return this._stream.attach(e)}attachVideo(e){return this._stream.attachVideo(e)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(e){return this._stream.seek(e)}chunks(e){return this._stream.chunks(e)}onSeeked(e){return this._stream.onSeeked(e)}on(e,n){return this._stream.on(e,n)}messages(){return this._stream.messages()}emit(e,n){return this._stream.emit(e,n)}dispose(){this._unsubscribeTrack()}},Je=class{constructor(e,n,r){this._session=e;this._notifiers.add(n),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),r&&this._attachReporter(r)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(e){let n=!1,r=!1,o=i=>{fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0}).catch(()=>{r||(r=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(o);let s=this._session.onPhase(i=>{if(i.name==="error"||i.name==="expired"){let u=i.error,c=u?.reason??(i.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);o({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else i.name==="live"&&!n&&(n=!0,o({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),a=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{a(),s()}}addNotifier(e){this._notifiers.add(e)}removeNotifier(e){this._notifiers.delete(e)}_notifyAll(){for(let e of this._notifiers)e()}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(e){return this._session.onPhase(e)}onDiagnostic(e){return this._session.onDiagnostic(e)}whenLive(e){return this._session.whenLive(e)}recover(){this._session.recover()}onRecovery(e){return this._session.onRecovery(e)}request(e,n){return this._session.request(e,n)}requestStream(e,n){return this._session.requestStream(e,n)}complete(e,n){return this._session.complete(e,n)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(e){let n=this._docs.get(e);return n||(n=new je(this._session.doc(e),()=>this._notifyAll()),this._docs.set(e,n)),n}stream(e){let n=this._streams.get(e);return n||(n=new Ke(this._session.stream(e),()=>this._notifyAll()),this._streams.set(e,n)),n}async end(){let e=await this._session.end();return this._disposeHandle(),e}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let e of this._docs.values())e.dispose();for(let e of this._streams.values())e.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function _n(){let t=xn(ue);if(!t)throw new Error("useApp must be used within <UrunProvider>");if(!t.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,e]=Un(s=>s+1,0),n=Ct(new Map),r=Ct(new Map),o=bt(()=>En(t.appId,{baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),[t.appId,t.baseUrl,t.orgId,t.jwt,t.getAccessToken,t.authProvider]);return Rn(()=>()=>{for(let[s,a]of r.current){let i=ce.get(s);i===a&&(i.handle.removeNotifier(e),i.refCount=Math.max(0,i.refCount-1),i.refCount===0&&(i.disposeTimer=setTimeout(()=>{let u=ce.get(s);!u||u.refCount!==0||(ce.delete(s),u.handle.disconnect())},0)))}r.current.clear(),n.current.clear()},[]),bt(()=>new Proxy({},{get(s,a){if(typeof a=="string")return i=>{let u=wn(a,i),c=n.current.get(u);if(c&&!c.disposed)return c;let p=An(t,a,i),l=ce.get(p);return l?.handle.disposed&&(l.disposeTimer&&clearTimeout(l.disposeTimer),ce.delete(p),r.current.get(p)===l&&r.current.delete(p),l=void 0),l?l.disposeTimer&&(clearTimeout(l.disposeTimer),l.disposeTimer=null):(l={handle:new Je(o[a](i),e,t.eventsUrl),refCount:0,disposeTimer:null},ce.set(p,l)),r.current.get(p)!==l&&(r.current.set(p,l),l.handle.addNotifier(e),l.refCount+=1),n.current.set(u,l.handle),l.handle}}}),[t,o])}import{useCallback as ze,useEffect as Mn,useMemo as Nn,useRef as Ue,useState as Xe}from"react";function le(t){let e=t;if(!e||typeof e.request!="function"||typeof e.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 e}function In(t){return t instanceof Error?t:new Error(String(t))}function Dn(t,e){let n=Nn(()=>le(t),[t]),[r,o]=Xe(void 0),[s,a]=Xe(null),[i,u]=Xe(!1),c=Ue(e);c.current=e;let p=Ue(0),l=Ue(null),f=Ue(!0);Mn(()=>(f.current=!0,()=>{f.current=!1,l.current?.abort()}),[]);let g=ze(async S=>{l.current?.abort();let y=new AbortController;l.current=y;let T=++p.current,C=()=>f.current&&p.current===T;C()&&(u(!0),a(null));try{let U=await n.request(S,{...c.current,signal:y.signal});return C()&&(o(U),u(!1),c.current?.onSuccess?.(U)),U}catch(U){let h=In(U);throw C()&&(a(h),u(!1),c.current?.onError?.(h)),h}},[n]),v=ze(S=>{g(S).catch(()=>{})},[g]),k=ze(()=>{p.current++,l.current?.abort(),l.current=null,o(void 0),a(null),u(!1)},[]);return{mutate:v,mutateAsync:g,data:r,error:s,isPending:i,reset:k}}import{useCallback as Pt,useEffect as Ln,useMemo as On,useRef as Ee,useState as Ge}from"react";function Tt(t){return t instanceof Error?t:new Error(String(t))}var qn=t=>typeof t=="string"?t:String(t);function Fn(t,e){let n=On(()=>le(t),[t]),[r,o]=Ge(""),[s,a]=Ge(!1),[i,u]=Ge(null),c=Ee(e);c.current=e;let p=Ee(0),l=Ee(null),f=Ee(!0);Ln(()=>(f.current=!0,()=>{f.current=!1,l.current?.cancel(),l.current=null}),[]);let g=Pt(()=>{p.current++,l.current?.cancel(),l.current=null,f.current&&a(!1)},[]),v=Pt(async k=>{l.current?.cancel();let S=++p.current,y=()=>f.current&&p.current===S,T=c.current,C=T?.parseChunk??qn,U=T?.buildPayload??(P=>({prompt:P}));y()&&(o(""),u(null),a(!0));let{parseChunk:h,buildPayload:E,onFinish:A,onError:d,...b}=T??{},x="",R;try{R=n.requestStream(U(k),b),l.current=R}catch(P){let q=Tt(P);y()&&(u(q),a(!1),T?.onError?.(q));return}try{for await(let P of R){if(p.current!==S)break;x+=C(P),y()&&o(x)}y()&&(a(!1),T?.onFinish?.(x))}catch(P){let q=Tt(P);y()&&(u(q),a(!1),T?.onError?.(q))}finally{l.current===R&&(l.current=null)}},[n]);return{completion:r,complete:v,stop:g,isStreaming:s,error:i}}import{useCallback as xt,useEffect as Wn,useMemo as Vn,useRef as de,useState as we}from"react";function Rt(t){return t instanceof Error?t:new Error(String(t))}var Bn=t=>typeof t=="string"?t:String(t),Ut=0;function Ze(t){return Ut+=1,`${t}-${Ut}`}function Hn(t,e){let n=Vn(()=>le(t),[t]),[r,o]=we(()=>(e?.initialMessages??[]).map(C=>({id:C.id??Ze("msg"),role:C.role,content:C.content}))),[s,a]=we(""),[i,u]=we(!1),[c,p]=we(null),l=de(e);l.current=e;let f=de(r);f.current=r;let g=de(s);g.current=s;let v=de(0),k=de(null),S=de(!0);Wn(()=>(S.current=!0,()=>{S.current=!1,k.current?.cancel(),k.current=null}),[]);let y=xt(()=>{v.current++,k.current?.cancel(),k.current=null,S.current&&u(!1)},[]),T=xt(async C=>{let U=C===void 0,h=(U?g.current:C)??"";if(!h.trim())return;k.current?.cancel();let A=++v.current,d=()=>S.current&&v.current===A,b=l.current,x=b?.parseChunk??Bn,R={id:Ze("msg"),role:"user",content:h},P={id:Ze("msg"),role:"assistant",content:""},q=[...f.current,R].map(L=>({role:L.role,content:L.content})),m=[...f.current,R,P];f.current=m,o(m),U&&a(""),p(null),u(!0);let M=b?.buildPayload??(L=>({messages:L})),{initialMessages:D,parseChunk:F,buildPayload:N,onFinish:J,onError:Te,...xe}=b??{},se=L=>{o(I=>I.map(z=>z.id===P.id?{...z,content:L}:z))},Q="",H;try{H=n.requestStream(M(q),xe),k.current=H}catch(L){let I=Rt(L);d()&&(p(I),u(!1),b?.onError?.(I));return}try{for await(let L of H){if(v.current!==A)break;Q+=x(L),d()&&se(Q)}d()&&(u(!1),b?.onFinish?.({...P,content:Q}))}catch(L){let I=Rt(L);d()&&(p(I),u(!1),b?.onError?.(I))}finally{k.current===H&&(k.current=null)}},[n]);return{messages:r,input:s,setInput:a,sendMessage:T,stop:y,isStreaming:i,error:c}}import{useCallback as G,useEffect as Et,useMemo as $n,useRef as wt,useState as At}from"react";import{createInputPresencePublisher as jn,INPUT_PRESENCE_DEFAULT_HZ as Kn,INPUT_PRESENCE_FIELD as Jn}from"@urun-sh/core";var Ye=[];function zn(t,e={}){let{field:n=Jn,hz:r=Kn}=e,o=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null,s=t?.presence??null,a=$n(()=>s?jn({awareness:{setLocalStateField:(h,E)=>s.setField(h,E)},field:n,hz:r}):null,[s,n,r]),i=wt(null);i.current=a;let[u,c]=At(!1),[p,l]=At(Ye),f=wt(!1);Et(()=>{if(a)return()=>a.dispose()},[a]);let g=G(()=>{let h=i.current;l(h?h.heldKeys():Ye)},[]),v=G(()=>{i.current?.clear(),l(Ye)},[]);Et(()=>{if(!o)return;let h=()=>!!o.pointerLockElement,E=()=>{if(h()){f.current=!1,c(!0);return}f.current||(c(!1),v())},A=P=>{h()&&(i.current?.keyDown(P.key),g())},d=P=>{i.current?.keyUp(P.key),g()},b=P=>{h()&&i.current?.movePointer(P.movementX,P.movementY)},x=P=>{h()&&i.current?.setButtons(P.buttons)},R=()=>{v()};return o.addEventListener("pointerlockchange",E),o.addEventListener("keydown",A),o.addEventListener("keyup",d),o.addEventListener("mousemove",b),o.addEventListener("mousedown",x),o.addEventListener("mouseup",x),o.defaultView?.addEventListener("blur",R),()=>{o.removeEventListener("pointerlockchange",E),o.removeEventListener("keydown",A),o.removeEventListener("keyup",d),o.removeEventListener("mousemove",b),o.removeEventListener("mousedown",x),o.removeEventListener("mouseup",x),o.defaultView?.removeEventListener("blur",R)}},[o,v,g]);let k=G(h=>{h.requestPointerLock?.()},[]),S=G(()=>{f.current=!0,c(!0)},[]),y=G(()=>{f.current=!1,o?.pointerLockElement&&o.exitPointerLock?.(),c(!1),v()},[o,v]),T=G(h=>{i.current?.keyDown(h),g()},[g]),C=G(h=>{i.current?.keyUp(h),g()},[g]),U=G((h,E)=>{i.current?.movePointer(h,E)},[]);return{engage:k,engageTouch:S,release:y,engaged:u,heldKeys:p,pressKey:T,releaseKey:C,movePointer:U}}var _t=new Map;function Xn(t,e,n){if(!n||typeof n.safeParse!="function")throw new Error(`registerComponent("${t}"): schema must be a valid Zod schema`);_t.set(t,{component:e,schema:n})}function Mt(t,e){let n=_t.get(t);if(!n)return{error:`Unknown component: "${t}"`};let r=n.schema.safeParse(e);return r.success?{Component:n.component,validatedProps:r.data}:{error:`Validation failed for "${t}": ${r.error.message}`}}import{Fragment as Zn,jsx as Ae}from"react/jsx-runtime";function Gn({name:t,props:e,fallback:n}){let r=Mt(t,e);if(r.error)return console.warn(`[urun] ComponentRenderer: ${r.error}`),n?Ae(Zn,{children:n}):Ae("div",{className:"urun-component-error",role:"alert",children:Ae("span",{className:"urun-component-error-text",children:r.error})});let o=r.Component;return Ae(o,{...r.validatedProps})}import{z as ve}from"zod";import{jsx as Qe,jsxs as Nt}from"react/jsx-runtime";var Yn=ve.object({step:ve.number().min(0),total:ve.number().min(1),label:ve.string().optional(),variant:ve.enum(["default","success","error"]).default("default")});function It(t){let{step:e,total:n,label:r,variant:o="default"}=t,s=Math.min(e/n*100,100),a=e>=n;return{step:e,total:n,label:r,variant:o,percentage:s,isComplete:a}}function Qn(t){let{step:e,total:n,label:r,variant:o,percentage:s}=It(t);return Nt("div",{className:"urun-progress-card","data-variant":o,children:[r&&Qe("div",{className:"urun-progress-label",children:r}),Qe("div",{className:"urun-progress-bar",children:Qe("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Nt("div",{className:"urun-progress-text",children:[e,"/",n]})]})}import{z as et}from"zod";import{jsx as Dt,jsxs as rr}from"react/jsx-runtime";var er=et.object({state:et.enum(["thinking","generating","idle","error"]),message:et.string().optional()}),tr={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Lt(t){let{state:e,message:n}=t,r=e==="thinking"||e==="generating",o=n??tr[e]??e;return{state:e,message:o,isActive:r}}function nr(t){let{state:e,message:n,isActive:r}=Lt(t);return rr("span",{className:"urun-status-badge","data-state":e,children:[Dt("span",{className:`urun-status-indicator${r?" urun-status-pulse":""}`}),Dt("span",{className:"urun-status-message",children:n})]})}import{useRef as Ot,useEffect as or}from"react";import{z as tt}from"zod";import{jsx as qt,jsxs as ar}from"react/jsx-runtime";var sr=tt.object({text:tt.string(),streaming:tt.boolean().default(!1)});function Ft(t){let{text:e,streaming:n=!1}=t,r=e.length===0;return{text:e,streaming:n,isEmpty:r}}function ir(t){let{text:e,streaming:n}=Ft(t),r=Ot(null),o=Ot(0);return or(()=>{let s=r.current;s&&e.length!==o.current&&(s.textContent=e,o.current=e.length)},[e]),ar("div",{className:"urun-text-stream",children:[qt("span",{ref:r,className:"urun-text-content"}),n&&qt("span",{className:"urun-text-cursor"})]})}import{z as _e}from"zod";import{jsx as Wt,jsxs as lr}from"react/jsx-runtime";var ur=_e.object({src:_e.string().url(),alt:_e.string().optional(),caption:_e.string().optional()});function Vt(t){let{src:e,alt:n,caption:r}=t;return{src:e,alt:n??"",caption:r}}function cr(t){let{src:e,alt:n,caption:r}=Vt(t);return lr("figure",{className:"urun-image-frame",children:[Wt("img",{className:"urun-image",src:e,alt:n}),r&&Wt("figcaption",{className:"urun-image-caption",children:r})]})}import{z as Z}from"zod";import{jsx as nt,jsxs as mr}from"react/jsx-runtime";var dr=Z.object({metrics:Z.array(Z.object({label:Z.string(),value:Z.union([Z.string(),Z.number()]),unit:Z.string().optional()}))});function Bt(t){return{metrics:t.metrics.map(n=>({...n,displayValue:n.unit?`${n.value} ${n.unit}`:String(n.value)}))}}function pr(t){let{metrics:e}=Bt(t);return nt("div",{className:"urun-metrics-panel",children:e.map((n,r)=>mr("div",{className:"urun-metric-card",children:[nt("div",{className:"urun-metric-label",children:n.label}),nt("div",{className:"urun-metric-value",children:n.displayValue})]},r))})}import{forwardRef as gr,useCallback as pe,useEffect as rt,useImperativeHandle as hr,useRef as me}from"react";import{observePageLifecycle as Sr}from"@urun-sh/core";var Me=null;function fr(){if(typeof window>"u")return null;let t=window;return t.AudioContext??t.webkitAudioContext??null}function Ne(){if(Me)return Me;let t=fr();return t?(Me=new t,Me):null}function Ie(){let t=Ne();t&&t.state==="suspended"&&t.resume().catch(()=>{})}import{jsx as yr}from"react/jsx-runtime";var vr=1e3,Ht=200;function ot(...t){console.debug("[urun-audio]",...t)}var st=gr(function(e,n){let{session:r,stream:o="audio",track:s,controls:a=!1,className:i,onTrack:u,onUnlockChange:c,onAudioElement:p}=e,l=me(null),f=me(null),g=me(null),v=me(null),k=me(u);k.current=u;let S=me(c);S.current=c;let y=pe(d=>{g.current!==d&&(g.current=d,S.current?.(d))},[]),T=pe(()=>{if(typeof MediaStream>"u")return null;f.current||(f.current=new MediaStream);let d=l.current;return d&&d.srcObject!==f.current&&(d.srcObject=f.current),f.current},[]),C=pe(d=>{let b=l.current;if(!b)return;let x=b.play();!x||typeof x.then!="function"||x.then(()=>{b.muted||y(!0)}).catch(R=>{let P=R instanceof Error?R.name:String(R);if(P==="AbortError"){ot(`play() aborted (${d}); retrying in ${Ht}ms`),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,C(`${d}:retry`)},Ht);return}if(P==="NotAllowedError"){ot(`play() blocked pending a user gesture (${d})`),y(!1);return}ot(`play() failed (${d})`,R)})},[y]),U=pe(d=>{let b=T();if(b){for(let x of b.getAudioTracks())x!==d&&b.removeTrack(x);d&&!b.getAudioTracks().includes(d)&&b.addTrack(d),d&&C("track-attach"),k.current?.(d)}},[T,C]),h=pe(()=>{let d=l.current;d&&(T(),d.muted=!1,C("gesture"),Ie(),y(!0))},[T,C,y]);hr(n,()=>({unlock:h,get unlocked(){return g.current===!0},get element(){return l.current}}),[h]);let E=pe(d=>{l.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),T()),p?.(d)},[T,p]),A=s!==void 0;return rt(()=>{if(A){U(s??null);return}if(!r)return;let d=r.stream(o),b=()=>{let m=f.current;return m?m.getAudioTracks()[0]??null:null},x=m=>{if(m!==b()&&(U(m),m)){let M=()=>{b()===m&&U(null)};m.addEventListener("ended",M)}},R=d.track;R&&R.readyState==="live"&&x(R);let P=d.on("track",m=>{m&&m.readyState!=="live"||x(m)}),q=setInterval(()=>{let m=d.track;m&&m.readyState==="live"&&x(m)},vr);return()=>{P(),clearInterval(q)}},[r,o,A,s,U]),rt(()=>Sr(()=>{Ie(),g.current===!0&&C("foreground")}),[C]),rt(()=>()=>{v.current&&clearTimeout(v.current)},[]),yr("audio",{ref:E,className:i,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})});import{forwardRef as kr,useCallback as fe,useEffect as $t,useImperativeHandle as br,useRef as j}from"react";import{observePageLifecycle as Cr,sessionFailureFromMediaError as Pr,sharedCaptureController as Tr}from"@urun-sh/core";import{jsx as Rr}from"react/jsx-runtime";var jt={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function De(...t){console.debug("[urun-voice]",...t)}var xr=kr(function(e,n){let{session:r,stream:o="audio",constraints:s=jt,connectTimeoutMs:a,attempts:i=3,retryDelayMs:u=1500,onActiveChange:c,onError:p,onMicStream:l,onTrack:f,onUnlockChange:g,capture:v}=e,k=j(null),S=j(null),y=j(null),T=j([]),C=j(!1),U=j(c);U.current=c;let h=j(p);h.current=p;let E=j(l);E.current=l;let A=fe(m=>{C.current!==m&&(C.current=m,U.current?.(m))},[]),d=fe(()=>{for(let m of T.current)m();T.current=[],y.current?.release(),y.current=null,S.current&&(S.current=null,E.current?.(null))},[]),b=fe(async()=>{let m=y.current;if(m){let N=await m.update(s);return S.current=m.stream,E.current?.(m.stream),N}let D=await(v??Tr()).claim("audio",s);y.current=D,T.current=[D.onTrack((N,J)=>{S.current=J,E.current?.(J),C.current&&r.stream(o).attach(N).catch(Te=>De("mic re-attach after one-capture re-acquire failed",Te))}),D.onLost(N=>{y.current=null,T.current=[],S.current=null,E.current?.(null),A(!1),h.current?.(N)})],S.current=D.stream,E.current?.(D.stream);let F=D.track;if(!F)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return F},[v,s,r,o,A]),x=fe(async()=>{d(),A(!1),await r.stream(o).detach().catch(()=>{})},[r,o,d,A]),R=fe(async()=>{k.current?.unlock();let m;try{m=await b()}catch(F){d();let N=Pr(F,r.status);throw h.current?.(N),N}r.connect?.();let M;for(let F=1;F<=i;F++)try{await r.whenLive(a!==void 0?{timeout:a}:void 0),await r.stream(o).attach(m),A(!0);return}catch(N){M=N,De(`start attempt ${F}/${i} failed`,N),F<i&&await new Promise(J=>setTimeout(J,u))}d(),A(!1);let D=M instanceof Error?M:new Error(String(M??"voice start failed"));throw h.current?.(D),D},[r,o,a,i,u,b,d,A]);br(n,()=>({start:R,stop:x,unlock:()=>k.current?.unlock(),get active(){return C.current},get micStream(){return S.current},get audio(){return k.current}}),[R,x]);let P=j(!1),q=fe(async()=>{if(!C.current||P.current)return;let m=S.current?.getAudioTracks()[0]??null;if(m&&m.readyState==="live"){try{await r.stream(o).attach(m)}catch(M){De("foreground mic re-assert failed (will retry on next pass)",M)}return}P.current=!0;try{let M=await b();await r.stream(o).attach(M)}catch(M){let D=M instanceof Error?M:new Error(String(M));De("foreground mic re-acquire failed",D),h.current?.(D)}finally{P.current=!1}},[r,o,b]);return $t(()=>{let m=()=>{q()};return typeof r.onRecovery=="function"?r.onRecovery(m):Cr(m)},[r,q]),$t(()=>d,[d]),Rr(st,{ref:k,session:r,stream:o,onTrack:f,onUnlockChange:g})});import{sessionFailureFromMediaError as Ur,sharedCaptureController as Er}from"@urun-sh/core";import{forwardRef as wr,useCallback as K,useEffect as Kt,useImperativeHandle as Ar,useRef as V,useState as ye}from"react";import{jsx as te,jsxs as Jt}from"react/jsx-runtime";var zt={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function it(...t){console.debug("[urun-camera]",...t)}function _r(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Mr(){let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof t?.enumerateDevices!="function")return null;try{return(await t.enumerateDevices()).filter(n=>n.kind==="videoinput")}catch{return null}}var Nr=wr(function(e,n){let{session:r,stream:o="video",constraints:s,facingMode:a="environment",mirror:i="auto",connectTimeoutMs:u,preview:c=!0,className:p,videoClassName:l,onActiveChange:f,onError:g,onStream:v,onTrack:k,children:S,capture:y,flipControl:T="auto",flipControlClassName:C,onDevices:U}=e,h=V(null),E=V(null),A=V(null),d=V([]),b=V(null),x=V(!1),R=V(a),[P,q]=ye(a),[m,M]=ye(!1),[D,F]=ye(null),[N,J]=ye(!1),[Te]=ye(_r),xe=V(f);xe.current=f;let se=V(g);se.current=g;let Q=V(v);Q.current=v;let H=V(k);H.current=k;let L=V(U);L.current=U;let I=K(w=>{x.current!==w&&(x.current=w,M(w),xe.current?.(w))},[]);Kt(()=>{if(!m){F(null);return}let w=!1,_=()=>{Mr().then(W=>{w||(F(W),W&&L.current?.(W))})};_();let O=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof O?.addEventListener=="function"?(O.addEventListener("devicechange",_),()=>{w=!0,O.removeEventListener?.("devicechange",_)}):()=>{w=!0}},[m]);let z=K(w=>{let _=h.current;_&&(_.muted=!0,_.defaultMuted=!0,_.setAttribute("muted",""),_.setAttribute("playsinline",""),_.setAttribute("webkit-playsinline",""),_.srcObject=w,w&&_.play()?.catch?.(O=>it("preview play() failed",O)))},[]),$=K(()=>{b.current?.(),b.current=null;for(let w of d.current)w();d.current=[],A.current?.release(),A.current=null,E.current&&(E.current=null,Q.current?.(null),H.current?.(null)),z(null)},[z]),Ve=K((w,_)=>{b.current?.(),E.current=_,z(_),Q.current?.(_);let O=()=>{E.current===_&&(it("camera track ended (device removed or permission revoked)"),$(),I(!1))};w.addEventListener("ended",O),b.current=()=>w.removeEventListener("ended",O)},[z,$,I]),ie=K(async w=>{let _={...zt,...s,facingMode:w},O;try{let W=A.current;if(W)O=await W.update(_);else{let ge=await(y??Er()).claim("video",_);if(A.current=ge,d.current=[ge.onTrack((he,mn)=>{Ve(he,mn),x.current&&r.stream(o).attachVideo(he).then(()=>H.current?.(he)).catch(fn=>it("camera re-publish after one-capture re-acquire failed",fn))}),ge.onLost(he=>{A.current=null,d.current=[],$(),I(!1),se.current?.(he)})],!ge.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});O=ge.track}}catch(W){let ae=Ur(W,r.status);throw se.current?.(ae),ae}R.current=w,q(w),Ve(O,A.current?.stream??new MediaStream([O]));try{r.connect?.(),await r.whenLive(u!==void 0?{timeout:u}:void 0),await r.stream(o).attachVideo(O)}catch(W){$(),I(!1);let ae=W instanceof Error?W:new Error(String(W));throw se.current?.(ae),ae}H.current?.(O),I(!0)},[r,o,s,u,y,Ve,$,I]),St=K(w=>ie(w?.facingMode??R.current),[ie]),vt=K(async w=>{x.current&&R.current===w||await ie(w)},[ie]),Be=K(()=>ie(R.current==="environment"?"user":"environment"),[ie]),yt=K(async()=>{$(),I(!1),await r.stream(o).detachVideo().catch(()=>{})},[r,o,$,I]);if(Ar(n,()=>({start:St,stop:yt,flip:Be,setFacingMode:vt,get active(){return x.current},get facingMode(){return R.current},get stream(){return E.current},get element(){return h.current}}),[St,yt,Be,vt]),Kt(()=>$,[$]),!c)return null;let ln=i==="auto"?P==="user":i,dn=m&&(T===!0||T==="auto"&&Te&&(D?.length??0)>1),pn=()=>{N||(J(!0),Be().catch(()=>{}).finally(()=>J(!1)))};return Jt("div",{className:p,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":P,children:[te("video",{ref:h,className:l,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...ln?{transform:"scaleX(-1)"}:{}}}),dn?te("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:pn,disabled:N,className:C,style:C?{opacity:N?.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:N?.6:1},children:Jt("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:[te("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),te("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),te("path",{d:"M14.5 10.5v1.6h-1.6"}),te("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),te("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,S]})});import{useEffect as Ir,useState as Dr}from"react";var at={level:0,speaking:!1};function Lr(t,e={}){let{fftSize:n=512,intervalMs:r=100,speakingThreshold:o=.02}=e,[s,a]=Dr(at);return Ir(()=>{if(!t){a(at);return}let i=Ne();if(!i||typeof MediaStream>"u")return;let u;t instanceof MediaStream?u=t:(u=new MediaStream,u.addTrack(t));let c,p;try{c=i.createMediaStreamSource(u),p=i.createAnalyser(),p.fftSize=n,c.connect(p)}catch{return}let l=new Uint8Array(p.fftSize),g=setInterval(()=>{p.getByteTimeDomainData(l);let v=0;for(let S=0;S<l.length;S++){let y=(l[S]-128)/128;v+=y*y}let k=Math.sqrt(v/l.length);a(S=>{let y=k>o;return Math.abs(S.level-k)<.005&&S.speaking===y?S:{level:k,speaking:y}})},r);return()=>{clearInterval(g),c.disconnect(),a(at)}},[t,n,r,o]),s}import{useEffect as Or,useState as qr}from"react";function Fr(t,e){let[n,r]=qr(null);return Or(()=>{if(!t||!e){r(null);return}let o=t.stream(e);return r(o.track),o.on("track",r)},[t,e]),n}import{useCallback as jr}from"react";import{useEffect as Hr,useMemo as $r}from"react";import{createStore as Wr}from"zustand/vanilla";import{useStore as Vr}from"zustand";var Br=()=>{};function ut(t,e={}){let n=c=>{t?.set(c)},r=()=>t?t.get()??{}:{},o=Wr(()=>({doc:r(),synced:t?t.synced:!1,set:n})),s=null,a=()=>{if(s){for(let c of s)c();s=null}},i=()=>t?(s||(o.setState({doc:r(),synced:t.synced}),s=[t.on("change",c=>o.setState({doc:c})),t.onSynced(()=>o.setState({synced:!0}))]),a):Br,u=(c=>Vr(o,c));return Object.assign(u,{getState:o.getState,getInitialState:o.getInitialState,subscribe:o.subscribe,set:n,bind:i,unbind:a}),e.bind!==!1&&i(),u}function ke(t,e){let n=$r(()=>ut(t&&e?t.doc(e):null,{bind:!1}),[t,e]);return Hr(()=>n.bind(),[n]),n}function Kr(t,e,n){let o=ke(t,e)(n??(i=>i)),s=jr(i=>{t&&e&&t.doc(e).set(i)},[t,e]);if(n)return o;let a=o;return{snapshot:t&&e?a.doc:null,synced:a.synced,set:s}}import{useEffect as Jr,useState as zr}from"react";var ne=200;function Y(t,e,n=200){let r=[...t,e];return r.length>n?r.slice(r.length-n):r}function be(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function ct(t){let e=t.trim();if(!e)return{ok:!1,error:"Enter a JSON object."};let n;try{n=JSON.parse(e)}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Invalid JSON."}}return n===null||typeof n!="object"||Array.isArray(n)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:n}}function lt(t,e,n={}){let r=n.cap??200,[o,s]=zr([]);return Jr(()=>{if(s([]),!t||!e)return;let a=!0,i=t.stream(e).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await i.next();if(!a||u.done)break;s(c=>Y(c,{at:Date.now(),payload:u.value},r))}})(),()=>{a=!1,i.return?.()}},[t,e,r]),o}import{jsx as Le,jsxs as Ce}from"react/jsx-runtime";function Xr({session:t,name:e,cap:n,className:r}){let o=lt(t,e,{cap:n});return Ce("div",{className:["urun-stream-tail",r].filter(Boolean).join(" "),children:[Ce("div",{className:"urun-stream-tail-meta",children:[Le("code",{children:e}),Ce("span",{className:"urun-stream-tail-count",children:[o.length," messages"]})]}),Le("div",{className:"urun-stream-tail-log",children:o.length===0?Ce("span",{className:"urun-stream-tail-empty",children:["Waiting for ",Le("code",{children:e})," messages\u2026"]}):o.map((s,a)=>Ce("div",{className:"urun-stream-tail-line",children:[Le("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",be(s.payload)]},`${s.at}-${a}`))})]})}import{useCallback as Gr,useState as Xt}from"react";import{jsx as re,jsxs as Oe}from"react/jsx-runtime";function qe({placeholder:t,buttonLabel:e,disabled:n,onApply:r}){let[o,s]=Xt(""),[a,i]=Xt(null),u=Gr(()=>{let c=ct(o);if(!c.ok){i(c.error);return}i(null),r(c.value,o.trim()),s("")},[o,r]);return Oe("div",{className:"urun-doc-patch",children:[re("textarea",{className:"urun-doc-patch-input",value:o,onChange:c=>s(c.target.value),placeholder:t,rows:3}),Oe("div",{className:"urun-doc-patch-actions",children:[re("button",{type:"button",className:"urun-doc-patch-button",disabled:n||!o.trim(),onClick:u,children:e}),a?re("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function Zr({session:t,docKey:e,editable:n=!0,patchPlaceholder:r='{"desired": {"prompt": {"text": "a sunset"}}}',className:o}){let s=ke(t,e),a=s(c=>c.doc),i=s(c=>c.synced),u=s(c=>c.set);return Oe("div",{className:["urun-doc-panel",o].filter(Boolean).join(" "),children:[Oe("div",{className:"urun-doc-panel-meta",children:[re("code",{children:e}),re("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),re("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),n?re(qe,{placeholder:r,buttonLabel:"Apply patch",disabled:!t,onApply:c=>u(c)}):null]})}import{useEffect as Yr,useState as Qr}from"react";import{jsx as Pe,jsxs as Zt}from"react/jsx-runtime";function Gt(t,e=600){return t.length>e?`${t.slice(0,e)}\u2026`:t}function eo({session:t,docKey:e="control",cap:n=200,className:r}){let[o,s]=Qr([]);return Yr(()=>(s([]),t?t.doc(e).on("change",i=>{s(u=>Y(u,{at:Date.now(),direction:"in",text:Gt(be(i))},n))}):void 0),[t,e,n]),Zt("div",{className:["urun-control-sender",r].filter(Boolean).join(" "),children:[Pe(qe,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${e}`,disabled:!t,onApply:(a,i)=>{t?.doc(e).set(a),s(u=>Y(u,{at:Date.now(),direction:"out",text:Gt(i)},n))}}),Pe("div",{className:"urun-control-sender-log",children:o.length===0?Pe("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...o].reverse().map((a,i)=>Zt("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[Pe("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",Pe("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${i}`))})]})}import{useEffect as to,useState as no}from"react";import{jsx as Fe,jsxs as oo}from"react/jsx-runtime";function ro({session:t,trackNames:e=["video","audio"],docKeys:n=["control"],cap:r=200,className:o}){let[s,a]=no([]),i=e.join(","),u=n.join(",");return to(()=>{if(a([]),!t)return;let c=(l,f)=>a(g=>Y(g,{at:Date.now(),kind:l,text:f},r)),p=[];p.push(t.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of e){let f=t.stream(l);p.push(f.on("track",g=>c("track",`${l}: ${g?"track arrived":"track ended"}`)))}for(let l of n){let f=t.doc(l);p.push(f.on("change",()=>c("doc",`${l} changed`)))}return()=>p.forEach(l=>l())},[t,i,u,r]),Fe("div",{className:["urun-event-spine",o].filter(Boolean).join(" "),children:s.length===0?Fe("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,p)=>oo("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[Fe("span",{className:"urun-event-spine-kind",children:c.kind})," ",Fe("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${p}`))})}import{describeSessionPhase as ko,isWakingPhase as bo}from"@urun-sh/core";import{useEffect as so,useState as io}from"react";function B(t){let[e,n]=io(t?.phase??null);return so(()=>{if(!t){n(null);return}return t.onPhase(n)},[t]),e}import{describeSessionPhase as po}from"@urun-sh/core";import{useEffect as ao,useRef as uo,useState as co}from"react";import{isWakingPhase as lo}from"@urun-sh/core";function dt(t){let e=B(t),n=lo(e?.name),r=uo(void 0);n?r.current??=Date.now():r.current=void 0;let o=n?e?.wakingSince??r.current:void 0,s=()=>o!==void 0?Math.max(0,Math.floor((Date.now()-o)/1e3)):0,[a,i]=co(s);return ao(()=>{if(o===void 0){i(0);return}i(Math.max(0,Math.floor((Date.now()-o)/1e3)));let u=setInterval(()=>{i(Math.max(0,Math.floor((Date.now()-o)/1e3)))},1e3);return()=>clearInterval(u)},[o]),{waking:n,phase:e,state:n?e?.runtime?.state:void 0,reason:n?e?.runtime?.reason:void 0,since:o,seconds:n?a:0}}import{Fragment as mo,jsx as Yt,jsxs as Qt}from"react/jsx-runtime";function pt({session:t,render:e,className:n}){let r=dt(t);return!r.waking||!r.phase?null:Yt("span",{className:["urun-session-waking",n].filter(Boolean).join(" "),"data-phase":r.phase.name,"data-runtime-state":r.state,children:e?e(r):Qt(mo,{children:[Yt("span",{className:"urun-session-waking-label",children:po(r.phase)})," ",Qt("span",{className:"urun-session-waking-elapsed",children:["(",r.seconds,"s)"]})]})})}import{useEffect as ho,useState as So}from"react";import{useEffect as en,useRef as fo,useState as tn}from"react";var go={event:null,elapsedMs:0};function mt(t,e){let[n,r]=tn(null),o=fo(0);en(()=>{if(r(null),!!t?.onActivation)return t.onActivation(i=>{e!==void 0&&i.stream!==e||(o.current=Date.now(),r(i))})},[t,e]);let[s,a]=tn(0);return en(()=>{if(!n){a(0);return}if(n.state==="first-media"){a(n.elapsedMs);return}let i=o.current,u=()=>n.elapsedMs+Math.max(0,Date.now()-i);a(u());let c=setInterval(()=>a(u()),1e3);return()=>clearInterval(c)},[n]),n?{event:n,elapsedMs:s}:go}import{jsx as nn,jsxs as rn}from"react/jsx-runtime";var vo={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 yo(t){let[e,n]=So(!1);return ho(()=>{if(n(!1),!t)return;let r=t;if(typeof r.requestVideoFrameCallback=="function"){let s=r.requestVideoFrameCallback(()=>n(!0));return()=>r.cancelVideoFrameCallback?.(s)}let o=()=>{let s=r.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:r.readyState>=2)&&n(!0)};return o(),r.addEventListener("loadeddata",o),r.addEventListener("timeupdate",o),()=>{r.removeEventListener("loadeddata",o),r.removeEventListener("timeupdate",o)}},[t]),e}function ft({session:t,stream:e,videoElement:n,render:r,className:o}){let s=mt(t,e),a=yo(n),i=s.event;if(!i||i.state==="first-media"||a)return null;let u=i.state;return nn("div",{className:["urun-activation-overlay",o].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:r?r(s):rn("div",{className:"urun-activation-overlay-card",children:[nn("span",{className:"urun-activation-overlay-copy",children:i.hint??vo[u]})," ",rn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as oe,jsxs as gt}from"react/jsx-runtime";var Co={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Po({session:t,className:e}){let n=B(t),r=n?.name??"idle",o=n?.name==="queued"&&n.queue?`pos ${n.queue.position} / depth ${n.queue.depth}`:(n?.name==="error"||n?.name==="expired")&&n.error?n.error.reason:n?.runtime?.reason??null;return gt("span",{className:["urun-session-status",e].filter(Boolean).join(" "),"data-phase":r,children:[oe("span",{className:"urun-session-status-dot","data-phase":r}),oe("span",{className:"urun-session-status-label",children:Co[r]}),o?oe("span",{className:"urun-session-status-detail",children:o}):null]})}function To({session:t,children:e,fallback:n,onStartOver:r,className:o}){let s=B(t);if(s?.name==="live")return gt("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:[e,oe(ft,{session:t})]});let a=n?n(s):oe("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&bo(s.name)?oe(pt,{session:t}):s&&s.name!=="idle"?ko(s):"Waiting for a live session\u2026"}),i=r!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return gt("div",{className:["urun-session-gate",o].filter(Boolean).join(" "),children:[a,i?oe("button",{type:"button",className:"urun-session-gate-start-over",onClick:r,children:"Start over"}):null]})}import{useEffect as xo,useState as Ro}from"react";import{jsx as wo}from"react/jsx-runtime";function on(t){return B(t)?.endsAt??null}function Uo(t){let e=Math.max(0,Math.floor(t/1e3)),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function Eo({session:t,urgentMs:e=6e4,className:n}){let o=on(t)?.getTime()??null,[s,a]=Ro(()=>o===null?null:Math.max(0,o-Date.now()));if(xo(()=>{if(o===null){a(null);return}let u=()=>a(Math.max(0,o-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[o]),s===null)return null;let i=Uo(s);return wo("span",{className:["urun-session-clock",n].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${i}`,"data-urgent":s<e?"":void 0,"data-expired":s<=0?"":void 0,children:i})}import{jsx as sn,jsxs as Mo}from"react/jsx-runtime";var Ao=new Set(["expired","ended","error"]);function _o({session:t,onNewSession:e,children:n,className:r}){let o=B(t);if(!o||!Ao.has(o.name))return null;let s=n?n(o):sn("span",{className:"urun-session-ended-copy",children:o.name==="expired"?"Session ended \u2014 start a new session":o.name==="error"?`Session failed${o.error?.reason?` \u2014 ${o.error.reason}`:""}.`:"Session ended."});return Mo("div",{className:["urun-session-ended",r].filter(Boolean).join(" "),"data-phase":o.name,children:[s,e?sn("button",{type:"button",className:"urun-session-ended-new",onClick:e,children:"New session"}):null]})}import{useEffect as an,useMemo as No,useState as un}from"react";import{jsx as We,jsxs as Lo}from"react/jsx-runtime";function ht(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.warning!==!0?null:{warning:!0,deadlineEpochS:typeof e.deadline_epoch_s=="number"?e.deadline_epoch_s:null,idleSinceEpochS:typeof e.idle_since_epoch_s=="number"?e.idle_since_epoch_s:null}}function cn(t){let e=No(()=>t?t.doc("control"):null,[t]),[n,r]=un(()=>e?ht(e.get("idle")):null);return an(()=>{if(!e){r(null);return}return r(ht(e.get("idle"))),e.on("change",()=>r(ht(e.get("idle"))))},[e]),n}function Io(t){let e=Math.max(0,Math.floor(t));return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function Do({session:t,onStillHere:e,className:n}){let r=cn(t),o=r?.deadlineEpochS??null,[s,a]=un(null);if(an(()=>{if(o===null){a(null);return}let u=()=>a(Math.max(0,o-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[o]),!r||!t)return null;let i=()=>{t.touch?.(),e?.()};return We("div",{className:["urun-idle-warning",n].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:Lo("div",{className:"urun-idle-warning-card",children:[We("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),We("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Io(s)} due to inactivity.`:"This session will end soon due to inactivity."}),We("button",{type:"button",className:"urun-idle-warning-confirm",onClick:i,children:"I'm still here"})]})})}import{useContext as Oo,useEffect as qo,useState as Fo}from"react";import{prewake as Wo}from"@urun-sh/core";function Vo(t){let e=Oo(ue),[n,r]=Fo(null),o=t.app??e?.appId,s=t.function,a=t.intervalS??60,i=e?.baseUrl,u=e?.orgId,c=e?.jwt,p=e?.getAccessToken,l=e?.authProvider;return qo(()=>{if(!i||!u||!o||!s)return;let f=!1,g=()=>{Wo({baseUrl:i,app:o,functionName:s,orgId:u,jwt:c,getAccessToken:p,authProvider:l}).then(k=>{f||r(k)}).catch(()=>{})};g();let v=setInterval(g,Math.max(1,a)*1e3);return()=>{f=!0,clearInterval(v)}},[o,s,a,i,u,c,p,l]),n}import{describeSessionPhase as iu,isWakingPhase as au}from"@urun-sh/core";export{Gn as ComponentRenderer,zt as DEFAULT_CAMERA_CONSTRAINTS,ne as DEFAULT_LOG_CAP,jt as DEFAULT_VOICE_CONSTRAINTS,qe as DocPatchForm,cr as ImageFrame,ur as ImageFrameSchema,pr as MetricsPanel,dr as MetricsPanelSchema,Qn as ProgressCard,Yn as ProgressCardSchema,nr as StatusBadge,er as StatusBadgeSchema,ir as TextStream,sr as TextStreamSchema,ft as UrunActivationOverlay,st as UrunAudio,gn as UrunAuthProvider,Nr as UrunCamera,eo as UrunControlSender,Zr as UrunDocPanel,Se as UrunErrorBoundary,ro as UrunEventSpine,Do as UrunIdleWarning,hn as UrunJwtProvider,Tn as UrunProvider,Eo as UrunSessionClock,_o as UrunSessionEnded,To as UrunSessionGate,Po as UrunSessionStatus,pt as UrunSessionWaking,Xr as UrunStreamTail,xr as UrunVoice,Re as authMode,ut as createDocStore,iu as describeSessionPhase,be as formatPayload,Ne as getUrunAudioContext,au as isWakingPhase,ct as parseJsonObject,Y as pushCapped,Xn as registerComponent,Ie as resumeUrunAudioContext,X as urunPublicEnv,mt as useActivation,_n as useApp,Hn as useChat,Fn as useCompletion,ke as useDocStore,Vt as useImageFrame,zn as useInputPresence,Bt as useMetricsPanel,It as useProgressCard,Dn as useRequest,Kr as useSessionDoc,on as useSessionEndsAt,cn as useSessionIdle,B as useSessionPhase,Fr as useSessionTrack,dt as useSessionWake,Lt as useStatusBadge,lt as useStreamMessages,Ft as useTextStream,Lr as useUrunAudioLevel,He as useUrunAuth,Vo as useUrunPrewake,kn as usesWorkOSAuth};
|
|
2
|
+
import{a as _r,b as Nr,c as et}from"./chunk-WF2OBDSX.mjs";import{useEffect as Vr,useMemo as qr,useState as Fr}from"react";import{Component as Ir}from"react";import{jsx as Lt,jsxs as Lr}from"react/jsx-runtime";var be=class extends Ir{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,r){console.error("[urun] Error caught by UrunErrorBoundary:",e,r)}render(){if(this.state.error){let{fallback:e}=this.props;return typeof e=="function"?e(this.state.error):e||Lr("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:[Lt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Lt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Dr}from"react";var pe=Dr(null);function se(t){return t&&t.trim()?t.trim():void 0}function ee(t){switch(t){case"NEXT_PUBLIC_AUTH_MODE":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return se(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"VERCEL_ENV":return se(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return se(typeof process<"u"?process.env?.[t]:void 0)}}function _e(){let t=ee("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return t==="jwt"||t==="customer-jwt"||t==="test-jwt"?"jwt":t==="workos"||ee("VERCEL_ENV")==="production"?"workos":ee("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Or(){return _e()==="workos"}import{jsx as tt}from"react/jsx-runtime";function Wr({baseUrl:t,orgId:e,appId:r,jwt:o,authProvider:n,eventsUrl:s,fallback:a,children:i}){let[c,u]=Fr(),m=et(),l=ee("NEXT_PUBLIC_SESSION_TOKEN")??ee("NEXT_PUBLIC_URUN_JWT"),v=_e(),y=v==="workos"&&!o,C=o??(v==="jwt"?l:void 0)??c,k=n??ee("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),b=y&&!C,S=qr(()=>({appId:r,baseUrl:t,orgId:e,jwt:C,getAccessToken:y?m?.getAccessToken:void 0,authProvider:k,eventsUrl:s}),[r,m,t,k,C,s,e,y]);return Vr(()=>{if(!y||!m)return;let x=!1,T=m;async function R(){try{let E=await T.getAccessToken();x||u(E??void 0)}catch{x||u(void 0)}}R();let g=window.setInterval(()=>{R()},6e4);return()=>{x=!0,window.clearInterval(g)}},[m,y]),tt(be,{fallback:a,children:b?tt("div",{role:"status","aria-live":"polite",children:"Signing in..."}):tt(pe.Provider,{value:S,children:i})})}import{useContext as Hr,useEffect as Br,useMemo as Dt,useReducer as $r,useRef as Ot}from"react";import{App as jr}from"@urun-sh/core";function Kr(t,e){return`${t}:${JSON.stringify(e??{})}`}function Jr(t,e,r){return JSON.stringify({appId:t.appId,baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,authProvider:t.authProvider,fnName:e,args:r??{}})}var me=new Map;var rt=class{constructor(e,r){this._doc=e;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(e,r){return this._doc.get(e,r)}set(e){this._doc.set(e),this._notify()}on(e,r){return this._doc.on(e,o=>r(o))}get synced(){return this._doc.synced}onSynced(e){return this._doc.onSynced(()=>{e(),this._notify()})}text(e){let r=this._doc.text(e),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,a=>{s(a),o()})}}dispose(){this._unsubscribeChange()}},nt=class{constructor(e,r){this._stream=e;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(e){return this._stream.attach(e)}attachVideo(e){return this._stream.attachVideo(e)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(e){return this._stream.seek(e)}chunks(e){return this._stream.chunks(e)}onSeeked(e){return this._stream.onSeeked(e)}on(e,r){return this._stream.on(e,r)}messages(){return this._stream.messages()}emit(e,r){return this._stream.emit(e,r)}dispose(){this._unsubscribeTrack()}},ot=class{constructor(e,r,o){this._session=e;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(e){let r=!1,o=!1,n=i=>{fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),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(i=>{if(i.name==="error"||i.name==="expired"){let c=i.error,u=c?.reason??(i.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:u,detail:{sessionId:this._session.id,code:c?.code,kind:c?.kind,httpStatus:c?.httpStatus}})}else i.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),a=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{a(),s()}}addNotifier(e){this._notifiers.add(e)}removeNotifier(e){this._notifiers.delete(e)}_notifyAll(){for(let e of this._notifiers)e()}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(e){return this._session.onPhase(e)}onDiagnostic(e){return this._session.onDiagnostic(e)}whenLive(e){return this._session.whenLive(e)}recover(){this._session.recover()}onRecovery(e){return this._session.onRecovery(e)}request(e,r){return this._session.request(e,r)}requestStream(e,r){return this._session.requestStream(e,r)}complete(e,r){return this._session.complete(e,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(e){let r=this._docs.get(e);return r||(r=new rt(this._session.doc(e),()=>this._notifyAll()),this._docs.set(e,r)),r}stream(e){let r=this._streams.get(e);return r||(r=new nt(this._session.stream(e),()=>this._notifyAll()),this._streams.set(e,r)),r}async end(){let e=await this._session.end();return this._disposeHandle(),e}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let e of this._docs.values())e.dispose();for(let e of this._streams.values())e.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function zr(){let t=Hr(pe);if(!t)throw new Error("useApp must be used within <UrunProvider>");if(!t.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,e]=$r(s=>s+1,0),r=Ot(new Map),o=Ot(new Map),n=Dt(()=>jr(t.appId,{baseUrl:t.baseUrl,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),[t.appId,t.baseUrl,t.orgId,t.jwt,t.getAccessToken,t.authProvider]);return Br(()=>()=>{for(let[s,a]of o.current){let i=me.get(s);i===a&&(i.handle.removeNotifier(e),i.refCount=Math.max(0,i.refCount-1),i.refCount===0&&(i.disposeTimer=setTimeout(()=>{let c=me.get(s);!c||c.refCount!==0||(me.delete(s),c.handle.disconnect())},0)))}o.current.clear(),r.current.clear()},[]),Dt(()=>new Proxy({},{get(s,a){if(typeof a=="string")return i=>{let c=Kr(a,i),u=r.current.get(c);if(u&&!u.disposed)return u;let m=Jr(t,a,i),l=me.get(m);return l?.handle.disposed&&(l.disposeTimer&&clearTimeout(l.disposeTimer),me.delete(m),o.current.get(m)===l&&o.current.delete(m),l=void 0),l?l.disposeTimer&&(clearTimeout(l.disposeTimer),l.disposeTimer=null):(l={handle:new ot(n[a](i),e,t.eventsUrl),refCount:0,disposeTimer:null},me.set(m,l)),o.current.get(m)!==l&&(o.current.set(m,l),l.handle.addNotifier(e),l.refCount+=1),r.current.set(c,l.handle),l.handle}}}),[t,n])}import{useCallback as st,useEffect as Xr,useMemo as Gr,useRef as Ne,useState as it}from"react";function fe(t){let e=t;if(!e||typeof e.request!="function"||typeof e.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 e}function Yr(t){return t instanceof Error?t:new Error(String(t))}function Zr(t,e){let r=Gr(()=>fe(t),[t]),[o,n]=it(void 0),[s,a]=it(null),[i,c]=it(!1),u=Ne(e);u.current=e;let m=Ne(0),l=Ne(null),v=Ne(!0);Xr(()=>(v.current=!0,()=>{v.current=!1,l.current?.abort()}),[]);let y=st(async b=>{l.current?.abort();let S=new AbortController;l.current=S;let x=++m.current,T=()=>v.current&&m.current===x;T()&&(c(!0),a(null));try{let R=await r.request(b,{...u.current,signal:S.signal});return T()&&(n(R),c(!1),u.current?.onSuccess?.(R)),R}catch(R){let g=Yr(R);throw T()&&(a(g),c(!1),u.current?.onError?.(g)),g}},[r]),C=st(b=>{y(b).catch(()=>{})},[y]),k=st(()=>{m.current++,l.current?.abort(),l.current=null,n(void 0),a(null),c(!1)},[]);return{mutate:C,mutateAsync:y,data:o,error:s,isPending:i,reset:k}}import{useCallback as Vt,useEffect as Qr,useMemo as en,useRef as Ie,useState as at}from"react";function qt(t){return t instanceof Error?t:new Error(String(t))}var tn=t=>typeof t=="string"?t:String(t);function rn(t,e){let r=en(()=>fe(t),[t]),[o,n]=at(""),[s,a]=at(!1),[i,c]=at(null),u=Ie(e);u.current=e;let m=Ie(0),l=Ie(null),v=Ie(!0);Qr(()=>(v.current=!0,()=>{v.current=!1,l.current?.cancel(),l.current=null}),[]);let y=Vt(()=>{m.current++,l.current?.cancel(),l.current=null,v.current&&a(!1)},[]),C=Vt(async k=>{l.current?.cancel();let b=++m.current,S=()=>v.current&&m.current===b,x=u.current,T=x?.parseChunk??tn,R=x?.buildPayload??(f=>({prompt:f}));S()&&(n(""),c(null),a(!0));let{parseChunk:g,buildPayload:E,onFinish:L,onError:A,...U}=x??{},d="",p;try{p=r.requestStream(R(k),U),l.current=p}catch(f){let P=qt(f);S()&&(c(P),a(!1),x?.onError?.(P));return}try{for await(let f of p){if(m.current!==b)break;d+=T(f),S()&&n(d)}S()&&(a(!1),x?.onFinish?.(d))}catch(f){let P=qt(f);S()&&(c(P),a(!1),x?.onError?.(P))}finally{l.current===p&&(l.current=null)}},[r]);return{completion:o,complete:C,stop:y,isStreaming:s,error:i}}import{useCallback as Ft,useEffect as nn,useMemo as on,useRef as Se,useState as Le}from"react";function Wt(t){return t instanceof Error?t:new Error(String(t))}var sn=t=>typeof t=="string"?t:String(t),Ht=0;function ct(t){return Ht+=1,`${t}-${Ht}`}function an(t,e){let r=on(()=>fe(t),[t]),[o,n]=Le(()=>(e?.initialMessages??[]).map(T=>({id:T.id??ct("msg"),role:T.role,content:T.content}))),[s,a]=Le(""),[i,c]=Le(!1),[u,m]=Le(null),l=Se(e);l.current=e;let v=Se(o);v.current=o;let y=Se(s);y.current=s;let C=Se(0),k=Se(null),b=Se(!0);nn(()=>(b.current=!0,()=>{b.current=!1,k.current?.cancel(),k.current=null}),[]);let S=Ft(()=>{C.current++,k.current?.cancel(),k.current=null,b.current&&c(!1)},[]),x=Ft(async T=>{let R=T===void 0,g=(R?y.current:T)??"";if(!g.trim())return;k.current?.cancel();let L=++C.current,A=()=>b.current&&C.current===L,U=l.current,d=U?.parseChunk??sn,p={id:ct("msg"),role:"user",content:g},f={id:ct("msg"),role:"assistant",content:""},P=[...v.current,p].map(V=>({role:V.role,content:V.content})),_=[...v.current,p,f];v.current=_,n(_),R&&a(""),m(null),c(!0);let F=U?.buildPayload??(V=>({messages:V})),{initialMessages:w,parseChunk:h,buildPayload:I,onFinish:D,onError:W,...O}=U??{},Y=V=>{n(J=>J.map(ue=>ue.id===f.id?{...ue,content:V}:ue))},Z="",K;try{K=r.requestStream(F(P),O),k.current=K}catch(V){let J=Wt(V);A()&&(m(J),c(!1),U?.onError?.(J));return}try{for await(let V of K){if(C.current!==L)break;Z+=d(V),A()&&Y(Z)}A()&&(c(!1),U?.onFinish?.({...f,content:Z}))}catch(V){let J=Wt(V);A()&&(m(J),c(!1),U?.onError?.(J))}finally{k.current===K&&(k.current=null)}},[r]);return{messages:o,input:s,setInput:a,sendMessage:x,stop:S,isStreaming:i,error:u}}import{useCallback as te,useEffect as Bt,useMemo as cn,useRef as $t,useState as jt}from"react";import{createInputPresencePublisher as un,INPUT_PRESENCE_DEFAULT_HZ as ln,INPUT_PRESENCE_FIELD as dn}from"@urun-sh/core";var ut=[];function pn(t,e={}){let{field:r=dn,hz:o=ln}=e,n=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null,s=t?.presence??null,a=cn(()=>s?un({awareness:{setLocalStateField:(g,E)=>s.setField(g,E)},field:r,hz:o}):null,[s,r,o]),i=$t(null);i.current=a;let[c,u]=jt(!1),[m,l]=jt(ut),v=$t(!1);Bt(()=>{if(a)return()=>a.dispose()},[a]);let y=te(()=>{let g=i.current;l(g?g.heldKeys():ut)},[]),C=te(()=>{i.current?.clear(),l(ut)},[]);Bt(()=>{if(!n)return;let g=()=>!!n.pointerLockElement,E=()=>{if(g()){v.current=!1,u(!0);return}v.current||(u(!1),C())},L=f=>{g()&&(i.current?.keyDown(f.key),y())},A=f=>{i.current?.keyUp(f.key),y()},U=f=>{g()&&i.current?.movePointer(f.movementX,f.movementY)},d=f=>{g()&&i.current?.setButtons(f.buttons)},p=()=>{C()};return n.addEventListener("pointerlockchange",E),n.addEventListener("keydown",L),n.addEventListener("keyup",A),n.addEventListener("mousemove",U),n.addEventListener("mousedown",d),n.addEventListener("mouseup",d),n.defaultView?.addEventListener("blur",p),()=>{n.removeEventListener("pointerlockchange",E),n.removeEventListener("keydown",L),n.removeEventListener("keyup",A),n.removeEventListener("mousemove",U),n.removeEventListener("mousedown",d),n.removeEventListener("mouseup",d),n.defaultView?.removeEventListener("blur",p)}},[n,C,y]);let k=te(g=>{g.requestPointerLock?.()},[]),b=te(()=>{v.current=!0,u(!0)},[]),S=te(()=>{v.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),u(!1),C()},[n,C]),x=te(g=>{i.current?.keyDown(g),y()},[y]),T=te(g=>{i.current?.keyUp(g),y()},[y]),R=te((g,E)=>{i.current?.movePointer(g,E)},[]);return{engage:k,engageTouch:b,release:S,engaged:c,heldKeys:m,pressKey:x,releaseKey:T,movePointer:R}}var Kt=new Map;function mn(t,e,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${t}"): schema must be a valid Zod schema`);Kt.set(t,{component:e,schema:r})}function Jt(t,e){let r=Kt.get(t);if(!r)return{error:`Unknown component: "${t}"`};let o=r.schema.safeParse(e);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${t}": ${o.error.message}`}}import{Fragment as Sn,jsx as De}from"react/jsx-runtime";function fn({name:t,props:e,fallback:r}){let o=Jt(t,e);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?De(Sn,{children:r}):De("div",{className:"urun-component-error",role:"alert",children:De("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return De(n,{...o.validatedProps})}import{z as Ce}from"zod";import{jsx as lt,jsxs as zt}from"react/jsx-runtime";var gn=Ce.object({step:Ce.number().min(0),total:Ce.number().min(1),label:Ce.string().optional(),variant:Ce.enum(["default","success","error"]).default("default")});function Xt(t){let{step:e,total:r,label:o,variant:n="default"}=t,s=Math.min(e/r*100,100),a=e>=r;return{step:e,total:r,label:o,variant:n,percentage:s,isComplete:a}}function hn(t){let{step:e,total:r,label:o,variant:n,percentage:s}=Xt(t);return zt("div",{className:"urun-progress-card","data-variant":n,children:[o&<("div",{className:"urun-progress-label",children:o}),lt("div",{className:"urun-progress-bar",children:lt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),zt("div",{className:"urun-progress-text",children:[e,"/",r]})]})}import{z as dt}from"zod";import{jsx as Gt,jsxs as bn}from"react/jsx-runtime";var vn=dt.object({state:dt.enum(["thinking","generating","idle","error"]),message:dt.string().optional()}),yn={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Yt(t){let{state:e,message:r}=t,o=e==="thinking"||e==="generating",n=r??yn[e]??e;return{state:e,message:n,isActive:o}}function kn(t){let{state:e,message:r,isActive:o}=Yt(t);return bn("span",{className:"urun-status-badge","data-state":e,children:[Gt("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Gt("span",{className:"urun-status-message",children:r})]})}import{useRef as Zt,useEffect as Cn}from"react";import{z as pt}from"zod";import{jsx as Qt,jsxs as Tn}from"react/jsx-runtime";var Pn=pt.object({text:pt.string(),streaming:pt.boolean().default(!1)});function er(t){let{text:e,streaming:r=!1}=t,o=e.length===0;return{text:e,streaming:r,isEmpty:o}}function xn(t){let{text:e,streaming:r}=er(t),o=Zt(null),n=Zt(0);return Cn(()=>{let s=o.current;s&&e.length!==n.current&&(s.textContent=e,n.current=e.length)},[e]),Tn("div",{className:"urun-text-stream",children:[Qt("span",{ref:o,className:"urun-text-content"}),r&&Qt("span",{className:"urun-text-cursor"})]})}import{z as Oe}from"zod";import{jsx as tr,jsxs as wn}from"react/jsx-runtime";var Rn=Oe.object({src:Oe.string().url(),alt:Oe.string().optional(),caption:Oe.string().optional()});function rr(t){let{src:e,alt:r,caption:o}=t;return{src:e,alt:r??"",caption:o}}function En(t){let{src:e,alt:r,caption:o}=rr(t);return wn("figure",{className:"urun-image-frame",children:[tr("img",{className:"urun-image",src:e,alt:r}),o&&tr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as re}from"zod";import{jsx as mt,jsxs as Mn}from"react/jsx-runtime";var An=re.object({metrics:re.array(re.object({label:re.string(),value:re.union([re.string(),re.number()]),unit:re.string().optional()}))});function nr(t){return{metrics:t.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Un(t){let{metrics:e}=nr(t);return mt("div",{className:"urun-metrics-panel",children:e.map((r,o)=>Mn("div",{className:"urun-metric-card",children:[mt("div",{className:"urun-metric-label",children:r.label}),mt("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{createContext as _n,useContext as Nn}from"react";import{jsx as Ln}from"react/jsx-runtime";var or=_n(null);function In({session:t,children:e}){return Ln(or.Provider,{value:t,children:e})}function j(){return Nn(or)}import{forwardRef as Dn,useCallback as Ve,useEffect as On,useImperativeHandle as Vn,useRef as ft,useState as qn}from"react";import{jsx as Hn,jsxs as Bn}from"react/jsx-runtime";var Fn=1e3;function Wn(...t){console.debug("[video]",...t)}var St=Dn(function(e,r){let{session:o,stream:n="video",track:s,muted:a=!0,mirror:i=!1,objectFit:c="contain",className:u,style:m,videoClassName:l,placeholder:v,children:y,onTrack:C}=e,k=j(),b=o??k,S=ft(null),x=ft(null),[T,R]=qn(!1),g=ft(C);g.current=C;let E=Ve(()=>{if(typeof MediaStream>"u")return null;x.current||(x.current=new MediaStream);let p=S.current;return p&&p.srcObject!==x.current&&(p.srcObject=x.current),x.current},[]),L=Ve(p=>{let f=S.current;if(!f)return;let P=f.play();!P||typeof P.catch!="function"||P.catch(_=>Wn(`play() failed (${p})`,_))},[]),A=Ve(p=>{let f=E();if(f){for(let P of f.getVideoTracks())P!==p&&f.removeTrack(P);if(p&&!f.getVideoTracks().includes(p)){f.addTrack(p);let P=S.current;P&&(P.srcObject=f)}p&&L("track-attach"),R(p!==null),g.current?.(p)}},[E,L]),U=Ve(p=>{S.current=p,p&&(a&&(p.muted=!0,p.defaultMuted=!0,p.setAttribute("muted","")),p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),E())},[E,a]);Vn(r,()=>({get element(){return S.current},get live(){return x.current?x.current.getVideoTracks().length>0:!1}}),[]);let d=s!==void 0;return On(()=>{if(d){A(s??null);return}if(!b)return;let p=b.stream(n),f=()=>{let h=x.current;return h?h.getVideoTracks()[0]??null:null},P=h=>{if(h!==f()&&(A(h),h)){let I=()=>{f()===h&&A(null)};h.addEventListener("ended",I)}},_=p.track;_&&_.readyState==="live"&&P(_);let F=p.on("track",h=>{h&&h.readyState!=="live"||P(h)}),w=setInterval(()=>{let h=p.track;h&&h.readyState==="live"&&P(h)},Fn);return()=>{F(),clearInterval(w)}},[b,n,d,s,A]),Bn("div",{className:u,style:{position:"relative",width:"100%",height:"100%",...m},"data-urun-video":"","data-urun-video-live":T?"true":"false",children:[Hn("video",{ref:U,className:l,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...i?{transform:"scaleX(-1)"}:{}}}),T?null:v,y]})});import{forwardRef as $n}from"react";import{jsx as Kn}from"react/jsx-runtime";var jn=$n(function(e,r){let{stream:o="image",...n}=e;return Kn(St,{ref:r,stream:o,...n})});import{forwardRef as zn,useCallback as ge,useEffect as gt,useImperativeHandle as Xn,useRef as he}from"react";import{observePageLifecycle as Gn}from"@urun-sh/core";var qe=null;function Jn(){if(typeof window>"u")return null;let t=window;return t.AudioContext??t.webkitAudioContext??null}function Fe(){if(qe)return qe;let t=Jn();return t?(qe=new t,qe):null}function We(){let t=Fe();t&&t.state==="suspended"&&t.resume().catch(()=>{})}import{jsx as Qn}from"react/jsx-runtime";var Yn=1e3,sr=200;function ht(...t){console.debug("[audio]",...t)}var He=zn(function(e,r){let{session:o,stream:n="audio",track:s,controls:a=!1,className:i,onTrack:c,onUnlockChange:u,onAudioElement:m}=e,l=j(),v=o??l,y=he(null),C=he(null),k=he(null),b=he(null),S=he(c);S.current=c;let x=he(u);x.current=u;let T=ge(d=>{k.current!==d&&(k.current=d,x.current?.(d))},[]),R=ge(()=>{if(typeof MediaStream>"u")return null;C.current||(C.current=new MediaStream);let d=y.current;return d&&d.srcObject!==C.current&&(d.srcObject=C.current),C.current},[]),g=ge(d=>{let p=y.current;if(!p)return;let f=p.play();!f||typeof f.then!="function"||f.then(()=>{p.muted||T(!0)}).catch(P=>{let _=P instanceof Error?P.name:String(P);if(_==="AbortError"){ht(`play() aborted (${d}); retrying in ${sr}ms`),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{b.current=null,g(`${d}:retry`)},sr);return}if(_==="NotAllowedError"){ht(`play() blocked pending a user gesture (${d})`),T(!1);return}ht(`play() failed (${d})`,P)})},[T]),E=ge(d=>{let p=R();if(p){for(let f of p.getAudioTracks())f!==d&&p.removeTrack(f);d&&!p.getAudioTracks().includes(d)&&p.addTrack(d),d&&g("track-attach"),S.current?.(d)}},[R,g]),L=ge(()=>{let d=y.current;d&&(R(),d.muted=!1,g("gesture"),We(),T(!0))},[R,g,T]);Xn(r,()=>({unlock:L,get unlocked(){return k.current===!0},get element(){return y.current}}),[L]);let A=ge(d=>{y.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),R()),m?.(d)},[R,m]),U=s!==void 0;return gt(()=>{if(U){E(s??null);return}if(!v)return;let d=v.stream(n),p=()=>{let w=C.current;return w?w.getAudioTracks()[0]??null:null},f=w=>{if(w!==p()&&(E(w),w)){let h=()=>{p()===w&&E(null)};w.addEventListener("ended",h)}},P=d.track;P&&P.readyState==="live"&&f(P);let _=d.on("track",w=>{w&&w.readyState!=="live"||f(w)}),F=setInterval(()=>{let w=d.track;w&&w.readyState==="live"&&f(w)},Yn);return()=>{_(),clearInterval(F)}},[v,n,U,s,E]),gt(()=>Gn(()=>{We(),k.current===!0&&g("foreground")}),[g]),gt(()=>()=>{b.current&&clearTimeout(b.current)},[]),Qn("audio",{ref:A,className:i,autoPlay:!0,playsInline:!0,controls:a,"data-urun-audio":""})}),Zn=He;import{forwardRef as eo,useCallback as ve,useEffect as ir,useImperativeHandle as to,useRef as X}from"react";import{observePageLifecycle as ro,sessionFailureFromMediaError as no,sharedCaptureController as oo}from"@urun-sh/core";import{jsx as io}from"react/jsx-runtime";var ar={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Be(...t){console.debug("[voice]",...t)}var $e=eo(function(e,r){let{session:o,stream:n="audio",playback:s=!0,constraints:a=ar,connectTimeoutMs:i,attempts:c=3,retryDelayMs:u=1500,onActiveChange:m,onError:l,onMicStream:v,onTrack:y,onUnlockChange:C,capture:k}=e,b=j(),S=o??b,x=X(null),T=X(null),R=X(null),g=X([]),E=X(!1),L=X(m);L.current=m;let A=X(l);A.current=l;let U=X(v);U.current=v;let d=ve(h=>{E.current!==h&&(E.current=h,L.current?.(h))},[]),p=ve(()=>{for(let h of g.current)h();g.current=[],R.current?.release(),R.current=null,T.current&&(T.current=null,U.current?.(null))},[]),f=ve(async()=>{let h=R.current;if(h){let O=await h.update(a);return T.current=h.stream,U.current?.(h.stream),O}let D=await(k??oo()).claim("audio",a);R.current=D,g.current=[D.onTrack((O,Y)=>{T.current=Y,U.current?.(Y),E.current&&S?.stream(n).attach(O).catch(Z=>Be("mic re-attach after one-capture re-acquire failed",Z))}),D.onLost(O=>{R.current=null,g.current=[],T.current=null,U.current?.(null),d(!1),A.current?.(O)})],T.current=D.stream,U.current?.(D.stream);let W=D.track;if(!W)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return W},[k,a,S,n,d]),P=ve(async()=>{p(),d(!1),await S?.stream(n).detach().catch(()=>{})},[S,n,p,d]),_=ve(async()=>{if(!S)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <SessionScope>");x.current?.unlock();let h;try{h=await f()}catch(W){p();let O=no(W,S.status);throw A.current?.(O),O}S.connect?.();let I;for(let W=1;W<=c;W++)try{await S.whenLive(i!==void 0?{timeout:i}:void 0),await S.stream(n).attach(h),d(!0);return}catch(O){I=O,Be(`start attempt ${W}/${c} failed`,O),W<c&&await new Promise(Y=>setTimeout(Y,u))}p(),d(!1);let D=I instanceof Error?I:new Error(String(I??"voice start failed"));throw A.current?.(D),D},[S,n,i,c,u,f,p,d]);to(r,()=>({start:_,stop:P,unlock:()=>x.current?.unlock(),get active(){return E.current},get micStream(){return T.current},get audio(){return x.current}}),[_,P]);let F=X(!1),w=ve(async()=>{if(!S||!E.current||F.current)return;let h=T.current?.getAudioTracks()[0]??null;if(h&&h.readyState==="live"){try{await S.stream(n).attach(h)}catch(I){Be("foreground mic re-assert failed (will retry on next pass)",I)}return}F.current=!0;try{let I=await f();await S.stream(n).attach(I)}catch(I){let D=I instanceof Error?I:new Error(String(I));Be("foreground mic re-acquire failed",D),A.current?.(D)}finally{F.current=!1}},[S,n,f]);return ir(()=>{let h=()=>{w()};return S&&typeof S.onRecovery=="function"?S.onRecovery(h):ro(h)},[S,w]),ir(()=>p,[p]),s?io(He,{ref:x,session:S,stream:n,onTrack:y,onUnlockChange:C}):null}),so=$e;import{forwardRef as uo,useEffect as lo,useImperativeHandle as po,useRef as cr,useState as mo}from"react";import{useEffect as ao,useState as co}from"react";var vt={level:0,speaking:!1};function yt(t,e={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=e,[s,a]=co(vt);return ao(()=>{if(!t){a(vt);return}let i=Fe();if(!i||typeof MediaStream>"u")return;let c;t instanceof MediaStream?c=t:(c=new MediaStream,c.addTrack(t));let u,m;try{u=i.createMediaStreamSource(c),m=i.createAnalyser(),m.fftSize=r,u.connect(m)}catch{return}let l=new Uint8Array(m.fftSize),y=setInterval(()=>{m.getByteTimeDomainData(l);let C=0;for(let b=0;b<l.length;b++){let S=(l[b]-128)/128;C+=S*S}let k=Math.sqrt(C/l.length);a(b=>{let S=k>n;return Math.abs(b.level-k)<.005&&b.speaking===S?b:{level:k,speaking:S}})},o);return()=>{clearInterval(y),u.disconnect(),a(vt)}},[t,r,o,n]),s}import{Fragment as ho,jsx as je,jsxs as vo}from"react/jsx-runtime";var fo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},So={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},go=uo(function(e,r){let{session:o,stream:n="audio",constraints:s,autoStart:a=!0,visible:i=!1,className:c,onActiveChange:u,onError:m,onMicStream:l,capture:v}=e,y=j(),C=o??y,k=cr(null),[b,S]=mo(null),x=cr(l);x.current=l;let{level:T,speaking:R}=yt(i?b:null);return po(r,()=>({start:()=>{let g=k.current;return g?g.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>k.current?.stop()??Promise.resolve(),get active(){return k.current?.active??!1},get micStream(){return k.current?.micStream??null}}),[]),lo(()=>{!a||!C||k.current?.start().catch(()=>{})},[a,C]),vo(ho,{children:[je($e,{ref:k,session:C,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...v!==void 0?{capture:v}:{},onActiveChange:u,onError:m,onMicStream:g=>{S(g),x.current?.(g)}}),i?je("span",{className:c,style:fo,"data-urun-mic":"","data-urun-mic-active":b?"true":"false","data-urun-mic-speaking":R?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(T*100)/100,children:je("span",{style:So,children:je("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]})});import{sessionFailureFromMediaError as yo,sharedCaptureController as ko}from"@urun-sh/core";import{forwardRef as lr,useCallback as G,useEffect as kt,useImperativeHandle as bo,useRef as H,useState as Pe}from"react";import{jsx as ne,jsxs as ur}from"react/jsx-runtime";var dr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function bt(...t){console.debug("[camera]",...t)}function Co(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Po(){let t=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof t?.enumerateDevices!="function")return null;try{return(await t.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var pr=lr(function(e,r){let{session:o,stream:n="video",constraints:s,front:a=!1,back:i=!1,facingMode:c,autoStart:u=!0,mirror:m="auto",connectTimeoutMs:l,visible:v=!1,className:y,videoClassName:C,onActiveChange:k,onError:b,onStream:S,onTrack:x,children:T,capture:R,flipControl:g="auto",flipControlClassName:E,onDevices:L}=e;if(a&&i)throw new Error("<Camera> takes `front` OR `back`, not both");let A=a?"user":i?"environment":c??"environment",U=j(),d=o??U,p=H(null),f=H(null),P=H(null),_=H([]),F=H(null),w=H(!1),h=H(A),[I,D]=Pe(A),[W,O]=Pe(!1),[Y,Z]=Pe(null),[K,V]=Pe(!1),[J]=Pe(Co),ue=H(k);ue.current=k;let we=H(b);we.current=b;let Ye=H(S);Ye.current=S;let Ae=H(x);Ae.current=x;let Mt=H(L);Mt.current=L;let Q=G(M=>{w.current!==M&&(w.current=M,O(M),ue.current?.(M))},[]);kt(()=>{if(!W){Z(null);return}let M=!1,N=()=>{Po().then(B=>{M||(Z(B),B&&Mt.current?.(B))})};N();let q=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof q?.addEventListener=="function"?(q.addEventListener("devicechange",N),()=>{M=!0,q.removeEventListener?.("devicechange",N)}):()=>{M=!0}},[W]);let Ue=G(M=>{let N=p.current;N&&(N.muted=!0,N.defaultMuted=!0,N.setAttribute("muted",""),N.setAttribute("playsinline",""),N.setAttribute("webkit-playsinline",""),N.srcObject=M,M&&N.play()?.catch?.(q=>bt("preview play() failed",q)))},[]),z=G(()=>{F.current?.(),F.current=null;for(let M of _.current)M();_.current=[],P.current?.release(),P.current=null,f.current&&(f.current=null,Ye.current?.(null),Ae.current?.(null)),Ue(null)},[Ue]),Ze=G((M,N)=>{F.current?.(),f.current=N,Ue(N),Ye.current?.(N);let q=()=>{f.current===N&&(bt("camera track ended (device removed or permission revoked)"),z(),Q(!1))};M.addEventListener("ended",q),F.current=()=>M.removeEventListener("ended",q)},[Ue,z,Q]),le=G(async M=>{if(!d)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <SessionScope>");let N={...dr,...s,facingMode:M},q;try{let B=P.current;if(B)q=await B.update(N);else{let ye=await(R??ko()).claim("video",N);if(P.current=ye,_.current=[ye.onTrack((ke,Ur)=>{Ze(ke,Ur),w.current&&d.stream(n).attachVideo(ke).then(()=>Ae.current?.(ke)).catch(Mr=>bt("camera re-publish after one-capture re-acquire failed",Mr))}),ye.onLost(ke=>{P.current=null,_.current=[],z(),Q(!1),we.current?.(ke)})],!ye.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});q=ye.track}}catch(B){let de=yo(B,d.status);throw we.current?.(de),de}h.current=M,D(M),Ze(q,P.current?.stream??new MediaStream([q]));try{d.connect?.(),await d.whenLive(l!==void 0?{timeout:l}:void 0),await d.stream(n).attachVideo(q)}catch(B){z(),Q(!1);let de=B instanceof Error?B:new Error(String(B));throw we.current?.(de),de}Ae.current?.(q),Q(!0)},[d,n,s,l,R,Ze,z,Q]),_t=G(M=>le(M?.facingMode??h.current),[le]),Me=G(async M=>{w.current&&h.current===M||await le(M)},[le]),Qe=G(()=>le(h.current==="environment"?"user":"environment"),[le]),Nt=G(async()=>{z(),Q(!1),await d?.stream(n).detachVideo().catch(()=>{})},[d,n,z,Q]);bo(r,()=>({start:_t,stop:Nt,flip:Qe,setFacingMode:Me,get active(){return w.current},get facingMode(){return h.current},get stream(){return f.current},get element(){return p.current}}),[_t,Nt,Qe,Me]);let It=H(Me);if(It.current=Me,kt(()=>{!u||!d||It.current(A).catch(()=>{})},[u,d,A]),kt(()=>z,[z]),!v)return null;let Er=m==="auto"?I==="user":m,wr=W&&(g===!0||g==="auto"&&J&&(Y?.length??0)>1),Ar=()=>{K||(V(!0),Qe().catch(()=>{}).finally(()=>V(!1)))};return ur("div",{className:y,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":I,children:[ne("video",{ref:p,className:C,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Er?{transform:"scaleX(-1)"}:{}}}),wr?ne("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Ar,disabled:K,className:E,style:E?{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:ur("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:[ne("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),ne("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),ne("path",{d:"M14.5 10.5v1.6h-1.6"}),ne("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),ne("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,T]})}),xo=lr(function({preview:e=!0,...r},o){return ne(pr,{ref:o,...r,visible:e,autoStart:!1})});import{useEffect as To,useState as Ro}from"react";function Eo(t,e){let[r,o]=Ro(null);return To(()=>{if(!t||!e){o(null);return}let n=t.stream(e);return o(n.track),n.on("track",o)},[t,e]),r}import{useCallback as No}from"react";import{useEffect as Mo,useMemo as _o}from"react";import{createStore as wo}from"zustand/vanilla";import{useStore as Ao}from"zustand";var Uo=()=>{};function Ct(t,e={}){let r=u=>{t?.set(u)},o=()=>t?t.get()??{}:{},n=wo(()=>({doc:o(),synced:t?t.synced:!1,set:r})),s=null,a=()=>{if(s){for(let u of s)u();s=null}},i=()=>t?(s||(n.setState({doc:o(),synced:t.synced}),s=[t.on("change",u=>n.setState({doc:u})),t.onSynced(()=>n.setState({synced:!0}))]),a):Uo,c=(u=>Ao(n,u));return Object.assign(c,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:i,unbind:a}),e.bind!==!1&&i(),c}function xe(t,e){let r=_o(()=>Ct(t&&e?t.doc(e):null,{bind:!1}),[t,e]);return Mo(()=>r.bind(),[r]),r}function Io(t,e,r){let n=xe(t,e)(r??(i=>i)),s=No(i=>{t&&e&&t.doc(e).set(i)},[t,e]);if(r)return n;let a=n;return{snapshot:t&&e?a.doc:null,synced:a.synced,set:s}}import{useEffect as Lo,useState as Do}from"react";var ie=200;function oe(t,e,r=200){let o=[...t,e];return o.length>r?o.slice(o.length-r):o}function Te(t){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function Pt(t){let e=t.trim();if(!e)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(e)}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 xt(t,e,r={}){let o=r.cap??200,[n,s]=Do([]);return Lo(()=>{if(s([]),!t||!e)return;let a=!0,i=t.stream(e).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let c=await i.next();if(!a||c.done)break;s(u=>oe(u,{at:Date.now(),payload:c.value},o))}})(),()=>{a=!1,i.return?.()}},[t,e,o]),n}import{jsx as Ke,jsxs as Re}from"react/jsx-runtime";function Oo({session:t,name:e,cap:r,className:o}){let n=xt(t,e,{cap:r});return Re("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[Re("div",{className:"urun-stream-tail-meta",children:[Ke("code",{children:e}),Re("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),Ke("div",{className:"urun-stream-tail-log",children:n.length===0?Re("span",{className:"urun-stream-tail-empty",children:["Waiting for ",Ke("code",{children:e})," messages\u2026"]}):n.map((s,a)=>Re("div",{className:"urun-stream-tail-line",children:[Ke("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Te(s.payload)]},`${s.at}-${a}`))})]})}import{useCallback as Vo,useState as mr}from"react";import{jsx as ae,jsxs as Je}from"react/jsx-runtime";function ze({placeholder:t,buttonLabel:e,disabled:r,onApply:o}){let[n,s]=mr(""),[a,i]=mr(null),c=Vo(()=>{let u=Pt(n);if(!u.ok){i(u.error);return}i(null),o(u.value,n.trim()),s("")},[n,o]);return Je("div",{className:"urun-doc-patch",children:[ae("textarea",{className:"urun-doc-patch-input",value:n,onChange:u=>s(u.target.value),placeholder:t,rows:3}),Je("div",{className:"urun-doc-patch-actions",children:[ae("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:c,children:e}),a?ae("span",{className:"urun-doc-patch-error",role:"alert",children:a}):null]})]})}function qo({session:t,docKey:e,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=xe(t,e),a=s(u=>u.doc),i=s(u=>u.synced),c=s(u=>u.set);return Je("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[Je("div",{className:"urun-doc-panel-meta",children:[ae("code",{children:e}),ae("span",{className:"urun-doc-panel-synced","data-synced":i?"true":"false",children:i?"synced":"syncing\u2026"})]}),ae("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(a??{},null,2)}),r?ae(ze,{placeholder:o,buttonLabel:"Apply patch",disabled:!t,onApply:u=>c(u)}):null]})}import{useEffect as Fo,useState as Wo}from"react";import{jsx as Ee,jsxs as Sr}from"react/jsx-runtime";function fr(t,e=600){return t.length>e?`${t.slice(0,e)}\u2026`:t}function Ho({session:t,docKey:e="control",cap:r=200,className:o}){let[n,s]=Wo([]);return Fo(()=>(s([]),t?t.doc(e).on("change",i=>{s(c=>oe(c,{at:Date.now(),direction:"in",text:fr(Te(i))},r))}):void 0),[t,e,r]),Sr("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Ee(ze,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${e}`,disabled:!t,onApply:(a,i)=>{t?.doc(e).set(a),s(c=>oe(c,{at:Date.now(),direction:"out",text:fr(i)},r))}}),Ee("div",{className:"urun-control-sender-log",children:n.length===0?Ee("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((a,i)=>Sr("div",{className:"urun-control-sender-line","data-direction":a.direction,children:[Ee("span",{className:"urun-control-sender-dir",children:a.direction==="out"?"sent":"change"})," ",Ee("span",{className:"urun-control-sender-time",children:new Date(a.at).toLocaleTimeString()})," ",a.text]},`${a.at}-${i}`))})]})}import{useEffect as Bo,useState as $o}from"react";import{jsx as Xe,jsxs as Ko}from"react/jsx-runtime";function jo({session:t,trackNames:e=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,a]=$o([]),i=e.join(","),c=r.join(",");return Bo(()=>{if(a([]),!t)return;let u=(l,v)=>a(y=>oe(y,{at:Date.now(),kind:l,text:v},o)),m=[];m.push(t.onPhase(l=>u("phase",`phase \u2192 ${l.name}`)));for(let l of e){let v=t.stream(l);m.push(v.on("track",y=>u("track",`${l}: ${y?"track arrived":"track ended"}`)))}for(let l of r){let v=t.doc(l);m.push(v.on("change",()=>u("doc",`${l} changed`)))}return()=>m.forEach(l=>l())},[t,i,c,o]),Xe("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?Xe("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((u,m)=>Ko("div",{className:"urun-event-spine-line","data-kind":u.kind,children:[Xe("span",{className:"urun-event-spine-kind",children:u.kind})," ",Xe("span",{className:"urun-event-spine-time",children:new Date(u.at).toLocaleTimeString()})," ",u.text]},`${u.at}-${m}`))})}import{describeSessionPhase as as,isWakingPhase as cs}from"@urun-sh/core";import{useEffect as Jo,useState as zo}from"react";function $(t){let[e,r]=zo(t?.phase??null);return Jo(()=>{if(!t){r(null);return}return t.onPhase(r)},[t]),e}import{describeSessionPhase as Qo}from"@urun-sh/core";import{useEffect as Xo,useRef as Go,useState as Yo}from"react";import{isWakingPhase as Zo}from"@urun-sh/core";function Tt(t){let e=$(t),r=Zo(e?.name),o=Go(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?e?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[a,i]=Yo(s);return Xo(()=>{if(n===void 0){i(0);return}i(Math.max(0,Math.floor((Date.now()-n)/1e3)));let c=setInterval(()=>{i(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(c)},[n]),{waking:r,phase:e,state:r?e?.runtime?.state:void 0,reason:r?e?.runtime?.reason:void 0,since:n,seconds:r?a:0}}import{Fragment as es,jsx as gr,jsxs as hr}from"react/jsx-runtime";function Rt({session:t,render:e,className:r}){let o=Tt(t);return!o.waking||!o.phase?null:gr("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:e?e(o):hr(es,{children:[gr("span",{className:"urun-session-waking-label",children:Qo(o.phase)})," ",hr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as ns,useState as os}from"react";import{useEffect as vr,useRef as ts,useState as yr}from"react";var rs={event:null,elapsedMs:0};function Et(t,e){let[r,o]=yr(null),n=ts(0);vr(()=>{if(o(null),!!t?.onActivation)return t.onActivation(i=>{e!==void 0&&i.stream!==e||(n.current=Date.now(),o(i))})},[t,e]);let[s,a]=yr(0);return vr(()=>{if(!r){a(0);return}if(r.state==="first-media"){a(r.elapsedMs);return}let i=n.current,c=()=>r.elapsedMs+Math.max(0,Date.now()-i);a(c());let u=setInterval(()=>a(c()),1e3);return()=>clearInterval(u)},[r]),r?{event:r,elapsedMs:s}:rs}import{jsx as kr,jsxs as br}from"react/jsx-runtime";var ss={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 is(t){let[e,r]=os(!1);return ns(()=>{if(r(!1),!t)return;let o=t;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)}},[t]),e}function wt({session:t,stream:e,videoElement:r,render:o,className:n}){let s=Et(t,e),a=is(r),i=s.event;if(!i||i.state==="first-media"||a)return null;let c=i.state;return kr("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":c,role:"status","aria-live":"polite",children:o?o(s):br("div",{className:"urun-activation-overlay-card",children:[kr("span",{className:"urun-activation-overlay-copy",children:i.hint??ss[c]})," ",br("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as ce,jsxs as At}from"react/jsx-runtime";var us={idle:"idle",queued:"queued",unavailable:"unavailable",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function ls({session:t,className:e}){let r=$(t),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?.reason??null;return At("span",{className:["urun-session-status",e].filter(Boolean).join(" "),"data-phase":o,children:[ce("span",{className:"urun-session-status-dot","data-phase":o}),ce("span",{className:"urun-session-status-label",children:us[o]}),n?ce("span",{className:"urun-session-status-detail",children:n}):null]})}function ds({session:t,children:e,fallback:r,onStartOver:o,className:n}){let s=$(t);if(s?.name==="live")return At("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[e,ce(wt,{session:t})]});let a=r?r(s):ce("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&cs(s.name)?ce(Rt,{session:t}):s&&s.name!=="idle"?as(s):"Waiting for a live session\u2026"}),i=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return At("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[a,i?ce("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as ps,useState as ms}from"react";import{jsx as gs}from"react/jsx-runtime";function Cr(t){return $(t)?.endsAt??null}function fs(t){let e=Math.max(0,Math.floor(t/1e3)),r=Math.floor(e/60),o=e%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Ss({session:t,urgentMs:e=6e4,className:r}){let n=Cr(t)?.getTime()??null,[s,a]=ms(()=>n===null?null:Math.max(0,n-Date.now()));if(ps(()=>{if(n===null){a(null);return}let c=()=>a(Math.max(0,n-Date.now()));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),s===null)return null;let i=fs(s);return gs("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${i}`,"data-urgent":s<e?"":void 0,"data-expired":s<=0?"":void 0,children:i})}import{jsx as Pr,jsxs as ys}from"react/jsx-runtime";var hs=new Set(["expired","ended","error"]);function vs({session:t,onNewSession:e,children:r,className:o}){let n=$(t);if(!n||!hs.has(n.name))return null;let s=r?r(n):Pr("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 ys("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,e?Pr("button",{type:"button",className:"urun-session-ended-new",onClick:e,children:"New session"}):null]})}import{useEffect as xr,useMemo as ks,useState as Tr}from"react";import{jsx as Ge,jsxs as Ps}from"react/jsx-runtime";function Ut(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.warning!==!0?null:{warning:!0,deadlineEpochS:typeof e.deadline_epoch_s=="number"?e.deadline_epoch_s:null,idleSinceEpochS:typeof e.idle_since_epoch_s=="number"?e.idle_since_epoch_s:null}}function Rr(t){let e=ks(()=>t?t.doc("control"):null,[t]),[r,o]=Tr(()=>e?Ut(e.get("idle")):null);return xr(()=>{if(!e){o(null);return}return o(Ut(e.get("idle"))),e.on("change",()=>o(Ut(e.get("idle"))))},[e]),r}function bs(t){let e=Math.max(0,Math.floor(t));return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function Cs({session:t,onStillHere:e,className:r}){let o=Rr(t),n=o?.deadlineEpochS??null,[s,a]=Tr(null);if(xr(()=>{if(n===null){a(null);return}let c=()=>a(Math.max(0,n-Date.now()/1e3));c();let u=setInterval(c,1e3);return()=>clearInterval(u)},[n]),!o||!t)return null;let i=()=>{t.touch?.(),e?.()};return Ge("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:Ps("div",{className:"urun-idle-warning-card",children:[Ge("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),Ge("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."}),Ge("button",{type:"button",className:"urun-idle-warning-confirm",onClick:i,children:"I'm still here"})]})})}import{useContext as xs,useEffect as Ts,useState as Rs}from"react";import{prewake as Es}from"@urun-sh/core";function ws(t){let e=xs(pe),[r,o]=Rs(null),n=t.app??e?.appId,s=t.function,a=t.intervalS??60,i=e?.baseUrl,c=e?.orgId,u=e?.jwt,m=e?.getAccessToken,l=e?.authProvider;return Ts(()=>{if(!i||!c||!n||!s)return;let v=!1,y=()=>{Es({baseUrl:i,app:n,functionName:s,orgId:c,jwt:u,getAccessToken:m,authProvider:l}).then(k=>{v||o(k)}).catch(()=>{})};y();let C=setInterval(y,Math.max(1,a)*1e3);return()=>{v=!0,clearInterval(C)}},[n,s,a,i,c,u,m,l]),r}import{describeSessionPhase as ku,isWakingPhase as bu}from"@urun-sh/core";export{He as Audio,pr as Camera,fn as ComponentRenderer,dr as DEFAULT_CAMERA_CONSTRAINTS,ie as DEFAULT_LOG_CAP,ar as DEFAULT_VOICE_CONSTRAINTS,ze as DocPatchForm,jn as Image,En as ImageFrame,Rn as ImageFrameSchema,Un as MetricsPanel,An as MetricsPanelSchema,go as Mic,hn as ProgressCard,gn as ProgressCardSchema,In as SessionScope,kn as StatusBadge,vn as StatusBadgeSchema,xn as TextStream,Pn as TextStreamSchema,wt as UrunActivationOverlay,Zn as UrunAudio,_r as UrunAuthProvider,xo as UrunCamera,Ho as UrunControlSender,qo as UrunDocPanel,be as UrunErrorBoundary,jo as UrunEventSpine,Cs as UrunIdleWarning,Nr as UrunJwtProvider,Wr as UrunProvider,Ss as UrunSessionClock,vs as UrunSessionEnded,ds as UrunSessionGate,ls as UrunSessionStatus,Rt as UrunSessionWaking,Oo as UrunStreamTail,so as UrunVoice,St as Video,$e as Voice,_e as authMode,Ct as createDocStore,ku as describeSessionPhase,Te as formatPayload,Fe as getUrunAudioContext,bu as isWakingPhase,Pt as parseJsonObject,oe as pushCapped,mn as registerComponent,We as resumeUrunAudioContext,ee as urunPublicEnv,Et as useActivation,zr as useApp,an as useChat,rn as useCompletion,xe as useDocStore,rr as useImageFrame,pn as useInputPresence,nr as useMetricsPanel,Xt as useProgressCard,Zr as useRequest,Io as useSessionDoc,Cr as useSessionEndsAt,Rr as useSessionIdle,$ as useSessionPhase,Eo as useSessionTrack,Tt as useSessionWake,Yt as useStatusBadge,xt as useStreamMessages,er as useTextStream,yt as useUrunAudioLevel,et as useUrunAuth,ws as useUrunPrewake,Or as usesWorkOSAuth};
|
package/dist/video.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import * as react from 'react';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import Player from 'video.js/dist/types/player';
|
|
4
4
|
|
|
5
|
-
interface
|
|
5
|
+
interface VideoPlayerProps {
|
|
6
6
|
|
|
7
7
|
track?: MediaStreamTrack | null;
|
|
8
8
|
|
|
@@ -33,6 +33,10 @@ interface UrunVideoProps {
|
|
|
33
33
|
children?: ReactNode;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
declare const
|
|
36
|
+
declare const VideoPlayer: react.ForwardRefExoticComponent<VideoPlayerProps & react.RefAttributes<HTMLVideoElement>>;
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
declare const UrunVideo: react.ForwardRefExoticComponent<VideoPlayerProps & react.RefAttributes<HTMLVideoElement>>;
|
|
39
|
+
|
|
40
|
+
type UrunVideoProps = VideoPlayerProps;
|
|
41
|
+
|
|
42
|
+
export { UrunVideo, type UrunVideoProps, VideoPlayer, type VideoPlayerProps };
|
package/dist/video.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as react from 'react';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import Player from 'video.js/dist/types/player';
|
|
4
4
|
|
|
5
|
-
interface
|
|
5
|
+
interface VideoPlayerProps {
|
|
6
6
|
|
|
7
7
|
track?: MediaStreamTrack | null;
|
|
8
8
|
|
|
@@ -33,6 +33,10 @@ interface UrunVideoProps {
|
|
|
33
33
|
children?: ReactNode;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
declare const
|
|
36
|
+
declare const VideoPlayer: react.ForwardRefExoticComponent<VideoPlayerProps & react.RefAttributes<HTMLVideoElement>>;
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
declare const UrunVideo: react.ForwardRefExoticComponent<VideoPlayerProps & react.RefAttributes<HTMLVideoElement>>;
|
|
39
|
+
|
|
40
|
+
type UrunVideoProps = VideoPlayerProps;
|
|
41
|
+
|
|
42
|
+
export { UrunVideo, type UrunVideoProps, VideoPlayer, type VideoPlayerProps };
|
package/dist/video.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var q=Object.create;var E=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var Q=(t,r)=>{for(var n in r)E(t,n,{get:r[n],enumerable:!0})},R=(t,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Y(r))!K.call(t,i)&&i!==n&&E(t,i,{get:()=>r[i],enumerable:!(s=G(r,i))||s.enumerable});return t};var X=(t,r,n)=>(n=t!=null?q(J(t)):{},R(r||!t||!t.__esModule?E(n,"default",{value:t,enumerable:!0}):n,t)),Z=t=>R(E({},"__esModule",{value:!0}),t);var se={};Q(se,{UrunVideo:()=>H,VideoPlayer:()=>z});module.exports=Z(se);var o=require("react"),A=X(require("video.js")),me=require("video.js/dist/video-js.css");var b=require("react");var w=require("react"),$=require("@urun-sh/core"),ee=require("@urun-sh/core/internal");var re=require("react/jsx-runtime"),N=(0,w.createContext)(null);function I(t){let r=(0,b.useContext)(N);if(!r)throw new Error("useTrack must be used within <SessionProvider> or <UrunProvider>");let[n,s]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let i=r.getState()._transport;if(!i)return;let g=i.getTrackByName?.bind(i),v=g?.(t);v&&v.readyState!=="ended"&&s(v);let T=i.on("track",h=>{let k=g?.(t);k&&k.id!==h.id||(s(h),h.addEventListener("ended",()=>{s(null)}))});return()=>{T()}},[t,r]),n}var l=require("react/jsx-runtime");function O(t){t.posterImage?.hide?.()}var te=`
|
|
3
3
|
[data-urun-video]{width:100%;height:100%}
|
|
4
4
|
[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}
|
|
5
5
|
[data-urun-video] .vjs-tech{object-fit:contain}
|
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
.urun-video-live.vjs-has-started .vjs-loading-spinner,
|
|
8
8
|
.urun-video-live.vjs-has-started .vjs-big-play-button{display:none !important}
|
|
9
9
|
.urun-video-live .vjs-poster{background-color:transparent}
|
|
10
|
-
`,U="urun-video-critical-css";function
|
|
10
|
+
`,U="urun-video-critical-css";function ne(){if(typeof document>"u"||document.getElementById(U))return;let t=document.createElement("style");t.id=U,t.textContent=te,document.head.appendChild(t)}var oe=["playToggle","volumePanel","fullscreenToggle"],ae=["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","remainingTimeDisplay","fullscreenToggle"],D=(0,o.forwardRef)(function(r,n){let{track:s,stream:i,src:g,type:v="video/mp4",className:T,videoClassName:h,poster:k,controls:_=!0,autoPlay:S=!0,muted:P=!0,onVideoElement:V,onPlayerReady:L,children:B}=r,j=typeof g=="string"&&g.length>0,c=!j,y=(0,o.useRef)(null),f=(0,o.useRef)(null),[F,x]=(0,o.useState)(!1),W=(0,o.useCallback)(e=>{y.current=e,typeof n=="function"?n(e):n&&(n.current=e),V?.(e)},[n,V]);(0,o.useImperativeHandle)(n,()=>y.current,[]);let m=(0,o.useCallback)(()=>{let e=y.current;if(!e||!e.srcObject&&!e.src)return;P&&(e.muted=!0,e.defaultMuted=!0),e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let a=e.play();a&&typeof a.then=="function"&&a.then(()=>x(!1)).catch(d=>{(d instanceof Error?d.name:String(d))!=="AbortError"&&x(!0)})},[P]);return(0,o.useEffect)(()=>{if(typeof document>"u")return;let e=y.current;if(!e)return;ne(),P&&(e.muted=!0,e.defaultMuted=!0,e.setAttribute("muted","")),e.autoplay=S,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let a=(0,A.default)(e,{controls:_,autoplay:S,muted:P,playsinline:!0,preload:"auto",fluid:!1,bigPlayButton:!0,poster:k,userActions:{click:!0,doubleClick:!1,hotkeys:!1},controlBar:{children:c?oe:ae}});c&&a.addClass("urun-video-live");let d=()=>x(!1),p=()=>{a.hasStarted(!0),O(a),d()},u=()=>{c&&m()};return e.addEventListener("playing",p),e.addEventListener("loadedmetadata",u),c&&e.addEventListener("pause",u),f.current=a,L?.(a),()=>{e.removeEventListener("playing",p),e.removeEventListener("loadedmetadata",u),e.removeEventListener("pause",u),L?.(null),f.current&&(f.current.dispose(),f.current=null)}},[c]),(0,o.useEffect)(()=>{if(!j)return;let e=f.current;if(!e)return;let a=e.tech?.(!0)?.el?.();a&&(a.srcObject=null),e.src({src:g,type:v}),S&&m()},[j,g,v,S,m]),(0,o.useEffect)(()=>{if(!c)return;let e=f.current;if(!e)return;let a=s??null,d=i??null;!d&&a&&(d=new MediaStream([a]));let p=e.tech?.(!0)?.el?.()??y.current;if(!p)return;if(!d){p.srcObject=null,x(!1);return}p.srcObject=d,m();let u=d.getVideoTracks()[0]??a??null,C=()=>{e.hasStarted(!0),O(e),m()},M=()=>{p.srcObject=null,x(!1)};return u&&(u.addEventListener("unmute",C),u.addEventListener("ended",M),u.muted||C()),()=>{u&&(u.removeEventListener("unmute",C),u.removeEventListener("ended",M))}},[c,s,i,m]),(0,l.jsxs)("div",{className:T,style:{position:"relative",width:"100%",height:"100%"},"data-urun-video":"","data-urun-video-mode":c?"live":"vod",children:[(0,l.jsx)("video",{ref:W,className:["video-js","vjs-default-skin",h].filter(Boolean).join(" "),playsInline:!0}),F&&(0,l.jsx)("button",{type:"button",onClick:m,"aria-label":"Tap to play",style:{position:"absolute",inset:0,zIndex:30,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",border:0,cursor:"pointer",color:"#fff"},children:(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,borderRadius:999,border:"1px solid rgba(255,255,255,0.2)",background:"rgba(255,255,255,0.1)",padding:"10px 20px",fontSize:14,fontWeight:500},children:[(0,l.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:16,height:16,"aria-hidden":!0,children:(0,l.jsx)("path",{d:"M8 5v14l11-7z"})}),"Tap to play"]})}),B]})}),ie=(0,o.forwardRef)(function({name:r,...n},s){let i=I(r);return(0,l.jsx)(D,{ref:s,...n,track:i})}),z=(0,o.forwardRef)(function(r,n){return!!r.name&&!r.track&&!r.stream&&!(typeof r.src=="string"&&r.src)?(0,l.jsx)(ie,{ref:n,...r,name:r.name}):(0,l.jsx)(D,{ref:n,...r})}),H=z;0&&(module.exports={UrunVideo,VideoPlayer});
|
package/dist/video.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
import{forwardRef as
|
|
2
|
+
import{forwardRef as T,useCallback as M,useEffect as E,useImperativeHandle as Y,useRef as R,useState as J}from"react";import K from"video.js";import"video.js/dist/video-js.css";import{useContext as W,useState as q,useEffect as G}from"react";import{createContext as F,useState as ae,useEffect as ie,useRef as se}from"react";import{observePageLifecycle as de}from"@urun-sh/core";import{TransportSession as ce}from"@urun-sh/core/internal";import{jsx as ge}from"react/jsx-runtime";var V=F(null);function L(o){let r=W(V);if(!r)throw new Error("useTrack must be used within <SessionProvider> or <UrunProvider>");let[n,s]=q(null);return G(()=>{let u=r.getState()._transport;if(!u)return;let c=u.getTrackByName?.bind(u),m=c?.(o);m&&m.readyState!=="ended"&&s(m);let k=u.on("track",f=>{let y=c?.(o);y&&y.id!==f.id||(s(f),f.addEventListener("ended",()=>{s(null)}))});return()=>{k()}},[o,r]),n}import{jsx as g,jsxs as O}from"react/jsx-runtime";function N(o){o.posterImage?.hide?.()}var Q=`
|
|
3
3
|
[data-urun-video]{width:100%;height:100%}
|
|
4
4
|
[data-urun-video] .video-js,[data-urun-video] .vjs-tech{width:100%;height:100%}
|
|
5
5
|
[data-urun-video] .vjs-tech{object-fit:contain}
|
|
@@ -7,4 +7,4 @@ import{forwardRef as j,useCallback as V,useEffect as T,useImperativeHandle as G,
|
|
|
7
7
|
.urun-video-live.vjs-has-started .vjs-loading-spinner,
|
|
8
8
|
.urun-video-live.vjs-has-started .vjs-big-play-button{display:none !important}
|
|
9
9
|
.urun-video-live .vjs-poster{background-color:transparent}
|
|
10
|
-
`,I="urun-video-critical-css";function
|
|
10
|
+
`,I="urun-video-critical-css";function X(){if(typeof document>"u"||document.getElementById(I))return;let o=document.createElement("style");o.id=I,o.textContent=Q,document.head.appendChild(o)}var Z=["playToggle","volumePanel","fullscreenToggle"],$=["playToggle","volumePanel","currentTimeDisplay","timeDivider","durationDisplay","progressControl","remainingTimeDisplay","fullscreenToggle"],U=T(function(r,n){let{track:s,stream:u,src:c,type:m="video/mp4",className:k,videoClassName:f,poster:y,controls:D=!0,autoPlay:x=!0,muted:w=!0,onVideoElement:j,onPlayerReady:C,children:H}=r,S=typeof c=="string"&&c.length>0,d=!S,b=R(null),v=R(null),[_,h]=J(!1),B=M(e=>{b.current=e,typeof n=="function"?n(e):n&&(n.current=e),j?.(e)},[n,j]);Y(n,()=>b.current,[]);let p=M(()=>{let e=b.current;if(!e||!e.srcObject&&!e.src)return;w&&(e.muted=!0,e.defaultMuted=!0),e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let t=e.play();t&&typeof t.then=="function"&&t.then(()=>h(!1)).catch(i=>{(i instanceof Error?i.name:String(i))!=="AbortError"&&h(!0)})},[w]);return E(()=>{if(typeof document>"u")return;let e=b.current;if(!e)return;X(),w&&(e.muted=!0,e.defaultMuted=!0,e.setAttribute("muted","")),e.autoplay=x,e.setAttribute("playsinline",""),e.setAttribute("webkit-playsinline","");let t=K(e,{controls:D,autoplay:x,muted:w,playsinline:!0,preload:"auto",fluid:!1,bigPlayButton:!0,poster:y,userActions:{click:!0,doubleClick:!1,hotkeys:!1},controlBar:{children:d?Z:$}});d&&t.addClass("urun-video-live");let i=()=>h(!1),l=()=>{t.hasStarted(!0),N(t),i()},a=()=>{d&&p()};return e.addEventListener("playing",l),e.addEventListener("loadedmetadata",a),d&&e.addEventListener("pause",a),v.current=t,C?.(t),()=>{e.removeEventListener("playing",l),e.removeEventListener("loadedmetadata",a),e.removeEventListener("pause",a),C?.(null),v.current&&(v.current.dispose(),v.current=null)}},[d]),E(()=>{if(!S)return;let e=v.current;if(!e)return;let t=e.tech?.(!0)?.el?.();t&&(t.srcObject=null),e.src({src:c,type:m}),x&&p()},[S,c,m,x,p]),E(()=>{if(!d)return;let e=v.current;if(!e)return;let t=s??null,i=u??null;!i&&t&&(i=new MediaStream([t]));let l=e.tech?.(!0)?.el?.()??b.current;if(!l)return;if(!i){l.srcObject=null,h(!1);return}l.srcObject=i,p();let a=i.getVideoTracks()[0]??t??null,P=()=>{e.hasStarted(!0),N(e),p()},z=()=>{l.srcObject=null,h(!1)};return a&&(a.addEventListener("unmute",P),a.addEventListener("ended",z),a.muted||P()),()=>{a&&(a.removeEventListener("unmute",P),a.removeEventListener("ended",z))}},[d,s,u,p]),O("div",{className:k,style:{position:"relative",width:"100%",height:"100%"},"data-urun-video":"","data-urun-video-mode":d?"live":"vod",children:[g("video",{ref:B,className:["video-js","vjs-default-skin",f].filter(Boolean).join(" "),playsInline:!0}),_&&g("button",{type:"button",onClick:p,"aria-label":"Tap to play",style:{position:"absolute",inset:0,zIndex:30,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.6)",border:0,cursor:"pointer",color:"#fff"},children:O("span",{style:{display:"inline-flex",alignItems:"center",gap:8,borderRadius:999,border:"1px solid rgba(255,255,255,0.2)",background:"rgba(255,255,255,0.1)",padding:"10px 20px",fontSize:14,fontWeight:500},children:[g("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:16,height:16,"aria-hidden":!0,children:g("path",{d:"M8 5v14l11-7z"})}),"Tap to play"]})}),H]})}),ee=T(function({name:r,...n},s){let u=L(r);return g(U,{ref:s,...n,track:u})}),A=T(function(r,n){return!!r.name&&!r.track&&!r.stream&&!(typeof r.src=="string"&&r.src)?g(ee,{ref:n,...r,name:r.name}):g(U,{ref:n,...r})}),re=A;export{re as UrunVideo,A as VideoPlayer};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urun-sh/react",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.23",
|
|
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.23",
|
|
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",
|