@urun-sh/react 0.2.58 → 0.2.59
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/README.md +42 -0
- package/dist/index.d.mts +70 -1
- package/dist/index.d.ts +70 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -188,6 +188,48 @@ Notes:
|
|
|
188
188
|
- Arrays in the doc are read as plain snapshots. Do not read-modify-write an array through `set` for append-only logs; use the platform's stream/text primitives for growing data.
|
|
189
189
|
- `useSessionDoc(session, key, selector?)` also accepts a selector for one-off reads.
|
|
190
190
|
|
|
191
|
+
## Streaming text (`Text`)
|
|
192
|
+
|
|
193
|
+
Point it at a named stream; it renders the text unstyled at whatever rate the
|
|
194
|
+
wire delivers (1k+ tok/s), because the network path touches **zero React state**:
|
|
195
|
+
chunks append to a plain buffer and a `requestAnimationFrame` loop drains it
|
|
196
|
+
into one bare DOM text node via `appendData` — one DOM write per frame, no
|
|
197
|
+
reconciliation, no parsing in the hot loop.
|
|
198
|
+
|
|
199
|
+
```tsx
|
|
200
|
+
import { Text } from '@urun-sh/react'
|
|
201
|
+
|
|
202
|
+
<Text session={session} stream={`llm-resp:${requestId}`} onDone={setFinalText} />
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
A reasoning pane is just a second `Text` on the other stream — nothing special:
|
|
206
|
+
|
|
207
|
+
```tsx
|
|
208
|
+
<Text session={session} stream={`llm-think:${requestId}`} />
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Props: `session`, `stream`, `onDone(text)`, `onError(error)`, `onMeter(meter)`,
|
|
212
|
+
`smooth` (typewriter drain below `smoothThreshold`, bypassed above it),
|
|
213
|
+
`smoothCharsPerFrame`, `smoothThreshold`, `className`, `style`.
|
|
214
|
+
|
|
215
|
+
Styling is the caller's — the container is an unstyled `<span>` and the content
|
|
216
|
+
is raw text. Apply markdown/code highlighting at block boundaries or on
|
|
217
|
+
completion, never per token.
|
|
218
|
+
|
|
219
|
+
### Headless: `useText` / `useTextMeter`
|
|
220
|
+
|
|
221
|
+
```tsx
|
|
222
|
+
const { ref, meterRef, getText } = useText({ session, stream: `llm-resp:${id}` })
|
|
223
|
+
const { chars, tokens, tokensPerSecond } = useTextMeter(meterRef, 250)
|
|
224
|
+
|
|
225
|
+
return <pre ref={ref} />
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`useText` holds no React state, so a component using it renders once on mount
|
|
229
|
+
regardless of chunk count. Counters are computed in the RAF loop and written
|
|
230
|
+
into `meterRef` in place; `useTextMeter` samples them on an interval so a
|
|
231
|
+
tok/s readout costs O(interval) renders, never O(chunks).
|
|
232
|
+
|
|
191
233
|
## Styling
|
|
192
234
|
|
|
193
235
|
Import the package CSS when using built-in components:
|
package/dist/index.d.mts
CHANGED
|
@@ -505,6 +505,75 @@ declare function useMetricsPanel(props: MetricsPanelProps): {
|
|
|
505
505
|
};
|
|
506
506
|
declare function MetricsPanel(props: MetricsPanelProps): react_jsx_runtime.JSX.Element;
|
|
507
507
|
|
|
508
|
+
interface TextStreamSource {
|
|
509
|
+
messages(): AsyncIterable<unknown>;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
interface TextSessionLike {
|
|
513
|
+
stream(name: string): TextStreamSource;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
declare function textDelta(frame: unknown): string;
|
|
517
|
+
|
|
518
|
+
declare class TextStreamError extends Error {
|
|
519
|
+
name: string;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
interface TextMeter {
|
|
523
|
+
|
|
524
|
+
chars: number;
|
|
525
|
+
|
|
526
|
+
tokens: number;
|
|
527
|
+
|
|
528
|
+
tokensPerSecond: number;
|
|
529
|
+
|
|
530
|
+
elapsedMs: number;
|
|
531
|
+
|
|
532
|
+
done: boolean;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
declare const DEFAULT_SMOOTH_CHARS_PER_FRAME = 3;
|
|
536
|
+
|
|
537
|
+
declare const DEFAULT_SMOOTH_THRESHOLD = 240;
|
|
538
|
+
interface UseTextOptions {
|
|
539
|
+
|
|
540
|
+
session: TextSessionLike | null | undefined;
|
|
541
|
+
|
|
542
|
+
stream: string;
|
|
543
|
+
|
|
544
|
+
smooth?: boolean;
|
|
545
|
+
|
|
546
|
+
smoothCharsPerFrame?: number;
|
|
547
|
+
|
|
548
|
+
smoothThreshold?: number;
|
|
549
|
+
|
|
550
|
+
onDone?: (text: string) => void;
|
|
551
|
+
|
|
552
|
+
onError?: (error: Error) => void;
|
|
553
|
+
|
|
554
|
+
onMeter?: (meter: TextMeter) => void;
|
|
555
|
+
}
|
|
556
|
+
interface UseTextResult {
|
|
557
|
+
|
|
558
|
+
ref: (element: HTMLElement | null) => void;
|
|
559
|
+
|
|
560
|
+
meterRef: RefObject<TextMeter>;
|
|
561
|
+
|
|
562
|
+
getText: () => string;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
declare function useText(options: UseTextOptions): UseTextResult;
|
|
566
|
+
|
|
567
|
+
declare function useTextMeter(meterRef: RefObject<TextMeter>, intervalMs?: number): TextMeter;
|
|
568
|
+
interface TextProps extends UseTextOptions {
|
|
569
|
+
|
|
570
|
+
className?: string;
|
|
571
|
+
|
|
572
|
+
style?: CSSProperties;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
declare function Text(props: TextProps): react_jsx_runtime.JSX.Element;
|
|
576
|
+
|
|
508
577
|
interface ScopedStreamSource {
|
|
509
578
|
|
|
510
579
|
readonly track: MediaStreamTrack | null;
|
|
@@ -1200,4 +1269,4 @@ interface UrunActivationOverlayProps {
|
|
|
1200
1269
|
|
|
1201
1270
|
declare function UrunActivationOverlay({ session, stream, videoElement, render, className, }: UrunActivationOverlayProps): react_jsx_runtime.JSX.Element | null;
|
|
1202
1271
|
|
|
1203
|
-
export { type ActivationProgress, Audio, type AudioHandle, type AudioProps, type AudioSessionSource, type AudioStreamSource, Camera, type CameraFacing, type CameraHandle, type CameraProps, type CameraSessionSource, type CameraStreamSource, type CapturePhotoOptions, type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, type FrameMarker, Image, ImageFrame, ImageFrameSchema, type ImageHandle, type ImageProps, type InputPresenceControls, type InputPresenceSession, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, Mic, type MicHandle, type MicProps, OPERATOR_CHORD_LABEL, OPERATOR_TOKEN_STORAGE_KEY, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type ReferenceImageCameraSource, type RegisteredComponent, ReprojectedVideo, type ReprojectedVideoHandle, type ReprojectedVideoProps, type ReprojectedVideoWarpOptions, type RequestCapableSession, type RequestStream, type ScopedSession, type ScopedStreamSource, Session, type SessionIdleState, type SessionProps, type SessionRequestOptions, type SessionStatsSource, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunActivationOverlay, type UrunActivationOverlayProps, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunIdleWarning, type UrunIdleWarningProps, UrunJwtProvider, UrunProvider, UrunSessionClock, type UrunSessionClockProps, UrunSessionEnded, type UrunSessionEndedProps, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseInputPresenceOptions, type UseReferenceImageOptions, type UseReferenceImageResult, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseUrunAudioLevelOptions, type UseUrunPrewakeOptions, Video, type VideoHandle, type VideoProps, type VideoSessionSource, type VideoStreamSource, Voice, type VoiceHandle, type VoiceProps, type VoiceSessionSource, type VoiceStreamSource, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, readOperatorToken, registerComponent, resumeUrunAudioContext, urunPublicEnv, useActivation, useApp, useChat, useCompletion, useConfirmOnLeave, useDocStore, useImageFrame, useInputPresence, useMetricsPanel, useOperatorOverride, useProgressCard, useReferenceImage, useRequest, useSession, useSessionDoc, useSessionEndsAt, useSessionIdle, useSessionPhase, useSessionStats, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useTextStream, useUrunAudioLevel, useUrunAuth, useUrunPrewake, usesWorkOSAuth };
|
|
1272
|
+
export { type ActivationProgress, Audio, type AudioHandle, type AudioProps, type AudioSessionSource, type AudioStreamSource, Camera, type CameraFacing, type CameraHandle, type CameraProps, type CameraSessionSource, type CameraStreamSource, type CapturePhotoOptions, type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_SMOOTH_CHARS_PER_FRAME, DEFAULT_SMOOTH_THRESHOLD, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, type FrameMarker, Image, ImageFrame, ImageFrameSchema, type ImageHandle, type ImageProps, type InputPresenceControls, type InputPresenceSession, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, Mic, type MicHandle, type MicProps, OPERATOR_CHORD_LABEL, OPERATOR_TOKEN_STORAGE_KEY, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type ReferenceImageCameraSource, type RegisteredComponent, ReprojectedVideo, type ReprojectedVideoHandle, type ReprojectedVideoProps, type ReprojectedVideoWarpOptions, type RequestCapableSession, type RequestStream, type ScopedSession, type ScopedStreamSource, Session, type SessionIdleState, type SessionProps, type SessionRequestOptions, type SessionStatsSource, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, Text, type TextMeter, type TextProps, type TextSessionLike, TextStream, TextStreamError, TextStreamSchema, type TextStreamSource, type UrunAccessToken, type UrunAccessTokenProvider, UrunActivationOverlay, type UrunActivationOverlayProps, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunIdleWarning, type UrunIdleWarningProps, UrunJwtProvider, UrunProvider, UrunSessionClock, type UrunSessionClockProps, UrunSessionEnded, type UrunSessionEndedProps, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseInputPresenceOptions, type UseReferenceImageOptions, type UseReferenceImageResult, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseTextOptions, type UseTextResult, type UseUrunAudioLevelOptions, type UseUrunPrewakeOptions, Video, type VideoHandle, type VideoProps, type VideoSessionSource, type VideoStreamSource, Voice, type VoiceHandle, type VoiceProps, type VoiceSessionSource, type VoiceStreamSource, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, readOperatorToken, registerComponent, resumeUrunAudioContext, textDelta, urunPublicEnv, useActivation, useApp, useChat, useCompletion, useConfirmOnLeave, useDocStore, useImageFrame, useInputPresence, useMetricsPanel, useOperatorOverride, useProgressCard, useReferenceImage, useRequest, useSession, useSessionDoc, useSessionEndsAt, useSessionIdle, useSessionPhase, useSessionStats, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useText, useTextMeter, useTextStream, useUrunAudioLevel, useUrunAuth, useUrunPrewake, usesWorkOSAuth };
|
package/dist/index.d.ts
CHANGED
|
@@ -505,6 +505,75 @@ declare function useMetricsPanel(props: MetricsPanelProps): {
|
|
|
505
505
|
};
|
|
506
506
|
declare function MetricsPanel(props: MetricsPanelProps): react_jsx_runtime.JSX.Element;
|
|
507
507
|
|
|
508
|
+
interface TextStreamSource {
|
|
509
|
+
messages(): AsyncIterable<unknown>;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
interface TextSessionLike {
|
|
513
|
+
stream(name: string): TextStreamSource;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
declare function textDelta(frame: unknown): string;
|
|
517
|
+
|
|
518
|
+
declare class TextStreamError extends Error {
|
|
519
|
+
name: string;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
interface TextMeter {
|
|
523
|
+
|
|
524
|
+
chars: number;
|
|
525
|
+
|
|
526
|
+
tokens: number;
|
|
527
|
+
|
|
528
|
+
tokensPerSecond: number;
|
|
529
|
+
|
|
530
|
+
elapsedMs: number;
|
|
531
|
+
|
|
532
|
+
done: boolean;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
declare const DEFAULT_SMOOTH_CHARS_PER_FRAME = 3;
|
|
536
|
+
|
|
537
|
+
declare const DEFAULT_SMOOTH_THRESHOLD = 240;
|
|
538
|
+
interface UseTextOptions {
|
|
539
|
+
|
|
540
|
+
session: TextSessionLike | null | undefined;
|
|
541
|
+
|
|
542
|
+
stream: string;
|
|
543
|
+
|
|
544
|
+
smooth?: boolean;
|
|
545
|
+
|
|
546
|
+
smoothCharsPerFrame?: number;
|
|
547
|
+
|
|
548
|
+
smoothThreshold?: number;
|
|
549
|
+
|
|
550
|
+
onDone?: (text: string) => void;
|
|
551
|
+
|
|
552
|
+
onError?: (error: Error) => void;
|
|
553
|
+
|
|
554
|
+
onMeter?: (meter: TextMeter) => void;
|
|
555
|
+
}
|
|
556
|
+
interface UseTextResult {
|
|
557
|
+
|
|
558
|
+
ref: (element: HTMLElement | null) => void;
|
|
559
|
+
|
|
560
|
+
meterRef: RefObject<TextMeter>;
|
|
561
|
+
|
|
562
|
+
getText: () => string;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
declare function useText(options: UseTextOptions): UseTextResult;
|
|
566
|
+
|
|
567
|
+
declare function useTextMeter(meterRef: RefObject<TextMeter>, intervalMs?: number): TextMeter;
|
|
568
|
+
interface TextProps extends UseTextOptions {
|
|
569
|
+
|
|
570
|
+
className?: string;
|
|
571
|
+
|
|
572
|
+
style?: CSSProperties;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
declare function Text(props: TextProps): react_jsx_runtime.JSX.Element;
|
|
576
|
+
|
|
508
577
|
interface ScopedStreamSource {
|
|
509
578
|
|
|
510
579
|
readonly track: MediaStreamTrack | null;
|
|
@@ -1200,4 +1269,4 @@ interface UrunActivationOverlayProps {
|
|
|
1200
1269
|
|
|
1201
1270
|
declare function UrunActivationOverlay({ session, stream, videoElement, render, className, }: UrunActivationOverlayProps): react_jsx_runtime.JSX.Element | null;
|
|
1202
1271
|
|
|
1203
|
-
export { type ActivationProgress, Audio, type AudioHandle, type AudioProps, type AudioSessionSource, type AudioStreamSource, Camera, type CameraFacing, type CameraHandle, type CameraProps, type CameraSessionSource, type CameraStreamSource, type CapturePhotoOptions, type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, type FrameMarker, Image, ImageFrame, ImageFrameSchema, type ImageHandle, type ImageProps, type InputPresenceControls, type InputPresenceSession, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, Mic, type MicHandle, type MicProps, OPERATOR_CHORD_LABEL, OPERATOR_TOKEN_STORAGE_KEY, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type ReferenceImageCameraSource, type RegisteredComponent, ReprojectedVideo, type ReprojectedVideoHandle, type ReprojectedVideoProps, type ReprojectedVideoWarpOptions, type RequestCapableSession, type RequestStream, type ScopedSession, type ScopedStreamSource, Session, type SessionIdleState, type SessionProps, type SessionRequestOptions, type SessionStatsSource, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, TextStream, TextStreamSchema, type UrunAccessToken, type UrunAccessTokenProvider, UrunActivationOverlay, type UrunActivationOverlayProps, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunIdleWarning, type UrunIdleWarningProps, UrunJwtProvider, UrunProvider, UrunSessionClock, type UrunSessionClockProps, UrunSessionEnded, type UrunSessionEndedProps, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseInputPresenceOptions, type UseReferenceImageOptions, type UseReferenceImageResult, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseUrunAudioLevelOptions, type UseUrunPrewakeOptions, Video, type VideoHandle, type VideoProps, type VideoSessionSource, type VideoStreamSource, Voice, type VoiceHandle, type VoiceProps, type VoiceSessionSource, type VoiceStreamSource, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, readOperatorToken, registerComponent, resumeUrunAudioContext, urunPublicEnv, useActivation, useApp, useChat, useCompletion, useConfirmOnLeave, useDocStore, useImageFrame, useInputPresence, useMetricsPanel, useOperatorOverride, useProgressCard, useReferenceImage, useRequest, useSession, useSessionDoc, useSessionEndsAt, useSessionIdle, useSessionPhase, useSessionStats, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useTextStream, useUrunAudioLevel, useUrunAuth, useUrunPrewake, usesWorkOSAuth };
|
|
1272
|
+
export { type ActivationProgress, Audio, type AudioHandle, type AudioProps, type AudioSessionSource, type AudioStreamSource, Camera, type CameraFacing, type CameraHandle, type CameraProps, type CameraSessionSource, type CameraStreamSource, type CapturePhotoOptions, type ChatMessage, type ChatRole, ComponentRenderer, type CreateDocStoreOptions, DEFAULT_CAMERA_CONSTRAINTS, DEFAULT_LOG_CAP, DEFAULT_SMOOTH_CHARS_PER_FRAME, DEFAULT_SMOOTH_THRESHOLD, DEFAULT_VOICE_CONSTRAINTS, type DeepPartial, type DocPatch, DocPatchForm, type DocState, type DocStore, type FrameMarker, Image, ImageFrame, ImageFrameSchema, type ImageHandle, type ImageProps, type InputPresenceControls, type InputPresenceSession, type JsonObjectParse, MetricsPanel, MetricsPanelSchema, Mic, type MicHandle, type MicProps, OPERATOR_CHORD_LABEL, OPERATOR_TOKEN_STORAGE_KEY, ProgressCard, ProgressCardSchema, type ReactApp, type ReactSession, type ReactSessionDocument, type ReactSessionStream, type ReferenceImageCameraSource, type RegisteredComponent, ReprojectedVideo, type ReprojectedVideoHandle, type ReprojectedVideoProps, type ReprojectedVideoWarpOptions, type RequestCapableSession, type RequestStream, type ScopedSession, type ScopedStreamSource, Session, type SessionIdleState, type SessionProps, type SessionRequestOptions, type SessionStatsSource, type SessionWake, type SpineEntry, StatusBadge, StatusBadgeSchema, type StreamMessageEntry, Text, type TextMeter, type TextProps, type TextSessionLike, TextStream, TextStreamError, TextStreamSchema, type TextStreamSource, type UrunAccessToken, type UrunAccessTokenProvider, UrunActivationOverlay, type UrunActivationOverlayProps, UrunAudio, type UrunAudioHandle, type UrunAudioLevel, type UrunAudioProps, type UrunAudioSessionSource, type UrunAudioStreamSource, type UrunAuthContextValue, type UrunAuthMode, UrunAuthProvider, type UrunAuthProviderProps, UrunCamera, type UrunCameraFacing, type UrunCameraHandle, type UrunCameraProps, type UrunCameraSessionSource, type UrunCameraStreamSource, UrunControlSender, type UrunControlSenderProps, UrunDocPanel, type UrunDocPanelProps, UrunErrorBoundary, UrunEventSpine, type UrunEventSpineProps, UrunIdleWarning, type UrunIdleWarningProps, UrunJwtProvider, UrunProvider, UrunSessionClock, type UrunSessionClockProps, UrunSessionEnded, type UrunSessionEndedProps, UrunSessionGate, type UrunSessionGateProps, UrunSessionStatus, type UrunSessionStatusProps, UrunSessionWaking, type UrunSessionWakingProps, UrunStreamTail, type UrunStreamTailProps, UrunVoice, type UrunVoiceHandle, type UrunVoiceProps, type UrunVoiceSessionSource, type UrunVoiceStreamSource, type UseChatOptions, type UseChatResult, type UseCompletionOptions, type UseCompletionResult, type UseInputPresenceOptions, type UseReferenceImageOptions, type UseReferenceImageResult, type UseRequestOptions, type UseRequestResult, type UseSessionDocResult, type UseStreamMessagesOptions, type UseTextOptions, type UseTextResult, type UseUrunAudioLevelOptions, type UseUrunPrewakeOptions, Video, type VideoHandle, type VideoProps, type VideoSessionSource, type VideoStreamSource, Voice, type VoiceHandle, type VoiceProps, type VoiceSessionSource, type VoiceStreamSource, type WorkbenchDocSource, type WorkbenchSession, type WorkbenchStreamSource, authMode, createDocStore, formatPayload, getUrunAudioContext, parseJsonObject, pushCapped, readOperatorToken, registerComponent, resumeUrunAudioContext, textDelta, urunPublicEnv, useActivation, useApp, useChat, useCompletion, useConfirmOnLeave, useDocStore, useImageFrame, useInputPresence, useMetricsPanel, useOperatorOverride, useProgressCard, useReferenceImage, useRequest, useSession, useSessionDoc, useSessionEndsAt, useSessionIdle, useSessionPhase, useSessionStats, useSessionTrack, useSessionWake, useStatusBadge, useStreamMessages, useText, useTextMeter, useTextStream, useUrunAudioLevel, useUrunAuth, useUrunPrewake, usesWorkOSAuth };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
"use strict";var ir=Object.defineProperty;var so=Object.getOwnPropertyDescriptor;var io=Object.getOwnPropertyNames;var ao=Object.prototype.hasOwnProperty;var uo=(e,t)=>{for(var r in t)ir(e,r,{get:t[r],enumerable:!0})},co=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of io(t))!ao.call(e,n)&&n!==r&&ir(e,n,{get:()=>t[n],enumerable:!(o=so(t,n))||o.enumerable});return e};var lo=e=>co(ir({},"__esModule",{value:!0}),e);var qo={};uo(qo,{Audio:()=>xt,Camera:()=>Er,ComponentRenderer:()=>mn,DEFAULT_CAMERA_CONSTRAINTS:()=>Cr,DEFAULT_LOG_CAP:()=>Fe,DEFAULT_VOICE_CONSTRAINTS:()=>br,DocPatchForm:()=>At,Image:()=>En,ImageFrame:()=>bn,ImageFrameSchema:()=>kn,MetricsPanel:()=>Rn,MetricsPanelSchema:()=>Pn,Mic:()=>Nn,OPERATOR_CHORD_LABEL:()=>Dr,OPERATOR_TOKEN_STORAGE_KEY:()=>Or,ProgressCard:()=>gn,ProgressCardSchema:()=>fn,ReprojectedVideo:()=>cn,Session:()=>Qr,StatusBadge:()=>hn,StatusBadgeSchema:()=>Sn,TextStream:()=>yn,TextStreamSchema:()=>vn,UrunActivationOverlay:()=>tr,UrunAudio:()=>Un,UrunAuthProvider:()=>ht,UrunCamera:()=>In,UrunControlSender:()=>jn,UrunDocPanel:()=>Wn,UrunErrorBoundary:()=>Ze,UrunEventSpine:()=>Kn,UrunIdleWarning:()=>Qn,UrunJwtProvider:()=>Nr,UrunProvider:()=>Br,UrunSessionClock:()=>Gn,UrunSessionEnded:()=>Zn,UrunSessionGate:()=>zn,UrunSessionStatus:()=>Jn,UrunSessionWaking:()=>Zt,UrunStreamTail:()=>Hn,UrunVoice:()=>Mn,Video:()=>Ke,Voice:()=>wt,authMode:()=>St,createDocStore:()=>Bt,describeSessionPhase:()=>sr.describeSessionPhase,formatPayload:()=>ct,getUrunAudioContext:()=>vt,isWakingPhase:()=>sr.isWakingPhase,parseJsonObject:()=>Kt,pushCapped:()=>Oe,readOperatorToken:()=>ar,registerComponent:()=>dn,resumeUrunAudioContext:()=>je,urunPublicEnv:()=>Re,useActivation:()=>Qt,useApp:()=>Kr,useChat:()=>Yr,useCompletion:()=>Jr,useConfirmOnLeave:()=>Lt,useDocStore:()=>ut,useImageFrame:()=>vr,useInputPresence:()=>Zr,useMetricsPanel:()=>yr,useOperatorOverride:()=>It,useProgressCard:()=>gr,useReferenceImage:()=>Ln,useRequest:()=>$r,useSession:()=>en,useSessionDoc:()=>qn,useSessionEndsAt:()=>Tr,useSessionIdle:()=>wr,useSessionPhase:()=>ye,useSessionStats:()=>ro,useSessionTrack:()=>On,useSessionWake:()=>Yt,useStatusBadge:()=>Sr,useStreamMessages:()=>Xt,useTextStream:()=>hr,useUrunAudioLevel:()=>Ht,useUrunAuth:()=>_t,useUrunPrewake:()=>to,usesWorkOSAuth:()=>Mr});module.exports=lo(qo);var ie=require("react");var Ur=require("react"),gt=require("react/jsx-runtime"),Ze=class extends Ur.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,gt.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,gt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,gt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var Ar=require("react"),Qe=(0,Ar.createContext)(null);function _e(e){return e&&e.trim()?e.trim():void 0}function Re(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return _e(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return _e(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return _e(typeof process<"u"?process.env?.[e]:void 0)}}function St(){let e=Re("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Re("VERCEL_ENV")==="production"?"workos":Re("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Mr(){return St()==="workos"}var et=require("react"),Ir=require("react/jsx-runtime"),_r=(0,et.createContext)(null);function ht({getAccessToken:e,children:t}){let r=(0,et.useMemo)(()=>({getAccessToken:e}),[e]);return(0,Ir.jsx)(_r.Provider,{value:r,children:t})}var Nr=ht;function _t(){return(0,et.useContext)(_r)}var Nt=require("react"),Or="urun.operator_token",Vr=null,Lr="op",Dr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function Fr(){return typeof window<"u"}function ar(){return Vr}function po(){if(!Fr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Lr);if(!r)return null;Vr=r,t.delete(Lr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function mo(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function It(e){let t=(0,Nt.useRef)(e);t.current=e,(0,Nt.useEffect)(()=>{if(!Fr())return;po();let r=o=>{if(!mo(o))return;let n=ar();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var qr=require("react");function Lt(e=!0){(0,qr.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var Ne=require("react/jsx-runtime"),fo="/api/urun-token",go=1e4;function So(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Hr(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function Wr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function ur(e){let t=e===void 0?void 0:JSON.stringify(e);return(0,ie.useMemo)(()=>e,[t])}function ho(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Ne.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Ne.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Ne.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Br({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,audioPlayout:g,videoPlayout:l,sessionStats:v,confirmOnLeave:R=!1,fallback:k,errorFallback:m,children:S}){let p=n===void 0&&t===void 0;if(!p&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!p&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let b=r??o;if(p&&(typeof b!="string"||b.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Lt(R);let[y,U]=(0,ie.useState)(),[h,C]=(0,ie.useState)(null),T=(0,ie.useRef)(void 0),w=(0,ie.useRef)(null),[I,d]=(0,ie.useState)(null);It(f=>d({jwt:f}));let E=_t(),P=Re("NEXT_PUBLIC_SESSION_TOKEN")??Re("NEXT_PUBLIC_URUN_JWT"),L=St(),q=I!==null,W=L==="workos"&&!n&&!q&&!p,V=n??(L==="jwt"?P:void 0)??y?.token,A=q?I.jwt:V,H=s??Re("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),J=W&&!A&&!E?.getAccessToken,Z=t??y?.orgId,j=e??y?.gatewayUrl,re=p&&y===void 0,ce=p&&y!==void 0&&!j?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,Q=J?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,B=h??ce??Q,z=Wr("NEXT_PUBLIC_URUN_TOKEN_URL",Re("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??fo,be=Wr("NEXT_PUBLIC_URUN_EVENTS_URL",Re("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,se=(0,ie.useCallback)(async f=>{if(!f?.forceRefresh){let x=T.current;if(!x)return x;let K=So(x);if(K===null||K-Date.now()>go)return x}return(await(w.current??(w.current=(async()=>{try{let x=await Hr(z);return T.current=x.token,U(x),x}finally{w.current=null}})()))).token},[z]),le=(0,ie.useCallback)(async()=>A,[A]),De=typeof A=="string"&&A.trim().length>0,de=W?E?.getAccessToken:p&&!q?se:De?le:void 0,xe=ur(g),pe=ur(l),ae=ur(v),ne=(0,ie.useMemo)(()=>({appId:b,baseUrl:j??"",orgId:Z??"",jwt:A,getAccessToken:W?E?.getAccessToken:p&&!q?se:void 0,authProvider:H,eventsUrl:be,sessionKey:a,releaseOnLeave:c,audioPlayout:xe,videoPlayout:pe,sessionStats:ae,priority:q?"preempt":void 0}),[b,E,j,H,A,be,Z,a,c,xe,pe,ae,W,q,p,se]);return(0,ie.useEffect)(()=>{if(!p)return;let f=new AbortController;return C(null),(async()=>{try{let _=await Hr(z,f.signal);T.current=_.token,U(_)}catch(_){if(f.signal.aborted)return;C(_ instanceof Error?_:new Error(String(_)))}})(),()=>f.abort()},[p,z]),(0,Ne.jsx)(Ze,{fallback:k,children:B?ho(m,B):re?(0,Ne.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Ne.jsx)(Qe.Provider,{value:ne,children:de?(0,Ne.jsx)(ht,{getAccessToken:de,children:S}):S})})}var me=require("react"),jr=require("@urun-sh/core");function vo(e,t){return`${e}:${JSON.stringify(t??{})}`}function yo(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var Be=new Map;var cr=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},lr=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},dr=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new cr(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new lr(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Kr(){let e=(0,me.useContext)(Qe);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,me.useReducer)(i=>i+1,0),r=(0,me.useRef)(new Map),o=(0,me.useRef)(new Map),n=(0,me.useRef)(null),s=(0,me.useMemo)(()=>(0,jr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return(0,me.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Be.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=Be.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let l=Be.get(u);!l||l.refCount!==0||(Be.delete(u),l.handle.disconnect())},0)))}n.current=a}},[]),(0,me.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=l=>{let v=vo(u,l),R=r.current.get(v);if(R&&!R.disposed)return R;let k=yo(e,u,l),m=Be.get(k);return m?.handle.disposed&&(m.disposeTimer&&clearTimeout(m.disposeTimer),Be.delete(k),o.current.get(k)===m&&o.current.delete(k),m=void 0),m?m.disposeTimer&&(clearTimeout(m.disposeTimer),m.disposeTimer=null):(m={handle:new dr(s[u](l),t,e.eventsUrl),refCount:0,disposeTimer:null},Be.set(k,m)),o.current.get(k)!==m&&(o.current.set(k,m),m.handle.addNotifier(t),m.refCount+=1),r.current.set(v,m.handle),m.handle};return i.set(u,g),g}})},[e,s])}var te=require("react");function tt(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function ko(e){return e instanceof Error?e:new Error(String(e))}function $r(e,t){let r=(0,te.useMemo)(()=>tt(e),[e]),[o,n]=(0,te.useState)(void 0),[s,i]=(0,te.useState)(null),[a,u]=(0,te.useState)(!1),c=(0,te.useRef)(t);c.current=t;let g=(0,te.useRef)(0),l=(0,te.useRef)(null),v=(0,te.useRef)(!0);(0,te.useEffect)(()=>(v.current=!0,()=>{v.current=!1,l.current?.abort()}),[]);let R=(0,te.useCallback)(async S=>{l.current?.abort();let p=new AbortController;l.current=p;let b=++g.current,y=()=>v.current&&g.current===b;y()&&(u(!0),i(null));try{let U=await r.request(S,{...c.current,signal:p.signal});return y()&&(n(U),u(!1),c.current?.onSuccess?.(U)),U}catch(U){let h=ko(U);throw y()&&(i(h),u(!1),c.current?.onError?.(h)),h}},[r]),k=(0,te.useCallback)(S=>{R(S).catch(()=>{})},[R]),m=(0,te.useCallback)(()=>{g.current++,l.current?.abort(),l.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:k,mutateAsync:R,data:o,error:s,isPending:a,reset:m}}var oe=require("react");function Xr(e){return e instanceof Error?e:new Error(String(e))}var bo=e=>typeof e=="string"?e:String(e);function Jr(e,t){let r=(0,oe.useMemo)(()=>tt(e),[e]),[o,n]=(0,oe.useState)(""),[s,i]=(0,oe.useState)(!1),[a,u]=(0,oe.useState)(null),c=(0,oe.useRef)(t);c.current=t;let g=(0,oe.useRef)(0),l=(0,oe.useRef)(null),v=(0,oe.useRef)(!0);(0,oe.useEffect)(()=>(v.current=!0,()=>{v.current=!1,l.current?.cancel(),l.current=null}),[]);let R=(0,oe.useCallback)(()=>{g.current++,l.current?.cancel(),l.current=null,v.current&&i(!1)},[]),k=(0,oe.useCallback)(async m=>{l.current?.cancel();let S=++g.current,p=()=>v.current&&g.current===S,b=c.current,y=b?.parseChunk??bo,U=b?.buildPayload??(P=>({prompt:P}));p()&&(n(""),u(null),i(!0));let{parseChunk:h,buildPayload:C,onFinish:T,onError:w,...I}=b??{},d="",E;try{E=r.requestStream(U(m),I),l.current=E}catch(P){let L=Xr(P);p()&&(u(L),i(!1),b?.onError?.(L));return}try{for await(let P of E){if(g.current!==S)break;d+=y(P),p()&&n(d)}p()&&(i(!1),b?.onFinish?.(d))}catch(P){let L=Xr(P);p()&&(u(L),i(!1),b?.onError?.(L))}finally{l.current===E&&(l.current=null)}},[r]);return{completion:o,complete:k,stop:R,isStreaming:s,error:a}}var Y=require("react");function zr(e){return e instanceof Error?e:new Error(String(e))}var Po=e=>typeof e=="string"?e:String(e),Gr=0;function pr(e){return Gr+=1,`${e}-${Gr}`}function Yr(e,t){let r=(0,Y.useMemo)(()=>tt(e),[e]),[o,n]=(0,Y.useState)(()=>(t?.initialMessages??[]).map(y=>({id:y.id??pr("msg"),role:y.role,content:y.content}))),[s,i]=(0,Y.useState)(""),[a,u]=(0,Y.useState)(!1),[c,g]=(0,Y.useState)(null),l=(0,Y.useRef)(t);l.current=t;let v=(0,Y.useRef)(o);v.current=o;let R=(0,Y.useRef)(s);R.current=s;let k=(0,Y.useRef)(0),m=(0,Y.useRef)(null),S=(0,Y.useRef)(!0);(0,Y.useEffect)(()=>(S.current=!0,()=>{S.current=!1,m.current?.cancel(),m.current=null}),[]);let p=(0,Y.useCallback)(()=>{k.current++,m.current?.cancel(),m.current=null,S.current&&u(!1)},[]),b=(0,Y.useCallback)(async y=>{let U=y===void 0,h=(U?R.current:y)??"";if(!h.trim())return;m.current?.cancel();let T=++k.current,w=()=>S.current&&k.current===T,I=l.current,d=I?.parseChunk??Po,E={id:pr("msg"),role:"user",content:h},P={id:pr("msg"),role:"assistant",content:""},L=[...v.current,E].map(B=>({role:B.role,content:B.content})),q=[...v.current,E,P];v.current=q,n(q),U&&i(""),g(null),u(!0);let W=I?.buildPayload??(B=>({messages:B})),{initialMessages:V,parseChunk:A,buildPayload:H,onFinish:J,onError:Z,...j}=I??{},re=B=>{n(z=>z.map(be=>be.id===P.id?{...be,content:B}:be))},ce="",Q;try{Q=r.requestStream(W(L),j),m.current=Q}catch(B){let z=zr(B);w()&&(g(z),u(!1),I?.onError?.(z));return}try{for await(let B of Q){if(k.current!==T)break;ce+=d(B),w()&&re(ce)}w()&&(u(!1),I?.onFinish?.({...P,content:ce}))}catch(B){let z=zr(B);w()&&(g(z),u(!1),I?.onError?.(z))}finally{m.current===Q&&(m.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:b,stop:p,isStreaming:a,error:c}}var G=require("react"),rt=require("@urun-sh/core"),mr=[];function Zr(e,t={}){let{field:r=rt.INPUT_PRESENCE_FIELD,hz:o=rt.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,G.useMemo)(()=>s?(0,rt.createInputPresencePublisher)({awareness:{setLocalStateField:(h,C)=>s.setField(h,C)},field:r,hz:o}):null,[s,r,o]),a=(0,G.useRef)(null);a.current=i;let[u,c]=(0,G.useState)(!1),[g,l]=(0,G.useState)(mr),v=(0,G.useRef)(!1);(0,G.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let R=(0,G.useCallback)(()=>{let h=a.current;l(h?h.heldKeys():mr)},[]),k=(0,G.useCallback)(()=>{a.current?.clear(),l(mr)},[]);(0,G.useEffect)(()=>{if(!n)return;let h=()=>!!n.pointerLockElement,C=()=>{if(h()){v.current=!1,c(!0);return}v.current||(c(!1),k())},T=P=>{h()&&(a.current?.keyDown(P.key),R())},w=P=>{a.current?.keyUp(P.key),R()},I=P=>{h()&&a.current?.movePointer(P.movementX,P.movementY)},d=P=>{h()&&a.current?.setButtons(P.buttons)},E=()=>{k()};return n.addEventListener("pointerlockchange",C),n.addEventListener("keydown",T),n.addEventListener("keyup",w),n.addEventListener("mousemove",I),n.addEventListener("mousedown",d),n.addEventListener("mouseup",d),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",C),n.removeEventListener("keydown",T),n.removeEventListener("keyup",w),n.removeEventListener("mousemove",I),n.removeEventListener("mousedown",d),n.removeEventListener("mouseup",d),n.defaultView?.removeEventListener("blur",E)}},[n,k,R]);let m=(0,G.useCallback)(h=>{h.requestPointerLock?.()},[]),S=(0,G.useCallback)(()=>{v.current=!0,c(!0)},[]),p=(0,G.useCallback)(()=>{v.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),k()},[n,k]),b=(0,G.useCallback)(h=>{a.current?.keyDown(h),R()},[R]),y=(0,G.useCallback)(h=>{a.current?.keyUp(h),R()},[R]),U=(0,G.useCallback)((h,C)=>{a.current?.movePointer(h,C)},[]);return{engage:m,engageTouch:S,release:p,engaged:u,heldKeys:g,pressKey:b,releaseKey:y,movePointer:U}}var ue=require("react"),un=require("@urun-sh/core");var O=require("react"),an=require("@urun-sh/core");var Ot=null;function Ro(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function vt(){if(Ot)return Ot;let e=Ro();return e?(Ot=new e,Ot):null}function je(){let e=vt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var yt=require("react"),tn=require("react/jsx-runtime"),fr=(0,yt.createContext)(null);function Qr({session:e,children:t}){return(0,tn.jsx)(fr.Provider,{value:e,children:t})}function Te(){return(0,yt.useContext)(fr)}function en(){let e=(0,yt.useContext)(fr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var kt=require("react/jsx-runtime");function Co(e,t){return e-t>>>0<2147483648}var rn=1e3;function nn(...e){console.debug("[video]",...e)}function on(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function sn(e,t,r){return r?[r,t]:[e,t]}var Ke=(0,O.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:g,style:l,videoClassName:v,placeholder:R,poster:k,children:m,onTrack:S,onFirstFrame:p,frameMarker:b,onFrameMarkerReached:y,onFrameMarkerUnsupported:U,onUnlockChange:h}=t,C=Te(),T=o??C,w=(0,O.useRef)(null),I=(0,O.useRef)(null),[d,E]=(0,O.useState)(!1),[P,L]=(0,O.useState)(!1),q=(0,O.useRef)(!1),W=(0,O.useRef)(null),V=(0,O.useRef)(S);V.current=S;let A=(0,O.useRef)(h);A.current=h;let H=(0,O.useRef)(p);H.current=p;let J=(0,O.useRef)(y);J.current=y;let Z=(0,O.useRef)(U);Z.current=U;let j=(0,O.useRef)(b??null);j.current=b??null;let re=(0,O.useCallback)(f=>{W.current!==f&&(W.current=f,A.current?.(f))},[]),ce=(0,O.useRef)(null),Q=(0,O.useRef)(null),B=(0,O.useCallback)((f,_=!1)=>{if(!_&&f===ce.current||(ce.current=f,Q.current?.(),Q.current=null,q.current=!1,L(!1),!f))return;let x=w.current;if(!x)return;let K=j.current,ge=K?.rtpTimestamp??null,we=!1,N=()=>{we||(we=!0,Z.current?.())};K&&ge==null&&N();let Ue=K!=null&&ge!=null,Ge=Me=>{Q.current?.(),Q.current=null,q.current=!0,L(!0),H.current?.(),Me&&J.current?.()};if(typeof x.requestVideoFrameCallback=="function"){let Me=!1,D=0,F=(Se,he)=>{if(!Me){if(Ue){let Pe=he?.rtpTimestamp;if(typeof Pe!="number"){N(),Ge(!1);return}if(!Co(Pe,ge)){D=x.requestVideoFrameCallback(F);return}Ge(!0);return}Ge(!1)}};D=x.requestVideoFrameCallback(F),Q.current=()=>{Me=!0,x.cancelVideoFrameCallback?.(D)};return}Ue&&N();let Ae=()=>{let Me=x.getVideoPlaybackQuality?.();(Me?Me.totalVideoFrames>0:x.readyState>=2&&x.videoWidth>0)&&Ge(!1)};x.addEventListener("loadeddata",Ae),x.addEventListener("timeupdate",Ae),x.addEventListener("playing",Ae),Q.current=()=>{x.removeEventListener("loadeddata",Ae),x.removeEventListener("timeupdate",Ae),x.removeEventListener("playing",Ae)},Ae()},[]);(0,O.useEffect)(()=>()=>{Q.current?.(),Q.current=null},[]);let z=b==null?null:`${b.rtpTimestamp??""}|${b.ptsMs??""}`,be=(0,O.useRef)(z);(0,O.useEffect)(()=>{if(be.current===z||(be.current=z,z==null))return;let f=ce.current;f&&B(f,!0)},[z,B]);let se=(0,O.useCallback)(()=>{if(typeof MediaStream>"u")return null;I.current||(I.current=new MediaStream);let f=w.current;return f&&f.srcObject!==I.current&&(f.srcObject=I.current),I.current},[]),le=(0,O.useCallback)(f=>{let _=w.current;if(!_)return;let x=_.play();!x||typeof x.then!="function"||x.then(()=>{_.muted||re(!0)}).catch(K=>{if((K instanceof Error?K.name:String(K))==="NotAllowedError"&&!_.muted){nn(`play() blocked pending a user gesture (${f})`),re(!1);return}nn(`play() failed (${f})`,K)})},[re]),De=(0,O.useCallback)(()=>{let f=w.current;f&&(se(),!f.muted&&(le("gesture"),je(),re(!0)))},[se,le,re]),de=(0,O.useCallback)(f=>{let _=se();if(_){for(let x of _.getVideoTracks())x!==f&&_.removeTrack(x);if(f&&!_.getVideoTracks().includes(f)){_.addTrack(f);let x=w.current;x&&(x.srcObject=_)}f&&le("track-attach"),E(f!==null),B(f),V.current?.(f)}},[se,le,B]),xe=(0,O.useCallback)(f=>{let _=se();if(_){for(let x of _.getAudioTracks())x!==f&&_.removeTrack(x);f&&!_.getAudioTracks().includes(f)&&_.addTrack(f),f&&le("audio-attach")}},[se,le]),pe=(0,O.useCallback)(f=>{w.current=f,f&&(a?(f.muted=!0,f.defaultMuted=!0,f.setAttribute("muted",""),W.current=null):(f.muted=!1,f.defaultMuted=!1,f.removeAttribute("muted")),f.setAttribute("playsinline",""),f.setAttribute("webkit-playsinline",""),se())},[se,a]);(0,O.useImperativeHandle)(r,()=>({get element(){return w.current},get live(){return I.current?I.current.getVideoTracks().length>0:!1},get framed(){return q.current},unlock:De,get unlocked(){return W.current===!0}}),[De]);let ae=(0,an.derivedLegRole)(n)!==void 0;(0,O.useEffect)(()=>{ae&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[ae,n]);let ne=i!==void 0;return(0,O.useEffect)(()=>{if(ne){de(i??null);return}if(ae){de(null);return}if(!T)return;let f=on(T,sn(n,"video")),_=()=>{let N=I.current;return N?N.getVideoTracks()[0]??null:null},x=N=>{if(N!==_()&&(de(N),N)){let Ue=()=>{_()===N&&de(null)};N.addEventListener("ended",Ue)}},K=f.track;K&&K.readyState==="live"&&x(K);let ge=f.on("track",N=>{N&&N.readyState!=="live"||x(N)}),we=setInterval(()=>{let N=f.track;N&&N.readyState==="live"&&x(N)},rn);return()=>{ge(),clearInterval(we)}},[T,n,ae,ne,i,de]),(0,O.useEffect)(()=>{if(ne||!T||s===!1||ae)return;let f=on(T,sn(n,"audio",s)),_=()=>{let N=I.current;return N?N.getAudioTracks()[0]??null:null},x=N=>{if(N!==_()&&(xe(N),N)){let Ue=()=>{_()===N&&xe(null)};N.addEventListener("ended",Ue)}},K=f.track;K&&K.readyState==="live"&&x(K);let ge=f.on("track",N=>{N&&N.readyState!=="live"||x(N)}),we=setInterval(()=>{let N=f.track;N&&N.readyState==="live"&&x(N)},rn);return()=>{ge(),clearInterval(we)}},[T,n,ae,s,ne,xe]),(0,kt.jsxs)("div",{className:g,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":d?"true":"false","data-urun-video-framed":P?"true":"false",children:[(0,kt.jsx)("video",{ref:pe,className:v,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),d?null:R,k===void 0?null:(0,kt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":P||void 0,style:{position:"absolute",inset:0,...P?{opacity:0,pointerEvents:"none"}:null},children:k}),m]})});var bt=require("react/jsx-runtime"),Eo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},cn=(0,ue.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...g}=o??{},l=c!==void 0?c:typeof document<"u"?document:null,v=(0,ue.useRef)(null),R=(0,ue.useRef)(null),k=(0,ue.useRef)(0),m=(0,ue.useRef)(g);m.current=g;let S=(0,ue.useMemo)(()=>(0,un.createCameraWarp)(m.current),[]);return(0,ue.useImperativeHandle)(r,()=>({get video(){return v.current},get canvas(){return R.current},warp:S,get lastDrawTs(){return k.current}}),[S]),(0,ue.useEffect)(()=>{if(!i)return;let p=0,b=0,y=null,U=C=>{typeof C.requestVideoFrameCallback=="function"&&(y=C,b=C.requestVideoFrameCallback(function T(){S.frameArrived(),b=C.requestVideoFrameCallback(T)}))},h=C=>{p=requestAnimationFrame(h);let T=R.current,w=v.current?.element??null;if(!T||!w||(w!==y&&(y&&b&&y.cancelVideoFrameCallback?.(b),U(w)),w.readyState<2))return;S.tick(C);let I=typeof devicePixelRatio=="number"?devicePixelRatio:1,d=Math.max(1,Math.round(T.clientWidth*I)),E=Math.max(1,Math.round(T.clientHeight*I));(T.width!==d||T.height!==E)&&(T.width=d,T.height=E);let P=T.getContext("2d");if(!P)return;let L=S.transform(),q=w.videoWidth||d,W=w.videoHeight||E,A=Math.max(d/q,E/W)*(1+a)*L.scale;P.setTransform(A,0,0,A,d/2+L.translateX*d,E/2+L.translateY*E),P.drawImage(w,-q/2,-W/2),k.current=C};return p=requestAnimationFrame(h),()=>{cancelAnimationFrame(p),y&&b&&y.cancelVideoFrameCallback?.(b)}},[i,a,S]),(0,ue.useEffect)(()=>{if(!i||!u||!l)return;let p=()=>!!l.pointerLockElement,b=T=>{p()&&S.keyDown(T.key)},y=T=>S.keyUp(T.key),U=T=>{p()&&S.pointerDelta(T.movementX,T.movementY)},h=()=>{p()||S.clearKeys()},C=()=>S.clearKeys();return l.addEventListener("keydown",b),l.addEventListener("keyup",y),l.addEventListener("mousemove",U),l.addEventListener("pointerlockchange",h),l.defaultView?.addEventListener("blur",C),()=>{l.removeEventListener("keydown",b),l.removeEventListener("keyup",y),l.removeEventListener("mousemove",U),l.removeEventListener("pointerlockchange",h),l.defaultView?.removeEventListener("blur",C)}},[i,u,l,S]),i?(0,bt.jsxs)(Ke,{ref:v,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,bt.jsx)("canvas",{ref:R,style:Eo,"data-urun-warp":""}),n]}):(0,bt.jsx)(Ke,{ref:v,...s,children:n})});var ln=new Map;function dn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);ln.set(e,{component:t,schema:r})}function pn(e,t){let r=ln.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var $e=require("react/jsx-runtime");function mn({name:e,props:t,fallback:r}){let o=pn(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,$e.jsx)($e.Fragment,{children:r}):(0,$e.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,$e.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,$e.jsx)(n,{...o.validatedProps})}var nt=require("zod"),Xe=require("react/jsx-runtime"),fn=nt.z.object({step:nt.z.number().min(0),total:nt.z.number().min(1),label:nt.z.string().optional(),variant:nt.z.enum(["default","success","error"]).default("default")});function gr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function gn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=gr(e);return(0,Xe.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,Xe.jsx)("div",{className:"urun-progress-label",children:o}),(0,Xe.jsx)("div",{className:"urun-progress-bar",children:(0,Xe.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,Xe.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Vt=require("zod"),Pt=require("react/jsx-runtime"),Sn=Vt.z.object({state:Vt.z.enum(["thinking","generating","idle","error"]),message:Vt.z.string().optional()}),To={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Sr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??To[t]??t;return{state:t,message:n,isActive:o}}function hn(e){let{state:t,message:r,isActive:o}=Sr(e);return(0,Pt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,Pt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,Pt.jsx)("span",{className:"urun-status-message",children:r})]})}var Rt=require("react"),Dt=require("zod"),Ct=require("react/jsx-runtime"),vn=Dt.z.object({text:Dt.z.string(),streaming:Dt.z.boolean().default(!1)});function hr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function yn(e){let{text:t,streaming:r}=hr(e),o=(0,Rt.useRef)(null),n=(0,Rt.useRef)(0);return(0,Rt.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Ct.jsxs)("div",{className:"urun-text-stream",children:[(0,Ct.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Ct.jsx)("span",{className:"urun-text-cursor"})]})}var Et=require("zod"),Tt=require("react/jsx-runtime"),kn=Et.z.object({src:Et.z.string().url(),alt:Et.z.string().optional(),caption:Et.z.string().optional()});function vr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function bn(e){let{src:t,alt:r,caption:o}=vr(e);return(0,Tt.jsxs)("figure",{className:"urun-image-frame",children:[(0,Tt.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,Tt.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Ie=require("zod"),ot=require("react/jsx-runtime"),Pn=Ie.z.object({metrics:Ie.z.array(Ie.z.object({label:Ie.z.string(),value:Ie.z.union([Ie.z.string(),Ie.z.number()]),unit:Ie.z.string().optional()}))});function yr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Rn(e){let{metrics:t}=yr(e);return(0,ot.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,ot.jsxs)("div",{className:"urun-metric-card",children:[(0,ot.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,ot.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var Cn=require("react");var Tn=require("react/jsx-runtime"),En=(0,Cn.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Tn.jsx)(Ke,{ref:r,stream:o,...n})});var X=require("react"),wn=require("@urun-sh/core");var An=require("react/jsx-runtime"),xo=1e3,xn=200;function kr(...e){console.debug("[audio]",...e)}var xt=(0,X.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,l=Te(),v=o??l,R=(0,X.useRef)(null),k=(0,X.useRef)(null),m=(0,X.useRef)(null),S=(0,X.useRef)(null),p=(0,X.useRef)(u);p.current=u;let b=(0,X.useRef)(c);b.current=c;let y=(0,X.useCallback)(d=>{m.current!==d&&(m.current=d,b.current?.(d))},[]),U=(0,X.useCallback)(()=>{if(typeof MediaStream>"u")return null;k.current||(k.current=new MediaStream);let d=R.current;return d&&d.srcObject!==k.current&&(d.srcObject=k.current),k.current},[]),h=(0,X.useCallback)(d=>{let E=R.current;if(!E)return;let P=E.play();!P||typeof P.then!="function"||P.then(()=>{E.muted||y(!0)}).catch(L=>{let q=L instanceof Error?L.name:String(L);if(q==="AbortError"){kr(`play() aborted (${d}); retrying in ${xn}ms`),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{S.current=null,h(`${d}:retry`)},xn);return}if(q==="NotAllowedError"){kr(`play() blocked pending a user gesture (${d})`),y(!1);return}kr(`play() failed (${d})`,L)})},[y]),C=(0,X.useCallback)(d=>{let E=U();if(E){for(let P of E.getAudioTracks())P!==d&&E.removeTrack(P);d&&!E.getAudioTracks().includes(d)&&E.addTrack(d),d&&h("track-attach"),p.current?.(d)}},[U,h]),T=(0,X.useCallback)(()=>{let d=R.current;d&&(U(),d.muted=!1,h("gesture"),je(),y(!0))},[U,h,y]);(0,X.useImperativeHandle)(r,()=>({unlock:T,get unlocked(){return m.current===!0},get element(){return R.current}}),[T]);let w=(0,X.useCallback)(d=>{R.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),U()),g?.(d)},[U,g]),I=s!==void 0;return(0,X.useEffect)(()=>{if(I){C(s??null);return}if(!v)return;let d=v.stream(n),E=()=>{let V=k.current;return V?V.getAudioTracks()[0]??null:null},P=V=>{if(V!==E()&&(C(V),V)){let A=()=>{E()===V&&C(null)};V.addEventListener("ended",A)}},L=d.track;L&&L.readyState==="live"&&P(L);let q=d.on("track",V=>{V&&V.readyState!=="live"||P(V)}),W=setInterval(()=>{let V=d.track;V&&V.readyState==="live"&&P(V)},xo);return()=>{q(),clearInterval(W)}},[v,n,I,s,C]),(0,X.useEffect)(()=>(0,wn.observePageLifecycle)(()=>{je(),m.current===!0&&h("foreground")}),[h]),(0,X.useEffect)(()=>()=>{S.current&&clearTimeout(S.current)},[]),(0,An.jsx)("audio",{ref:w,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Un=xt;var $=require("react"),st=require("@urun-sh/core");var _n=require("react/jsx-runtime"),br={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Ft(...e){console.debug("[voice]",...e)}var wt=(0,$.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=br,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:l,onMicStream:v,onTrack:R,onUnlockChange:k,capture:m}=t,S=Te(),p=o??S,b=(0,$.useRef)(null),y=(0,$.useRef)(null),U=(0,$.useRef)(null),h=(0,$.useRef)([]),C=(0,$.useRef)(!1),T=(0,$.useRef)(g);T.current=g;let w=(0,$.useRef)(l);w.current=l;let I=(0,$.useRef)(v);I.current=v;let d=(0,$.useCallback)(A=>{C.current!==A&&(C.current=A,T.current?.(A))},[]),E=(0,$.useCallback)(()=>{for(let A of h.current)A();h.current=[],U.current?.release(),U.current=null,y.current&&(y.current=null,I.current?.(null))},[]),P=(0,$.useCallback)(async()=>{let A=U.current;if(A){let j=await A.update(i);return y.current=A.stream,I.current?.(A.stream),j}let J=await(m??(0,st.sharedCaptureController)()).claim("audio",i);U.current=J,h.current=[J.onTrack((j,re)=>{y.current=re,I.current?.(re),C.current&&p?.stream(n).attach(j).catch(ce=>Ft("mic re-attach after one-capture re-acquire failed",ce))}),J.onLost(j=>{U.current=null,h.current=[],y.current=null,I.current?.(null),d(!1),w.current?.(j)})],y.current=J.stream,I.current?.(J.stream);let Z=J.track;if(!Z)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return Z},[m,i,p,n,d]),L=(0,$.useCallback)(async()=>{E(),d(!1),await p?.stream(n).detach().catch(()=>{})},[p,n,E,d]),q=(0,$.useCallback)(async()=>{if(!p)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");b.current?.unlock();let A;try{A=await P()}catch(Z){E();let j=(0,st.sessionFailureFromMediaError)(Z,p.status);throw w.current?.(j),j}p.connect?.();let H;for(let Z=1;Z<=u;Z++)try{await p.whenLive(a!==void 0?{timeout:a}:void 0),await p.stream(n).attach(A),d(!0);return}catch(j){H=j,Ft(`start attempt ${Z}/${u} failed`,j),Z<u&&await new Promise(re=>setTimeout(re,c))}E(),d(!1);let J=H instanceof Error?H:new Error(String(H??"voice start failed"));throw w.current?.(J),J},[p,n,a,u,c,P,E,d]);(0,$.useImperativeHandle)(r,()=>({start:q,stop:L,unlock:()=>b.current?.unlock(),get active(){return C.current},get micStream(){return y.current},get audio(){return b.current}}),[q,L]);let W=(0,$.useRef)(!1),V=(0,$.useCallback)(async()=>{if(!p||!C.current||W.current)return;let A=y.current?.getAudioTracks()[0]??null;if(A&&A.readyState==="live"){try{await p.stream(n).attach(A)}catch(H){Ft("foreground mic re-assert failed (will retry on next pass)",H)}return}W.current=!0;try{let H=await P();await p.stream(n).attach(H)}catch(H){let J=H instanceof Error?H:new Error(String(H));Ft("foreground mic re-acquire failed",J),w.current?.(J)}finally{W.current=!1}},[p,n,P]);return(0,$.useEffect)(()=>{let A=()=>{V()};return p&&typeof p.onRecovery=="function"?p.onRecovery(A):(0,st.observePageLifecycle)(A)},[p,V]),(0,$.useEffect)(()=>E,[E]),s?(0,_n.jsx)(xt,{ref:b,session:p,stream:n,onTrack:R,onUnlockChange:k}):null}),Mn=wt;var Ce=require("react");var qt=require("react");var Pr={level:0,speaking:!1};function Ht(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,qt.useState)(Pr);return(0,qt.useEffect)(()=>{if(!e){i(Pr);return}let a=vt();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let l=new Uint8Array(g.fftSize),R=setInterval(()=>{g.getByteTimeDomainData(l);let k=0;for(let S=0;S<l.length;S++){let p=(l[S]-128)/128;k+=p*p}let m=Math.sqrt(k/l.length);i(S=>{let p=m>n;return Math.abs(S.level-m)<.005&&S.speaking===p?S:{level:m,speaking:p}})},o);return()=>{clearInterval(R),c.disconnect(),i(Pr)}},[e,r,o,n]),s}var Le=require("react/jsx-runtime"),wo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Uo={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Nn=(0,Ce.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:l,capture:v}=t,R=Te(),k=o??R,m=(0,Ce.useRef)(null),[S,p]=(0,Ce.useState)(null),b=(0,Ce.useRef)(l);b.current=l;let{level:y,speaking:U}=Ht(a?S:null);return(0,Ce.useImperativeHandle)(r,()=>({start:()=>{let h=m.current;return h?h.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>m.current?.stop()??Promise.resolve(),get active(){return m.current?.active??!1},get micStream(){return m.current?.micStream??null}}),[]),(0,Ce.useEffect)(()=>{!i||!k||m.current?.start().catch(()=>{})},[i,k]),(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)(wt,{ref:m,session:k,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...v!==void 0?{capture:v}:{},onActiveChange:c,onError:g,onMicStream:h=>{p(h),b.current?.(h)}}),a?(0,Le.jsx)("span",{className:u,style:wo,"data-urun-mic":"","data-urun-mic-active":S?"true":"false","data-urun-mic-speaking":U?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(y*100)/100,children:(0,Le.jsx)("span",{style:Uo,children:(0,Le.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(y*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var it=require("@urun-sh/core"),M=require("react");var ve=require("react/jsx-runtime"),Cr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Rr(...e){console.debug("[camera]",...e)}function Ao(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Mo(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var Er=(0,M.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:l,visible:v=!1,className:R,videoClassName:k,onActiveChange:m,onError:S,onStream:p,onTrack:b,children:y,capture:U,flipControl:h="auto",flipControlClassName:C,onDevices:T}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let w=i?"user":a?"environment":u??"environment",I=Te(),d=o??I,E=(0,M.useRef)(null),P=(0,M.useRef)(null),L=(0,M.useRef)(null),q=(0,M.useRef)([]),W=(0,M.useRef)(null),V=(0,M.useRef)(!1),A=(0,M.useRef)(!1),H=(0,M.useRef)(w),[J,Z]=(0,M.useState)(w),[j,re]=(0,M.useState)(!1),[ce,Q]=(0,M.useState)(null),[B,z]=(0,M.useState)(!1),[be]=(0,M.useState)(Ao),se=(0,M.useRef)(m);se.current=m;let le=(0,M.useRef)(S);le.current=S;let De=(0,M.useRef)(p);De.current=p;let de=(0,M.useRef)(b);de.current=b;let xe=(0,M.useRef)(T);xe.current=T;let pe=(0,M.useCallback)(D=>{V.current!==D&&(V.current=D,re(D),se.current?.(D))},[]);(0,M.useEffect)(()=>{if(!j){Q(null);return}let D=!1,F=()=>{Mo().then(he=>{D||(Q(he),he&&xe.current?.(he))})};F();let Se=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof Se?.addEventListener=="function"?(Se.addEventListener("devicechange",F),()=>{D=!0,Se.removeEventListener?.("devicechange",F)}):()=>{D=!0}},[j]);let ae=(0,M.useCallback)(D=>{let F=E.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=D,D&&F.play()?.catch?.(Se=>Rr("preview play() failed",Se)))},[]),ne=(0,M.useCallback)(()=>{A.current=!1,W.current?.(),W.current=null;for(let D of q.current)D();q.current=[],L.current?.release(),L.current=null,P.current&&(P.current=null,De.current?.(null),de.current?.(null)),ae(null)},[ae]),f=(0,M.useCallback)((D,F)=>{W.current?.(),P.current=F,ae(F),De.current?.(F);let Se=()=>{P.current===F&&(Rr("camera track ended (device removed or permission revoked)"),ne(),pe(!1))};D.addEventListener("ended",Se),W.current=()=>D.removeEventListener("ended",Se)},[ae,ne,pe]),_=(0,M.useCallback)(async D=>{let F=n!==!1;if(F&&!d)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let Se={...Cr,...s,facingMode:D},he;try{let Pe=L.current;if(Pe)he=await Pe.update(Se);else{let mt=await(U??(0,it.sharedCaptureController)()).claim("video",Se);if(L.current=mt,q.current=[mt.onTrack((ft,no)=>{f(ft,no),V.current&&(!F||!d||d.stream(n).attachVideo(ft).then(()=>de.current?.(ft)).catch(oo=>Rr("camera re-publish after one-capture re-acquire failed",oo)))}),mt.onLost(ft=>{L.current=null,q.current=[],ne(),pe(!1),le.current?.(ft)})],!mt.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});he=mt.track}}catch(Pe){let Ye=(0,it.sessionFailureFromMediaError)(Pe,d?.status);throw le.current?.(Ye),Ye}H.current=D,Z(D),f(he,L.current?.stream??new MediaStream([he]));try{F&&d&&(d.connect?.(),await d.whenLive(l!==void 0?{timeout:l}:void 0),await d.stream(n).attachVideo(he)),A.current=F?n:!1}catch(Pe){ne(),pe(!1);let Ye=Pe instanceof Error?Pe:new Error(String(Pe));throw le.current?.(Ye),Ye}de.current?.(he),pe(!0)},[d,n,s,l,U,f,ne,pe]),x=(0,M.useCallback)(D=>_(D?.facingMode??H.current),[_]),K=(0,M.useCallback)(async D=>{let F=A.current===n;V.current&&H.current===D&&F||await _(D)},[_,n]),ge=(0,M.useCallback)(()=>_(H.current==="environment"?"user":"environment"),[_]),we=(0,M.useCallback)(async()=>{ne(),pe(!1),n!==!1&&await d?.stream(n).detachVideo().catch(()=>{})},[d,n,ne,pe]),N=(0,M.useCallback)(async D=>{let F=E.current;if(!F)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,it.captureStillFromVideo)(F,D)},[]);(0,M.useImperativeHandle)(r,()=>({start:x,stop:we,flip:ge,setFacingMode:K,capturePhoto:N,get active(){return V.current},get facingMode(){return H.current},get stream(){return P.current},get element(){return E.current}}),[x,we,ge,K,N]);let Ue=(0,M.useRef)(K);if(Ue.current=K,(0,M.useEffect)(()=>{c&&(n!==!1&&!d||Ue.current(w).catch(()=>{}))},[c,d,w,n]),(0,M.useEffect)(()=>ne,[ne]),!v)return null;let Ge=g==="auto"?J==="user":g,Ae=j&&(h===!0||h==="auto"&&be&&(ce?.length??0)>1),Me=()=>{B||(z(!0),ge().catch(()=>{}).finally(()=>z(!1)))};return(0,ve.jsxs)("div",{className:R,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":J,children:[(0,ve.jsx)("video",{ref:E,className:k,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ge?{transform:"scaleX(-1)"}:{}}}),Ae?(0,ve.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:Me,disabled:B,className:C,style:C?{opacity:B?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:B?.6:1},children:(0,ve.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,ve.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ve.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ve.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ve.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ve.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,y]})}),In=(0,M.forwardRef)(function({preview:t=!0,...r},o){return(0,ve.jsx)(Er,{ref:o,...r,visible:t,autoStart:!1})});var at=require("@urun-sh/core"),ee=require("react");function Ln(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,ee.useState)(null),[a,u]=(0,ee.useState)(null),[c,g]=(0,ee.useState)(!1),[l,v]=(0,ee.useState)(null),[R]=(0,ee.useState)(at.cameraCaptureAvailable),k=(0,ee.useRef)(n);k.current=n;let m=(0,ee.useRef)(null),S=(0,ee.useRef)(0),p=(0,ee.useCallback)(C=>{m.current&&URL.revokeObjectURL(m.current),m.current=C?URL.createObjectURL(new Blob([C.bytes],{type:C.type})):null,u(m.current),i(C),k.current?.(C)},[]);(0,ee.useEffect)(()=>()=>{S.current++,m.current&&URL.revokeObjectURL(m.current),m.current=null},[]);let b=(0,ee.useCallback)(async C=>{let T=++S.current;g(!0),v(null);try{let w=await C();if(S.current!==T)return;p(w)}catch(w){if(S.current!==T)return;v((0,at.referenceImageErrorMessage)(w))}finally{S.current===T&&g(!1)}},[p]),y=(0,ee.useCallback)(C=>b(()=>(0,at.normalizeReferenceImage)(C,{maxSize:t,type:r,quality:o,source:"file"})),[b,t,r,o]),U=(0,ee.useCallback)(C=>b(()=>C.capturePhoto({maxSize:t,type:r,quality:o})),[b,t,r,o]),h=(0,ee.useCallback)(()=>{S.current++,v(null),g(!1),p(null)},[p]);return{reference:s,previewUrl:a,pick:y,capture:U,clear:h,busy:c,error:l,cameraAvailable:R}}var Wt=require("react");function On(e,t){let[r,o]=(0,Wt.useState)(null);return(0,Wt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var Fn=require("react");var jt=require("react");var Vn=require("zustand/vanilla"),Dn=require("zustand"),_o=()=>{};function Bt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,Vn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):_o,u=(c=>(0,Dn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function ut(e,t){let r=(0,jt.useMemo)(()=>Bt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,jt.useEffect)(()=>r.bind(),[r]),r}function qn(e,t,r){let n=ut(e,t)(r??(a=>a)),s=(0,Fn.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var $t=require("react");var Fe=200;function Oe(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function ct(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Kt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Xt(e,t,r={}){let o=r.cap??200,[n,s]=(0,$t.useState)([]);return(0,$t.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>Oe(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var Ee=require("react/jsx-runtime");function Hn({session:e,name:t,cap:r,className:o}){let n=Xt(e,t,{cap:r});return(0,Ee.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,Ee.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,Ee.jsx)("code",{children:t}),(0,Ee.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,Ee.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,Ee.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,Ee.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,Ee.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,Ee.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",ct(s.payload)]},`${s.at}-${i}`))})]})}var Ut=require("react");var fe=require("react/jsx-runtime");function At({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,Ut.useState)(""),[i,a]=(0,Ut.useState)(null),u=(0,Ut.useCallback)(()=>{let c=Kt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,fe.jsxs)("div",{className:"urun-doc-patch",children:[(0,fe.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,fe.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,fe.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,fe.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Wn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=ut(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,fe.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,fe.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,fe.jsx)("code",{children:t}),(0,fe.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,fe.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,fe.jsx)(At,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var Jt=require("react");var Ve=require("react/jsx-runtime");function Bn(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function jn({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,Jt.useState)([]);return(0,Jt.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>Oe(u,{at:Date.now(),direction:"in",text:Bn(ct(a))},r))}):void 0),[e,t,r]),(0,Ve.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,Ve.jsx)(At,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>Oe(u,{at:Date.now(),direction:"out",text:Bn(a)},r))}}),(0,Ve.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,Ve.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,Ve.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Ve.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Ve.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var zt=require("react");var Je=require("react/jsx-runtime");function Kn({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,zt.useState)([]),a=t.join(","),u=r.join(",");return(0,zt.useEffect)(()=>{if(i([]),!e)return;let c=(l,v)=>i(R=>Oe(R,{at:Date.now(),kind:l,text:v},o)),g=[];g.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of t){let v=e.stream(l);g.push(v.on("track",R=>c("track",`${l}: ${R?"track arrived":"track ended"}`)))}for(let l of r){let v=e.doc(l);g.push(v.on("change",()=>c("doc",`${l} changed`)))}return()=>g.forEach(l=>l())},[e,a,u,o]),(0,Je.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Je.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,g)=>(0,Je.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Je.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Je.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}var rr=require("@urun-sh/core");var Gt=require("react");function ye(e){let[t,r]=(0,Gt.useState)(e?.phase??null);return(0,Gt.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var Xn=require("@urun-sh/core");var lt=require("react"),$n=require("@urun-sh/core");function Yt(e){let t=ye(e),r=(0,$n.isWakingPhase)(t?.name),o=(0,lt.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,lt.useState)(s);return(0,lt.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var qe=require("react/jsx-runtime");function Zt({session:e,render:t,className:r}){let o=Yt(e);return!o.waking||!o.phase?null:(0,qe.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,qe.jsxs)(qe.Fragment,{children:[(0,qe.jsx)("span",{className:"urun-session-waking-label",children:(0,Xn.describeSessionPhase)(o.phase)})," ",(0,qe.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var er=require("react");var He=require("react"),No={event:null,elapsedMs:0};function Qt(e,t){let[r,o]=(0,He.useState)(null),n=(0,He.useRef)(0);(0,He.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,He.useState)(0);return(0,He.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:No}var dt=require("react/jsx-runtime"),Io={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 Lo(e){let[t,r]=(0,er.useState)(!1);return(0,er.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function tr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=Qt(e,t),i=Lo(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,dt.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,dt.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,dt.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??Io[u]})," ",(0,dt.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var ke=require("react/jsx-runtime"),Oo={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Jn({session:e,className:t}){let r=ye(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,ke.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,ke.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,ke.jsx)("span",{className:"urun-session-status-label",children:Oo[o]}),n?(0,ke.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function zn({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ye(e);if(s?.name==="live")return(0,ke.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,ke.jsx)(tr,{session:e})]});let i=r?r(s):(0,ke.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,rr.isWakingPhase)(s.name)?(0,ke.jsx)(Zt,{session:e}):s&&s.name!=="idle"?(0,rr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,ke.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,ke.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var nr=require("react");var Yn=require("react/jsx-runtime");function Tr(e){return ye(e)?.endsAt??null}function Vo(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Gn({session:e,urgentMs:t=6e4,className:r}){let n=Tr(e)?.getTime()??null,[s,i]=(0,nr.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,nr.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Vo(s);return(0,Yn.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var Mt=require("react/jsx-runtime"),Do=new Set(["expired","ended","error"]);function Zn({session:e,onNewSession:t,children:r,className:o}){let n=ye(e);if(!n||!Do.has(n.name))return null;let s=r?r(n):(0,Mt.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,Mt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,Mt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var We=require("react"),ze=require("react/jsx-runtime");function xr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function wr(e){let t=(0,We.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,We.useState)(()=>t?xr(t.get("idle")):null);return(0,We.useEffect)(()=>{if(!t){o(null);return}return o(xr(t.get("idle"))),t.on("change",()=>o(xr(t.get("idle"))))},[t]),r}function Fo(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Qn({session:e,onStillHere:t,className:r}){let o=wr(e),n=o?.deadlineEpochS??null,[s,i]=(0,We.useState)(null);if((0,We.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,ze.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,ze.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,ze.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,ze.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Fo(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,ze.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var pt=require("react"),eo=require("@urun-sh/core");function to(e){let t=(0,pt.useContext)(Qe),[r,o]=(0,pt.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,l=t?.authProvider;return(0,pt.useEffect)(()=>{if(!a||!u||!n||!s)return;let v=!1,R=()=>{(0,eo.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:l}).then(m=>{v||o(m)}).catch(()=>{})};R();let k=setInterval(R,Math.max(1,i)*1e3);return()=>{v=!0,clearInterval(k)}},[n,s,i,a,u,c,g,l]),r}var or=require("react");function ro(e){let[t,r]=(0,or.useState)(null);return(0,or.useEffect)(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}var sr=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,ReprojectedVideo,Session,StatusBadge,StatusBadgeSchema,TextStream,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useReferenceImage,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionStats,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
|
2
|
+
"use strict";var cr=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var vo=Object.getOwnPropertyNames;var yo=Object.prototype.hasOwnProperty;var ko=(e,t)=>{for(var r in t)cr(e,r,{get:t[r],enumerable:!0})},bo=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vo(t))!yo.call(e,n)&&n!==r&&cr(e,n,{get:()=>t[n],enumerable:!(o=ho(t,n))||o.enumerable});return e};var To=e=>bo(cr({},"__esModule",{value:!0}),e);var rs={};ko(rs,{Audio:()=>At,Camera:()=>_r,ComponentRenderer:()=>kn,DEFAULT_CAMERA_CONSTRAINTS:()=>Mr,DEFAULT_LOG_CAP:()=>qe,DEFAULT_SMOOTH_CHARS_PER_FRAME:()=>Pr,DEFAULT_SMOOTH_THRESHOLD:()=>xr,DEFAULT_VOICE_CONSTRAINTS:()=>wr,DocPatchForm:()=>Nt,Image:()=>In,ImageFrame:()=>wn,ImageFrameSchema:()=>Cn,MetricsPanel:()=>An,MetricsPanelSchema:()=>Un,Mic:()=>jn,OPERATOR_CHORD_LABEL:()=>Kr,OPERATOR_TOKEN_STORAGE_KEY:()=>Br,ProgressCard:()=>Tn,ProgressCardSchema:()=>bn,ReprojectedVideo:()=>Sn,Session:()=>an,StatusBadge:()=>Pn,StatusBadgeSchema:()=>Rn,Text:()=>Nn,TextStream:()=>En,TextStreamError:()=>at,TextStreamSchema:()=>xn,UrunActivationOverlay:()=>or,UrunAudio:()=>Hn,UrunAuthProvider:()=>kt,UrunCamera:()=>Kn,UrunControlSender:()=>to,UrunDocPanel:()=>Qn,UrunErrorBoundary:()=>et,UrunEventSpine:()=>ro,UrunIdleWarning:()=>lo,UrunJwtProvider:()=>Hr,UrunProvider:()=>Gr,UrunSessionClock:()=>ao,UrunSessionEnded:()=>co,UrunSessionGate:()=>io,UrunSessionStatus:()=>so,UrunSessionWaking:()=>tr,UrunStreamTail:()=>Zn,UrunVoice:()=>Wn,Video:()=>Xe,Voice:()=>Mt,authMode:()=>yt,createDocStore:()=>$t,describeSessionPhase:()=>ur.describeSessionPhase,formatPayload:()=>pt,getUrunAudioContext:()=>bt,isWakingPhase:()=>ur.isWakingPhase,parseJsonObject:()=>Jt,pushCapped:()=>De,readOperatorToken:()=>lr,registerComponent:()=>vn,resumeUrunAudioContext:()=>$e,textDelta:()=>Rr,urunPublicEnv:()=>Pe,useActivation:()=>rr,useApp:()=>Zr,useChat:()=>on,useCompletion:()=>tn,useConfirmOnLeave:()=>Vt,useDocStore:()=>dt,useImageFrame:()=>br,useInputPresence:()=>sn,useMetricsPanel:()=>Tr,useOperatorOverride:()=>Dt,useProgressCard:()=>vr,useReferenceImage:()=>$n,useRequest:()=>Qr,useSession:()=>un,useSessionDoc:()=>Yn,useSessionEndsAt:()=>Nr,useSessionIdle:()=>Or,useSessionPhase:()=>ke,useSessionStats:()=>fo,useSessionTrack:()=>Xn,useSessionWake:()=>er,useStatusBadge:()=>yr,useStreamMessages:()=>Gt,useText:()=>Er,useTextMeter:()=>_n,useTextStream:()=>kr,useUrunAudioLevel:()=>jt,useUrunAuth:()=>Ot,useUrunPrewake:()=>mo,usesWorkOSAuth:()=>Vr});module.exports=To(rs);var ae=require("react");var Ir=require("react"),vt=require("react/jsx-runtime"),et=class extends Ir.Component{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||(0,vt.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,vt.jsx)("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),(0,vt.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};var Dr=require("react"),tt=(0,Dr.createContext)(null);function Ne(e){return e&&e.trim()?e.trim():void 0}function Pe(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return Ne(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return Ne(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return Ne(typeof process<"u"?process.env?.[e]:void 0)}}function yt(){let e=Pe("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||Pe("VERCEL_ENV")==="production"?"workos":Pe("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Vr(){return yt()==="workos"}var rt=require("react"),qr=require("react/jsx-runtime"),Fr=(0,rt.createContext)(null);function kt({getAccessToken:e,children:t}){let r=(0,rt.useMemo)(()=>({getAccessToken:e}),[e]);return(0,qr.jsx)(Fr.Provider,{value:r,children:t})}var Hr=kt;function Ot(){return(0,rt.useContext)(Fr)}var It=require("react"),Br="urun.operator_token",jr=null,Wr="op",Kr="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function $r(){return typeof window<"u"}function lr(){return jr}function Ro(){if(!$r())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(Wr);if(!r)return null;jr=r,t.delete(Wr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function Po(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Dt(e){let t=(0,It.useRef)(e);t.current=e,(0,It.useEffect)(()=>{if(!$r())return;Ro();let r=o=>{if(!Po(o))return;let n=lr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}var Xr=require("react");function Vt(e=!0){(0,Xr.useEffect)(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}var Le=require("react/jsx-runtime"),xo="/api/urun-token",Eo=1e4;function Co(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function Jr(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function zr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function dr(e){let t=e===void 0?void 0:JSON.stringify(e);return(0,ae.useMemo)(()=>e,[t])}function wo(e,t){return typeof e=="function"?e(t):e!==void 0?e:(0,Le.jsxs)("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[(0,Le.jsx)("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),(0,Le.jsx)("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Gr({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,audioPlayout:g,videoPlayout:l,sessionStats:y,confirmOnLeave:b=!1,fallback:T,errorFallback:f,children:v}){let d=n===void 0&&t===void 0;if(!d&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!d&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let E=r??o;if(d&&(typeof E!="string"||E.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Vt(b);let[S,k]=(0,ae.useState)(),[m,R]=(0,ae.useState)(null),P=(0,ae.useRef)(void 0),C=(0,ae.useRef)(null),[A,p]=(0,ae.useState)(null);Dt(h=>p({jwt:h}));let w=Ot(),x=Pe("NEXT_PUBLIC_SESSION_TOKEN")??Pe("NEXT_PUBLIC_URUN_JWT"),O=yt(),H=A!==null,W=O==="workos"&&!n&&!H&&!d,D=n??(O==="jwt"?x:void 0)??S?.token,M=H?A.jwt:D,q=s??Pe("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),z=W&&!M&&!w?.getAccessToken,Q=t??S?.orgId,j=e??S?.gatewayUrl,ne=d&&S===void 0,le=d&&S!==void 0&&!j?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,ee=z?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,B=m??le??ee,G=zr("NEXT_PUBLIC_URUN_TOKEN_URL",Pe("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??xo,Te=zr("NEXT_PUBLIC_URUN_EVENTS_URL",Pe("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,ie=(0,ae.useCallback)(async h=>{if(!h?.forceRefresh){let U=P.current;if(!U)return U;let K=Co(U);if(K===null||K-Date.now()>Eo)return U}return(await(C.current??(C.current=(async()=>{try{let U=await Jr(G);return P.current=U.token,k(U),U}finally{C.current=null}})()))).token},[G]),de=(0,ae.useCallback)(async()=>M,[M]),Fe=typeof M=="string"&&M.trim().length>0,pe=W?w?.getAccessToken:d&&!H?ie:Fe?de:void 0,we=dr(g),me=dr(l),ue=dr(y),oe=(0,ae.useMemo)(()=>({appId:E,baseUrl:j??"",orgId:Q??"",jwt:M,getAccessToken:W?w?.getAccessToken:d&&!H?ie:void 0,authProvider:q,eventsUrl:Te,sessionKey:a,releaseOnLeave:c,audioPlayout:we,videoPlayout:me,sessionStats:ue,priority:H?"preempt":void 0}),[E,w,j,q,M,Te,Q,a,c,we,me,ue,W,H,d,ie]);return(0,ae.useEffect)(()=>{if(!d)return;let h=new AbortController;return R(null),(async()=>{try{let N=await Jr(G,h.signal);P.current=N.token,k(N)}catch(N){if(h.signal.aborted)return;R(N instanceof Error?N:new Error(String(N)))}})(),()=>h.abort()},[d,G]),(0,Le.jsx)(et,{fallback:T,children:B?wo(f,B):ne?(0,Le.jsx)("div",{role:"status","aria-live":"polite",children:"Signing in..."}):(0,Le.jsx)(tt.Provider,{value:oe,children:pe?(0,Le.jsx)(kt,{getAccessToken:pe,children:v}):v})})}var fe=require("react"),Yr=require("@urun-sh/core");function Uo(e,t){return`${e}:${JSON.stringify(t??{})}`}function Ao(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var Ke=new Map;var pr=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},mr=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},fr=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new pr(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new mr(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Zr(){let e=(0,fe.useContext)(tt);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=(0,fe.useReducer)(i=>i+1,0),r=(0,fe.useRef)(new Map),o=(0,fe.useRef)(new Map),n=(0,fe.useRef)(null),s=(0,fe.useMemo)(()=>(0,Yr.App)(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return(0,fe.useEffect)(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Ke.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=Ke.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let l=Ke.get(u);!l||l.refCount!==0||(Ke.delete(u),l.handle.disconnect())},0)))}n.current=a}},[]),(0,fe.useMemo)(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=l=>{let y=Uo(u,l),b=r.current.get(y);if(b&&!b.disposed)return b;let T=Ao(e,u,l),f=Ke.get(T);return f?.handle.disposed&&(f.disposeTimer&&clearTimeout(f.disposeTimer),Ke.delete(T),o.current.get(T)===f&&o.current.delete(T),f=void 0),f?f.disposeTimer&&(clearTimeout(f.disposeTimer),f.disposeTimer=null):(f={handle:new fr(s[u](l),t,e.eventsUrl),refCount:0,disposeTimer:null},Ke.set(T,f)),o.current.get(T)!==f&&(o.current.set(T,f),f.handle.addNotifier(t),f.refCount+=1),r.current.set(y,f.handle),f.handle};return i.set(u,g),g}})},[e,s])}var re=require("react");function nt(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Mo(e){return e instanceof Error?e:new Error(String(e))}function Qr(e,t){let r=(0,re.useMemo)(()=>nt(e),[e]),[o,n]=(0,re.useState)(void 0),[s,i]=(0,re.useState)(null),[a,u]=(0,re.useState)(!1),c=(0,re.useRef)(t);c.current=t;let g=(0,re.useRef)(0),l=(0,re.useRef)(null),y=(0,re.useRef)(!0);(0,re.useEffect)(()=>(y.current=!0,()=>{y.current=!1,l.current?.abort()}),[]);let b=(0,re.useCallback)(async v=>{l.current?.abort();let d=new AbortController;l.current=d;let E=++g.current,S=()=>y.current&&g.current===E;S()&&(u(!0),i(null));try{let k=await r.request(v,{...c.current,signal:d.signal});return S()&&(n(k),u(!1),c.current?.onSuccess?.(k)),k}catch(k){let m=Mo(k);throw S()&&(i(m),u(!1),c.current?.onError?.(m)),m}},[r]),T=(0,re.useCallback)(v=>{b(v).catch(()=>{})},[b]),f=(0,re.useCallback)(()=>{g.current++,l.current?.abort(),l.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:T,mutateAsync:b,data:o,error:s,isPending:a,reset:f}}var se=require("react");function en(e){return e instanceof Error?e:new Error(String(e))}var _o=e=>typeof e=="string"?e:String(e);function tn(e,t){let r=(0,se.useMemo)(()=>nt(e),[e]),[o,n]=(0,se.useState)(""),[s,i]=(0,se.useState)(!1),[a,u]=(0,se.useState)(null),c=(0,se.useRef)(t);c.current=t;let g=(0,se.useRef)(0),l=(0,se.useRef)(null),y=(0,se.useRef)(!0);(0,se.useEffect)(()=>(y.current=!0,()=>{y.current=!1,l.current?.cancel(),l.current=null}),[]);let b=(0,se.useCallback)(()=>{g.current++,l.current?.cancel(),l.current=null,y.current&&i(!1)},[]),T=(0,se.useCallback)(async f=>{l.current?.cancel();let v=++g.current,d=()=>y.current&&g.current===v,E=c.current,S=E?.parseChunk??_o,k=E?.buildPayload??(x=>({prompt:x}));d()&&(n(""),u(null),i(!0));let{parseChunk:m,buildPayload:R,onFinish:P,onError:C,...A}=E??{},p="",w;try{w=r.requestStream(k(f),A),l.current=w}catch(x){let O=en(x);d()&&(u(O),i(!1),E?.onError?.(O));return}try{for await(let x of w){if(g.current!==v)break;p+=S(x),d()&&n(p)}d()&&(i(!1),E?.onFinish?.(p))}catch(x){let O=en(x);d()&&(u(O),i(!1),E?.onError?.(O))}finally{l.current===w&&(l.current=null)}},[r]);return{completion:o,complete:T,stop:b,isStreaming:s,error:a}}var Z=require("react");function rn(e){return e instanceof Error?e:new Error(String(e))}var No=e=>typeof e=="string"?e:String(e),nn=0;function gr(e){return nn+=1,`${e}-${nn}`}function on(e,t){let r=(0,Z.useMemo)(()=>nt(e),[e]),[o,n]=(0,Z.useState)(()=>(t?.initialMessages??[]).map(S=>({id:S.id??gr("msg"),role:S.role,content:S.content}))),[s,i]=(0,Z.useState)(""),[a,u]=(0,Z.useState)(!1),[c,g]=(0,Z.useState)(null),l=(0,Z.useRef)(t);l.current=t;let y=(0,Z.useRef)(o);y.current=o;let b=(0,Z.useRef)(s);b.current=s;let T=(0,Z.useRef)(0),f=(0,Z.useRef)(null),v=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(v.current=!0,()=>{v.current=!1,f.current?.cancel(),f.current=null}),[]);let d=(0,Z.useCallback)(()=>{T.current++,f.current?.cancel(),f.current=null,v.current&&u(!1)},[]),E=(0,Z.useCallback)(async S=>{let k=S===void 0,m=(k?b.current:S)??"";if(!m.trim())return;f.current?.cancel();let P=++T.current,C=()=>v.current&&T.current===P,A=l.current,p=A?.parseChunk??No,w={id:gr("msg"),role:"user",content:m},x={id:gr("msg"),role:"assistant",content:""},O=[...y.current,w].map(B=>({role:B.role,content:B.content})),H=[...y.current,w,x];y.current=H,n(H),k&&i(""),g(null),u(!0);let W=A?.buildPayload??(B=>({messages:B})),{initialMessages:D,parseChunk:M,buildPayload:q,onFinish:z,onError:Q,...j}=A??{},ne=B=>{n(G=>G.map(Te=>Te.id===x.id?{...Te,content:B}:Te))},le="",ee;try{ee=r.requestStream(W(O),j),f.current=ee}catch(B){let G=rn(B);C()&&(g(G),u(!1),A?.onError?.(G));return}try{for await(let B of ee){if(T.current!==P)break;le+=p(B),C()&&ne(le)}C()&&(u(!1),A?.onFinish?.({...x,content:le}))}catch(B){let G=rn(B);C()&&(g(G),u(!1),A?.onError?.(G))}finally{f.current===ee&&(f.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:E,stop:d,isStreaming:a,error:c}}var Y=require("react"),ot=require("@urun-sh/core"),Sr=[];function sn(e,t={}){let{field:r=ot.INPUT_PRESENCE_FIELD,hz:o=ot.INPUT_PRESENCE_DEFAULT_HZ}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=(0,Y.useMemo)(()=>s?(0,ot.createInputPresencePublisher)({awareness:{setLocalStateField:(m,R)=>s.setField(m,R)},field:r,hz:o}):null,[s,r,o]),a=(0,Y.useRef)(null);a.current=i;let[u,c]=(0,Y.useState)(!1),[g,l]=(0,Y.useState)(Sr),y=(0,Y.useRef)(!1);(0,Y.useEffect)(()=>{if(i)return()=>i.dispose()},[i]);let b=(0,Y.useCallback)(()=>{let m=a.current;l(m?m.heldKeys():Sr)},[]),T=(0,Y.useCallback)(()=>{a.current?.clear(),l(Sr)},[]);(0,Y.useEffect)(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,R=()=>{if(m()){y.current=!1,c(!0);return}y.current||(c(!1),T())},P=x=>{m()&&(a.current?.keyDown(x.key),b())},C=x=>{a.current?.keyUp(x.key),b()},A=x=>{m()&&a.current?.movePointer(x.movementX,x.movementY)},p=x=>{m()&&a.current?.setButtons(x.buttons)},w=()=>{T()};return n.addEventListener("pointerlockchange",R),n.addEventListener("keydown",P),n.addEventListener("keyup",C),n.addEventListener("mousemove",A),n.addEventListener("mousedown",p),n.addEventListener("mouseup",p),n.defaultView?.addEventListener("blur",w),()=>{n.removeEventListener("pointerlockchange",R),n.removeEventListener("keydown",P),n.removeEventListener("keyup",C),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",p),n.removeEventListener("mouseup",p),n.defaultView?.removeEventListener("blur",w)}},[n,T,b]);let f=(0,Y.useCallback)(m=>{m.requestPointerLock?.()},[]),v=(0,Y.useCallback)(()=>{y.current=!0,c(!0)},[]),d=(0,Y.useCallback)(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),T()},[n,T]),E=(0,Y.useCallback)(m=>{a.current?.keyDown(m),b()},[b]),S=(0,Y.useCallback)(m=>{a.current?.keyUp(m),b()},[b]),k=(0,Y.useCallback)((m,R)=>{a.current?.movePointer(m,R)},[]);return{engage:f,engageTouch:v,release:d,engaged:u,heldKeys:g,pressKey:E,releaseKey:S,movePointer:k}}var ce=require("react"),gn=require("@urun-sh/core");var I=require("react"),fn=require("@urun-sh/core");var Ft=null;function Lo(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function bt(){if(Ft)return Ft;let e=Lo();return e?(Ft=new e,Ft):null}function $e(){let e=bt();e&&e.state==="suspended"&&e.resume().catch(()=>{})}var Tt=require("react"),cn=require("react/jsx-runtime"),hr=(0,Tt.createContext)(null);function an({session:e,children:t}){return(0,cn.jsx)(hr.Provider,{value:e,children:t})}function Ce(){return(0,Tt.useContext)(hr)}function un(){let e=(0,Tt.useContext)(hr);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}var Rt=require("react/jsx-runtime");function Oo(e,t){return e-t>>>0<2147483648}var ln=1e3;function dn(...e){console.debug("[video]",...e)}function pn(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function mn(e,t,r){return r?[r,t]:[e,t]}var Xe=(0,I.forwardRef)(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:g,style:l,videoClassName:y,placeholder:b,poster:T,children:f,onTrack:v,onFirstFrame:d,frameMarker:E,onFrameMarkerReached:S,onFrameMarkerUnsupported:k,onUnlockChange:m}=t,R=Ce(),P=o??R,C=(0,I.useRef)(null),A=(0,I.useRef)(null),[p,w]=(0,I.useState)(!1),[x,O]=(0,I.useState)(!1),H=(0,I.useRef)(!1),W=(0,I.useRef)(null),D=(0,I.useRef)(v);D.current=v;let M=(0,I.useRef)(m);M.current=m;let q=(0,I.useRef)(d);q.current=d;let z=(0,I.useRef)(S);z.current=S;let Q=(0,I.useRef)(k);Q.current=k;let j=(0,I.useRef)(E??null);j.current=E??null;let ne=(0,I.useCallback)(h=>{W.current!==h&&(W.current=h,M.current?.(h))},[]),le=(0,I.useRef)(null),ee=(0,I.useRef)(null),B=(0,I.useCallback)((h,N=!1)=>{if(!N&&h===le.current||(le.current=h,ee.current?.(),ee.current=null,H.current=!1,O(!1),!h))return;let U=C.current;if(!U)return;let K=j.current,Se=K?.rtpTimestamp??null,Ue=!1,L=()=>{Ue||(Ue=!0,Q.current?.())};K&&Se==null&&L();let Ae=K!=null&&Se!=null,Ze=_e=>{ee.current?.(),ee.current=null,H.current=!0,O(!0),q.current?.(),_e&&z.current?.()};if(typeof U.requestVideoFrameCallback=="function"){let _e=!1,V=0,F=(he,ve)=>{if(!_e){if(Ae){let Re=ve?.rtpTimestamp;if(typeof Re!="number"){L(),Ze(!1);return}if(!Oo(Re,Se)){V=U.requestVideoFrameCallback(F);return}Ze(!0);return}Ze(!1)}};V=U.requestVideoFrameCallback(F),ee.current=()=>{_e=!0,U.cancelVideoFrameCallback?.(V)};return}Ae&&L();let Me=()=>{let _e=U.getVideoPlaybackQuality?.();(_e?_e.totalVideoFrames>0:U.readyState>=2&&U.videoWidth>0)&&Ze(!1)};U.addEventListener("loadeddata",Me),U.addEventListener("timeupdate",Me),U.addEventListener("playing",Me),ee.current=()=>{U.removeEventListener("loadeddata",Me),U.removeEventListener("timeupdate",Me),U.removeEventListener("playing",Me)},Me()},[]);(0,I.useEffect)(()=>()=>{ee.current?.(),ee.current=null},[]);let G=E==null?null:`${E.rtpTimestamp??""}|${E.ptsMs??""}`,Te=(0,I.useRef)(G);(0,I.useEffect)(()=>{if(Te.current===G||(Te.current=G,G==null))return;let h=le.current;h&&B(h,!0)},[G,B]);let ie=(0,I.useCallback)(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let h=C.current;return h&&h.srcObject!==A.current&&(h.srcObject=A.current),A.current},[]),de=(0,I.useCallback)(h=>{let N=C.current;if(!N)return;let U=N.play();!U||typeof U.then!="function"||U.then(()=>{N.muted||ne(!0)}).catch(K=>{if((K instanceof Error?K.name:String(K))==="NotAllowedError"&&!N.muted){dn(`play() blocked pending a user gesture (${h})`),ne(!1);return}dn(`play() failed (${h})`,K)})},[ne]),Fe=(0,I.useCallback)(()=>{let h=C.current;h&&(ie(),!h.muted&&(de("gesture"),$e(),ne(!0)))},[ie,de,ne]),pe=(0,I.useCallback)(h=>{let N=ie();if(N){for(let U of N.getVideoTracks())U!==h&&N.removeTrack(U);if(h&&!N.getVideoTracks().includes(h)){N.addTrack(h);let U=C.current;U&&(U.srcObject=N)}h&&de("track-attach"),w(h!==null),B(h),D.current?.(h)}},[ie,de,B]),we=(0,I.useCallback)(h=>{let N=ie();if(N){for(let U of N.getAudioTracks())U!==h&&N.removeTrack(U);h&&!N.getAudioTracks().includes(h)&&N.addTrack(h),h&&de("audio-attach")}},[ie,de]),me=(0,I.useCallback)(h=>{C.current=h,h&&(a?(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted",""),W.current=null):(h.muted=!1,h.defaultMuted=!1,h.removeAttribute("muted")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),ie())},[ie,a]);(0,I.useImperativeHandle)(r,()=>({get element(){return C.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return H.current},unlock:Fe,get unlocked(){return W.current===!0}}),[Fe]);let ue=(0,fn.derivedLegRole)(n)!==void 0;(0,I.useEffect)(()=>{ue&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[ue,n]);let oe=i!==void 0;return(0,I.useEffect)(()=>{if(oe){pe(i??null);return}if(ue){pe(null);return}if(!P)return;let h=pn(P,mn(n,"video")),N=()=>{let L=A.current;return L?L.getVideoTracks()[0]??null:null},U=L=>{if(L!==N()&&(pe(L),L)){let Ae=()=>{N()===L&&pe(null)};L.addEventListener("ended",Ae)}},K=h.track;K&&K.readyState==="live"&&U(K);let Se=h.on("track",L=>{L&&L.readyState!=="live"||U(L)}),Ue=setInterval(()=>{let L=h.track;L&&L.readyState==="live"&&U(L)},ln);return()=>{Se(),clearInterval(Ue)}},[P,n,ue,oe,i,pe]),(0,I.useEffect)(()=>{if(oe||!P||s===!1||ue)return;let h=pn(P,mn(n,"audio",s)),N=()=>{let L=A.current;return L?L.getAudioTracks()[0]??null:null},U=L=>{if(L!==N()&&(we(L),L)){let Ae=()=>{N()===L&&we(null)};L.addEventListener("ended",Ae)}},K=h.track;K&&K.readyState==="live"&&U(K);let Se=h.on("track",L=>{L&&L.readyState!=="live"||U(L)}),Ue=setInterval(()=>{let L=h.track;L&&L.readyState==="live"&&U(L)},ln);return()=>{Se(),clearInterval(Ue)}},[P,n,ue,s,oe,we]),(0,Rt.jsxs)("div",{className:g,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":p?"true":"false","data-urun-video-framed":x?"true":"false",children:[(0,Rt.jsx)("video",{ref:me,className:y,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),p?null:b,T===void 0?null:(0,Rt.jsx)("div",{"data-urun-video-poster":"","aria-hidden":x||void 0,style:{position:"absolute",inset:0,...x?{opacity:0,pointerEvents:"none"}:null},children:T}),f]})});var Pt=require("react/jsx-runtime"),Io={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},Sn=(0,ce.forwardRef)(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...g}=o??{},l=c!==void 0?c:typeof document<"u"?document:null,y=(0,ce.useRef)(null),b=(0,ce.useRef)(null),T=(0,ce.useRef)(0),f=(0,ce.useRef)(g);f.current=g;let v=(0,ce.useMemo)(()=>(0,gn.createCameraWarp)(f.current),[]);return(0,ce.useImperativeHandle)(r,()=>({get video(){return y.current},get canvas(){return b.current},warp:v,get lastDrawTs(){return T.current}}),[v]),(0,ce.useEffect)(()=>{if(!i)return;let d=0,E=0,S=null,k=R=>{typeof R.requestVideoFrameCallback=="function"&&(S=R,E=R.requestVideoFrameCallback(function P(){v.frameArrived(),E=R.requestVideoFrameCallback(P)}))},m=R=>{d=requestAnimationFrame(m);let P=b.current,C=y.current?.element??null;if(!P||!C||(C!==S&&(S&&E&&S.cancelVideoFrameCallback?.(E),k(C)),C.readyState<2))return;v.tick(R);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,p=Math.max(1,Math.round(P.clientWidth*A)),w=Math.max(1,Math.round(P.clientHeight*A));(P.width!==p||P.height!==w)&&(P.width=p,P.height=w);let x=P.getContext("2d");if(!x)return;let O=v.transform(),H=C.videoWidth||p,W=C.videoHeight||w,M=Math.max(p/H,w/W)*(1+a)*O.scale;x.setTransform(M,0,0,M,p/2+O.translateX*p,w/2+O.translateY*w),x.drawImage(C,-H/2,-W/2),T.current=R};return d=requestAnimationFrame(m),()=>{cancelAnimationFrame(d),S&&E&&S.cancelVideoFrameCallback?.(E)}},[i,a,v]),(0,ce.useEffect)(()=>{if(!i||!u||!l)return;let d=()=>!!l.pointerLockElement,E=P=>{d()&&v.keyDown(P.key)},S=P=>v.keyUp(P.key),k=P=>{d()&&v.pointerDelta(P.movementX,P.movementY)},m=()=>{d()||v.clearKeys()},R=()=>v.clearKeys();return l.addEventListener("keydown",E),l.addEventListener("keyup",S),l.addEventListener("mousemove",k),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",R),()=>{l.removeEventListener("keydown",E),l.removeEventListener("keyup",S),l.removeEventListener("mousemove",k),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",R)}},[i,u,l,v]),i?(0,Pt.jsxs)(Xe,{ref:y,...s,videoClassName:s.videoClassName,style:{...s.style},children:[(0,Pt.jsx)("canvas",{ref:b,style:Io,"data-urun-warp":""}),n]}):(0,Pt.jsx)(Xe,{ref:y,...s,children:n})});var hn=new Map;function vn(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);hn.set(e,{component:t,schema:r})}function yn(e,t){let r=hn.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}var Je=require("react/jsx-runtime");function kn({name:e,props:t,fallback:r}){let o=yn(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?(0,Je.jsx)(Je.Fragment,{children:r}):(0,Je.jsx)("div",{className:"urun-component-error",role:"alert",children:(0,Je.jsx)("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return(0,Je.jsx)(n,{...o.validatedProps})}var st=require("zod"),ze=require("react/jsx-runtime"),bn=st.z.object({step:st.z.number().min(0),total:st.z.number().min(1),label:st.z.string().optional(),variant:st.z.enum(["default","success","error"]).default("default")});function vr(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Tn(e){let{step:t,total:r,label:o,variant:n,percentage:s}=vr(e);return(0,ze.jsxs)("div",{className:"urun-progress-card","data-variant":n,children:[o&&(0,ze.jsx)("div",{className:"urun-progress-label",children:o}),(0,ze.jsx)("div",{className:"urun-progress-bar",children:(0,ze.jsx)("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),(0,ze.jsxs)("div",{className:"urun-progress-text",children:[t,"/",r]})]})}var Ht=require("zod"),xt=require("react/jsx-runtime"),Rn=Ht.z.object({state:Ht.z.enum(["thinking","generating","idle","error"]),message:Ht.z.string().optional()}),Do={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function yr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Do[t]??t;return{state:t,message:n,isActive:o}}function Pn(e){let{state:t,message:r,isActive:o}=yr(e);return(0,xt.jsxs)("span",{className:"urun-status-badge","data-state":t,children:[(0,xt.jsx)("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),(0,xt.jsx)("span",{className:"urun-status-message",children:r})]})}var Et=require("react"),qt=require("zod"),Ct=require("react/jsx-runtime"),xn=qt.z.object({text:qt.z.string(),streaming:qt.z.boolean().default(!1)});function kr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function En(e){let{text:t,streaming:r}=kr(e),o=(0,Et.useRef)(null),n=(0,Et.useRef)(0);return(0,Et.useEffect)(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),(0,Ct.jsxs)("div",{className:"urun-text-stream",children:[(0,Ct.jsx)("span",{ref:o,className:"urun-text-content"}),r&&(0,Ct.jsx)("span",{className:"urun-text-cursor"})]})}var wt=require("zod"),Ut=require("react/jsx-runtime"),Cn=wt.z.object({src:wt.z.string().url(),alt:wt.z.string().optional(),caption:wt.z.string().optional()});function br(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function wn(e){let{src:t,alt:r,caption:o}=br(e);return(0,Ut.jsxs)("figure",{className:"urun-image-frame",children:[(0,Ut.jsx)("img",{className:"urun-image",src:t,alt:r}),o&&(0,Ut.jsx)("figcaption",{className:"urun-image-caption",children:o})]})}var Oe=require("zod"),it=require("react/jsx-runtime"),Un=Oe.z.object({metrics:Oe.z.array(Oe.z.object({label:Oe.z.string(),value:Oe.z.union([Oe.z.string(),Oe.z.number()]),unit:Oe.z.string().optional()}))});function Tr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function An(e){let{metrics:t}=Tr(e);return(0,it.jsx)("div",{className:"urun-metrics-panel",children:t.map((r,o)=>(0,it.jsxs)("div",{className:"urun-metric-card",children:[(0,it.jsx)("div",{className:"urun-metric-label",children:r.label}),(0,it.jsx)("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}var $=require("react"),Ln=require("react/jsx-runtime");function He(e){return e&&typeof e=="object"?e:null}function Rr(e){if(typeof e=="string")return e;let t=He(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function Vo(e){if(typeof e=="string")return"delta";let t=He(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function Fo(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function Ho(e){let t=He(e),r=t?.body;return Fo(r,He(He(r)?.error)?.message,He(r)?.error,He(r)?.message,He(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var at=class extends Error{name="TextStreamError"},qo=4,Pr=3,xr=240;function Mn(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function Wo(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function Er(e){let{session:t,stream:r}=e,o=(0,$.useRef)(e);(0,$.useEffect)(()=>{o.current=e});let n=(0,$.useRef)(null),s=(0,$.useRef)(()=>{}),i=(0,$.useRef)(null),a=(0,$.useRef)(""),u=(0,$.useRef)(""),c=(0,$.useRef)(null),g=(0,$.useRef)(!1),l=(0,$.useRef)(!1),y=(0,$.useRef)(!1),b=(0,$.useRef)(0),T=(0,$.useRef)(Mn()),f=(0,$.useCallback)(S=>{if(n.current=S,!S){i.current=null;return}let k=i.current;if(k&&k.parentNode===S)return;let m=S.ownerDocument.createTextNode(u.current);S.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),v=(0,$.useCallback)(()=>{c.current=null;let S=i.current,k=a.current;if(k.length>0){let A=o.current,p=A.smoothCharsPerFrame??Pr,w=A.smoothThreshold??xr,x=A.smooth&&k.length<=w?k.slice(0,p):k;a.current=k.slice(x.length),u.current+=x,S?.appendData(x)}let m=T.current,R=u.current.length,P=b.current===0?0:Date.now()-b.current,C=Math.round(R/qo);if(m.chars=R,m.tokens=C,m.elapsedMs=P,m.tokensPerSecond=P>0?C*1e3/P:0,a.current.length>0){d(),o.current.onMeter?.(m);return}if(!g.current&&!y.current){y.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(u.current);return}o.current.onMeter?.(m)},[]),d=(0,$.useCallback)(()=>{c.current===null&&(c.current=globalThis.requestAnimationFrame(()=>v()))},[v]);s.current=d,(0,$.useEffect)(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",u.current="",l.current=!1,y.current=!1,b.current=0,g.current=!0,Wo(T.current),i.current&&(i.current.data="");let S=!1,k=null;return(async()=>{try{for(k=t.stream(r).messages()[Symbol.asyncIterator]();;){let R=await k.next();if(S)return;if(R.done)break;let P=R.value,C=Vo(P);if(C==="error")throw new at(Ho(P));if(C==="done")break;if(C==="ignore")continue;let A=Rr(P);A&&(b.current===0&&(b.current=Date.now()),a.current+=A,d())}if(S)return;k.return?.(void 0),g.current=!1,d()}catch(m){if(S)return;k?.return?.(void 0),l.current=!0,g.current=!1,o.current.onError?.(m instanceof Error?m:new at(String(m))),d()}})(),()=>{S=!0,g.current=!1,k?.return?.(void 0),c.current!==null&&(globalThis.cancelAnimationFrame?.(c.current),c.current=null)}},[t,r,d]);let E=(0,$.useCallback)(()=>u.current,[]);return{ref:f,meterRef:T,getText:E}}function _n(e,t=250){let[r,o]=(0,$.useState)(Mn);return(0,$.useEffect)(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function Nn(e){let{className:t,style:r,...o}=e,{ref:n}=Er(o);return(0,Ln.jsx)("span",{ref:n,className:t,style:r})}var On=require("react");var Dn=require("react/jsx-runtime"),In=(0,On.forwardRef)(function(t,r){let{stream:o="image",...n}=t;return(0,Dn.jsx)(Xe,{ref:r,stream:o,...n})});var J=require("react"),Fn=require("@urun-sh/core");var qn=require("react/jsx-runtime"),Bo=1e3,Vn=200;function Cr(...e){console.debug("[audio]",...e)}var At=(0,J.forwardRef)(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,l=Ce(),y=o??l,b=(0,J.useRef)(null),T=(0,J.useRef)(null),f=(0,J.useRef)(null),v=(0,J.useRef)(null),d=(0,J.useRef)(u);d.current=u;let E=(0,J.useRef)(c);E.current=c;let S=(0,J.useCallback)(p=>{f.current!==p&&(f.current=p,E.current?.(p))},[]),k=(0,J.useCallback)(()=>{if(typeof MediaStream>"u")return null;T.current||(T.current=new MediaStream);let p=b.current;return p&&p.srcObject!==T.current&&(p.srcObject=T.current),T.current},[]),m=(0,J.useCallback)(p=>{let w=b.current;if(!w)return;let x=w.play();!x||typeof x.then!="function"||x.then(()=>{w.muted||S(!0)}).catch(O=>{let H=O instanceof Error?O.name:String(O);if(H==="AbortError"){Cr(`play() aborted (${p}); retrying in ${Vn}ms`),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,m(`${p}:retry`)},Vn);return}if(H==="NotAllowedError"){Cr(`play() blocked pending a user gesture (${p})`),S(!1);return}Cr(`play() failed (${p})`,O)})},[S]),R=(0,J.useCallback)(p=>{let w=k();if(w){for(let x of w.getAudioTracks())x!==p&&w.removeTrack(x);p&&!w.getAudioTracks().includes(p)&&w.addTrack(p),p&&m("track-attach"),d.current?.(p)}},[k,m]),P=(0,J.useCallback)(()=>{let p=b.current;p&&(k(),p.muted=!1,m("gesture"),$e(),S(!0))},[k,m,S]);(0,J.useImperativeHandle)(r,()=>({unlock:P,get unlocked(){return f.current===!0},get element(){return b.current}}),[P]);let C=(0,J.useCallback)(p=>{b.current=p,p&&(p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),k()),g?.(p)},[k,g]),A=s!==void 0;return(0,J.useEffect)(()=>{if(A){R(s??null);return}if(!y)return;let p=y.stream(n),w=()=>{let D=T.current;return D?D.getAudioTracks()[0]??null:null},x=D=>{if(D!==w()&&(R(D),D)){let M=()=>{w()===D&&R(null)};D.addEventListener("ended",M)}},O=p.track;O&&O.readyState==="live"&&x(O);let H=p.on("track",D=>{D&&D.readyState!=="live"||x(D)}),W=setInterval(()=>{let D=p.track;D&&D.readyState==="live"&&x(D)},Bo);return()=>{H(),clearInterval(W)}},[y,n,A,s,R]),(0,J.useEffect)(()=>(0,Fn.observePageLifecycle)(()=>{$e(),f.current===!0&&m("foreground")}),[m]),(0,J.useEffect)(()=>()=>{v.current&&clearTimeout(v.current)},[]),(0,qn.jsx)("audio",{ref:C,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Hn=At;var X=require("react"),ut=require("@urun-sh/core");var Bn=require("react/jsx-runtime"),wr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function Wt(...e){console.debug("[voice]",...e)}var Mt=(0,X.forwardRef)(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=wr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:l,onMicStream:y,onTrack:b,onUnlockChange:T,capture:f}=t,v=Ce(),d=o??v,E=(0,X.useRef)(null),S=(0,X.useRef)(null),k=(0,X.useRef)(null),m=(0,X.useRef)([]),R=(0,X.useRef)(!1),P=(0,X.useRef)(g);P.current=g;let C=(0,X.useRef)(l);C.current=l;let A=(0,X.useRef)(y);A.current=y;let p=(0,X.useCallback)(M=>{R.current!==M&&(R.current=M,P.current?.(M))},[]),w=(0,X.useCallback)(()=>{for(let M of m.current)M();m.current=[],k.current?.release(),k.current=null,S.current&&(S.current=null,A.current?.(null))},[]),x=(0,X.useCallback)(async()=>{let M=k.current;if(M){let j=await M.update(i);return S.current=M.stream,A.current?.(M.stream),j}let z=await(f??(0,ut.sharedCaptureController)()).claim("audio",i);k.current=z,m.current=[z.onTrack((j,ne)=>{S.current=ne,A.current?.(ne),R.current&&d?.stream(n).attach(j).catch(le=>Wt("mic re-attach after one-capture re-acquire failed",le))}),z.onLost(j=>{k.current=null,m.current=[],S.current=null,A.current?.(null),p(!1),C.current?.(j)})],S.current=z.stream,A.current?.(z.stream);let Q=z.track;if(!Q)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return Q},[f,i,d,n,p]),O=(0,X.useCallback)(async()=>{w(),p(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,w,p]),H=(0,X.useCallback)(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");E.current?.unlock();let M;try{M=await x()}catch(Q){w();let j=(0,ut.sessionFailureFromMediaError)(Q,d.status);throw C.current?.(j),j}d.connect?.();let q;for(let Q=1;Q<=u;Q++)try{await d.whenLive(a!==void 0?{timeout:a}:void 0),await d.stream(n).attach(M),p(!0);return}catch(j){q=j,Wt(`start attempt ${Q}/${u} failed`,j),Q<u&&await new Promise(ne=>setTimeout(ne,c))}w(),p(!1);let z=q instanceof Error?q:new Error(String(q??"voice start failed"));throw C.current?.(z),z},[d,n,a,u,c,x,w,p]);(0,X.useImperativeHandle)(r,()=>({start:H,stop:O,unlock:()=>E.current?.unlock(),get active(){return R.current},get micStream(){return S.current},get audio(){return E.current}}),[H,O]);let W=(0,X.useRef)(!1),D=(0,X.useCallback)(async()=>{if(!d||!R.current||W.current)return;let M=S.current?.getAudioTracks()[0]??null;if(M&&M.readyState==="live"){try{await d.stream(n).attach(M)}catch(q){Wt("foreground mic re-assert failed (will retry on next pass)",q)}return}W.current=!0;try{let q=await x();await d.stream(n).attach(q)}catch(q){let z=q instanceof Error?q:new Error(String(q));Wt("foreground mic re-acquire failed",z),C.current?.(z)}finally{W.current=!1}},[d,n,x]);return(0,X.useEffect)(()=>{let M=()=>{D()};return d&&typeof d.onRecovery=="function"?d.onRecovery(M):(0,ut.observePageLifecycle)(M)},[d,D]),(0,X.useEffect)(()=>w,[w]),s?(0,Bn.jsx)(At,{ref:E,session:d,stream:n,onTrack:b,onUnlockChange:T}):null}),Wn=Mt;var xe=require("react");var Bt=require("react");var Ur={level:0,speaking:!1};function jt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=(0,Bt.useState)(Ur);return(0,Bt.useEffect)(()=>{if(!e){i(Ur);return}let a=bt();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let l=new Uint8Array(g.fftSize),b=setInterval(()=>{g.getByteTimeDomainData(l);let T=0;for(let v=0;v<l.length;v++){let d=(l[v]-128)/128;T+=d*d}let f=Math.sqrt(T/l.length);i(v=>{let d=f>n;return Math.abs(v.level-f)<.005&&v.speaking===d?v:{level:f,speaking:d}})},o);return()=>{clearInterval(b),c.disconnect(),i(Ur)}},[e,r,o,n]),s}var Ie=require("react/jsx-runtime"),jo={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Ko={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},jn=(0,xe.forwardRef)(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:l,capture:y}=t,b=Ce(),T=o??b,f=(0,xe.useRef)(null),[v,d]=(0,xe.useState)(null),E=(0,xe.useRef)(l);E.current=l;let{level:S,speaking:k}=jt(a?v:null);return(0,xe.useImperativeHandle)(r,()=>({start:()=>{let m=f.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>f.current?.stop()??Promise.resolve(),get active(){return f.current?.active??!1},get micStream(){return f.current?.micStream??null}}),[]),(0,xe.useEffect)(()=>{!i||!T||f.current?.start().catch(()=>{})},[i,T]),(0,Ie.jsxs)(Ie.Fragment,{children:[(0,Ie.jsx)(Mt,{ref:f,session:T,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:g,onMicStream:m=>{d(m),E.current?.(m)}}),a?(0,Ie.jsx)("span",{className:u,style:jo,"data-urun-mic":"","data-urun-mic-active":v?"true":"false","data-urun-mic-speaking":k?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(S*100)/100,children:(0,Ie.jsx)("span",{style:Ko,children:(0,Ie.jsx)("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(S*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});var ct=require("@urun-sh/core"),_=require("react");var ye=require("react/jsx-runtime"),Mr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Ar(...e){console.debug("[camera]",...e)}function $o(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Xo(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var _r=(0,_.forwardRef)(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:l,visible:y=!1,className:b,videoClassName:T,onActiveChange:f,onError:v,onStream:d,onTrack:E,children:S,capture:k,flipControl:m="auto",flipControlClassName:R,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let C=i?"user":a?"environment":u??"environment",A=Ce(),p=o??A,w=(0,_.useRef)(null),x=(0,_.useRef)(null),O=(0,_.useRef)(null),H=(0,_.useRef)([]),W=(0,_.useRef)(null),D=(0,_.useRef)(!1),M=(0,_.useRef)(!1),q=(0,_.useRef)(C),[z,Q]=(0,_.useState)(C),[j,ne]=(0,_.useState)(!1),[le,ee]=(0,_.useState)(null),[B,G]=(0,_.useState)(!1),[Te]=(0,_.useState)($o),ie=(0,_.useRef)(f);ie.current=f;let de=(0,_.useRef)(v);de.current=v;let Fe=(0,_.useRef)(d);Fe.current=d;let pe=(0,_.useRef)(E);pe.current=E;let we=(0,_.useRef)(P);we.current=P;let me=(0,_.useCallback)(V=>{D.current!==V&&(D.current=V,ne(V),ie.current?.(V))},[]);(0,_.useEffect)(()=>{if(!j){ee(null);return}let V=!1,F=()=>{Xo().then(ve=>{V||(ee(ve),ve&&we.current?.(ve))})};F();let he=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof he?.addEventListener=="function"?(he.addEventListener("devicechange",F),()=>{V=!0,he.removeEventListener?.("devicechange",F)}):()=>{V=!0}},[j]);let ue=(0,_.useCallback)(V=>{let F=w.current;F&&(F.muted=!0,F.defaultMuted=!0,F.setAttribute("muted",""),F.setAttribute("playsinline",""),F.setAttribute("webkit-playsinline",""),F.srcObject=V,V&&F.play()?.catch?.(he=>Ar("preview play() failed",he)))},[]),oe=(0,_.useCallback)(()=>{M.current=!1,W.current?.(),W.current=null;for(let V of H.current)V();H.current=[],O.current?.release(),O.current=null,x.current&&(x.current=null,Fe.current?.(null),pe.current?.(null)),ue(null)},[ue]),h=(0,_.useCallback)((V,F)=>{W.current?.(),x.current=F,ue(F),Fe.current?.(F);let he=()=>{x.current===F&&(Ar("camera track ended (device removed or permission revoked)"),oe(),me(!1))};V.addEventListener("ended",he),W.current=()=>V.removeEventListener("ended",he)},[ue,oe,me]),N=(0,_.useCallback)(async V=>{let F=n!==!1;if(F&&!p)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let he={...Mr,...s,facingMode:V},ve;try{let Re=O.current;if(Re)ve=await Re.update(he);else{let St=await(k??(0,ct.sharedCaptureController)()).claim("video",he);if(O.current=St,H.current=[St.onTrack((ht,go)=>{h(ht,go),D.current&&(!F||!p||p.stream(n).attachVideo(ht).then(()=>pe.current?.(ht)).catch(So=>Ar("camera re-publish after one-capture re-acquire failed",So)))}),St.onLost(ht=>{O.current=null,H.current=[],oe(),me(!1),de.current?.(ht)})],!St.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ve=St.track}}catch(Re){let Qe=(0,ct.sessionFailureFromMediaError)(Re,p?.status);throw de.current?.(Qe),Qe}q.current=V,Q(V),h(ve,O.current?.stream??new MediaStream([ve]));try{F&&p&&(p.connect?.(),await p.whenLive(l!==void 0?{timeout:l}:void 0),await p.stream(n).attachVideo(ve)),M.current=F?n:!1}catch(Re){oe(),me(!1);let Qe=Re instanceof Error?Re:new Error(String(Re));throw de.current?.(Qe),Qe}pe.current?.(ve),me(!0)},[p,n,s,l,k,h,oe,me]),U=(0,_.useCallback)(V=>N(V?.facingMode??q.current),[N]),K=(0,_.useCallback)(async V=>{let F=M.current===n;D.current&&q.current===V&&F||await N(V)},[N,n]),Se=(0,_.useCallback)(()=>N(q.current==="environment"?"user":"environment"),[N]),Ue=(0,_.useCallback)(async()=>{oe(),me(!1),n!==!1&&await p?.stream(n).detachVideo().catch(()=>{})},[p,n,oe,me]),L=(0,_.useCallback)(async V=>{let F=w.current;if(!F)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await(0,ct.captureStillFromVideo)(F,V)},[]);(0,_.useImperativeHandle)(r,()=>({start:U,stop:Ue,flip:Se,setFacingMode:K,capturePhoto:L,get active(){return D.current},get facingMode(){return q.current},get stream(){return x.current},get element(){return w.current}}),[U,Ue,Se,K,L]);let Ae=(0,_.useRef)(K);if(Ae.current=K,(0,_.useEffect)(()=>{c&&(n!==!1&&!p||Ae.current(C).catch(()=>{}))},[c,p,C,n]),(0,_.useEffect)(()=>oe,[oe]),!y)return null;let Ze=g==="auto"?z==="user":g,Me=j&&(m===!0||m==="auto"&&Te&&(le?.length??0)>1),_e=()=>{B||(G(!0),Se().catch(()=>{}).finally(()=>G(!1)))};return(0,ye.jsxs)("div",{className:b,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":z,children:[(0,ye.jsx)("video",{ref:w,className:T,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ze?{transform:"scaleX(-1)"}:{}}}),Me?(0,ye.jsx)("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:_e,disabled:B,className:R,style:R?{opacity:B?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:B?.6:1},children:(0,ye.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[(0,ye.jsx)("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),(0,ye.jsx)("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),(0,ye.jsx)("path",{d:"M14.5 10.5v1.6h-1.6"}),(0,ye.jsx)("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),(0,ye.jsx)("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,S]})}),Kn=(0,_.forwardRef)(function({preview:t=!0,...r},o){return(0,ye.jsx)(_r,{ref:o,...r,visible:t,autoStart:!1})});var lt=require("@urun-sh/core"),te=require("react");function $n(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=(0,te.useState)(null),[a,u]=(0,te.useState)(null),[c,g]=(0,te.useState)(!1),[l,y]=(0,te.useState)(null),[b]=(0,te.useState)(lt.cameraCaptureAvailable),T=(0,te.useRef)(n);T.current=n;let f=(0,te.useRef)(null),v=(0,te.useRef)(0),d=(0,te.useCallback)(R=>{f.current&&URL.revokeObjectURL(f.current),f.current=R?URL.createObjectURL(new Blob([R.bytes],{type:R.type})):null,u(f.current),i(R),T.current?.(R)},[]);(0,te.useEffect)(()=>()=>{v.current++,f.current&&URL.revokeObjectURL(f.current),f.current=null},[]);let E=(0,te.useCallback)(async R=>{let P=++v.current;g(!0),y(null);try{let C=await R();if(v.current!==P)return;d(C)}catch(C){if(v.current!==P)return;y((0,lt.referenceImageErrorMessage)(C))}finally{v.current===P&&g(!1)}},[d]),S=(0,te.useCallback)(R=>E(()=>(0,lt.normalizeReferenceImage)(R,{maxSize:t,type:r,quality:o,source:"file"})),[E,t,r,o]),k=(0,te.useCallback)(R=>E(()=>R.capturePhoto({maxSize:t,type:r,quality:o})),[E,t,r,o]),m=(0,te.useCallback)(()=>{v.current++,y(null),g(!1),d(null)},[d]);return{reference:s,previewUrl:a,pick:S,capture:k,clear:m,busy:c,error:l,cameraAvailable:b}}var Kt=require("react");function Xn(e,t){let[r,o]=(0,Kt.useState)(null);return(0,Kt.useEffect)(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}var Gn=require("react");var Xt=require("react");var Jn=require("zustand/vanilla"),zn=require("zustand"),Jo=()=>{};function $t(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=(0,Jn.createStore)(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Jo,u=(c=>(0,zn.useStore)(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function dt(e,t){let r=(0,Xt.useMemo)(()=>$t(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return(0,Xt.useEffect)(()=>r.bind(),[r]),r}function Yn(e,t,r){let n=dt(e,t)(r??(a=>a)),s=(0,Gn.useCallback)(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}var zt=require("react");var qe=200;function De(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function pt(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Jt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Gt(e,t,r={}){let o=r.cap??200,[n,s]=(0,zt.useState)([]);return(0,zt.useEffect)(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>De(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}var Ee=require("react/jsx-runtime");function Zn({session:e,name:t,cap:r,className:o}){let n=Gt(e,t,{cap:r});return(0,Ee.jsxs)("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[(0,Ee.jsxs)("div",{className:"urun-stream-tail-meta",children:[(0,Ee.jsx)("code",{children:t}),(0,Ee.jsxs)("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),(0,Ee.jsx)("div",{className:"urun-stream-tail-log",children:n.length===0?(0,Ee.jsxs)("span",{className:"urun-stream-tail-empty",children:["Waiting for ",(0,Ee.jsx)("code",{children:t})," messages\u2026"]}):n.map((s,i)=>(0,Ee.jsxs)("div",{className:"urun-stream-tail-line",children:[(0,Ee.jsx)("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",pt(s.payload)]},`${s.at}-${i}`))})]})}var _t=require("react");var ge=require("react/jsx-runtime");function Nt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=(0,_t.useState)(""),[i,a]=(0,_t.useState)(null),u=(0,_t.useCallback)(()=>{let c=Jt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return(0,ge.jsxs)("div",{className:"urun-doc-patch",children:[(0,ge.jsx)("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),(0,ge.jsxs)("div",{className:"urun-doc-patch-actions",children:[(0,ge.jsx)("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?(0,ge.jsx)("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Qn({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=dt(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return(0,ge.jsxs)("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[(0,ge.jsxs)("div",{className:"urun-doc-panel-meta",children:[(0,ge.jsx)("code",{children:t}),(0,ge.jsx)("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),(0,ge.jsx)("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?(0,ge.jsx)(Nt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}var Yt=require("react");var Ve=require("react/jsx-runtime");function eo(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function to({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=(0,Yt.useState)([]);return(0,Yt.useEffect)(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>De(u,{at:Date.now(),direction:"in",text:eo(pt(a))},r))}):void 0),[e,t,r]),(0,Ve.jsxs)("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[(0,Ve.jsx)(Nt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>De(u,{at:Date.now(),direction:"out",text:eo(a)},r))}}),(0,Ve.jsx)("div",{className:"urun-control-sender-log",children:n.length===0?(0,Ve.jsx)("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>(0,Ve.jsxs)("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[(0,Ve.jsx)("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",(0,Ve.jsx)("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}var Zt=require("react");var Ge=require("react/jsx-runtime");function ro({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=(0,Zt.useState)([]),a=t.join(","),u=r.join(",");return(0,Zt.useEffect)(()=>{if(i([]),!e)return;let c=(l,y)=>i(b=>De(b,{at:Date.now(),kind:l,text:y},o)),g=[];g.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of t){let y=e.stream(l);g.push(y.on("track",b=>c("track",`${l}: ${b?"track arrived":"track ended"}`)))}for(let l of r){let y=e.doc(l);g.push(y.on("change",()=>c("doc",`${l} changed`)))}return()=>g.forEach(l=>l())},[e,a,u,o]),(0,Ge.jsx)("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?(0,Ge.jsx)("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,g)=>(0,Ge.jsxs)("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[(0,Ge.jsx)("span",{className:"urun-event-spine-kind",children:c.kind})," ",(0,Ge.jsx)("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}var sr=require("@urun-sh/core");var Qt=require("react");function ke(e){let[t,r]=(0,Qt.useState)(e?.phase??null);return(0,Qt.useEffect)(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}var oo=require("@urun-sh/core");var mt=require("react"),no=require("@urun-sh/core");function er(e){let t=ke(e),r=(0,no.isWakingPhase)(t?.name),o=(0,mt.useRef)(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=(0,mt.useState)(s);return(0,mt.useEffect)(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}var We=require("react/jsx-runtime");function tr({session:e,render:t,className:r}){let o=er(e);return!o.waking||!o.phase?null:(0,We.jsx)("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("span",{className:"urun-session-waking-label",children:(0,oo.describeSessionPhase)(o.phase)})," ",(0,We.jsxs)("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}var nr=require("react");var Be=require("react"),zo={event:null,elapsedMs:0};function rr(e,t){let[r,o]=(0,Be.useState)(null),n=(0,Be.useRef)(0);(0,Be.useEffect)(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=(0,Be.useState)(0);return(0,Be.useEffect)(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:zo}var ft=require("react/jsx-runtime"),Go={activating:"starting stream\u2026","still-activating":"model warming up \u2014 this can take a minute","cold-boot":"cold boot \u2014 compiling/loading the model, hang tight",degraded:"taking longer than usual \u2014 still trying"};function Yo(e){let[t,r]=(0,nr.useState)(!1);return(0,nr.useEffect)(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function or({session:e,stream:t,videoElement:r,render:o,className:n}){let s=rr(e,t),i=Yo(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return(0,ft.jsx)("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):(0,ft.jsxs)("div",{className:"urun-activation-overlay-card",children:[(0,ft.jsx)("span",{className:"urun-activation-overlay-copy",children:a.hint??Go[u]})," ",(0,ft.jsxs)("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}var be=require("react/jsx-runtime"),Zo={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function so({session:e,className:t}){let r=ke(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return(0,be.jsxs)("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[(0,be.jsx)("span",{className:"urun-session-status-dot","data-phase":o}),(0,be.jsx)("span",{className:"urun-session-status-label",children:Zo[o]}),n?(0,be.jsx)("span",{className:"urun-session-status-detail",children:n}):null]})}function io({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ke(e);if(s?.name==="live")return(0,be.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,(0,be.jsx)(or,{session:e})]});let i=r?r(s):(0,be.jsx)("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&(0,sr.isWakingPhase)(s.name)?(0,be.jsx)(tr,{session:e}):s&&s.name!=="idle"?(0,sr.describeSessionPhase)(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return(0,be.jsxs)("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?(0,be.jsx)("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}var ir=require("react");var uo=require("react/jsx-runtime");function Nr(e){return ke(e)?.endsAt??null}function Qo(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function ao({session:e,urgentMs:t=6e4,className:r}){let n=Nr(e)?.getTime()??null,[s,i]=(0,ir.useState)(()=>n===null?null:Math.max(0,n-Date.now()));if((0,ir.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Qo(s);return(0,uo.jsx)("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}var Lt=require("react/jsx-runtime"),es=new Set(["expired","ended","error"]);function co({session:e,onNewSession:t,children:r,className:o}){let n=ke(e);if(!n||!es.has(n.name))return null;let s=r?r(n):(0,Lt.jsx)("span",{className:"urun-session-ended-copy",children:n.name==="expired"?"Session ended \u2014 start a new session":n.name==="error"?`Session failed${n.error?.reason?` \u2014 ${n.error.reason}`:""}.`:"Session ended."});return(0,Lt.jsxs)("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?(0,Lt.jsx)("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}var je=require("react"),Ye=require("react/jsx-runtime");function Lr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function Or(e){let t=(0,je.useMemo)(()=>e?e.doc("control"):null,[e]),[r,o]=(0,je.useState)(()=>t?Lr(t.get("idle")):null);return(0,je.useEffect)(()=>{if(!t){o(null);return}return o(Lr(t.get("idle"))),t.on("change",()=>o(Lr(t.get("idle"))))},[t]),r}function ts(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function lo({session:e,onStillHere:t,className:r}){let o=Or(e),n=o?.deadlineEpochS??null,[s,i]=(0,je.useState)(null);if((0,je.useEffect)(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return(0,Ye.jsx)("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:(0,Ye.jsxs)("div",{className:"urun-idle-warning-card",children:[(0,Ye.jsx)("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),(0,Ye.jsx)("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${ts(s)} due to inactivity.`:"This session will end soon due to inactivity."}),(0,Ye.jsx)("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}var gt=require("react"),po=require("@urun-sh/core");function mo(e){let t=(0,gt.useContext)(tt),[r,o]=(0,gt.useState)(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,l=t?.authProvider;return(0,gt.useEffect)(()=>{if(!a||!u||!n||!s)return;let y=!1,b=()=>{(0,po.prewake)({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:l}).then(f=>{y||o(f)}).catch(()=>{})};b();let T=setInterval(b,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(T)}},[n,s,i,a,u,c,g,l]),r}var ar=require("react");function fo(e){let[t,r]=(0,ar.useState)(null);return(0,ar.useEffect)(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}var ur=require("@urun-sh/core");0&&(module.exports={Audio,Camera,ComponentRenderer,DEFAULT_CAMERA_CONSTRAINTS,DEFAULT_LOG_CAP,DEFAULT_SMOOTH_CHARS_PER_FRAME,DEFAULT_SMOOTH_THRESHOLD,DEFAULT_VOICE_CONSTRAINTS,DocPatchForm,Image,ImageFrame,ImageFrameSchema,MetricsPanel,MetricsPanelSchema,Mic,OPERATOR_CHORD_LABEL,OPERATOR_TOKEN_STORAGE_KEY,ProgressCard,ProgressCardSchema,ReprojectedVideo,Session,StatusBadge,StatusBadgeSchema,Text,TextStream,TextStreamError,TextStreamSchema,UrunActivationOverlay,UrunAudio,UrunAuthProvider,UrunCamera,UrunControlSender,UrunDocPanel,UrunErrorBoundary,UrunEventSpine,UrunIdleWarning,UrunJwtProvider,UrunProvider,UrunSessionClock,UrunSessionEnded,UrunSessionGate,UrunSessionStatus,UrunSessionWaking,UrunStreamTail,UrunVoice,Video,Voice,authMode,createDocStore,describeSessionPhase,formatPayload,getUrunAudioContext,isWakingPhase,parseJsonObject,pushCapped,readOperatorToken,registerComponent,resumeUrunAudioContext,textDelta,urunPublicEnv,useActivation,useApp,useChat,useCompletion,useConfirmOnLeave,useDocStore,useImageFrame,useInputPresence,useMetricsPanel,useOperatorOverride,useProgressCard,useReferenceImage,useRequest,useSession,useSessionDoc,useSessionEndsAt,useSessionIdle,useSessionPhase,useSessionStats,useSessionTrack,useSessionWake,useStatusBadge,useStreamMessages,useText,useTextMeter,useTextStream,useUrunAudioLevel,useUrunAuth,useUrunPrewake,usesWorkOSAuth});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client"
|
|
2
|
-
import{a as ht,b as ln,c as vt}from"./chunk-WF2OBDSX.mjs";import{useCallback as or,useEffect as Pn,useMemo as ur,useRef as sr,useState as bt}from"react";import{Component as dn}from"react";import{jsx as Qt,jsxs as pn}from"react/jsx-runtime";var Be=class extends dn{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||pn("div",{role:"status","aria-live":"polite",style:{padding:"16px",border:"1px solid rgba(17, 24, 39, 0.12)",borderRadius:"8px",background:"#ffffff",color:"#111827",fontFamily:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',maxWidth:"360px"},children:[Qt("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),Qt("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as mn}from"react";var _e=mn(null);function ve(e){return e&&e.trim()?e.trim():void 0}function le(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return ve(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return ve(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ve(typeof process<"u"?process.env?.[e]:void 0)}}function Qe(){let e=le("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||le("VERCEL_ENV")==="production"?"workos":le("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function fn(){return Qe()==="workos"}import{useEffect as gn,useRef as Sn}from"react";var hn="urun.operator_token",tr=null,er="op",vn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function rr(){return typeof window<"u"}function nr(){return tr}function yn(){if(!rr())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(er);if(!r)return null;tr=r,t.delete(er);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function kn(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function yt(e){let t=Sn(e);t.current=e,gn(()=>{if(!rr())return;yn();let r=o=>{if(!kn(o))return;let n=nr();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as bn}from"react";function kt(e=!0){bn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as Ne,jsxs as xn}from"react/jsx-runtime";var Rn="/api/urun-token",Cn=1e4;function En(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function ir(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function ar(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function Pt(e){let t=e===void 0?void 0:JSON.stringify(e);return ur(()=>e,[t])}function Tn(e,t){return typeof e=="function"?e(t):e!==void 0?e:xn("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:[Ne("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ne("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function wn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,audioPlayout:g,videoPlayout:l,sessionStats:v,confirmOnLeave:R=!1,fallback:k,errorFallback:m,children:S}){let p=n===void 0&&t===void 0;if(!p&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!p&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let b=r??o;if(p&&(typeof b!="string"||b.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);kt(R);let[y,U]=bt(),[h,C]=bt(null),T=sr(void 0),x=sr(null),[N,d]=bt(null);yt(f=>d({jwt:f}));let E=vt(),P=le("NEXT_PUBLIC_SESSION_TOKEN")??le("NEXT_PUBLIC_URUN_JWT"),I=Qe(),D=N!==null,q=I==="workos"&&!n&&!D&&!p,L=n??(I==="jwt"?P:void 0)??y?.token,A=D?N.jwt:L,F=s??le("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),j=q&&!A&&!E?.getAccessToken,$=t??y?.orgId,W=e??y?.gatewayUrl,J=p&&y===void 0,Q=p&&y!==void 0&&!W?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,X=j?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,H=h??Q??X,K=ar("NEXT_PUBLIC_URUN_TOKEN_URL",le("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??Rn,ae=ar("NEXT_PUBLIC_URUN_EVENTS_URL",le("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,G=or(async f=>{if(!f?.forceRefresh){let w=T.current;if(!w)return w;let B=En(w);if(B===null||B-Date.now()>Cn)return w}return(await(x.current??(x.current=(async()=>{try{let w=await ir(K);return T.current=w.token,U(w),w}finally{x.current=null}})()))).token},[K]),ee=or(async()=>A,[A]),ke=typeof A=="string"&&A.trim().length>0,te=q?E?.getAccessToken:p&&!D?G:ke?ee:void 0,me=Pt(g),re=Pt(l),Y=Pt(v),z=ur(()=>({appId:b,baseUrl:W??"",orgId:$??"",jwt:A,getAccessToken:q?E?.getAccessToken:p&&!D?G:void 0,authProvider:F,eventsUrl:ae,sessionKey:a,releaseOnLeave:c,audioPlayout:me,videoPlayout:re,sessionStats:Y,priority:D?"preempt":void 0}),[b,E,W,F,A,ae,$,a,c,me,re,Y,q,D,p,G]);return Pn(()=>{if(!p)return;let f=new AbortController;return C(null),(async()=>{try{let M=await ir(K,f.signal);T.current=M.token,U(M)}catch(M){if(f.signal.aborted)return;C(M instanceof Error?M:new Error(String(M)))}})(),()=>f.abort()},[p,K]),Ne(Be,{fallback:k,children:H?Tn(m,H):J?Ne("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ne(_e.Provider,{value:z,children:te?Ne(ht,{getAccessToken:te,children:S}):S})})}import{useContext as Un,useEffect as An,useMemo as cr,useReducer as Mn,useRef as Rt}from"react";import{App as _n}from"@urun-sh/core";function Nn(e,t){return`${e}:${JSON.stringify(t??{})}`}function In(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var Te=new Map;var Ct=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Et=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},Tt=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new Ct(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Et(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Ln(){let e=Un(_e);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=Mn(i=>i+1,0),r=Rt(new Map),o=Rt(new Map),n=Rt(null),s=cr(()=>_n(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return An(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=Te.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=Te.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let l=Te.get(u);!l||l.refCount!==0||(Te.delete(u),l.handle.disconnect())},0)))}n.current=a}},[]),cr(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=l=>{let v=Nn(u,l),R=r.current.get(v);if(R&&!R.disposed)return R;let k=In(e,u,l),m=Te.get(k);return m?.handle.disposed&&(m.disposeTimer&&clearTimeout(m.disposeTimer),Te.delete(k),o.current.get(k)===m&&o.current.delete(k),m=void 0),m?m.disposeTimer&&(clearTimeout(m.disposeTimer),m.disposeTimer=null):(m={handle:new Tt(s[u](l),t,e.eventsUrl),refCount:0,disposeTimer:null},Te.set(k,m)),o.current.get(k)!==m&&(o.current.set(k,m),m.handle.addNotifier(t),m.refCount+=1),r.current.set(v,m.handle),m.handle};return i.set(u,g),g}})},[e,s])}import{useCallback as wt,useEffect as On,useMemo as Vn,useRef as et,useState as xt}from"react";function Ie(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Dn(e){return e instanceof Error?e:new Error(String(e))}function Fn(e,t){let r=Vn(()=>Ie(e),[e]),[o,n]=xt(void 0),[s,i]=xt(null),[a,u]=xt(!1),c=et(t);c.current=t;let g=et(0),l=et(null),v=et(!0);On(()=>(v.current=!0,()=>{v.current=!1,l.current?.abort()}),[]);let R=wt(async S=>{l.current?.abort();let p=new AbortController;l.current=p;let b=++g.current,y=()=>v.current&&g.current===b;y()&&(u(!0),i(null));try{let U=await r.request(S,{...c.current,signal:p.signal});return y()&&(n(U),u(!1),c.current?.onSuccess?.(U)),U}catch(U){let h=Dn(U);throw y()&&(i(h),u(!1),c.current?.onError?.(h)),h}},[r]),k=wt(S=>{R(S).catch(()=>{})},[R]),m=wt(()=>{g.current++,l.current?.abort(),l.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:k,mutateAsync:R,data:o,error:s,isPending:a,reset:m}}import{useCallback as lr,useEffect as qn,useMemo as Hn,useRef as tt,useState as Ut}from"react";function dr(e){return e instanceof Error?e:new Error(String(e))}var Wn=e=>typeof e=="string"?e:String(e);function Bn(e,t){let r=Hn(()=>Ie(e),[e]),[o,n]=Ut(""),[s,i]=Ut(!1),[a,u]=Ut(null),c=tt(t);c.current=t;let g=tt(0),l=tt(null),v=tt(!0);qn(()=>(v.current=!0,()=>{v.current=!1,l.current?.cancel(),l.current=null}),[]);let R=lr(()=>{g.current++,l.current?.cancel(),l.current=null,v.current&&i(!1)},[]),k=lr(async m=>{l.current?.cancel();let S=++g.current,p=()=>v.current&&g.current===S,b=c.current,y=b?.parseChunk??Wn,U=b?.buildPayload??(P=>({prompt:P}));p()&&(n(""),u(null),i(!0));let{parseChunk:h,buildPayload:C,onFinish:T,onError:x,...N}=b??{},d="",E;try{E=r.requestStream(U(m),N),l.current=E}catch(P){let I=dr(P);p()&&(u(I),i(!1),b?.onError?.(I));return}try{for await(let P of E){if(g.current!==S)break;d+=y(P),p()&&n(d)}p()&&(i(!1),b?.onFinish?.(d))}catch(P){let I=dr(P);p()&&(u(I),i(!1),b?.onError?.(I))}finally{l.current===E&&(l.current=null)}},[r]);return{completion:o,complete:k,stop:R,isStreaming:s,error:a}}import{useCallback as pr,useEffect as jn,useMemo as Kn,useRef as Le,useState as rt}from"react";function mr(e){return e instanceof Error?e:new Error(String(e))}var $n=e=>typeof e=="string"?e:String(e),fr=0;function At(e){return fr+=1,`${e}-${fr}`}function Xn(e,t){let r=Kn(()=>Ie(e),[e]),[o,n]=rt(()=>(t?.initialMessages??[]).map(y=>({id:y.id??At("msg"),role:y.role,content:y.content}))),[s,i]=rt(""),[a,u]=rt(!1),[c,g]=rt(null),l=Le(t);l.current=t;let v=Le(o);v.current=o;let R=Le(s);R.current=s;let k=Le(0),m=Le(null),S=Le(!0);jn(()=>(S.current=!0,()=>{S.current=!1,m.current?.cancel(),m.current=null}),[]);let p=pr(()=>{k.current++,m.current?.cancel(),m.current=null,S.current&&u(!1)},[]),b=pr(async y=>{let U=y===void 0,h=(U?R.current:y)??"";if(!h.trim())return;m.current?.cancel();let T=++k.current,x=()=>S.current&&k.current===T,N=l.current,d=N?.parseChunk??$n,E={id:At("msg"),role:"user",content:h},P={id:At("msg"),role:"assistant",content:""},I=[...v.current,E].map(H=>({role:H.role,content:H.content})),D=[...v.current,E,P];v.current=D,n(D),U&&i(""),g(null),u(!0);let q=N?.buildPayload??(H=>({messages:H})),{initialMessages:L,parseChunk:A,buildPayload:F,onFinish:j,onError:$,...W}=N??{},J=H=>{n(K=>K.map(ae=>ae.id===P.id?{...ae,content:H}:ae))},Q="",X;try{X=r.requestStream(q(I),W),m.current=X}catch(H){let K=mr(H);x()&&(g(K),u(!1),N?.onError?.(K));return}try{for await(let H of X){if(k.current!==T)break;Q+=d(H),x()&&J(Q)}x()&&(u(!1),N?.onFinish?.({...P,content:Q}))}catch(H){let K=mr(H);x()&&(g(K),u(!1),N?.onError?.(K))}finally{m.current===X&&(m.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:b,stop:p,isStreaming:a,error:c}}import{useCallback as be,useEffect as gr,useMemo as Jn,useRef as Sr,useState as hr}from"react";import{createInputPresencePublisher as zn,INPUT_PRESENCE_DEFAULT_HZ as Gn,INPUT_PRESENCE_FIELD as Yn}from"@urun-sh/core";var Mt=[];function Zn(e,t={}){let{field:r=Yn,hz:o=Gn}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=Jn(()=>s?zn({awareness:{setLocalStateField:(h,C)=>s.setField(h,C)},field:r,hz:o}):null,[s,r,o]),a=Sr(null);a.current=i;let[u,c]=hr(!1),[g,l]=hr(Mt),v=Sr(!1);gr(()=>{if(i)return()=>i.dispose()},[i]);let R=be(()=>{let h=a.current;l(h?h.heldKeys():Mt)},[]),k=be(()=>{a.current?.clear(),l(Mt)},[]);gr(()=>{if(!n)return;let h=()=>!!n.pointerLockElement,C=()=>{if(h()){v.current=!1,c(!0);return}v.current||(c(!1),k())},T=P=>{h()&&(a.current?.keyDown(P.key),R())},x=P=>{a.current?.keyUp(P.key),R()},N=P=>{h()&&a.current?.movePointer(P.movementX,P.movementY)},d=P=>{h()&&a.current?.setButtons(P.buttons)},E=()=>{k()};return n.addEventListener("pointerlockchange",C),n.addEventListener("keydown",T),n.addEventListener("keyup",x),n.addEventListener("mousemove",N),n.addEventListener("mousedown",d),n.addEventListener("mouseup",d),n.defaultView?.addEventListener("blur",E),()=>{n.removeEventListener("pointerlockchange",C),n.removeEventListener("keydown",T),n.removeEventListener("keyup",x),n.removeEventListener("mousemove",N),n.removeEventListener("mousedown",d),n.removeEventListener("mouseup",d),n.defaultView?.removeEventListener("blur",E)}},[n,k,R]);let m=be(h=>{h.requestPointerLock?.()},[]),S=be(()=>{v.current=!0,c(!0)},[]),p=be(()=>{v.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),k()},[n,k]),b=be(h=>{a.current?.keyDown(h),R()},[R]),y=be(h=>{a.current?.keyUp(h),R()},[R]),U=be((h,C)=>{a.current?.movePointer(h,C)},[]);return{engage:m,engageTouch:S,release:p,engaged:u,heldKeys:g,pressKey:b,releaseKey:y,movePointer:U}}import{forwardRef as co,useEffect as Er,useImperativeHandle as lo,useMemo as po,useRef as st}from"react";import{createCameraWarp as mo}from"@urun-sh/core";import{forwardRef as oo,useCallback as Pe,useEffect as je,useImperativeHandle as so,useRef as ne,useState as yr}from"react";import{derivedLegRole as io}from"@urun-sh/core";var nt=null;function Qn(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function ot(){if(nt)return nt;let e=Qn();return e?(nt=new e,nt):null}function Oe(){let e=ot();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as eo,useContext as vr}from"react";import{jsx as no}from"react/jsx-runtime";var _t=eo(null);function to({session:e,children:t}){return no(_t.Provider,{value:e,children:t})}function de(){return vr(_t)}function ro(){let e=vr(_t);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{jsx as Cr,jsxs as uo}from"react/jsx-runtime";function ao(e,t){return e-t>>>0<2147483648}var kr=1e3;function br(...e){console.debug("[video]",...e)}function Pr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function Rr(e,t,r){return r?[r,t]:[e,t]}var Ve=oo(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:g,style:l,videoClassName:v,placeholder:R,poster:k,children:m,onTrack:S,onFirstFrame:p,frameMarker:b,onFrameMarkerReached:y,onFrameMarkerUnsupported:U,onUnlockChange:h}=t,C=de(),T=o??C,x=ne(null),N=ne(null),[d,E]=yr(!1),[P,I]=yr(!1),D=ne(!1),q=ne(null),L=ne(S);L.current=S;let A=ne(h);A.current=h;let F=ne(p);F.current=p;let j=ne(y);j.current=y;let $=ne(U);$.current=U;let W=ne(b??null);W.current=b??null;let J=Pe(f=>{q.current!==f&&(q.current=f,A.current?.(f))},[]),Q=ne(null),X=ne(null),H=Pe((f,M=!1)=>{if(!M&&f===Q.current||(Q.current=f,X.current?.(),X.current=null,D.current=!1,I(!1),!f))return;let w=x.current;if(!w)return;let B=W.current,oe=B?.rtpTimestamp??null,fe=!1,_=()=>{fe||(fe=!0,$.current?.())};B&&oe==null&&_();let ge=B!=null&&oe!=null,Ae=he=>{X.current?.(),X.current=null,D.current=!0,I(!0),F.current?.(),he&&j.current?.()};if(typeof w.requestVideoFrameCallback=="function"){let he=!1,O=0,V=(se,ie)=>{if(!he){if(ge){let ue=ie?.rtpTimestamp;if(typeof ue!="number"){_(),Ae(!1);return}if(!ao(ue,oe)){O=w.requestVideoFrameCallback(V);return}Ae(!0);return}Ae(!1)}};O=w.requestVideoFrameCallback(V),X.current=()=>{he=!0,w.cancelVideoFrameCallback?.(O)};return}ge&&_();let Se=()=>{let he=w.getVideoPlaybackQuality?.();(he?he.totalVideoFrames>0:w.readyState>=2&&w.videoWidth>0)&&Ae(!1)};w.addEventListener("loadeddata",Se),w.addEventListener("timeupdate",Se),w.addEventListener("playing",Se),X.current=()=>{w.removeEventListener("loadeddata",Se),w.removeEventListener("timeupdate",Se),w.removeEventListener("playing",Se)},Se()},[]);je(()=>()=>{X.current?.(),X.current=null},[]);let K=b==null?null:`${b.rtpTimestamp??""}|${b.ptsMs??""}`,ae=ne(K);je(()=>{if(ae.current===K||(ae.current=K,K==null))return;let f=Q.current;f&&H(f,!0)},[K,H]);let G=Pe(()=>{if(typeof MediaStream>"u")return null;N.current||(N.current=new MediaStream);let f=x.current;return f&&f.srcObject!==N.current&&(f.srcObject=N.current),N.current},[]),ee=Pe(f=>{let M=x.current;if(!M)return;let w=M.play();!w||typeof w.then!="function"||w.then(()=>{M.muted||J(!0)}).catch(B=>{if((B instanceof Error?B.name:String(B))==="NotAllowedError"&&!M.muted){br(`play() blocked pending a user gesture (${f})`),J(!1);return}br(`play() failed (${f})`,B)})},[J]),ke=Pe(()=>{let f=x.current;f&&(G(),!f.muted&&(ee("gesture"),Oe(),J(!0)))},[G,ee,J]),te=Pe(f=>{let M=G();if(M){for(let w of M.getVideoTracks())w!==f&&M.removeTrack(w);if(f&&!M.getVideoTracks().includes(f)){M.addTrack(f);let w=x.current;w&&(w.srcObject=M)}f&&ee("track-attach"),E(f!==null),H(f),L.current?.(f)}},[G,ee,H]),me=Pe(f=>{let M=G();if(M){for(let w of M.getAudioTracks())w!==f&&M.removeTrack(w);f&&!M.getAudioTracks().includes(f)&&M.addTrack(f),f&&ee("audio-attach")}},[G,ee]),re=Pe(f=>{x.current=f,f&&(a?(f.muted=!0,f.defaultMuted=!0,f.setAttribute("muted",""),q.current=null):(f.muted=!1,f.defaultMuted=!1,f.removeAttribute("muted")),f.setAttribute("playsinline",""),f.setAttribute("webkit-playsinline",""),G())},[G,a]);so(r,()=>({get element(){return x.current},get live(){return N.current?N.current.getVideoTracks().length>0:!1},get framed(){return D.current},unlock:ke,get unlocked(){return q.current===!0}}),[ke]);let Y=io(n)!==void 0;je(()=>{Y&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[Y,n]);let z=i!==void 0;return je(()=>{if(z){te(i??null);return}if(Y){te(null);return}if(!T)return;let f=Pr(T,Rr(n,"video")),M=()=>{let _=N.current;return _?_.getVideoTracks()[0]??null:null},w=_=>{if(_!==M()&&(te(_),_)){let ge=()=>{M()===_&&te(null)};_.addEventListener("ended",ge)}},B=f.track;B&&B.readyState==="live"&&w(B);let oe=f.on("track",_=>{_&&_.readyState!=="live"||w(_)}),fe=setInterval(()=>{let _=f.track;_&&_.readyState==="live"&&w(_)},kr);return()=>{oe(),clearInterval(fe)}},[T,n,Y,z,i,te]),je(()=>{if(z||!T||s===!1||Y)return;let f=Pr(T,Rr(n,"audio",s)),M=()=>{let _=N.current;return _?_.getAudioTracks()[0]??null:null},w=_=>{if(_!==M()&&(me(_),_)){let ge=()=>{M()===_&&me(null)};_.addEventListener("ended",ge)}},B=f.track;B&&B.readyState==="live"&&w(B);let oe=f.on("track",_=>{_&&_.readyState!=="live"||w(_)}),fe=setInterval(()=>{let _=f.track;_&&_.readyState==="live"&&w(_)},kr);return()=>{oe(),clearInterval(fe)}},[T,n,Y,s,z,me]),uo("div",{className:g,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":d?"true":"false","data-urun-video-framed":P?"true":"false",children:[Cr("video",{ref:re,className:v,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),d?null:R,k===void 0?null:Cr("div",{"data-urun-video-poster":"","aria-hidden":P||void 0,style:{position:"absolute",inset:0,...P?{opacity:0,pointerEvents:"none"}:null},children:k}),m]})});import{jsx as Tr,jsxs as So}from"react/jsx-runtime";var fo={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},go=co(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...g}=o??{},l=c!==void 0?c:typeof document<"u"?document:null,v=st(null),R=st(null),k=st(0),m=st(g);m.current=g;let S=po(()=>mo(m.current),[]);return lo(r,()=>({get video(){return v.current},get canvas(){return R.current},warp:S,get lastDrawTs(){return k.current}}),[S]),Er(()=>{if(!i)return;let p=0,b=0,y=null,U=C=>{typeof C.requestVideoFrameCallback=="function"&&(y=C,b=C.requestVideoFrameCallback(function T(){S.frameArrived(),b=C.requestVideoFrameCallback(T)}))},h=C=>{p=requestAnimationFrame(h);let T=R.current,x=v.current?.element??null;if(!T||!x||(x!==y&&(y&&b&&y.cancelVideoFrameCallback?.(b),U(x)),x.readyState<2))return;S.tick(C);let N=typeof devicePixelRatio=="number"?devicePixelRatio:1,d=Math.max(1,Math.round(T.clientWidth*N)),E=Math.max(1,Math.round(T.clientHeight*N));(T.width!==d||T.height!==E)&&(T.width=d,T.height=E);let P=T.getContext("2d");if(!P)return;let I=S.transform(),D=x.videoWidth||d,q=x.videoHeight||E,A=Math.max(d/D,E/q)*(1+a)*I.scale;P.setTransform(A,0,0,A,d/2+I.translateX*d,E/2+I.translateY*E),P.drawImage(x,-D/2,-q/2),k.current=C};return p=requestAnimationFrame(h),()=>{cancelAnimationFrame(p),y&&b&&y.cancelVideoFrameCallback?.(b)}},[i,a,S]),Er(()=>{if(!i||!u||!l)return;let p=()=>!!l.pointerLockElement,b=T=>{p()&&S.keyDown(T.key)},y=T=>S.keyUp(T.key),U=T=>{p()&&S.pointerDelta(T.movementX,T.movementY)},h=()=>{p()||S.clearKeys()},C=()=>S.clearKeys();return l.addEventListener("keydown",b),l.addEventListener("keyup",y),l.addEventListener("mousemove",U),l.addEventListener("pointerlockchange",h),l.defaultView?.addEventListener("blur",C),()=>{l.removeEventListener("keydown",b),l.removeEventListener("keyup",y),l.removeEventListener("mousemove",U),l.removeEventListener("pointerlockchange",h),l.defaultView?.removeEventListener("blur",C)}},[i,u,l,S]),i?So(Ve,{ref:v,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Tr("canvas",{ref:R,style:fo,"data-urun-warp":""}),n]}):Tr(Ve,{ref:v,...s,children:n})});var wr=new Map;function ho(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);wr.set(e,{component:t,schema:r})}function xr(e,t){let r=wr.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as yo,jsx as it}from"react/jsx-runtime";function vo({name:e,props:t,fallback:r}){let o=xr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?it(yo,{children:r}):it("div",{className:"urun-component-error",role:"alert",children:it("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return it(n,{...o.validatedProps})}import{z as Ke}from"zod";import{jsx as Nt,jsxs as Ur}from"react/jsx-runtime";var ko=Ke.object({step:Ke.number().min(0),total:Ke.number().min(1),label:Ke.string().optional(),variant:Ke.enum(["default","success","error"]).default("default")});function Ar(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function bo(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Ar(e);return Ur("div",{className:"urun-progress-card","data-variant":n,children:[o&&Nt("div",{className:"urun-progress-label",children:o}),Nt("div",{className:"urun-progress-bar",children:Nt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Ur("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as It}from"zod";import{jsx as Mr,jsxs as Eo}from"react/jsx-runtime";var Po=It.object({state:It.enum(["thinking","generating","idle","error"]),message:It.string().optional()}),Ro={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function _r(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??Ro[t]??t;return{state:t,message:n,isActive:o}}function Co(e){let{state:t,message:r,isActive:o}=_r(e);return Eo("span",{className:"urun-status-badge","data-state":t,children:[Mr("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Mr("span",{className:"urun-status-message",children:r})]})}import{useRef as Nr,useEffect as To}from"react";import{z as Lt}from"zod";import{jsx as Ir,jsxs as Uo}from"react/jsx-runtime";var wo=Lt.object({text:Lt.string(),streaming:Lt.boolean().default(!1)});function Lr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function xo(e){let{text:t,streaming:r}=Lr(e),o=Nr(null),n=Nr(0);return To(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Uo("div",{className:"urun-text-stream",children:[Ir("span",{ref:o,className:"urun-text-content"}),r&&Ir("span",{className:"urun-text-cursor"})]})}import{z as at}from"zod";import{jsx as Or,jsxs as _o}from"react/jsx-runtime";var Ao=at.object({src:at.string().url(),alt:at.string().optional(),caption:at.string().optional()});function Vr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function Mo(e){let{src:t,alt:r,caption:o}=Vr(e);return _o("figure",{className:"urun-image-frame",children:[Or("img",{className:"urun-image",src:t,alt:r}),o&&Or("figcaption",{className:"urun-image-caption",children:o})]})}import{z as Re}from"zod";import{jsx as Ot,jsxs as Lo}from"react/jsx-runtime";var No=Re.object({metrics:Re.array(Re.object({label:Re.string(),value:Re.union([Re.string(),Re.number()]),unit:Re.string().optional()}))});function Dr(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function Io(e){let{metrics:t}=Dr(e);return Ot("div",{className:"urun-metrics-panel",children:t.map((r,o)=>Lo("div",{className:"urun-metric-card",children:[Ot("div",{className:"urun-metric-label",children:r.label}),Ot("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{forwardRef as Oo}from"react";import{jsx as Do}from"react/jsx-runtime";var Vo=Oo(function(t,r){let{stream:o="image",...n}=t;return Do(Ve,{ref:r,stream:o,...n})});import{forwardRef as Fo,useCallback as De,useEffect as Vt,useImperativeHandle as qo,useRef as Fe}from"react";import{observePageLifecycle as Ho}from"@urun-sh/core";import{jsx as jo}from"react/jsx-runtime";var Wo=1e3,Fr=200;function Dt(...e){console.debug("[audio]",...e)}var ut=Fo(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,l=de(),v=o??l,R=Fe(null),k=Fe(null),m=Fe(null),S=Fe(null),p=Fe(u);p.current=u;let b=Fe(c);b.current=c;let y=De(d=>{m.current!==d&&(m.current=d,b.current?.(d))},[]),U=De(()=>{if(typeof MediaStream>"u")return null;k.current||(k.current=new MediaStream);let d=R.current;return d&&d.srcObject!==k.current&&(d.srcObject=k.current),k.current},[]),h=De(d=>{let E=R.current;if(!E)return;let P=E.play();!P||typeof P.then!="function"||P.then(()=>{E.muted||y(!0)}).catch(I=>{let D=I instanceof Error?I.name:String(I);if(D==="AbortError"){Dt(`play() aborted (${d}); retrying in ${Fr}ms`),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{S.current=null,h(`${d}:retry`)},Fr);return}if(D==="NotAllowedError"){Dt(`play() blocked pending a user gesture (${d})`),y(!1);return}Dt(`play() failed (${d})`,I)})},[y]),C=De(d=>{let E=U();if(E){for(let P of E.getAudioTracks())P!==d&&E.removeTrack(P);d&&!E.getAudioTracks().includes(d)&&E.addTrack(d),d&&h("track-attach"),p.current?.(d)}},[U,h]),T=De(()=>{let d=R.current;d&&(U(),d.muted=!1,h("gesture"),Oe(),y(!0))},[U,h,y]);qo(r,()=>({unlock:T,get unlocked(){return m.current===!0},get element(){return R.current}}),[T]);let x=De(d=>{R.current=d,d&&(d.setAttribute("playsinline",""),d.setAttribute("webkit-playsinline",""),U()),g?.(d)},[U,g]),N=s!==void 0;return Vt(()=>{if(N){C(s??null);return}if(!v)return;let d=v.stream(n),E=()=>{let L=k.current;return L?L.getAudioTracks()[0]??null:null},P=L=>{if(L!==E()&&(C(L),L)){let A=()=>{E()===L&&C(null)};L.addEventListener("ended",A)}},I=d.track;I&&I.readyState==="live"&&P(I);let D=d.on("track",L=>{L&&L.readyState!=="live"||P(L)}),q=setInterval(()=>{let L=d.track;L&&L.readyState==="live"&&P(L)},Wo);return()=>{D(),clearInterval(q)}},[v,n,N,s,C]),Vt(()=>Ho(()=>{Oe(),m.current===!0&&h("foreground")}),[h]),Vt(()=>()=>{S.current&&clearTimeout(S.current)},[]),jo("audio",{ref:x,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),Bo=ut;import{forwardRef as Ko,useCallback as qe,useEffect as qr,useImperativeHandle as $o,useRef as ye}from"react";import{observePageLifecycle as Xo,sessionFailureFromMediaError as Jo,sharedCaptureController as zo}from"@urun-sh/core";import{jsx as Yo}from"react/jsx-runtime";var Hr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function ct(...e){console.debug("[voice]",...e)}var lt=Ko(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=Hr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:l,onMicStream:v,onTrack:R,onUnlockChange:k,capture:m}=t,S=de(),p=o??S,b=ye(null),y=ye(null),U=ye(null),h=ye([]),C=ye(!1),T=ye(g);T.current=g;let x=ye(l);x.current=l;let N=ye(v);N.current=v;let d=qe(A=>{C.current!==A&&(C.current=A,T.current?.(A))},[]),E=qe(()=>{for(let A of h.current)A();h.current=[],U.current?.release(),U.current=null,y.current&&(y.current=null,N.current?.(null))},[]),P=qe(async()=>{let A=U.current;if(A){let W=await A.update(i);return y.current=A.stream,N.current?.(A.stream),W}let j=await(m??zo()).claim("audio",i);U.current=j,h.current=[j.onTrack((W,J)=>{y.current=J,N.current?.(J),C.current&&p?.stream(n).attach(W).catch(Q=>ct("mic re-attach after one-capture re-acquire failed",Q))}),j.onLost(W=>{U.current=null,h.current=[],y.current=null,N.current?.(null),d(!1),x.current?.(W)})],y.current=j.stream,N.current?.(j.stream);let $=j.track;if(!$)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return $},[m,i,p,n,d]),I=qe(async()=>{E(),d(!1),await p?.stream(n).detach().catch(()=>{})},[p,n,E,d]),D=qe(async()=>{if(!p)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");b.current?.unlock();let A;try{A=await P()}catch($){E();let W=Jo($,p.status);throw x.current?.(W),W}p.connect?.();let F;for(let $=1;$<=u;$++)try{await p.whenLive(a!==void 0?{timeout:a}:void 0),await p.stream(n).attach(A),d(!0);return}catch(W){F=W,ct(`start attempt ${$}/${u} failed`,W),$<u&&await new Promise(J=>setTimeout(J,c))}E(),d(!1);let j=F instanceof Error?F:new Error(String(F??"voice start failed"));throw x.current?.(j),j},[p,n,a,u,c,P,E,d]);$o(r,()=>({start:D,stop:I,unlock:()=>b.current?.unlock(),get active(){return C.current},get micStream(){return y.current},get audio(){return b.current}}),[D,I]);let q=ye(!1),L=qe(async()=>{if(!p||!C.current||q.current)return;let A=y.current?.getAudioTracks()[0]??null;if(A&&A.readyState==="live"){try{await p.stream(n).attach(A)}catch(F){ct("foreground mic re-assert failed (will retry on next pass)",F)}return}q.current=!0;try{let F=await P();await p.stream(n).attach(F)}catch(F){let j=F instanceof Error?F:new Error(String(F));ct("foreground mic re-acquire failed",j),x.current?.(j)}finally{q.current=!1}},[p,n,P]);return qr(()=>{let A=()=>{L()};return p&&typeof p.onRecovery=="function"?p.onRecovery(A):Xo(A)},[p,L]),qr(()=>E,[E]),s?Yo(ut,{ref:b,session:p,stream:n,onTrack:R,onUnlockChange:k}):null}),Go=lt;import{forwardRef as es,useEffect as ts,useImperativeHandle as rs,useRef as Wr,useState as ns}from"react";import{useEffect as Zo,useState as Qo}from"react";var Ft={level:0,speaking:!1};function qt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=Qo(Ft);return Zo(()=>{if(!e){i(Ft);return}let a=ot();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let l=new Uint8Array(g.fftSize),R=setInterval(()=>{g.getByteTimeDomainData(l);let k=0;for(let S=0;S<l.length;S++){let p=(l[S]-128)/128;k+=p*p}let m=Math.sqrt(k/l.length);i(S=>{let p=m>n;return Math.abs(S.level-m)<.005&&S.speaking===p?S:{level:m,speaking:p}})},o);return()=>{clearInterval(R),c.disconnect(),i(Ft)}},[e,r,o,n]),s}import{Fragment as as,jsx as dt,jsxs as us}from"react/jsx-runtime";var os={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},ss={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},is=es(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:l,capture:v}=t,R=de(),k=o??R,m=Wr(null),[S,p]=ns(null),b=Wr(l);b.current=l;let{level:y,speaking:U}=qt(a?S:null);return rs(r,()=>({start:()=>{let h=m.current;return h?h.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>m.current?.stop()??Promise.resolve(),get active(){return m.current?.active??!1},get micStream(){return m.current?.micStream??null}}),[]),ts(()=>{!i||!k||m.current?.start().catch(()=>{})},[i,k]),us(as,{children:[dt(lt,{ref:m,session:k,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...v!==void 0?{capture:v}:{},onActiveChange:c,onError:g,onMicStream:h=>{p(h),b.current?.(h)}}),a?dt("span",{className:u,style:os,"data-urun-mic":"","data-urun-mic-active":S?"true":"false","data-urun-mic-speaking":U?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(y*100)/100,children:dt("span",{style:ss,children:dt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(y*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as cs,sessionFailureFromMediaError as ls,sharedCaptureController as ds}from"@urun-sh/core";import{forwardRef as jr,useCallback as pe,useEffect as Ht,useImperativeHandle as ps,useRef as Z,useState as $e}from"react";import{jsx as Ce,jsxs as Br}from"react/jsx-runtime";var Kr={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Wt(...e){console.debug("[camera]",...e)}function ms(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function fs(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var $r=jr(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:l,visible:v=!1,className:R,videoClassName:k,onActiveChange:m,onError:S,onStream:p,onTrack:b,children:y,capture:U,flipControl:h="auto",flipControlClassName:C,onDevices:T}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let x=i?"user":a?"environment":u??"environment",N=de(),d=o??N,E=Z(null),P=Z(null),I=Z(null),D=Z([]),q=Z(null),L=Z(!1),A=Z(!1),F=Z(x),[j,$]=$e(x),[W,J]=$e(!1),[Q,X]=$e(null),[H,K]=$e(!1),[ae]=$e(ms),G=Z(m);G.current=m;let ee=Z(S);ee.current=S;let ke=Z(p);ke.current=p;let te=Z(b);te.current=b;let me=Z(T);me.current=T;let re=pe(O=>{L.current!==O&&(L.current=O,J(O),G.current?.(O))},[]);Ht(()=>{if(!W){X(null);return}let O=!1,V=()=>{fs().then(ie=>{O||(X(ie),ie&&me.current?.(ie))})};V();let se=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof se?.addEventListener=="function"?(se.addEventListener("devicechange",V),()=>{O=!0,se.removeEventListener?.("devicechange",V)}):()=>{O=!0}},[W]);let Y=pe(O=>{let V=E.current;V&&(V.muted=!0,V.defaultMuted=!0,V.setAttribute("muted",""),V.setAttribute("playsinline",""),V.setAttribute("webkit-playsinline",""),V.srcObject=O,O&&V.play()?.catch?.(se=>Wt("preview play() failed",se)))},[]),z=pe(()=>{A.current=!1,q.current?.(),q.current=null;for(let O of D.current)O();D.current=[],I.current?.release(),I.current=null,P.current&&(P.current=null,ke.current?.(null),te.current?.(null)),Y(null)},[Y]),f=pe((O,V)=>{q.current?.(),P.current=V,Y(V),ke.current?.(V);let se=()=>{P.current===V&&(Wt("camera track ended (device removed or permission revoked)"),z(),re(!1))};O.addEventListener("ended",se),q.current=()=>O.removeEventListener("ended",se)},[Y,z,re]),M=pe(async O=>{let V=n!==!1;if(V&&!d)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let se={...Kr,...s,facingMode:O},ie;try{let ue=I.current;if(ue)ie=await ue.update(se);else{let He=await(U??ds()).claim("video",se);if(I.current=He,D.current=[He.onTrack((We,un)=>{f(We,un),L.current&&(!V||!d||d.stream(n).attachVideo(We).then(()=>te.current?.(We)).catch(cn=>Wt("camera re-publish after one-capture re-acquire failed",cn)))}),He.onLost(We=>{I.current=null,D.current=[],z(),re(!1),ee.current?.(We)})],!He.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ie=He.track}}catch(ue){let Me=ls(ue,d?.status);throw ee.current?.(Me),Me}F.current=O,$(O),f(ie,I.current?.stream??new MediaStream([ie]));try{V&&d&&(d.connect?.(),await d.whenLive(l!==void 0?{timeout:l}:void 0),await d.stream(n).attachVideo(ie)),A.current=V?n:!1}catch(ue){z(),re(!1);let Me=ue instanceof Error?ue:new Error(String(ue));throw ee.current?.(Me),Me}te.current?.(ie),re(!0)},[d,n,s,l,U,f,z,re]),w=pe(O=>M(O?.facingMode??F.current),[M]),B=pe(async O=>{let V=A.current===n;L.current&&F.current===O&&V||await M(O)},[M,n]),oe=pe(()=>M(F.current==="environment"?"user":"environment"),[M]),fe=pe(async()=>{z(),re(!1),n!==!1&&await d?.stream(n).detachVideo().catch(()=>{})},[d,n,z,re]),_=pe(async O=>{let V=E.current;if(!V)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await cs(V,O)},[]);ps(r,()=>({start:w,stop:fe,flip:oe,setFacingMode:B,capturePhoto:_,get active(){return L.current},get facingMode(){return F.current},get stream(){return P.current},get element(){return E.current}}),[w,fe,oe,B,_]);let ge=Z(B);if(ge.current=B,Ht(()=>{c&&(n!==!1&&!d||ge.current(x).catch(()=>{}))},[c,d,x,n]),Ht(()=>z,[z]),!v)return null;let Ae=g==="auto"?j==="user":g,Se=W&&(h===!0||h==="auto"&&ae&&(Q?.length??0)>1),he=()=>{H||(K(!0),oe().catch(()=>{}).finally(()=>K(!1)))};return Br("div",{className:R,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":j,children:[Ce("video",{ref:E,className:k,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",...Ae?{transform:"scaleX(-1)"}:{}}}),Se?Ce("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:he,disabled:H,className:C,style:C?{opacity:H?.6:void 0}:{position:"absolute",right:16,bottom:"calc(env(safe-area-inset-bottom, 0px) + 16px)",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",width:44,height:44,borderRadius:9999,border:"1px solid rgba(255,255,255,0.25)",background:"rgba(0,0,0,0.5)",color:"#fff",cursor:"pointer",opacity:H?.6:1},children:Br("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:[Ce("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),Ce("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),Ce("path",{d:"M14.5 10.5v1.6h-1.6"}),Ce("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),Ce("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,y]})}),gs=jr(function({preview:t=!0,...r},o){return Ce($r,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Ss,normalizeReferenceImage as hs,referenceImageErrorMessage as vs}from"@urun-sh/core";import{useCallback as Xe,useEffect as ys,useRef as Bt,useState as Je}from"react";function ks(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=Je(null),[a,u]=Je(null),[c,g]=Je(!1),[l,v]=Je(null),[R]=Je(Ss),k=Bt(n);k.current=n;let m=Bt(null),S=Bt(0),p=Xe(C=>{m.current&&URL.revokeObjectURL(m.current),m.current=C?URL.createObjectURL(new Blob([C.bytes],{type:C.type})):null,u(m.current),i(C),k.current?.(C)},[]);ys(()=>()=>{S.current++,m.current&&URL.revokeObjectURL(m.current),m.current=null},[]);let b=Xe(async C=>{let T=++S.current;g(!0),v(null);try{let x=await C();if(S.current!==T)return;p(x)}catch(x){if(S.current!==T)return;v(vs(x))}finally{S.current===T&&g(!1)}},[p]),y=Xe(C=>b(()=>hs(C,{maxSize:t,type:r,quality:o,source:"file"})),[b,t,r,o]),U=Xe(C=>b(()=>C.capturePhoto({maxSize:t,type:r,quality:o})),[b,t,r,o]),h=Xe(()=>{S.current++,v(null),g(!1),p(null)},[p]);return{reference:s,previewUrl:a,pick:y,capture:U,clear:h,busy:c,error:l,cameraAvailable:R}}import{useEffect as bs,useState as Ps}from"react";function Rs(e,t){let[r,o]=Ps(null);return bs(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as Us}from"react";import{useEffect as ws,useMemo as xs}from"react";import{createStore as Cs}from"zustand/vanilla";import{useStore as Es}from"zustand";var Ts=()=>{};function jt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Cs(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Ts,u=(c=>Es(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function ze(e,t){let r=xs(()=>jt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return ws(()=>r.bind(),[r]),r}function As(e,t,r){let n=ze(e,t)(r??(a=>a)),s=Us(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as Ms,useState as _s}from"react";var we=200;function Ee(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Ge(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Kt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function $t(e,t,r={}){let o=r.cap??200,[n,s]=_s([]);return Ms(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>Ee(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as pt,jsxs as Ye}from"react/jsx-runtime";function Ns({session:e,name:t,cap:r,className:o}){let n=$t(e,t,{cap:r});return Ye("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[Ye("div",{className:"urun-stream-tail-meta",children:[pt("code",{children:t}),Ye("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),pt("div",{className:"urun-stream-tail-log",children:n.length===0?Ye("span",{className:"urun-stream-tail-empty",children:["Waiting for ",pt("code",{children:t})," messages\u2026"]}):n.map((s,i)=>Ye("div",{className:"urun-stream-tail-line",children:[pt("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Ge(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as Is,useState as Xr}from"react";import{jsx as xe,jsxs as mt}from"react/jsx-runtime";function ft({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=Xr(""),[i,a]=Xr(null),u=Is(()=>{let c=Kt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return mt("div",{className:"urun-doc-patch",children:[xe("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),mt("div",{className:"urun-doc-patch-actions",children:[xe("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?xe("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function Ls({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=ze(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return mt("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[mt("div",{className:"urun-doc-panel-meta",children:[xe("code",{children:t}),xe("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),xe("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?xe(ft,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as Os,useState as Vs}from"react";import{jsx as Ze,jsxs as zr}from"react/jsx-runtime";function Jr(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Ds({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=Vs([]);return Os(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>Ee(u,{at:Date.now(),direction:"in",text:Jr(Ge(a))},r))}):void 0),[e,t,r]),zr("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[Ze(ft,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>Ee(u,{at:Date.now(),direction:"out",text:Jr(a)},r))}}),Ze("div",{className:"urun-control-sender-log",children:n.length===0?Ze("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>zr("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[Ze("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",Ze("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as Fs,useState as qs}from"react";import{jsx as gt,jsxs as Ws}from"react/jsx-runtime";function Hs({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=qs([]),a=t.join(","),u=r.join(",");return Fs(()=>{if(i([]),!e)return;let c=(l,v)=>i(R=>Ee(R,{at:Date.now(),kind:l,text:v},o)),g=[];g.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of t){let v=e.stream(l);g.push(v.on("track",R=>c("track",`${l}: ${R?"track arrived":"track ended"}`)))}for(let l of r){let v=e.doc(l);g.push(v.on("change",()=>c("doc",`${l} changed`)))}return()=>g.forEach(l=>l())},[e,a,u,o]),gt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?gt("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,g)=>Ws("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[gt("span",{className:"urun-event-spine-kind",children:c.kind})," ",gt("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}import{describeSessionPhase as ni,isWakingPhase as oi}from"@urun-sh/core";import{useEffect as Bs,useState as js}from"react";function ce(e){let[t,r]=js(e?.phase??null);return Bs(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as zs}from"@urun-sh/core";import{useEffect as Ks,useRef as $s,useState as Xs}from"react";import{isWakingPhase as Js}from"@urun-sh/core";function Xt(e){let t=ce(e),r=Js(t?.name),o=$s(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=Xs(s);return Ks(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as Gs,jsx as Gr,jsxs as Yr}from"react/jsx-runtime";function Jt({session:e,render:t,className:r}){let o=Xt(e);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:t?t(o):Yr(Gs,{children:[Gr("span",{className:"urun-session-waking-label",children:zs(o.phase)})," ",Yr("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as Qs,useState as ei}from"react";import{useEffect as Zr,useRef as Ys,useState as Qr}from"react";var Zs={event:null,elapsedMs:0};function zt(e,t){let[r,o]=Qr(null),n=Ys(0);Zr(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=Qr(0);return Zr(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:Zs}import{jsx as en,jsxs as tn}from"react/jsx-runtime";var ti={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 ri(e){let[t,r]=ei(!1);return Qs(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function Gt({session:e,stream:t,videoElement:r,render:o,className:n}){let s=zt(e,t),i=ri(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return en("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):tn("div",{className:"urun-activation-overlay-card",children:[en("span",{className:"urun-activation-overlay-copy",children:a.hint??ti[u]})," ",tn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Ue,jsxs as Yt}from"react/jsx-runtime";var si={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function ii({session:e,className:t}){let r=ce(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return Yt("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Ue("span",{className:"urun-session-status-dot","data-phase":o}),Ue("span",{className:"urun-session-status-label",children:si[o]}),n?Ue("span",{className:"urun-session-status-detail",children:n}):null]})}function ai({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=ce(e);if(s?.name==="live")return Yt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Ue(Gt,{session:e})]});let i=r?r(s):Ue("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&oi(s.name)?Ue(Jt,{session:e}):s&&s.name!=="idle"?ni(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return Yt("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Ue("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as ui,useState as ci}from"react";import{jsx as pi}from"react/jsx-runtime";function rn(e){return ce(e)?.endsAt??null}function li(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function di({session:e,urgentMs:t=6e4,className:r}){let n=rn(e)?.getTime()??null,[s,i]=ci(()=>n===null?null:Math.max(0,n-Date.now()));if(ui(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=li(s);return pi("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{jsx as nn,jsxs as gi}from"react/jsx-runtime";var mi=new Set(["expired","ended","error"]);function fi({session:e,onNewSession:t,children:r,className:o}){let n=ce(e);if(!n||!mi.has(n.name))return null;let s=r?r(n):nn("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 gi("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?nn("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as on,useMemo as Si,useState as sn}from"react";import{jsx as St,jsxs as yi}from"react/jsx-runtime";function Zt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function an(e){let t=Si(()=>e?e.doc("control"):null,[e]),[r,o]=sn(()=>t?Zt(t.get("idle")):null);return on(()=>{if(!t){o(null);return}return o(Zt(t.get("idle"))),t.on("change",()=>o(Zt(t.get("idle"))))},[t]),r}function hi(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function vi({session:e,onStillHere:t,className:r}){let o=an(e),n=o?.deadlineEpochS??null,[s,i]=sn(null);if(on(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return St("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:yi("div",{className:"urun-idle-warning-card",children:[St("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),St("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${hi(s)} due to inactivity.`:"This session will end soon due to inactivity."}),St("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as ki,useEffect as bi,useState as Pi}from"react";import{prewake as Ri}from"@urun-sh/core";function Ci(e){let t=ki(_e),[r,o]=Pi(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,l=t?.authProvider;return bi(()=>{if(!a||!u||!n||!s)return;let v=!1,R=()=>{Ri({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:l}).then(m=>{v||o(m)}).catch(()=>{})};R();let k=setInterval(R,Math.max(1,i)*1e3);return()=>{v=!0,clearInterval(k)}},[n,s,i,a,u,c,g,l]),r}import{useEffect as Ei,useState as Ti}from"react";function wi(e){let[t,r]=Ti(null);return Ei(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as Wl,isWakingPhase as Bl}from"@urun-sh/core";export{ut as Audio,$r as Camera,vo as ComponentRenderer,Kr as DEFAULT_CAMERA_CONSTRAINTS,we as DEFAULT_LOG_CAP,Hr as DEFAULT_VOICE_CONSTRAINTS,ft as DocPatchForm,Vo as Image,Mo as ImageFrame,Ao as ImageFrameSchema,Io as MetricsPanel,No as MetricsPanelSchema,is as Mic,vn as OPERATOR_CHORD_LABEL,hn as OPERATOR_TOKEN_STORAGE_KEY,bo as ProgressCard,ko as ProgressCardSchema,go as ReprojectedVideo,to as Session,Co as StatusBadge,Po as StatusBadgeSchema,xo as TextStream,wo as TextStreamSchema,Gt as UrunActivationOverlay,Bo as UrunAudio,ht as UrunAuthProvider,gs as UrunCamera,Ds as UrunControlSender,Ls as UrunDocPanel,Be as UrunErrorBoundary,Hs as UrunEventSpine,vi as UrunIdleWarning,ln as UrunJwtProvider,wn as UrunProvider,di as UrunSessionClock,fi as UrunSessionEnded,ai as UrunSessionGate,ii as UrunSessionStatus,Jt as UrunSessionWaking,Ns as UrunStreamTail,Go as UrunVoice,Ve as Video,lt as Voice,Qe as authMode,jt as createDocStore,Wl as describeSessionPhase,Ge as formatPayload,ot as getUrunAudioContext,Bl as isWakingPhase,Kt as parseJsonObject,Ee as pushCapped,nr as readOperatorToken,ho as registerComponent,Oe as resumeUrunAudioContext,le as urunPublicEnv,zt as useActivation,Ln as useApp,Xn as useChat,Bn as useCompletion,kt as useConfirmOnLeave,ze as useDocStore,Vr as useImageFrame,Zn as useInputPresence,Dr as useMetricsPanel,yt as useOperatorOverride,Ar as useProgressCard,ks as useReferenceImage,Fn as useRequest,ro as useSession,As as useSessionDoc,rn as useSessionEndsAt,an as useSessionIdle,ce as useSessionPhase,wi as useSessionStats,Rs as useSessionTrack,Xt as useSessionWake,_r as useStatusBadge,$t as useStreamMessages,Lr as useTextStream,qt as useUrunAudioLevel,vt as useUrunAuth,Ci as useUrunPrewake,fn as usesWorkOSAuth};
|
|
2
|
+
import{a as bt,b as kn,c as Rt}from"./chunk-WF2OBDSX.mjs";import{useCallback as cr,useEffect as _n,useMemo as mr,useRef as lr,useState as Et}from"react";import{Component as bn}from"react";import{jsx as or,jsxs as Rn}from"react/jsx-runtime";var Ke=class extends bn{constructor(t){super(t),this.state={error:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,r){console.error("[urun] Error caught by UrunErrorBoundary:",t,r)}render(){if(this.state.error){let{fallback:t}=this.props;return typeof t=="function"?t(this.state.error):t||Rn("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:[or("p",{style:{margin:0,fontWeight:600},children:"Connection interrupted"}),or("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:"Reconnecting automatically."})]})}return this.props.children}};import{createContext as Tn}from"react";var Le=Tn(null);function ye(e){return e&&e.trim()?e.trim():void 0}function de(e){switch(e){case"NEXT_PUBLIC_AUTH_MODE":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_MODE:void 0);case"NEXT_PUBLIC_AUTH_ENABLED":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_AUTH_ENABLED:void 0);case"NEXT_PUBLIC_SESSION_AUTH_PROVIDER":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_AUTH_PROVIDER:void 0);case"NEXT_PUBLIC_SESSION_TOKEN":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_SESSION_TOKEN:void 0);case"NEXT_PUBLIC_URUN_JWT":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_JWT:void 0);case"NEXT_PUBLIC_URUN_TOKEN_URL":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_TOKEN_URL:void 0);case"NEXT_PUBLIC_URUN_EVENTS_URL":return ye(typeof process<"u"?process.env?.NEXT_PUBLIC_URUN_EVENTS_URL:void 0);case"VERCEL_ENV":return ye(typeof process<"u"?process.env?.VERCEL_ENV:void 0);default:return ye(typeof process<"u"?process.env?.[e]:void 0)}}function rt(){let e=de("NEXT_PUBLIC_AUTH_MODE")?.toLowerCase();return e==="jwt"||e==="customer-jwt"||e==="test-jwt"?"jwt":e==="workos"||de("VERCEL_ENV")==="production"?"workos":de("NEXT_PUBLIC_AUTH_ENABLED")==="false"?"jwt":"workos"}function Pn(){return rt()==="workos"}import{useEffect as En,useRef as xn}from"react";var Cn="urun.operator_token",ir=null,sr="op",wn="\u2318\u21E7\u23CE (Ctrl+Shift+Enter)";function ar(){return typeof window<"u"}function ur(){return ir}function Un(){if(!ar())return null;let e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;let t=new URLSearchParams(e),r=t.get(sr);if(!r)return null;ir=r,t.delete(sr);let o=t.toString(),n=window.location.pathname+window.location.search+(o?`#${o}`:"");try{window.history.replaceState(null,"",n)}catch{}return r}function An(e){return(e.metaKey||e.ctrlKey)&&e.shiftKey&&!e.altKey&&e.key==="Enter"}function Tt(e){let t=xn(e);t.current=e,En(()=>{if(!ar())return;Un();let r=o=>{if(!An(o))return;let n=ur();n&&(o.preventDefault(),o.stopPropagation(),t.current(n))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{useEffect as Mn}from"react";function Pt(e=!0){Mn(()=>{if(!e||typeof window>"u"||typeof window.addEventListener!="function")return;let t=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",t),()=>window.removeEventListener("beforeunload",t)},[e])}import{jsx as Ie,jsxs as Vn}from"react/jsx-runtime";var Nn="/api/urun-token",Ln=1e4;function In(e){let t=e.split(".")[1];if(!t)return null;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(o)).exp;return typeof s=="number"&&Number.isFinite(s)?s*1e3:null}catch{return null}}async function dr(e,t){let r=await fetch(e,{method:"POST",signal:t});if(!r.ok)throw new Error(`[urun] token endpoint ${e} answered ${r.status}`);let o=await r.json(),n=typeof o.token=="string"?o.token:"",s=typeof o.orgId=="string"?o.orgId:"";if(!n||!s)throw new Error(`[urun] token endpoint ${e} returned no { token, orgId } \u2014 is it createTokenRoute() from @urun-sh/next?`);return{token:n,orgId:s,gatewayUrl:typeof o.gatewayUrl=="string"?o.gatewayUrl:void 0}}function pr(e,t){if(t===void 0)return;let r;try{r=new URL(t).hostname}catch{throw new Error(`[urun] ${e} is not a valid URL: ${t}`)}if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`[urun] ${e} must point at a loopback endpoint \u2014 the CLI launcher (urun dev/demo) is this variable's only legitimate producer and it must never be set on a deployed site. Refusing ${t}.`);return t}function xt(e){let t=e===void 0?void 0:JSON.stringify(e);return mr(()=>e,[t])}function On(e,t){return typeof e=="function"?e(t):e!==void 0?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:[Ie("p",{style:{margin:0,fontWeight:600},children:"Sign-in failed"}),Ie("p",{style:{margin:"6px 0 0",color:"#4b5563"},children:t.message})]})}function Dn({baseUrl:e,orgId:t,app:r,appId:o,jwt:n,authProvider:s,eventsUrl:i,sessionKey:a,tokenEndpoint:u,releaseOnLeave:c,audioPlayout:g,videoPlayout:l,sessionStats:y,confirmOnLeave:b=!1,fallback:R,errorFallback:f,children:v}){let d=n===void 0&&t===void 0;if(!d&&(typeof t!="string"||t.trim().length===0))throw new Error("[urun] <UrunProvider> requires a non-empty orgId \u2014 set your org id deployment env var (e.g. NEXT_PUBLIC_SESSION_TENANT_ID) and pass it through the provider (or pass NEITHER orgId NOR jwt to let the provider mint from its tokenEndpoint).");if(!d&&(typeof e!="string"||e.trim().length===0))throw new Error("[urun] <UrunProvider> requires baseUrl when orgId/jwt are passed explicitly (self-mint mode reads it from the token endpoint instead).");let x=r??o;if(d&&(typeof x!="string"||x.trim().length===0))throw new Error(`[urun] <UrunProvider> requires app \u2014 hardcode your app name, mirroring the backend's App("..."): <UrunProvider app="rolling-sink">.`);Pt(b);let[S,k]=Et(),[m,T]=Et(null),P=lr(void 0),C=lr(null),[A,p]=Et(null);Tt(h=>p({jwt:h}));let w=Rt(),E=de("NEXT_PUBLIC_SESSION_TOKEN")??de("NEXT_PUBLIC_URUN_JWT"),L=rt(),V=A!==null,H=L==="workos"&&!n&&!V&&!d,I=n??(L==="jwt"?E:void 0)??S?.token,M=V?A.jwt:I,F=s??de("NEXT_PUBLIC_SESSION_AUTH_PROVIDER"),j=H&&!M&&!w?.getAccessToken,$=t??S?.orgId,W=e??S?.gatewayUrl,J=d&&S===void 0,Q=d&&S!==void 0&&!W?new Error("[urun] the token endpoint returned no gatewayUrl and no baseUrl prop was passed \u2014 upgrade the route to createTokenRoute() from @urun-sh/next (which introspects it from URUN_API_KEY) or pass baseUrl explicitly."):null,X=j?new Error('[urun] <UrunProvider> resolved authMode()="workos" but no auth context is mounted: there is no <UrunWorkOSProvider> (or <UrunAuthProvider>) ancestor supplying getAccessToken, and no jwt prop was passed, so no session token can be obtained. Note NEXT_PUBLIC_SESSION_TOKEN and NEXT_PUBLIC_URUN_JWT are IGNORED in workos mode, so setting them will not help. Either mount UrunWorkOSProvider from @urun-sh/react/next-workos, or select jwt mode with NEXT_PUBLIC_AUTH_MODE=jwt (or NEXT_PUBLIC_AUTH_ENABLED=false) and supply a token.'):null,q=m??Q??X,K=pr("NEXT_PUBLIC_URUN_TOKEN_URL",de("NEXT_PUBLIC_URUN_TOKEN_URL"))??u??Nn,ue=pr("NEXT_PUBLIC_URUN_EVENTS_URL",de("NEXT_PUBLIC_URUN_EVENTS_URL"))??i,G=cr(async h=>{if(!h?.forceRefresh){let U=P.current;if(!U)return U;let B=In(U);if(B===null||B-Date.now()>Ln)return U}return(await(C.current??(C.current=(async()=>{try{let U=await dr(K);return P.current=U.token,k(U),U}finally{C.current=null}})()))).token},[K]),ee=cr(async()=>M,[M]),be=typeof M=="string"&&M.trim().length>0,te=H?w?.getAccessToken:d&&!V?G:be?ee:void 0,fe=xt(g),re=xt(l),Y=xt(y),z=mr(()=>({appId:x,baseUrl:W??"",orgId:$??"",jwt:M,getAccessToken:H?w?.getAccessToken:d&&!V?G:void 0,authProvider:F,eventsUrl:ue,sessionKey:a,releaseOnLeave:c,audioPlayout:fe,videoPlayout:re,sessionStats:Y,priority:V?"preempt":void 0}),[x,w,W,F,M,ue,$,a,c,fe,re,Y,H,V,d,G]);return _n(()=>{if(!d)return;let h=new AbortController;return T(null),(async()=>{try{let _=await dr(K,h.signal);P.current=_.token,k(_)}catch(_){if(h.signal.aborted)return;T(_ instanceof Error?_:new Error(String(_)))}})(),()=>h.abort()},[d,K]),Ie(Ke,{fallback:R,children:q?On(f,q):J?Ie("div",{role:"status","aria-live":"polite",children:"Signing in..."}):Ie(Le.Provider,{value:z,children:te?Ie(bt,{getAccessToken:te,children:v}):v})})}import{useContext as Fn,useEffect as Hn,useMemo as fr,useReducer as qn,useRef as Ct}from"react";import{App as Wn}from"@urun-sh/core";function Bn(e,t){return`${e}:${JSON.stringify(t??{})}`}function jn(e,t,r){return JSON.stringify({appId:e.appId,baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionKey:e.sessionKey,priority:e.priority,fnName:t,args:r??{}})}var we=new Map;var wt=class{constructor(t,r){this._doc=t;this._notify=r;this._unsubscribeChange=this._doc.on("change",()=>this._notify())}_doc;_notify;_unsubscribeChange;get(t,r){return this._doc.get(t,r)}set(t){this._doc.set(t),this._notify()}on(t,r){return this._doc.on(t,o=>r(o))}get synced(){return this._doc.synced}onSynced(t){return this._doc.onSynced(()=>{t(),this._notify()})}onConnectionState(t){return this._doc.onConnectionState?this._doc.onConnectionState(r=>{t(r),this._notify()}):(t({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}text(t){let r=this._doc.text(t),o=this._notify;return{append(n){r.append(n),o()},toString:()=>r.toString(),get length(){return r.length},on:(n,s)=>r.on(n,i=>{s(i),o()})}}dispose(){this._unsubscribeChange()}},Ut=class{constructor(t,r){this._stream=t;this._notify=r;this._unsubscribeTrack=this._stream.on("track",()=>this._notify())}_stream;_notify;_unsubscribeTrack;get track(){return this._stream.track}attach(t){return this._stream.attach(t)}attachVideo(t){return this._stream.attachVideo(t)}detach(){return this._stream.detach()}detachVideo(){return this._stream.detachVideo()}seek(t){return this._stream.seek(t)}chunks(t){return this._stream.chunks(t)}onSeeked(t){return this._stream.onSeeked(t)}on(t,r){return this._stream.on(t,r)}messages(){return this._stream.messages()}emit(t,r){return this._stream.emit(t,r)}dispose(){this._unsubscribeTrack()}},At=class{constructor(t,r,o){this._session=t;this._notifiers.add(r),this._unsubscribePhase=this._session.onPhase(()=>this._notifyAll()),o&&this._attachReporter(o)}_session;_docs=new Map;_streams=new Map;_unsubscribePhase;_unsubscribeReporterDiagnostic=null;_notifiers=new Set;_disposed=!1;get disposed(){return this._disposed}_attachReporter(t){let r=!1,o=!1,n=a=>{fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{o||(o=!0,console.debug("[urun] unable to forward session events"))})};this._unsubscribeReporterDiagnostic=this._session.onDiagnostic(n);let s=this._session.onPhase(a=>{if(a.name==="error"||a.name==="expired"){let u=a.error,c=u?.reason??(a.name==="expired"?`session ${this._session.id} expired`:`session ${this._session.id} entered the error phase`);n({level:"error",kind:"phase-error",message:c,detail:{sessionId:this._session.id,code:u?.code,kind:u?.kind,httpStatus:u?.httpStatus}})}else a.name==="live"&&!r&&(r=!0,n({level:"info",kind:"session-live",message:`session ${this._session.id} live`}))}),i=this._unsubscribeReporterDiagnostic;this._unsubscribeReporterDiagnostic=()=>{i(),s()}}addNotifier(t){this._notifiers.add(t)}removeNotifier(t){this._notifiers.delete(t)}_notifyAll(){for(let t of this._notifiers)t()}get id(){return this._session.id}get mediaTransport(){return this._session.mediaTransport}get phase(){return this._session.phase}get status(){return this._session.status}get endsAt(){return this._session.endsAt}onPhase(t){return this._session.onPhase(t)}onDiagnostic(t){return this._session.onDiagnostic(t)}onStats(t){return this._session.onStats?this._session.onStats(t):()=>{}}whenLive(t){return this._session.whenLive(t)}recover(){this._session.recover()}onRecovery(t){return this._session.onRecovery(t)}request(t,r){return this._session.request(t,r)}requestStream(t,r){return this._session.requestStream(t,r)}complete(t,r){return this._session.complete(t,r)}get recordings(){return this._session.recordings}get artifacts(){return this._session.artifacts}get presence(){return this._session.presence}touch(){this._session.touch()}doc(t){let r=this._docs.get(t);return r||(r=new wt(this._session.doc(t),()=>this._notifyAll()),this._docs.set(t,r)),r}stream(t){let r=this._streams.get(t);return r||(r=new Ut(this._session.stream(t),()=>this._notifyAll()),this._streams.set(t,r)),r}async end(){let t=await this._session.end();return this._disposeHandle(),t}disconnect(){this._disposeHandle(),this._session.disconnect()}_disposeHandle(){this._disposed=!0;for(let t of this._docs.values())t.dispose();for(let t of this._streams.values())t.dispose();this._docs.clear(),this._streams.clear(),this._unsubscribePhase(),this._unsubscribeReporterDiagnostic?.(),this._notifyAll(),this._notifiers.clear()}};function Kn(){let e=Fn(Le);if(!e)throw new Error("useApp must be used within <UrunProvider>");if(!e.appId)throw new Error('useApp requires <UrunProvider appId="...">');let[,t]=qn(i=>i+1,0),r=Ct(new Map),o=Ct(new Map),n=Ct(null),s=fr(()=>Wn(e.appId,{baseUrl:e.baseUrl,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,sessionKey:e.sessionKey,releaseOnLeave:e.releaseOnLeave,priority:e.priority,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats}),[e.appId,e.baseUrl,e.orgId,e.jwt,e.getAccessToken,e.authProvider,e.sessionKey,e.releaseOnLeave,e.priority,e.audioPlayout,e.videoPlayout,e.sessionStats]);return Hn(()=>{let i=n.current;if(i){n.current=null;for(let[a,u]of i){let c=we.get(a);c===u&&o.current.get(a)===u&&(c.disposeTimer&&(clearTimeout(c.disposeTimer),c.disposeTimer=null),c.handle.addNotifier(t),c.refCount+=1)}}return()=>{let a=new Map;for(let[u,c]of o.current){let g=we.get(u);g===c&&(g.handle.removeNotifier(t),g.refCount=Math.max(0,g.refCount-1),a.set(u,g),g.refCount===0&&(g.disposeTimer=setTimeout(()=>{let l=we.get(u);!l||l.refCount!==0||(we.delete(u),l.handle.disconnect())},0)))}n.current=a}},[]),fr(()=>{let i=new Map;return new Proxy({},{get(a,u){if(typeof u!="string")return;let c=i.get(u);if(c)return c;let g=l=>{let y=Bn(u,l),b=r.current.get(y);if(b&&!b.disposed)return b;let R=jn(e,u,l),f=we.get(R);return f?.handle.disposed&&(f.disposeTimer&&clearTimeout(f.disposeTimer),we.delete(R),o.current.get(R)===f&&o.current.delete(R),f=void 0),f?f.disposeTimer&&(clearTimeout(f.disposeTimer),f.disposeTimer=null):(f={handle:new At(s[u](l),t,e.eventsUrl),refCount:0,disposeTimer:null},we.set(R,f)),o.current.get(R)!==f&&(o.current.set(R,f),f.handle.addNotifier(t),f.refCount+=1),r.current.set(y,f.handle),f.handle};return i.set(u,g),g}})},[e,s])}import{useCallback as Mt,useEffect as $n,useMemo as Xn,useRef as nt,useState as _t}from"react";function Oe(e){let t=e;if(!t||typeof t.request!="function"||typeof t.requestStream!="function")throw new Error("This session does not support request/requestStream. Upgrade @urun-sh/core to a version that ships the request/response primitive.");return t}function Jn(e){return e instanceof Error?e:new Error(String(e))}function zn(e,t){let r=Xn(()=>Oe(e),[e]),[o,n]=_t(void 0),[s,i]=_t(null),[a,u]=_t(!1),c=nt(t);c.current=t;let g=nt(0),l=nt(null),y=nt(!0);$n(()=>(y.current=!0,()=>{y.current=!1,l.current?.abort()}),[]);let b=Mt(async v=>{l.current?.abort();let d=new AbortController;l.current=d;let x=++g.current,S=()=>y.current&&g.current===x;S()&&(u(!0),i(null));try{let k=await r.request(v,{...c.current,signal:d.signal});return S()&&(n(k),u(!1),c.current?.onSuccess?.(k)),k}catch(k){let m=Jn(k);throw S()&&(i(m),u(!1),c.current?.onError?.(m)),m}},[r]),R=Mt(v=>{b(v).catch(()=>{})},[b]),f=Mt(()=>{g.current++,l.current?.abort(),l.current=null,n(void 0),i(null),u(!1)},[]);return{mutate:R,mutateAsync:b,data:o,error:s,isPending:a,reset:f}}import{useCallback as gr,useEffect as Gn,useMemo as Yn,useRef as ot,useState as Nt}from"react";function Sr(e){return e instanceof Error?e:new Error(String(e))}var Zn=e=>typeof e=="string"?e:String(e);function Qn(e,t){let r=Yn(()=>Oe(e),[e]),[o,n]=Nt(""),[s,i]=Nt(!1),[a,u]=Nt(null),c=ot(t);c.current=t;let g=ot(0),l=ot(null),y=ot(!0);Gn(()=>(y.current=!0,()=>{y.current=!1,l.current?.cancel(),l.current=null}),[]);let b=gr(()=>{g.current++,l.current?.cancel(),l.current=null,y.current&&i(!1)},[]),R=gr(async f=>{l.current?.cancel();let v=++g.current,d=()=>y.current&&g.current===v,x=c.current,S=x?.parseChunk??Zn,k=x?.buildPayload??(E=>({prompt:E}));d()&&(n(""),u(null),i(!0));let{parseChunk:m,buildPayload:T,onFinish:P,onError:C,...A}=x??{},p="",w;try{w=r.requestStream(k(f),A),l.current=w}catch(E){let L=Sr(E);d()&&(u(L),i(!1),x?.onError?.(L));return}try{for await(let E of w){if(g.current!==v)break;p+=S(E),d()&&n(p)}d()&&(i(!1),x?.onFinish?.(p))}catch(E){let L=Sr(E);d()&&(u(L),i(!1),x?.onError?.(L))}finally{l.current===w&&(l.current=null)}},[r]);return{completion:o,complete:R,stop:b,isStreaming:s,error:a}}import{useCallback as hr,useEffect as eo,useMemo as to,useRef as De,useState as st}from"react";function vr(e){return e instanceof Error?e:new Error(String(e))}var ro=e=>typeof e=="string"?e:String(e),yr=0;function Lt(e){return yr+=1,`${e}-${yr}`}function no(e,t){let r=to(()=>Oe(e),[e]),[o,n]=st(()=>(t?.initialMessages??[]).map(S=>({id:S.id??Lt("msg"),role:S.role,content:S.content}))),[s,i]=st(""),[a,u]=st(!1),[c,g]=st(null),l=De(t);l.current=t;let y=De(o);y.current=o;let b=De(s);b.current=s;let R=De(0),f=De(null),v=De(!0);eo(()=>(v.current=!0,()=>{v.current=!1,f.current?.cancel(),f.current=null}),[]);let d=hr(()=>{R.current++,f.current?.cancel(),f.current=null,v.current&&u(!1)},[]),x=hr(async S=>{let k=S===void 0,m=(k?b.current:S)??"";if(!m.trim())return;f.current?.cancel();let P=++R.current,C=()=>v.current&&R.current===P,A=l.current,p=A?.parseChunk??ro,w={id:Lt("msg"),role:"user",content:m},E={id:Lt("msg"),role:"assistant",content:""},L=[...y.current,w].map(q=>({role:q.role,content:q.content})),V=[...y.current,w,E];y.current=V,n(V),k&&i(""),g(null),u(!0);let H=A?.buildPayload??(q=>({messages:q})),{initialMessages:I,parseChunk:M,buildPayload:F,onFinish:j,onError:$,...W}=A??{},J=q=>{n(K=>K.map(ue=>ue.id===E.id?{...ue,content:q}:ue))},Q="",X;try{X=r.requestStream(H(L),W),f.current=X}catch(q){let K=vr(q);C()&&(g(K),u(!1),A?.onError?.(K));return}try{for await(let q of X){if(R.current!==P)break;Q+=p(q),C()&&J(Q)}C()&&(u(!1),A?.onFinish?.({...E,content:Q}))}catch(q){let K=vr(q);C()&&(g(K),u(!1),A?.onError?.(K))}finally{f.current===X&&(f.current=null)}},[r]);return{messages:o,input:s,setInput:i,sendMessage:x,stop:d,isStreaming:a,error:c}}import{useCallback as Re,useEffect as kr,useMemo as oo,useRef as br,useState as Rr}from"react";import{createInputPresencePublisher as so,INPUT_PRESENCE_DEFAULT_HZ as io,INPUT_PRESENCE_FIELD as ao}from"@urun-sh/core";var It=[];function uo(e,t={}){let{field:r=ao,hz:o=io}=t,n=t.documentTarget!==void 0?t.documentTarget:typeof document<"u"?document:null,s=e?.presence??null,i=oo(()=>s?so({awareness:{setLocalStateField:(m,T)=>s.setField(m,T)},field:r,hz:o}):null,[s,r,o]),a=br(null);a.current=i;let[u,c]=Rr(!1),[g,l]=Rr(It),y=br(!1);kr(()=>{if(i)return()=>i.dispose()},[i]);let b=Re(()=>{let m=a.current;l(m?m.heldKeys():It)},[]),R=Re(()=>{a.current?.clear(),l(It)},[]);kr(()=>{if(!n)return;let m=()=>!!n.pointerLockElement,T=()=>{if(m()){y.current=!1,c(!0);return}y.current||(c(!1),R())},P=E=>{m()&&(a.current?.keyDown(E.key),b())},C=E=>{a.current?.keyUp(E.key),b()},A=E=>{m()&&a.current?.movePointer(E.movementX,E.movementY)},p=E=>{m()&&a.current?.setButtons(E.buttons)},w=()=>{R()};return n.addEventListener("pointerlockchange",T),n.addEventListener("keydown",P),n.addEventListener("keyup",C),n.addEventListener("mousemove",A),n.addEventListener("mousedown",p),n.addEventListener("mouseup",p),n.defaultView?.addEventListener("blur",w),()=>{n.removeEventListener("pointerlockchange",T),n.removeEventListener("keydown",P),n.removeEventListener("keyup",C),n.removeEventListener("mousemove",A),n.removeEventListener("mousedown",p),n.removeEventListener("mouseup",p),n.defaultView?.removeEventListener("blur",w)}},[n,R,b]);let f=Re(m=>{m.requestPointerLock?.()},[]),v=Re(()=>{y.current=!0,c(!0)},[]),d=Re(()=>{y.current=!1,n?.pointerLockElement&&n.exitPointerLock?.(),c(!1),R()},[n,R]),x=Re(m=>{a.current?.keyDown(m),b()},[b]),S=Re(m=>{a.current?.keyUp(m),b()},[b]),k=Re((m,T)=>{a.current?.movePointer(m,T)},[]);return{engage:f,engageTouch:v,release:d,engaged:u,heldKeys:g,pressKey:x,releaseKey:S,movePointer:k}}import{forwardRef as ko,useEffect as Ar,useImperativeHandle as bo,useMemo as Ro,useRef as ut}from"react";import{createCameraWarp as To}from"@urun-sh/core";import{forwardRef as go,useCallback as Te,useEffect as $e,useImperativeHandle as So,useRef as ne,useState as Pr}from"react";import{derivedLegRole as ho}from"@urun-sh/core";var it=null;function co(){if(typeof window>"u")return null;let e=window;return e.AudioContext??e.webkitAudioContext??null}function at(){if(it)return it;let e=co();return e?(it=new e,it):null}function Ve(){let e=at();e&&e.state==="suspended"&&e.resume().catch(()=>{})}import{createContext as lo,useContext as Tr}from"react";import{jsx as fo}from"react/jsx-runtime";var Ot=lo(null);function po({session:e,children:t}){return fo(Ot.Provider,{value:e,children:t})}function pe(){return Tr(Ot)}function mo(){let e=Tr(Ot);if(!e)throw new Error("[urun] useSession() needs a mounted <Session session={...}> ancestor with a non-null session \u2014 create one with useApp() (e.g. app.generate({...})) and pass it to the scope.");return e}import{jsx as Ur,jsxs as yo}from"react/jsx-runtime";function vo(e,t){return e-t>>>0<2147483648}var Er=1e3;function xr(...e){console.debug("[video]",...e)}function Cr(e,t){let r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>e.stream(s)),n=()=>{for(let s of o){let i=s.track;if(i&&i.readyState==="live")return i}return null};return{get track(){return n()},on(s,i){let a=o.map(u=>u.on("track",()=>i(n())));return()=>{for(let u of a)u()}}}}function wr(e,t,r){return r?[r,t]:[e,t]}var Fe=go(function(t,r){let{session:o,stream:n="video",audioStream:s="audio",track:i,muted:a=!0,mirror:u=!1,objectFit:c="contain",className:g,style:l,videoClassName:y,placeholder:b,poster:R,children:f,onTrack:v,onFirstFrame:d,frameMarker:x,onFrameMarkerReached:S,onFrameMarkerUnsupported:k,onUnlockChange:m}=t,T=pe(),P=o??T,C=ne(null),A=ne(null),[p,w]=Pr(!1),[E,L]=Pr(!1),V=ne(!1),H=ne(null),I=ne(v);I.current=v;let M=ne(m);M.current=m;let F=ne(d);F.current=d;let j=ne(S);j.current=S;let $=ne(k);$.current=k;let W=ne(x??null);W.current=x??null;let J=Te(h=>{H.current!==h&&(H.current=h,M.current?.(h))},[]),Q=ne(null),X=ne(null),q=Te((h,_=!1)=>{if(!_&&h===Q.current||(Q.current=h,X.current?.(),X.current=null,V.current=!1,L(!1),!h))return;let U=C.current;if(!U)return;let B=W.current,oe=B?.rtpTimestamp??null,ge=!1,N=()=>{ge||(ge=!0,$.current?.())};B&&oe==null&&N();let Se=B!=null&&oe!=null,_e=ve=>{X.current?.(),X.current=null,V.current=!0,L(!0),F.current?.(),ve&&j.current?.()};if(typeof U.requestVideoFrameCallback=="function"){let ve=!1,O=0,D=(se,ie)=>{if(!ve){if(Se){let ce=ie?.rtpTimestamp;if(typeof ce!="number"){N(),_e(!1);return}if(!vo(ce,oe)){O=U.requestVideoFrameCallback(D);return}_e(!0);return}_e(!1)}};O=U.requestVideoFrameCallback(D),X.current=()=>{ve=!0,U.cancelVideoFrameCallback?.(O)};return}Se&&N();let he=()=>{let ve=U.getVideoPlaybackQuality?.();(ve?ve.totalVideoFrames>0:U.readyState>=2&&U.videoWidth>0)&&_e(!1)};U.addEventListener("loadeddata",he),U.addEventListener("timeupdate",he),U.addEventListener("playing",he),X.current=()=>{U.removeEventListener("loadeddata",he),U.removeEventListener("timeupdate",he),U.removeEventListener("playing",he)},he()},[]);$e(()=>()=>{X.current?.(),X.current=null},[]);let K=x==null?null:`${x.rtpTimestamp??""}|${x.ptsMs??""}`,ue=ne(K);$e(()=>{if(ue.current===K||(ue.current=K,K==null))return;let h=Q.current;h&&q(h,!0)},[K,q]);let G=Te(()=>{if(typeof MediaStream>"u")return null;A.current||(A.current=new MediaStream);let h=C.current;return h&&h.srcObject!==A.current&&(h.srcObject=A.current),A.current},[]),ee=Te(h=>{let _=C.current;if(!_)return;let U=_.play();!U||typeof U.then!="function"||U.then(()=>{_.muted||J(!0)}).catch(B=>{if((B instanceof Error?B.name:String(B))==="NotAllowedError"&&!_.muted){xr(`play() blocked pending a user gesture (${h})`),J(!1);return}xr(`play() failed (${h})`,B)})},[J]),be=Te(()=>{let h=C.current;h&&(G(),!h.muted&&(ee("gesture"),Ve(),J(!0)))},[G,ee,J]),te=Te(h=>{let _=G();if(_){for(let U of _.getVideoTracks())U!==h&&_.removeTrack(U);if(h&&!_.getVideoTracks().includes(h)){_.addTrack(h);let U=C.current;U&&(U.srcObject=_)}h&&ee("track-attach"),w(h!==null),q(h),I.current?.(h)}},[G,ee,q]),fe=Te(h=>{let _=G();if(_){for(let U of _.getAudioTracks())U!==h&&_.removeTrack(U);h&&!_.getAudioTracks().includes(h)&&_.addTrack(h),h&&ee("audio-attach")}},[G,ee]),re=Te(h=>{C.current=h,h&&(a?(h.muted=!0,h.defaultMuted=!0,h.setAttribute("muted",""),H.current=null):(h.muted=!1,h.defaultMuted=!1,h.removeAttribute("muted")),h.setAttribute("playsinline",""),h.setAttribute("webkit-playsinline",""),G())},[G,a]);So(r,()=>({get element(){return C.current},get live(){return A.current?A.current.getVideoTracks().length>0:!1},get framed(){return V.current},unlock:be,get unlocked(){return H.current===!0}}),[be]);let Y=ho(n)!==void 0;$e(()=>{Y&&console.error(`[video] stream=${JSON.stringify(n)} is an INTERNAL A/V leg name, not a consumable stream \u2014 address the PARENT (e.g. "${n.slice(0,n.lastIndexOf("--"))}") instead. Rendering empty.`)},[Y,n]);let z=i!==void 0;return $e(()=>{if(z){te(i??null);return}if(Y){te(null);return}if(!P)return;let h=Cr(P,wr(n,"video")),_=()=>{let N=A.current;return N?N.getVideoTracks()[0]??null:null},U=N=>{if(N!==_()&&(te(N),N)){let Se=()=>{_()===N&&te(null)};N.addEventListener("ended",Se)}},B=h.track;B&&B.readyState==="live"&&U(B);let oe=h.on("track",N=>{N&&N.readyState!=="live"||U(N)}),ge=setInterval(()=>{let N=h.track;N&&N.readyState==="live"&&U(N)},Er);return()=>{oe(),clearInterval(ge)}},[P,n,Y,z,i,te]),$e(()=>{if(z||!P||s===!1||Y)return;let h=Cr(P,wr(n,"audio",s)),_=()=>{let N=A.current;return N?N.getAudioTracks()[0]??null:null},U=N=>{if(N!==_()&&(fe(N),N)){let Se=()=>{_()===N&&fe(null)};N.addEventListener("ended",Se)}},B=h.track;B&&B.readyState==="live"&&U(B);let oe=h.on("track",N=>{N&&N.readyState!=="live"||U(N)}),ge=setInterval(()=>{let N=h.track;N&&N.readyState==="live"&&U(N)},Er);return()=>{oe(),clearInterval(ge)}},[P,n,Y,s,z,fe]),yo("div",{className:g,style:{position:"relative",width:"100%",height:"100%",...l},"data-urun-video":"","data-urun-video-live":p?"true":"false","data-urun-video-framed":E?"true":"false",children:[Ur("video",{ref:re,className:y,autoPlay:!0,muted:a,playsInline:!0,style:{width:"100%",height:"100%",objectFit:c,...u?{transform:"scaleX(-1)"}:{}}}),p?null:b,R===void 0?null:Ur("div",{"data-urun-video-poster":"","aria-hidden":E||void 0,style:{position:"absolute",inset:0,...E?{opacity:0,pointerEvents:"none"}:null},children:R}),f]})});import{jsx as Mr,jsxs as xo}from"react/jsx-runtime";var Po={position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},Eo=ko(function(t,r){let{warp:o,children:n,...s}=t,{enabled:i=!0,overscan:a=.08,captureInput:u=!0,documentTarget:c,...g}=o??{},l=c!==void 0?c:typeof document<"u"?document:null,y=ut(null),b=ut(null),R=ut(0),f=ut(g);f.current=g;let v=Ro(()=>To(f.current),[]);return bo(r,()=>({get video(){return y.current},get canvas(){return b.current},warp:v,get lastDrawTs(){return R.current}}),[v]),Ar(()=>{if(!i)return;let d=0,x=0,S=null,k=T=>{typeof T.requestVideoFrameCallback=="function"&&(S=T,x=T.requestVideoFrameCallback(function P(){v.frameArrived(),x=T.requestVideoFrameCallback(P)}))},m=T=>{d=requestAnimationFrame(m);let P=b.current,C=y.current?.element??null;if(!P||!C||(C!==S&&(S&&x&&S.cancelVideoFrameCallback?.(x),k(C)),C.readyState<2))return;v.tick(T);let A=typeof devicePixelRatio=="number"?devicePixelRatio:1,p=Math.max(1,Math.round(P.clientWidth*A)),w=Math.max(1,Math.round(P.clientHeight*A));(P.width!==p||P.height!==w)&&(P.width=p,P.height=w);let E=P.getContext("2d");if(!E)return;let L=v.transform(),V=C.videoWidth||p,H=C.videoHeight||w,M=Math.max(p/V,w/H)*(1+a)*L.scale;E.setTransform(M,0,0,M,p/2+L.translateX*p,w/2+L.translateY*w),E.drawImage(C,-V/2,-H/2),R.current=T};return d=requestAnimationFrame(m),()=>{cancelAnimationFrame(d),S&&x&&S.cancelVideoFrameCallback?.(x)}},[i,a,v]),Ar(()=>{if(!i||!u||!l)return;let d=()=>!!l.pointerLockElement,x=P=>{d()&&v.keyDown(P.key)},S=P=>v.keyUp(P.key),k=P=>{d()&&v.pointerDelta(P.movementX,P.movementY)},m=()=>{d()||v.clearKeys()},T=()=>v.clearKeys();return l.addEventListener("keydown",x),l.addEventListener("keyup",S),l.addEventListener("mousemove",k),l.addEventListener("pointerlockchange",m),l.defaultView?.addEventListener("blur",T),()=>{l.removeEventListener("keydown",x),l.removeEventListener("keyup",S),l.removeEventListener("mousemove",k),l.removeEventListener("pointerlockchange",m),l.defaultView?.removeEventListener("blur",T)}},[i,u,l,v]),i?xo(Fe,{ref:y,...s,videoClassName:s.videoClassName,style:{...s.style},children:[Mr("canvas",{ref:b,style:Po,"data-urun-warp":""}),n]}):Mr(Fe,{ref:y,...s,children:n})});var _r=new Map;function Co(e,t,r){if(!r||typeof r.safeParse!="function")throw new Error(`registerComponent("${e}"): schema must be a valid Zod schema`);_r.set(e,{component:t,schema:r})}function Nr(e,t){let r=_r.get(e);if(!r)return{error:`Unknown component: "${e}"`};let o=r.schema.safeParse(t);return o.success?{Component:r.component,validatedProps:o.data}:{error:`Validation failed for "${e}": ${o.error.message}`}}import{Fragment as Uo,jsx as ct}from"react/jsx-runtime";function wo({name:e,props:t,fallback:r}){let o=Nr(e,t);if(o.error)return console.warn(`[urun] ComponentRenderer: ${o.error}`),r?ct(Uo,{children:r}):ct("div",{className:"urun-component-error",role:"alert",children:ct("span",{className:"urun-component-error-text",children:o.error})});let n=o.Component;return ct(n,{...o.validatedProps})}import{z as Xe}from"zod";import{jsx as Dt,jsxs as Lr}from"react/jsx-runtime";var Ao=Xe.object({step:Xe.number().min(0),total:Xe.number().min(1),label:Xe.string().optional(),variant:Xe.enum(["default","success","error"]).default("default")});function Ir(e){let{step:t,total:r,label:o,variant:n="default"}=e,s=Math.min(t/r*100,100),i=t>=r;return{step:t,total:r,label:o,variant:n,percentage:s,isComplete:i}}function Mo(e){let{step:t,total:r,label:o,variant:n,percentage:s}=Ir(e);return Lr("div",{className:"urun-progress-card","data-variant":n,children:[o&&Dt("div",{className:"urun-progress-label",children:o}),Dt("div",{className:"urun-progress-bar",children:Dt("div",{className:"urun-progress-fill",style:{width:`${s}%`}})}),Lr("div",{className:"urun-progress-text",children:[t,"/",r]})]})}import{z as Vt}from"zod";import{jsx as Or,jsxs as Io}from"react/jsx-runtime";var _o=Vt.object({state:Vt.enum(["thinking","generating","idle","error"]),message:Vt.string().optional()}),No={thinking:"Thinking...",generating:"Generating...",idle:"Idle",error:"Error"};function Dr(e){let{state:t,message:r}=e,o=t==="thinking"||t==="generating",n=r??No[t]??t;return{state:t,message:n,isActive:o}}function Lo(e){let{state:t,message:r,isActive:o}=Dr(e);return Io("span",{className:"urun-status-badge","data-state":t,children:[Or("span",{className:`urun-status-indicator${o?" urun-status-pulse":""}`}),Or("span",{className:"urun-status-message",children:r})]})}import{useRef as Vr,useEffect as Oo}from"react";import{z as Ft}from"zod";import{jsx as Fr,jsxs as Fo}from"react/jsx-runtime";var Do=Ft.object({text:Ft.string(),streaming:Ft.boolean().default(!1)});function Hr(e){let{text:t,streaming:r=!1}=e,o=t.length===0;return{text:t,streaming:r,isEmpty:o}}function Vo(e){let{text:t,streaming:r}=Hr(e),o=Vr(null),n=Vr(0);return Oo(()=>{let s=o.current;s&&t.length!==n.current&&(s.textContent=t,n.current=t.length)},[t]),Fo("div",{className:"urun-text-stream",children:[Fr("span",{ref:o,className:"urun-text-content"}),r&&Fr("span",{className:"urun-text-cursor"})]})}import{z as lt}from"zod";import{jsx as qr,jsxs as Wo}from"react/jsx-runtime";var Ho=lt.object({src:lt.string().url(),alt:lt.string().optional(),caption:lt.string().optional()});function Wr(e){let{src:t,alt:r,caption:o}=e;return{src:t,alt:r??"",caption:o}}function qo(e){let{src:t,alt:r,caption:o}=Wr(e);return Wo("figure",{className:"urun-image-frame",children:[qr("img",{className:"urun-image",src:t,alt:r}),o&&qr("figcaption",{className:"urun-image-caption",children:o})]})}import{z as Pe}from"zod";import{jsx as Ht,jsxs as Ko}from"react/jsx-runtime";var Bo=Pe.object({metrics:Pe.array(Pe.object({label:Pe.string(),value:Pe.union([Pe.string(),Pe.number()]),unit:Pe.string().optional()}))});function Br(e){return{metrics:e.metrics.map(r=>({...r,displayValue:r.unit?`${r.value} ${r.unit}`:String(r.value)}))}}function jo(e){let{metrics:t}=Br(e);return Ht("div",{className:"urun-metrics-panel",children:t.map((r,o)=>Ko("div",{className:"urun-metric-card",children:[Ht("div",{className:"urun-metric-label",children:r.label}),Ht("div",{className:"urun-metric-value",children:r.displayValue})]},o))})}import{useCallback as dt,useEffect as qt,useRef as ae,useState as $o}from"react";import{jsx as es}from"react/jsx-runtime";function Ee(e){return e&&typeof e=="object"?e:null}function jr(e){if(typeof e=="string")return e;let t=Ee(e);return t&&t.t==="delta"&&typeof t.delta=="string"?t.delta:""}function Xo(e){if(typeof e=="string")return"delta";let t=Ee(e);return t?t.t==="delta"?"delta":t.t==="response"?"done":t.t==="error"?"error":"ignore":"ignore"}function Jo(...e){for(let t of e)if(typeof t=="string"&&t)return t;return""}function zo(e){let t=Ee(e),r=t?.body;return Jo(r,Ee(Ee(r)?.error)?.message,Ee(r)?.error,Ee(r)?.message,Ee(t?.error)?.message,t?.error,t?.message)||"stream reported an error"}var Je=class extends Error{name="TextStreamError"},Go=4,Kr=3,$r=240;function Xr(){return{chars:0,tokens:0,tokensPerSecond:0,elapsedMs:0,done:!1}}function Yo(e){e.chars=0,e.tokens=0,e.tokensPerSecond=0,e.elapsedMs=0,e.done=!1}function Jr(e){let{session:t,stream:r}=e,o=ae(e);qt(()=>{o.current=e});let n=ae(null),s=ae(()=>{}),i=ae(null),a=ae(""),u=ae(""),c=ae(null),g=ae(!1),l=ae(!1),y=ae(!1),b=ae(0),R=ae(Xr()),f=dt(S=>{if(n.current=S,!S){i.current=null;return}let k=i.current;if(k&&k.parentNode===S)return;let m=S.ownerDocument.createTextNode(u.current);S.appendChild(m),i.current=m,a.current.length>0&&s.current()},[]),v=dt(()=>{c.current=null;let S=i.current,k=a.current;if(k.length>0){let A=o.current,p=A.smoothCharsPerFrame??Kr,w=A.smoothThreshold??$r,E=A.smooth&&k.length<=w?k.slice(0,p):k;a.current=k.slice(E.length),u.current+=E,S?.appendData(E)}let m=R.current,T=u.current.length,P=b.current===0?0:Date.now()-b.current,C=Math.round(T/Go);if(m.chars=T,m.tokens=C,m.elapsedMs=P,m.tokensPerSecond=P>0?C*1e3/P:0,a.current.length>0){d(),o.current.onMeter?.(m);return}if(!g.current&&!y.current){y.current=!0,m.done=!0,o.current.onMeter?.(m),l.current||o.current.onDone?.(u.current);return}o.current.onMeter?.(m)},[]),d=dt(()=>{c.current===null&&(c.current=globalThis.requestAnimationFrame(()=>v()))},[v]);s.current=d,qt(()=>{if(!t)return;if(typeof globalThis.requestAnimationFrame!="function")throw new Error("[urun] Text requires requestAnimationFrame. Render it in a browser (or a DOM test environment).");a.current="",u.current="",l.current=!1,y.current=!1,b.current=0,g.current=!0,Yo(R.current),i.current&&(i.current.data="");let S=!1,k=null;return(async()=>{try{for(k=t.stream(r).messages()[Symbol.asyncIterator]();;){let T=await k.next();if(S)return;if(T.done)break;let P=T.value,C=Xo(P);if(C==="error")throw new Je(zo(P));if(C==="done")break;if(C==="ignore")continue;let A=jr(P);A&&(b.current===0&&(b.current=Date.now()),a.current+=A,d())}if(S)return;k.return?.(void 0),g.current=!1,d()}catch(m){if(S)return;k?.return?.(void 0),l.current=!0,g.current=!1,o.current.onError?.(m instanceof Error?m:new Je(String(m))),d()}})(),()=>{S=!0,g.current=!1,k?.return?.(void 0),c.current!==null&&(globalThis.cancelAnimationFrame?.(c.current),c.current=null)}},[t,r,d]);let x=dt(()=>u.current,[]);return{ref:f,meterRef:R,getText:x}}function Zo(e,t=250){let[r,o]=$o(Xr);return qt(()=>{let n=setInterval(()=>{let s=e.current;o(i=>i.chars===s.chars&&i.done===s.done?i:{...s})},t);return()=>clearInterval(n)},[e,t]),r}function Qo(e){let{className:t,style:r,...o}=e,{ref:n}=Jr(o);return es("span",{ref:n,className:t,style:r})}import{forwardRef as ts}from"react";import{jsx as ns}from"react/jsx-runtime";var rs=ts(function(t,r){let{stream:o="image",...n}=t;return ns(Fe,{ref:r,stream:o,...n})});import{forwardRef as os,useCallback as He,useEffect as Wt,useImperativeHandle as ss,useRef as qe}from"react";import{observePageLifecycle as is}from"@urun-sh/core";import{jsx as cs}from"react/jsx-runtime";var as=1e3,zr=200;function Bt(...e){console.debug("[audio]",...e)}var pt=os(function(t,r){let{session:o,stream:n="audio",track:s,controls:i=!1,className:a,onTrack:u,onUnlockChange:c,onAudioElement:g}=t,l=pe(),y=o??l,b=qe(null),R=qe(null),f=qe(null),v=qe(null),d=qe(u);d.current=u;let x=qe(c);x.current=c;let S=He(p=>{f.current!==p&&(f.current=p,x.current?.(p))},[]),k=He(()=>{if(typeof MediaStream>"u")return null;R.current||(R.current=new MediaStream);let p=b.current;return p&&p.srcObject!==R.current&&(p.srcObject=R.current),R.current},[]),m=He(p=>{let w=b.current;if(!w)return;let E=w.play();!E||typeof E.then!="function"||E.then(()=>{w.muted||S(!0)}).catch(L=>{let V=L instanceof Error?L.name:String(L);if(V==="AbortError"){Bt(`play() aborted (${p}); retrying in ${zr}ms`),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,m(`${p}:retry`)},zr);return}if(V==="NotAllowedError"){Bt(`play() blocked pending a user gesture (${p})`),S(!1);return}Bt(`play() failed (${p})`,L)})},[S]),T=He(p=>{let w=k();if(w){for(let E of w.getAudioTracks())E!==p&&w.removeTrack(E);p&&!w.getAudioTracks().includes(p)&&w.addTrack(p),p&&m("track-attach"),d.current?.(p)}},[k,m]),P=He(()=>{let p=b.current;p&&(k(),p.muted=!1,m("gesture"),Ve(),S(!0))},[k,m,S]);ss(r,()=>({unlock:P,get unlocked(){return f.current===!0},get element(){return b.current}}),[P]);let C=He(p=>{b.current=p,p&&(p.setAttribute("playsinline",""),p.setAttribute("webkit-playsinline",""),k()),g?.(p)},[k,g]),A=s!==void 0;return Wt(()=>{if(A){T(s??null);return}if(!y)return;let p=y.stream(n),w=()=>{let I=R.current;return I?I.getAudioTracks()[0]??null:null},E=I=>{if(I!==w()&&(T(I),I)){let M=()=>{w()===I&&T(null)};I.addEventListener("ended",M)}},L=p.track;L&&L.readyState==="live"&&E(L);let V=p.on("track",I=>{I&&I.readyState!=="live"||E(I)}),H=setInterval(()=>{let I=p.track;I&&I.readyState==="live"&&E(I)},as);return()=>{V(),clearInterval(H)}},[y,n,A,s,T]),Wt(()=>is(()=>{Ve(),f.current===!0&&m("foreground")}),[m]),Wt(()=>()=>{v.current&&clearTimeout(v.current)},[]),cs("audio",{ref:C,className:a,autoPlay:!0,playsInline:!0,controls:i,"data-urun-audio":""})}),us=pt;import{forwardRef as ls,useCallback as We,useEffect as Gr,useImperativeHandle as ds,useRef as ke}from"react";import{observePageLifecycle as ps,sessionFailureFromMediaError as ms,sharedCaptureController as fs}from"@urun-sh/core";import{jsx as Ss}from"react/jsx-runtime";var Yr={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};function mt(...e){console.debug("[voice]",...e)}var ft=ls(function(t,r){let{session:o,stream:n="audio",playback:s=!0,constraints:i=Yr,connectTimeoutMs:a,attempts:u=3,retryDelayMs:c=1500,onActiveChange:g,onError:l,onMicStream:y,onTrack:b,onUnlockChange:R,capture:f}=t,v=pe(),d=o??v,x=ke(null),S=ke(null),k=ke(null),m=ke([]),T=ke(!1),P=ke(g);P.current=g;let C=ke(l);C.current=l;let A=ke(y);A.current=y;let p=We(M=>{T.current!==M&&(T.current=M,P.current?.(M))},[]),w=We(()=>{for(let M of m.current)M();m.current=[],k.current?.release(),k.current=null,S.current&&(S.current=null,A.current?.(null))},[]),E=We(async()=>{let M=k.current;if(M){let W=await M.update(i);return S.current=M.stream,A.current?.(M.stream),W}let j=await(f??fs()).claim("audio",i);k.current=j,m.current=[j.onTrack((W,J)=>{S.current=J,A.current?.(J),T.current&&d?.stream(n).attach(W).catch(Q=>mt("mic re-attach after one-capture re-acquire failed",Q))}),j.onLost(W=>{k.current=null,m.current=[],S.current=null,A.current?.(null),p(!1),C.current?.(W)})],S.current=j.stream,A.current?.(j.stream);let $=j.track;if(!$)throw Object.assign(new Error("no microphone audio track"),{name:"NotFoundError"});return $},[f,i,d,n,p]),L=We(async()=>{w(),p(!1),await d?.stream(n).detach().catch(()=>{})},[d,n,w,p]),V=We(async()=>{if(!d)throw new Error("<Voice> needs a session: pass the `session` prop or mount inside <Session>");x.current?.unlock();let M;try{M=await E()}catch($){w();let W=ms($,d.status);throw C.current?.(W),W}d.connect?.();let F;for(let $=1;$<=u;$++)try{await d.whenLive(a!==void 0?{timeout:a}:void 0),await d.stream(n).attach(M),p(!0);return}catch(W){F=W,mt(`start attempt ${$}/${u} failed`,W),$<u&&await new Promise(J=>setTimeout(J,c))}w(),p(!1);let j=F instanceof Error?F:new Error(String(F??"voice start failed"));throw C.current?.(j),j},[d,n,a,u,c,E,w,p]);ds(r,()=>({start:V,stop:L,unlock:()=>x.current?.unlock(),get active(){return T.current},get micStream(){return S.current},get audio(){return x.current}}),[V,L]);let H=ke(!1),I=We(async()=>{if(!d||!T.current||H.current)return;let M=S.current?.getAudioTracks()[0]??null;if(M&&M.readyState==="live"){try{await d.stream(n).attach(M)}catch(F){mt("foreground mic re-assert failed (will retry on next pass)",F)}return}H.current=!0;try{let F=await E();await d.stream(n).attach(F)}catch(F){let j=F instanceof Error?F:new Error(String(F));mt("foreground mic re-acquire failed",j),C.current?.(j)}finally{H.current=!1}},[d,n,E]);return Gr(()=>{let M=()=>{I()};return d&&typeof d.onRecovery=="function"?d.onRecovery(M):ps(M)},[d,I]),Gr(()=>w,[w]),s?Ss(pt,{ref:x,session:d,stream:n,onTrack:b,onUnlockChange:R}):null}),gs=ft;import{forwardRef as ys,useEffect as ks,useImperativeHandle as bs,useRef as Zr,useState as Rs}from"react";import{useEffect as hs,useState as vs}from"react";var jt={level:0,speaking:!1};function Kt(e,t={}){let{fftSize:r=512,intervalMs:o=100,speakingThreshold:n=.02}=t,[s,i]=vs(jt);return hs(()=>{if(!e){i(jt);return}let a=at();if(!a||typeof MediaStream>"u")return;let u;e instanceof MediaStream?u=e:(u=new MediaStream,u.addTrack(e));let c,g;try{c=a.createMediaStreamSource(u),g=a.createAnalyser(),g.fftSize=r,c.connect(g)}catch{return}let l=new Uint8Array(g.fftSize),b=setInterval(()=>{g.getByteTimeDomainData(l);let R=0;for(let v=0;v<l.length;v++){let d=(l[v]-128)/128;R+=d*d}let f=Math.sqrt(R/l.length);i(v=>{let d=f>n;return Math.abs(v.level-f)<.005&&v.speaking===d?v:{level:f,speaking:d}})},o);return()=>{clearInterval(b),c.disconnect(),i(jt)}},[e,r,o,n]),s}import{Fragment as xs,jsx as gt,jsxs as Cs}from"react/jsx-runtime";var Ts={display:"inline-flex",alignItems:"center",gap:6,minWidth:48,height:12},Ps={flex:1,height:4,borderRadius:9999,background:"rgba(128,128,128,0.35)",overflow:"hidden"},Es=ys(function(t,r){let{session:o,stream:n="audio",constraints:s,autoStart:i=!0,visible:a=!1,className:u,onActiveChange:c,onError:g,onMicStream:l,capture:y}=t,b=pe(),R=o??b,f=Zr(null),[v,d]=Rs(null),x=Zr(l);x.current=l;let{level:S,speaking:k}=Kt(a?v:null);return bs(r,()=>({start:()=>{let m=f.current;return m?m.start():Promise.reject(new Error("<Mic> is not mounted"))},stop:()=>f.current?.stop()??Promise.resolve(),get active(){return f.current?.active??!1},get micStream(){return f.current?.micStream??null}}),[]),ks(()=>{!i||!R||f.current?.start().catch(()=>{})},[i,R]),Cs(xs,{children:[gt(ft,{ref:f,session:R,stream:n,playback:!1,...s!==void 0?{constraints:s}:{},...y!==void 0?{capture:y}:{},onActiveChange:c,onError:g,onMicStream:m=>{d(m),x.current?.(m)}}),a?gt("span",{className:u,style:Ts,"data-urun-mic":"","data-urun-mic-active":v?"true":"false","data-urun-mic-speaking":k?"true":"false",role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":1,"aria-valuenow":Math.round(S*100)/100,children:gt("span",{style:Ps,children:gt("span",{"data-urun-mic-level":"",style:{display:"block",height:"100%",width:`${Math.min(100,Math.round(S*300))}%`,borderRadius:9999,background:"currentColor",transition:"width 100ms linear"}})})}):null]})});import{captureStillFromVideo as ws,sessionFailureFromMediaError as Us,sharedCaptureController as As}from"@urun-sh/core";import{forwardRef as en,useCallback as me,useEffect as $t,useImperativeHandle as Ms,useRef as Z,useState as ze}from"react";import{jsx as xe,jsxs as Qr}from"react/jsx-runtime";var tn={width:{ideal:960},height:{ideal:720},frameRate:{ideal:8}};function Xt(...e){console.debug("[camera]",...e)}function _s(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}async function Ns(){let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(typeof e?.enumerateDevices!="function")return null;try{return(await e.enumerateDevices()).filter(r=>r.kind==="videoinput")}catch{return null}}var rn=en(function(t,r){let{session:o,stream:n="video",constraints:s,front:i=!1,back:a=!1,facingMode:u,autoStart:c=!0,mirror:g="auto",connectTimeoutMs:l,visible:y=!1,className:b,videoClassName:R,onActiveChange:f,onError:v,onStream:d,onTrack:x,children:S,capture:k,flipControl:m="auto",flipControlClassName:T,onDevices:P}=t;if(i&&a)throw new Error("<Camera> takes `front` OR `back`, not both");let C=i?"user":a?"environment":u??"environment",A=pe(),p=o??A,w=Z(null),E=Z(null),L=Z(null),V=Z([]),H=Z(null),I=Z(!1),M=Z(!1),F=Z(C),[j,$]=ze(C),[W,J]=ze(!1),[Q,X]=ze(null),[q,K]=ze(!1),[ue]=ze(_s),G=Z(f);G.current=f;let ee=Z(v);ee.current=v;let be=Z(d);be.current=d;let te=Z(x);te.current=x;let fe=Z(P);fe.current=P;let re=me(O=>{I.current!==O&&(I.current=O,J(O),G.current?.(O))},[]);$t(()=>{if(!W){X(null);return}let O=!1,D=()=>{Ns().then(ie=>{O||(X(ie),ie&&fe.current?.(ie))})};D();let se=typeof navigator<"u"?navigator.mediaDevices:void 0;return typeof se?.addEventListener=="function"?(se.addEventListener("devicechange",D),()=>{O=!0,se.removeEventListener?.("devicechange",D)}):()=>{O=!0}},[W]);let Y=me(O=>{let D=w.current;D&&(D.muted=!0,D.defaultMuted=!0,D.setAttribute("muted",""),D.setAttribute("playsinline",""),D.setAttribute("webkit-playsinline",""),D.srcObject=O,O&&D.play()?.catch?.(se=>Xt("preview play() failed",se)))},[]),z=me(()=>{M.current=!1,H.current?.(),H.current=null;for(let O of V.current)O();V.current=[],L.current?.release(),L.current=null,E.current&&(E.current=null,be.current?.(null),te.current?.(null)),Y(null)},[Y]),h=me((O,D)=>{H.current?.(),E.current=D,Y(D),be.current?.(D);let se=()=>{E.current===D&&(Xt("camera track ended (device removed or permission revoked)"),z(),re(!1))};O.addEventListener("ended",se),H.current=()=>O.removeEventListener("ended",se)},[Y,z,re]),_=me(async O=>{let D=n!==!1;if(D&&!p)throw new Error("<Camera> needs a session: pass the `session` prop or mount inside <Session>");let se={...tn,...s,facingMode:O},ie;try{let ce=L.current;if(ce)ie=await ce.update(se);else{let Be=await(k??As()).claim("video",se);if(L.current=Be,V.current=[Be.onTrack((je,vn)=>{h(je,vn),I.current&&(!D||!p||p.stream(n).attachVideo(je).then(()=>te.current?.(je)).catch(yn=>Xt("camera re-publish after one-capture re-acquire failed",yn)))}),Be.onLost(je=>{L.current=null,V.current=[],z(),re(!1),ee.current?.(je)})],!Be.track)throw Object.assign(new Error("no camera video track"),{name:"NotFoundError"});ie=Be.track}}catch(ce){let Ne=Us(ce,p?.status);throw ee.current?.(Ne),Ne}F.current=O,$(O),h(ie,L.current?.stream??new MediaStream([ie]));try{D&&p&&(p.connect?.(),await p.whenLive(l!==void 0?{timeout:l}:void 0),await p.stream(n).attachVideo(ie)),M.current=D?n:!1}catch(ce){z(),re(!1);let Ne=ce instanceof Error?ce:new Error(String(ce));throw ee.current?.(Ne),Ne}te.current?.(ie),re(!0)},[p,n,s,l,k,h,z,re]),U=me(O=>_(O?.facingMode??F.current),[_]),B=me(async O=>{let D=M.current===n;I.current&&F.current===O&&D||await _(O)},[_,n]),oe=me(()=>_(F.current==="environment"?"user":"environment"),[_]),ge=me(async()=>{z(),re(!1),n!==!1&&await p?.stream(n).detachVideo().catch(()=>{})},[p,n,z,re]),N=me(async O=>{let D=w.current;if(!D)throw new Error("<Camera> needs `visible` to capture a photo (no preview to read a frame from)");return await ws(D,O)},[]);Ms(r,()=>({start:U,stop:ge,flip:oe,setFacingMode:B,capturePhoto:N,get active(){return I.current},get facingMode(){return F.current},get stream(){return E.current},get element(){return w.current}}),[U,ge,oe,B,N]);let Se=Z(B);if(Se.current=B,$t(()=>{c&&(n!==!1&&!p||Se.current(C).catch(()=>{}))},[c,p,C,n]),$t(()=>z,[z]),!y)return null;let _e=g==="auto"?j==="user":g,he=W&&(m===!0||m==="auto"&&ue&&(Q?.length??0)>1),ve=()=>{q||(K(!0),oe().catch(()=>{}).finally(()=>K(!1)))};return Qr("div",{className:b,style:{position:"relative",width:"100%",height:"100%"},"data-urun-camera":"","data-urun-camera-facing":j,children:[xe("video",{ref:w,className:R,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"100%",objectFit:"contain",..._e?{transform:"scaleX(-1)"}:{}}}),he?xe("button",{type:"button","data-urun-camera-flip":"","aria-label":"Switch camera",title:"Switch camera",onClick:ve,disabled:q,className:T,style:T?{opacity:q?.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:q?.6:1},children:Qr("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{width:20,height:20},"aria-hidden":!0,children:[xe("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),xe("path",{d:"M9.5 13.5a2.8 2.8 0 0 1 5-1.4"}),xe("path",{d:"M14.5 10.5v1.6h-1.6"}),xe("path",{d:"M14.5 14.5a2.8 2.8 0 0 1-5 1.4"}),xe("path",{d:"M9.5 17.5v-1.6h1.6"})]})}):null,S]})}),Ls=en(function({preview:t=!0,...r},o){return xe(rn,{ref:o,...r,visible:t,autoStart:!1})});import{cameraCaptureAvailable as Is,normalizeReferenceImage as Os,referenceImageErrorMessage as Ds}from"@urun-sh/core";import{useCallback as Ge,useEffect as Vs,useRef as Jt,useState as Ye}from"react";function Fs(e){let{maxSize:t,type:r,quality:o,onChange:n}=e??{},[s,i]=Ye(null),[a,u]=Ye(null),[c,g]=Ye(!1),[l,y]=Ye(null),[b]=Ye(Is),R=Jt(n);R.current=n;let f=Jt(null),v=Jt(0),d=Ge(T=>{f.current&&URL.revokeObjectURL(f.current),f.current=T?URL.createObjectURL(new Blob([T.bytes],{type:T.type})):null,u(f.current),i(T),R.current?.(T)},[]);Vs(()=>()=>{v.current++,f.current&&URL.revokeObjectURL(f.current),f.current=null},[]);let x=Ge(async T=>{let P=++v.current;g(!0),y(null);try{let C=await T();if(v.current!==P)return;d(C)}catch(C){if(v.current!==P)return;y(Ds(C))}finally{v.current===P&&g(!1)}},[d]),S=Ge(T=>x(()=>Os(T,{maxSize:t,type:r,quality:o,source:"file"})),[x,t,r,o]),k=Ge(T=>x(()=>T.capturePhoto({maxSize:t,type:r,quality:o})),[x,t,r,o]),m=Ge(()=>{v.current++,y(null),g(!1),d(null)},[d]);return{reference:s,previewUrl:a,pick:S,capture:k,clear:m,busy:c,error:l,cameraAvailable:b}}import{useEffect as Hs,useState as qs}from"react";function Ws(e,t){let[r,o]=qs(null);return Hs(()=>{if(!e||!t){o(null);return}let n=e.stream(t);return o(n.track),n.on("track",o)},[e,t]),r}import{useCallback as Js}from"react";import{useEffect as $s,useMemo as Xs}from"react";import{createStore as Bs}from"zustand/vanilla";import{useStore as js}from"zustand";var Ks=()=>{};function zt(e,t={}){let r=c=>{e?.set(c)},o=()=>e?e.get()??{}:{},n=Bs(()=>({doc:o(),synced:e?e.synced:!1,set:r})),s=null,i=()=>{if(s){for(let c of s)c();s=null}},a=()=>e?(s||(n.setState({doc:o(),synced:e.synced}),s=[e.on("change",c=>n.setState({doc:c})),e.onSynced(()=>n.setState({synced:!0}))]),i):Ks,u=(c=>js(n,c));return Object.assign(u,{getState:n.getState,getInitialState:n.getInitialState,subscribe:n.subscribe,set:r,bind:a,unbind:i}),t.bind!==!1&&a(),u}function Ze(e,t){let r=Xs(()=>zt(e&&t?e.doc(t):null,{bind:!1}),[e,t]);return $s(()=>r.bind(),[r]),r}function zs(e,t,r){let n=Ze(e,t)(r??(a=>a)),s=Js(a=>{e&&t&&e.doc(t).set(a)},[e,t]);if(r)return n;let i=n;return{snapshot:e&&t?i.doc:null,synced:i.synced,set:s}}import{useEffect as Gs,useState as Ys}from"react";var Ue=200;function Ce(e,t,r=200){let o=[...e,t];return o.length>r?o.slice(o.length-r):o}function Qe(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Gt(e){let t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON object."};let r;try{r=JSON.parse(t)}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Invalid JSON."}}return r===null||typeof r!="object"||Array.isArray(r)?{ok:!1,error:"The payload must be a JSON object."}:{ok:!0,value:r}}function Yt(e,t,r={}){let o=r.cap??200,[n,s]=Ys([]);return Gs(()=>{if(s([]),!e||!t)return;let i=!0,a=e.stream(t).messages()[Symbol.asyncIterator]();return(async()=>{for(;;){let u=await a.next();if(!i||u.done)break;s(c=>Ce(c,{at:Date.now(),payload:u.value},o))}})(),()=>{i=!1,a.return?.()}},[e,t,o]),n}import{jsx as St,jsxs as et}from"react/jsx-runtime";function Zs({session:e,name:t,cap:r,className:o}){let n=Yt(e,t,{cap:r});return et("div",{className:["urun-stream-tail",o].filter(Boolean).join(" "),children:[et("div",{className:"urun-stream-tail-meta",children:[St("code",{children:t}),et("span",{className:"urun-stream-tail-count",children:[n.length," messages"]})]}),St("div",{className:"urun-stream-tail-log",children:n.length===0?et("span",{className:"urun-stream-tail-empty",children:["Waiting for ",St("code",{children:t})," messages\u2026"]}):n.map((s,i)=>et("div",{className:"urun-stream-tail-line",children:[St("span",{className:"urun-stream-tail-time",children:new Date(s.at).toLocaleTimeString()})," ",Qe(s.payload)]},`${s.at}-${i}`))})]})}import{useCallback as Qs,useState as nn}from"react";import{jsx as Ae,jsxs as ht}from"react/jsx-runtime";function vt({placeholder:e,buttonLabel:t,disabled:r,onApply:o}){let[n,s]=nn(""),[i,a]=nn(null),u=Qs(()=>{let c=Gt(n);if(!c.ok){a(c.error);return}a(null),o(c.value,n.trim()),s("")},[n,o]);return ht("div",{className:"urun-doc-patch",children:[Ae("textarea",{className:"urun-doc-patch-input",value:n,onChange:c=>s(c.target.value),placeholder:e,rows:3}),ht("div",{className:"urun-doc-patch-actions",children:[Ae("button",{type:"button",className:"urun-doc-patch-button",disabled:r||!n.trim(),onClick:u,children:t}),i?Ae("span",{className:"urun-doc-patch-error",role:"alert",children:i}):null]})]})}function ei({session:e,docKey:t,editable:r=!0,patchPlaceholder:o='{"desired": {"prompt": {"text": "a sunset"}}}',className:n}){let s=Ze(e,t),i=s(c=>c.doc),a=s(c=>c.synced),u=s(c=>c.set);return ht("div",{className:["urun-doc-panel",n].filter(Boolean).join(" "),children:[ht("div",{className:"urun-doc-panel-meta",children:[Ae("code",{children:t}),Ae("span",{className:"urun-doc-panel-synced","data-synced":a?"true":"false",children:a?"synced":"syncing\u2026"})]}),Ae("pre",{className:"urun-doc-panel-snapshot",children:JSON.stringify(i??{},null,2)}),r?Ae(vt,{placeholder:o,buttonLabel:"Apply patch",disabled:!e,onApply:c=>u(c)}):null]})}import{useEffect as ti,useState as ri}from"react";import{jsx as tt,jsxs as sn}from"react/jsx-runtime";function on(e,t=600){return e.length>t?`${e.slice(0,t)}\u2026`:e}function ni({session:e,docKey:t="control",cap:r=200,className:o}){let[n,s]=ri([]);return ti(()=>(s([]),e?e.doc(t).on("change",a=>{s(u=>Ce(u,{at:Date.now(),direction:"in",text:on(Qe(a))},r))}):void 0),[e,t,r]),sn("div",{className:["urun-control-sender",o].filter(Boolean).join(" "),children:[tt(vt,{placeholder:'{"desired": {"settings": {"values": {}}}}',buttonLabel:`Send to ${t}`,disabled:!e,onApply:(i,a)=>{e?.doc(t).set(i),s(u=>Ce(u,{at:Date.now(),direction:"out",text:on(a)},r))}}),tt("div",{className:"urun-control-sender-log",children:n.length===0?tt("span",{className:"urun-control-sender-empty",children:"Nothing yet."}):[...n].reverse().map((i,a)=>sn("div",{className:"urun-control-sender-line","data-direction":i.direction,children:[tt("span",{className:"urun-control-sender-dir",children:i.direction==="out"?"sent":"change"})," ",tt("span",{className:"urun-control-sender-time",children:new Date(i.at).toLocaleTimeString()})," ",i.text]},`${i.at}-${a}`))})]})}import{useEffect as oi,useState as si}from"react";import{jsx as yt,jsxs as ai}from"react/jsx-runtime";function ii({session:e,trackNames:t=["video","audio"],docKeys:r=["control"],cap:o=200,className:n}){let[s,i]=si([]),a=t.join(","),u=r.join(",");return oi(()=>{if(i([]),!e)return;let c=(l,y)=>i(b=>Ce(b,{at:Date.now(),kind:l,text:y},o)),g=[];g.push(e.onPhase(l=>c("phase",`phase \u2192 ${l.name}`)));for(let l of t){let y=e.stream(l);g.push(y.on("track",b=>c("track",`${l}: ${b?"track arrived":"track ended"}`)))}for(let l of r){let y=e.doc(l);g.push(y.on("change",()=>c("doc",`${l} changed`)))}return()=>g.forEach(l=>l())},[e,a,u,o]),yt("div",{className:["urun-event-spine",n].filter(Boolean).join(" "),children:s.length===0?yt("span",{className:"urun-event-spine-empty",children:"No activity yet \u2014 the spine fills as the session moves through its lifecycle."}):[...s].reverse().map((c,g)=>ai("div",{className:"urun-event-spine-line","data-kind":c.kind,children:[yt("span",{className:"urun-event-spine-kind",children:c.kind})," ",yt("span",{className:"urun-event-spine-time",children:new Date(c.at).toLocaleTimeString()})," ",c.text]},`${c.at}-${g}`))})}import{describeSessionPhase as Ri,isWakingPhase as Ti}from"@urun-sh/core";import{useEffect as ui,useState as ci}from"react";function le(e){let[t,r]=ci(e?.phase??null);return ui(()=>{if(!e){r(null);return}return e.onPhase(r)},[e]),t}import{describeSessionPhase as fi}from"@urun-sh/core";import{useEffect as li,useRef as di,useState as pi}from"react";import{isWakingPhase as mi}from"@urun-sh/core";function Zt(e){let t=le(e),r=mi(t?.name),o=di(void 0);r?o.current??=Date.now():o.current=void 0;let n=r?t?.wakingSince??o.current:void 0,s=()=>n!==void 0?Math.max(0,Math.floor((Date.now()-n)/1e3)):0,[i,a]=pi(s);return li(()=>{if(n===void 0){a(0);return}a(Math.max(0,Math.floor((Date.now()-n)/1e3)));let u=setInterval(()=>{a(Math.max(0,Math.floor((Date.now()-n)/1e3)))},1e3);return()=>clearInterval(u)},[n]),{waking:r,phase:t,state:r?t?.runtime?.state:void 0,reason:r?t?.runtime?.reason:void 0,since:n,seconds:r?i:0}}import{Fragment as gi,jsx as an,jsxs as un}from"react/jsx-runtime";function Qt({session:e,render:t,className:r}){let o=Zt(e);return!o.waking||!o.phase?null:an("span",{className:["urun-session-waking",r].filter(Boolean).join(" "),"data-phase":o.phase.name,"data-runtime-state":o.state,children:t?t(o):un(gi,{children:[an("span",{className:"urun-session-waking-label",children:fi(o.phase)})," ",un("span",{className:"urun-session-waking-elapsed",children:["(",o.seconds,"s)"]})]})})}import{useEffect as vi,useState as yi}from"react";import{useEffect as cn,useRef as Si,useState as ln}from"react";var hi={event:null,elapsedMs:0};function er(e,t){let[r,o]=ln(null),n=Si(0);cn(()=>{if(o(null),!!e?.onActivation)return e.onActivation(a=>{t!==void 0&&a.stream!==t||(n.current=Date.now(),o(a))})},[e,t]);let[s,i]=ln(0);return cn(()=>{if(!r){i(0);return}if(r.state==="first-media"){i(r.elapsedMs);return}let a=n.current,u=()=>r.elapsedMs+Math.max(0,Date.now()-a);i(u());let c=setInterval(()=>i(u()),1e3);return()=>clearInterval(c)},[r]),r?{event:r,elapsedMs:s}:hi}import{jsx as dn,jsxs as pn}from"react/jsx-runtime";var ki={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 bi(e){let[t,r]=yi(!1);return vi(()=>{if(r(!1),!e)return;let o=e;if(typeof o.requestVideoFrameCallback=="function"){let s=o.requestVideoFrameCallback(()=>r(!0));return()=>o.cancelVideoFrameCallback?.(s)}let n=()=>{let s=o.getVideoPlaybackQuality?.();(s?s.totalVideoFrames>0:o.readyState>=2)&&r(!0)};return n(),o.addEventListener("loadeddata",n),o.addEventListener("timeupdate",n),()=>{o.removeEventListener("loadeddata",n),o.removeEventListener("timeupdate",n)}},[e]),t}function tr({session:e,stream:t,videoElement:r,render:o,className:n}){let s=er(e,t),i=bi(r),a=s.event;if(!a||a.state==="first-media"||i)return null;let u=a.state;return dn("div",{className:["urun-activation-overlay",n].filter(Boolean).join(" "),"data-state":u,role:"status","aria-live":"polite",children:o?o(s):pn("div",{className:"urun-activation-overlay-card",children:[dn("span",{className:"urun-activation-overlay-copy",children:a.hint??ki[u]})," ",pn("span",{className:"urun-activation-overlay-elapsed",children:["(",Math.floor(s.elapsedMs/1e3),"s)"]})]})})}import{jsx as Me,jsxs as rr}from"react/jsx-runtime";var Pi={idle:"idle",queued:"queued",unavailable:"starting",provisioning:"provisioning",connecting:"connecting",live:"live",error:"error",ended:"ended",expired:"expired"};function Ei({session:e,className:t}){let r=le(e),o=r?.name??"idle",n=r?.name==="queued"&&r.queue?`pos ${r.queue.position} / depth ${r.queue.depth}`:(r?.name==="error"||r?.name==="expired")&&r.error?r.error.reason:r?.runtime&&r.runtime.state!=="unavailable"?r.runtime.reason??null:null;return rr("span",{className:["urun-session-status",t].filter(Boolean).join(" "),"data-phase":o,children:[Me("span",{className:"urun-session-status-dot","data-phase":o}),Me("span",{className:"urun-session-status-label",children:Pi[o]}),n?Me("span",{className:"urun-session-status-detail",children:n}):null]})}function xi({session:e,children:t,fallback:r,onStartOver:o,className:n}){let s=le(e);if(s?.name==="live")return rr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[t,Me(tr,{session:e})]});let i=r?r(s):Me("span",{className:"urun-session-gate-fallback",children:s?.name==="error"?`Session ${s.error?.reason??"failed"}.`:s?.name==="ended"?"Session ended.":s&&Ti(s.name)?Me(Qt,{session:e}):s&&s.name!=="idle"?Ri(s):"Waiting for a live session\u2026"}),a=o!==void 0&&(s?.name==="error"||s?.name==="ended"||s?.name==="expired");return rr("div",{className:["urun-session-gate",n].filter(Boolean).join(" "),children:[i,a?Me("button",{type:"button",className:"urun-session-gate-start-over",onClick:o,children:"Start over"}):null]})}import{useEffect as Ci,useState as wi}from"react";import{jsx as Mi}from"react/jsx-runtime";function mn(e){return le(e)?.endsAt??null}function Ui(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),o=t%60;return`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Ai({session:e,urgentMs:t=6e4,className:r}){let n=mn(e)?.getTime()??null,[s,i]=wi(()=>n===null?null:Math.max(0,n-Date.now()));if(Ci(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),s===null)return null;let a=Ui(s);return Mi("span",{className:["urun-session-clock",r].filter(Boolean).join(" "),role:"timer","aria-label":`Session time remaining ${a}`,"data-urgent":s<t?"":void 0,"data-expired":s<=0?"":void 0,children:a})}import{jsx as fn,jsxs as Li}from"react/jsx-runtime";var _i=new Set(["expired","ended","error"]);function Ni({session:e,onNewSession:t,children:r,className:o}){let n=le(e);if(!n||!_i.has(n.name))return null;let s=r?r(n):fn("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 Li("div",{className:["urun-session-ended",o].filter(Boolean).join(" "),"data-phase":n.name,children:[s,t?fn("button",{type:"button",className:"urun-session-ended-new",onClick:t,children:"New session"}):null]})}import{useEffect as gn,useMemo as Ii,useState as Sn}from"react";import{jsx as kt,jsxs as Vi}from"react/jsx-runtime";function nr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.warning!==!0?null:{warning:!0,deadlineEpochS:typeof t.deadline_epoch_s=="number"?t.deadline_epoch_s:null,idleSinceEpochS:typeof t.idle_since_epoch_s=="number"?t.idle_since_epoch_s:null}}function hn(e){let t=Ii(()=>e?e.doc("control"):null,[e]),[r,o]=Sn(()=>t?nr(t.get("idle")):null);return gn(()=>{if(!t){o(null);return}return o(nr(t.get("idle"))),t.on("change",()=>o(nr(t.get("idle"))))},[t]),r}function Oi(e){let t=Math.max(0,Math.floor(e));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Di({session:e,onStillHere:t,className:r}){let o=hn(e),n=o?.deadlineEpochS??null,[s,i]=Sn(null);if(gn(()=>{if(n===null){i(null);return}let u=()=>i(Math.max(0,n-Date.now()/1e3));u();let c=setInterval(u,1e3);return()=>clearInterval(c)},[n]),!o||!e)return null;let a=()=>{e.touch?.(),t?.()};return kt("div",{className:["urun-idle-warning",r].filter(Boolean).join(" "),role:"alertdialog","aria-live":"assertive","aria-label":"Inactivity warning","data-urgent":s!==null&&s<30?"":void 0,children:Vi("div",{className:"urun-idle-warning-card",children:[kt("span",{className:"urun-idle-warning-title",children:"Are you still there?"}),kt("span",{className:"urun-idle-warning-copy",children:s!==null?`This session will end in ${Oi(s)} due to inactivity.`:"This session will end soon due to inactivity."}),kt("button",{type:"button",className:"urun-idle-warning-confirm",onClick:a,children:"I'm still here"})]})})}import{useContext as Fi,useEffect as Hi,useState as qi}from"react";import{prewake as Wi}from"@urun-sh/core";function Bi(e){let t=Fi(Le),[r,o]=qi(null),n=e.app??t?.appId,s=e.function,i=e.intervalS??60,a=t?.baseUrl,u=t?.orgId,c=t?.jwt,g=t?.getAccessToken,l=t?.authProvider;return Hi(()=>{if(!a||!u||!n||!s)return;let y=!1,b=()=>{Wi({baseUrl:a,app:n,functionName:s,orgId:u,jwt:c,getAccessToken:g,authProvider:l}).then(f=>{y||o(f)}).catch(()=>{})};b();let R=setInterval(b,Math.max(1,i)*1e3);return()=>{y=!0,clearInterval(R)}},[n,s,i,a,u,c,g,l]),r}import{useEffect as ji,useState as Ki}from"react";function $i(e){let[t,r]=Ki(null);return ji(()=>{if(r(null),!!e?.onStats)return e.onStats(r)},[e]),t}import{describeSessionPhase as dd,isWakingPhase as pd}from"@urun-sh/core";export{pt as Audio,rn as Camera,wo as ComponentRenderer,tn as DEFAULT_CAMERA_CONSTRAINTS,Ue as DEFAULT_LOG_CAP,Kr as DEFAULT_SMOOTH_CHARS_PER_FRAME,$r as DEFAULT_SMOOTH_THRESHOLD,Yr as DEFAULT_VOICE_CONSTRAINTS,vt as DocPatchForm,rs as Image,qo as ImageFrame,Ho as ImageFrameSchema,jo as MetricsPanel,Bo as MetricsPanelSchema,Es as Mic,wn as OPERATOR_CHORD_LABEL,Cn as OPERATOR_TOKEN_STORAGE_KEY,Mo as ProgressCard,Ao as ProgressCardSchema,Eo as ReprojectedVideo,po as Session,Lo as StatusBadge,_o as StatusBadgeSchema,Qo as Text,Vo as TextStream,Je as TextStreamError,Do as TextStreamSchema,tr as UrunActivationOverlay,us as UrunAudio,bt as UrunAuthProvider,Ls as UrunCamera,ni as UrunControlSender,ei as UrunDocPanel,Ke as UrunErrorBoundary,ii as UrunEventSpine,Di as UrunIdleWarning,kn as UrunJwtProvider,Dn as UrunProvider,Ai as UrunSessionClock,Ni as UrunSessionEnded,xi as UrunSessionGate,Ei as UrunSessionStatus,Qt as UrunSessionWaking,Zs as UrunStreamTail,gs as UrunVoice,Fe as Video,ft as Voice,rt as authMode,zt as createDocStore,dd as describeSessionPhase,Qe as formatPayload,at as getUrunAudioContext,pd as isWakingPhase,Gt as parseJsonObject,Ce as pushCapped,ur as readOperatorToken,Co as registerComponent,Ve as resumeUrunAudioContext,jr as textDelta,de as urunPublicEnv,er as useActivation,Kn as useApp,no as useChat,Qn as useCompletion,Pt as useConfirmOnLeave,Ze as useDocStore,Wr as useImageFrame,uo as useInputPresence,Br as useMetricsPanel,Tt as useOperatorOverride,Ir as useProgressCard,Fs as useReferenceImage,zn as useRequest,mo as useSession,zs as useSessionDoc,mn as useSessionEndsAt,hn as useSessionIdle,le as useSessionPhase,$i as useSessionStats,Ws as useSessionTrack,Zt as useSessionWake,Dr as useStatusBadge,Yt as useStreamMessages,Jr as useText,Zo as useTextMeter,Hr as useTextStream,Kt as useUrunAudioLevel,Rt as useUrunAuth,Bi as useUrunPrewake,Pn as usesWorkOSAuth};
|