@livelayer/react 0.3.0 → 0.5.0
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 +91 -2
- package/dist/index.d.ts +122 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +1445 -1029
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -153,11 +153,81 @@ Or attach extra app state without replacing the walker:
|
|
|
153
153
|
/>
|
|
154
154
|
```
|
|
155
155
|
|
|
156
|
-
### 4.
|
|
156
|
+
### 4. Let the agent click + scroll + fill forms (0.4.0)
|
|
157
|
+
|
|
158
|
+
**Click anything the agent should be able to trigger**: tag interactive elements with `data-ll-action` (or any selector you want — `button[aria-label="..."]` works too).
|
|
159
|
+
|
|
160
|
+
```tsx
|
|
161
|
+
<button data-ll-action="open-pricing-modal" onClick={openPricing}>
|
|
162
|
+
See pricing
|
|
163
|
+
</button>
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The agent emits `{ type: "click", selector: "[data-ll-action='open-pricing-modal']" }` and the widget triggers a click. **Use `onNavigate` for nav-shaped clicks** — `click` is for buttons, dialog toggles, expand/collapse, etc.
|
|
167
|
+
|
|
168
|
+
**Page scrolling**: the agent can call `scroll_page` with `direction: "up" | "down" | "top" | "bottom"`. Default behavior scrolls the window by ±1 viewport height. Override with `onScrollPage` for custom scroll containers.
|
|
169
|
+
|
|
170
|
+
**Forms** — declarative wrappers. Tag the form and the fields the agent is allowed to fill:
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
import { LiveLayerForm, LiveLayerField } from "@livelayer/react";
|
|
174
|
+
|
|
175
|
+
<LiveLayerForm id="contact" intent="contact us — send a message">
|
|
176
|
+
<LiveLayerField name="name" label="Your name" />
|
|
177
|
+
<LiveLayerField name="email" label="Email" type="email" />
|
|
178
|
+
<LiveLayerField name="message" as="textarea" label="Message" />
|
|
179
|
+
<button type="submit">Send</button>
|
|
180
|
+
</LiveLayerForm>
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Or use raw HTML with `data-ll-form` / `data-ll-field`:
|
|
184
|
+
|
|
185
|
+
```html
|
|
186
|
+
<form data-ll-form="contact" data-ll-intent="contact us">
|
|
187
|
+
<input data-ll-field="name" name="name" />
|
|
188
|
+
<input data-ll-field="email" name="email" type="email" />
|
|
189
|
+
<textarea data-ll-field="message" name="message"></textarea>
|
|
190
|
+
<button type="submit">Send</button>
|
|
191
|
+
</form>
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The agent sees these in `PageContext.forms` and calls:
|
|
195
|
+
- `fill_form` — sets values via the React-controlled-input pattern (your `onChange` listeners fire correctly)
|
|
196
|
+
- `focus_field` — moves focus to a specific field
|
|
197
|
+
- `submit_form` — calls `form.requestSubmit()`. The widget publishes `{ type: "form_submitted", formId }` on success or `{ type: "form_submit_blocked", formId, reason: "validation" }` on HTML5 validation failure
|
|
198
|
+
|
|
199
|
+
**Privacy is enforced regardless of tagging**: `type="password"`, `autocomplete="cc-*"`, and `[data-ll-private="true"]` fields are NEVER agent-fillable. Card fields belong in Stripe Elements; we will not be the rail.
|
|
200
|
+
|
|
201
|
+
**Routes**: the agent can call `request_routes` to get up to 200 deduped `<a href>` entries from the page (internal flagged separately from external). Useful for "where can I go?" prompts.
|
|
202
|
+
|
|
203
|
+
### 5. Restrict what the agent can do (0.4.0)
|
|
204
|
+
|
|
205
|
+
Compliance / safety knob: pass an allowlist.
|
|
206
|
+
|
|
207
|
+
```tsx
|
|
208
|
+
<AvatarWidget
|
|
209
|
+
agentId="..."
|
|
210
|
+
capabilities={["read_page", "navigate", "scroll", "fill_forms"]}
|
|
211
|
+
// not in list: "click", "submit_forms"
|
|
212
|
+
/>
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
| Capability | Commands gated |
|
|
216
|
+
|---|---|
|
|
217
|
+
| `navigate` | `navigate` |
|
|
218
|
+
| `scroll` | `scroll_to`, `scroll_page` |
|
|
219
|
+
| `click` | `click` |
|
|
220
|
+
| `fill_forms` | `fill_form`, `focus_field` |
|
|
221
|
+
| `submit_forms` | `submit_form` |
|
|
222
|
+
| `read_page` | `request_page_context`, `request_routes` |
|
|
223
|
+
|
|
224
|
+
Default (`capabilities` undefined) = all enabled. **Recommended starter**: omit `submit_forms` for the first few weeks of production. Filling is reversible, submitting isn't.
|
|
225
|
+
|
|
226
|
+
### 6. Persist the session across pages (multi-page apps)
|
|
157
227
|
|
|
158
228
|
For SPAs (Next.js, Remix, React Router), mount the widget at the app root and the session survives route changes automatically. For multi-page apps where the entire React tree unmounts, use `controlledSession` to own the LiveKit Room yourself and keep it alive across reloads. See [the `ControlledSession` interface](src/AvatarWidget.tsx) for the contract.
|
|
159
229
|
|
|
160
|
-
###
|
|
230
|
+
### 7. Custom branding
|
|
161
231
|
|
|
162
232
|
```tsx
|
|
163
233
|
<AvatarWidget
|
|
@@ -188,8 +258,11 @@ All props are optional except `agentId`.
|
|
|
188
258
|
| `hideOn` | `RoutePattern[]` | Never render on matching paths. Wins over `showOn`. |
|
|
189
259
|
| `onNavigate` | `(href: string) => void` | Called on agent `navigate` command. Wire to your router. |
|
|
190
260
|
| `onScrollToSelector` | `(sel, behavior?) => void` | Called on agent `scroll_to` command. Default: `scrollIntoView({ behavior: "smooth" })`. |
|
|
261
|
+
| `onScrollPage` | `(direction, behavior?) => void` | Called on agent `scroll_page` command. Default: `window.scrollBy` / `scrollTo`. |
|
|
262
|
+
| `onClick` | `(selector: string) => void` | Called on agent `click` command. Default: `document.querySelector(selector)?.click()`. |
|
|
191
263
|
| `getPageContext` | `() => PageContext \| Promise<PageContext>` | Override the default DOM walker. |
|
|
192
264
|
| `pageContextExtras` | `Record<string, unknown>` | Extra app state attached to every page context snapshot. |
|
|
265
|
+
| `capabilities` | `AgentCapability[]` | Allowlist gating which commands the agent can run. |
|
|
193
266
|
| `position` | `"top-left" \| "top-right" \| "bottom-left" \| "bottom-right" \| "custom"` | Where the widget docks. Defaults to `"bottom-right"`. |
|
|
194
267
|
| `defaultDisplayMode` | `"hidden" \| "minimized" \| "expanded"` | Initial display mode. |
|
|
195
268
|
| `branding` | `BrandingConfig` | Colors, product name, logo. |
|
|
@@ -208,6 +281,22 @@ All props are optional except `agentId`.
|
|
|
208
281
|
|
|
209
282
|
Renders a wrapper element with `data-ll-region` + `data-ll-intent` that the page-context extractor prioritizes.
|
|
210
283
|
|
|
284
|
+
### `<LiveLayerForm>` + `<LiveLayerField>` (form primitives, 0.4.0)
|
|
285
|
+
|
|
286
|
+
```tsx
|
|
287
|
+
<LiveLayerForm id="signup" intent="create account" onSubmit={handleSubmit}>
|
|
288
|
+
<LiveLayerField name="email" label="Email" type="email" />
|
|
289
|
+
<LiveLayerField name="bio" as="textarea" label="Bio" />
|
|
290
|
+
<LiveLayerField name="role" as="select" label="Role">
|
|
291
|
+
<option value="dev">Developer</option>
|
|
292
|
+
<option value="pm">PM</option>
|
|
293
|
+
</LiveLayerField>
|
|
294
|
+
<button type="submit">Sign up</button>
|
|
295
|
+
</LiveLayerForm>
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
Equivalent to raw HTML with `data-ll-form` + `data-ll-field` attributes. Untagged forms remain invisible to the agent.
|
|
299
|
+
|
|
211
300
|
### Hooks (power users)
|
|
212
301
|
|
|
213
302
|
`useLiveKitSession`, `useDisplayMode`, `useAgentInfo`, `usePathname`, `useRouteMatch`, `useAudioLevel`, `useMicrophoneState`, `useCameraState`, `useScreenShareState`, `useMediaDevices`, `useTranscript`. All exported from the package root.
|
package/dist/index.d.ts
CHANGED
|
@@ -6,15 +6,35 @@ import { CSSProperties } from 'react';
|
|
|
6
6
|
import { ElementType } from 'react';
|
|
7
7
|
import { ErrorInfo } from 'react';
|
|
8
8
|
import { FC } from 'react';
|
|
9
|
+
import { FormHTMLAttributes } from 'react';
|
|
9
10
|
import { ForwardRefExoticComponent } from 'react';
|
|
11
|
+
import { InputHTMLAttributes } from 'react';
|
|
10
12
|
import { JSX } from 'react/jsx-runtime';
|
|
11
13
|
import { LiveKitSession } from '@livelayer/sdk';
|
|
12
14
|
import { ReactNode } from 'react';
|
|
13
15
|
import { RefAttributes } from 'react';
|
|
14
16
|
import { Room } from 'livekit-client';
|
|
17
|
+
import { SelectHTMLAttributes } from 'react';
|
|
15
18
|
import { SessionOptions } from '@livelayer/sdk';
|
|
19
|
+
import { TextareaHTMLAttributes } from 'react';
|
|
16
20
|
import { TranscriptEntry } from '@livelayer/sdk';
|
|
17
21
|
|
|
22
|
+
/**
|
|
23
|
+
* What the agent's data-channel commands are allowed to do. Pass to
|
|
24
|
+
* `<AvatarWidget capabilities={[...]} />` to restrict.
|
|
25
|
+
*
|
|
26
|
+
* Mapping:
|
|
27
|
+
* "navigate" → navigate command
|
|
28
|
+
* "scroll" → scroll_to + scroll_page commands
|
|
29
|
+
* "click" → click command
|
|
30
|
+
* "fill_forms" → fill_form + focus_field commands
|
|
31
|
+
* "submit_forms" → submit_form command
|
|
32
|
+
* "read_page" → request_page_context + request_routes commands
|
|
33
|
+
*
|
|
34
|
+
* Default (undefined): everything enabled (matches 0.3.x behavior).
|
|
35
|
+
*/
|
|
36
|
+
export declare type AgentCapability = "navigate" | "scroll" | "click" | "fill_forms" | "submit_forms" | "read_page";
|
|
37
|
+
|
|
18
38
|
/**
|
|
19
39
|
* Agent commands streamed over the LiveKit data channel. The base package
|
|
20
40
|
* recognizes universal types (agent_state, avatar_active, etc.) and forwards
|
|
@@ -39,6 +59,20 @@ export declare interface AgentInfo {
|
|
|
39
59
|
name: string;
|
|
40
60
|
avatarImageUrl: string;
|
|
41
61
|
idleLoopUrl: string | null;
|
|
62
|
+
/**
|
|
63
|
+
* 0.5.0 — capability allowlist set by the agent's owner in the
|
|
64
|
+
* Navigation settings tab. null = unrestricted. The widget applies
|
|
65
|
+
* this as the default for its `capabilities` prop unless the
|
|
66
|
+
* consumer overrides explicitly.
|
|
67
|
+
*/
|
|
68
|
+
capabilities?: string[] | null;
|
|
69
|
+
/**
|
|
70
|
+
* 0.5.0 — when true, the agent runtime fetches page context before
|
|
71
|
+
* each user turn. Surfaced here for observability; the widget does
|
|
72
|
+
* not need to behave differently based on this (the agent runtime
|
|
73
|
+
* does the work).
|
|
74
|
+
*/
|
|
75
|
+
autoPageContext?: boolean;
|
|
42
76
|
}
|
|
43
77
|
|
|
44
78
|
export declare interface AgentInfoHandle {
|
|
@@ -141,6 +175,32 @@ export declare interface AvatarWidgetProps {
|
|
|
141
175
|
getPageContext?: (extras?: Record<string, unknown>) => PageContext | Promise<PageContext>;
|
|
142
176
|
/** Free-form metadata bag the agent should always know about. */
|
|
143
177
|
pageContextExtras?: Record<string, unknown>;
|
|
178
|
+
/**
|
|
179
|
+
* Called on agent `scroll_page` commands. Default: scrolls window
|
|
180
|
+
* by ±1 viewport height (or to top/bottom). Override to scroll a
|
|
181
|
+
* custom container.
|
|
182
|
+
*/
|
|
183
|
+
onScrollPage?: (direction: "up" | "down" | "top" | "bottom", behavior?: "smooth" | "instant") => void;
|
|
184
|
+
/**
|
|
185
|
+
* Called on agent `click` commands. Default: dispatches click on
|
|
186
|
+
* the matched element. Override to add safety checks or block
|
|
187
|
+
* specific selectors. **Use `onNavigate` for nav-shaped clicks** —
|
|
188
|
+
* `click` here is for non-nav buttons / dialogs / state toggles.
|
|
189
|
+
*/
|
|
190
|
+
onClick?: (selector: string) => void;
|
|
191
|
+
/**
|
|
192
|
+
* Restrict what the agent's commands can do. If undefined, ALL
|
|
193
|
+
* capabilities are allowed (default — matches 0.3.x behavior).
|
|
194
|
+
*
|
|
195
|
+
* Available capabilities:
|
|
196
|
+
* "navigate" — navigate command
|
|
197
|
+
* "scroll" — scroll_to + scroll_page
|
|
198
|
+
* "click" — click
|
|
199
|
+
* "fill_forms" — fill_form + focus_field
|
|
200
|
+
* "submit_forms" — submit_form
|
|
201
|
+
* "read_page" — request_page_context + request_routes
|
|
202
|
+
*/
|
|
203
|
+
capabilities?: AgentCapability[];
|
|
144
204
|
onConnect?: () => void;
|
|
145
205
|
onDisconnect?: () => void;
|
|
146
206
|
onTranscript?: (entries: TranscriptEntry[]) => void;
|
|
@@ -188,6 +248,17 @@ export declare interface CameraStateHandle {
|
|
|
188
248
|
|
|
189
249
|
export declare function clearPageContextCache(): void;
|
|
190
250
|
|
|
251
|
+
export declare function clearRoutesCache(): void;
|
|
252
|
+
|
|
253
|
+
declare interface CommonFieldProps {
|
|
254
|
+
/** Field identifier. Becomes `data-ll-field` AND the input's `name`. */
|
|
255
|
+
name: string;
|
|
256
|
+
/** Visible label. Wrapped in <label>. */
|
|
257
|
+
label?: ReactNode;
|
|
258
|
+
/** Optional className for the wrapping <label>. */
|
|
259
|
+
labelClassName?: string;
|
|
260
|
+
}
|
|
261
|
+
|
|
191
262
|
export { ConnectionState }
|
|
192
263
|
|
|
193
264
|
/**
|
|
@@ -231,6 +302,13 @@ export declare class ErrorBoundary extends Component<Props, State> {
|
|
|
231
302
|
render(): ReactNode;
|
|
232
303
|
}
|
|
233
304
|
|
|
305
|
+
export declare interface ExtractedRoute {
|
|
306
|
+
href: string;
|
|
307
|
+
text: string;
|
|
308
|
+
/** Same origin as `window.location.origin`. External links surface but flagged. */
|
|
309
|
+
internal: boolean;
|
|
310
|
+
}
|
|
311
|
+
|
|
234
312
|
declare interface ExtractOptions {
|
|
235
313
|
/** Override doc — for tests. */
|
|
236
314
|
doc?: Document;
|
|
@@ -238,8 +316,14 @@ declare interface ExtractOptions {
|
|
|
238
316
|
|
|
239
317
|
export declare function extractPageContext(extras?: Record<string, unknown>, opts?: ExtractOptions): PageContext;
|
|
240
318
|
|
|
319
|
+
export declare function extractRoutes(doc?: Document): ExtractedRoute[];
|
|
320
|
+
|
|
321
|
+
declare type FieldElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
|
322
|
+
|
|
241
323
|
export declare function getCachedPageContext(extras?: Record<string, unknown>, opts?: ExtractOptions): PageContext;
|
|
242
324
|
|
|
325
|
+
export declare function getCachedRoutes(): ExtractedRoute[];
|
|
326
|
+
|
|
243
327
|
export declare interface LegacyAgentEventDetail {
|
|
244
328
|
eventName: string;
|
|
245
329
|
data: Record<string, unknown>;
|
|
@@ -247,6 +331,30 @@ export declare interface LegacyAgentEventDetail {
|
|
|
247
331
|
|
|
248
332
|
declare type LevelSubscriber = (level: number) => void;
|
|
249
333
|
|
|
334
|
+
export declare const LiveLayerField: ForwardRefExoticComponent<LiveLayerFieldProps & RefAttributes<FieldElement>>;
|
|
335
|
+
|
|
336
|
+
export declare type LiveLayerFieldProps = (CommonFieldProps & {
|
|
337
|
+
as?: "input";
|
|
338
|
+
} & Omit<InputHTMLAttributes<HTMLInputElement>, "name">) | (CommonFieldProps & {
|
|
339
|
+
as: "textarea";
|
|
340
|
+
} & Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "name">) | (CommonFieldProps & {
|
|
341
|
+
as: "select";
|
|
342
|
+
children: ReactNode;
|
|
343
|
+
} & Omit<SelectHTMLAttributes<HTMLSelectElement>, "name">);
|
|
344
|
+
|
|
345
|
+
export declare const LiveLayerForm: ForwardRefExoticComponent<LiveLayerFormProps & RefAttributes<HTMLFormElement>>;
|
|
346
|
+
|
|
347
|
+
export declare interface LiveLayerFormProps extends FormHTMLAttributes<HTMLFormElement> {
|
|
348
|
+
/** Stable identifier for the form. Becomes `data-ll-form`. */
|
|
349
|
+
id: string;
|
|
350
|
+
/**
|
|
351
|
+
* One-line description the agent sees. e.g. "create account",
|
|
352
|
+
* "request a demo". The agent uses this to decide WHEN to fill the
|
|
353
|
+
* form (matching user intent → form intent).
|
|
354
|
+
*/
|
|
355
|
+
intent?: string;
|
|
356
|
+
}
|
|
357
|
+
|
|
250
358
|
export declare const LiveLayerRegion: ForwardRefExoticComponent<LiveLayerRegionProps & RefAttributes<HTMLElement>>;
|
|
251
359
|
|
|
252
360
|
export declare interface LiveLayerRegionProps {
|
|
@@ -367,6 +475,20 @@ export declare interface PageContext {
|
|
|
367
475
|
label: string;
|
|
368
476
|
type: string;
|
|
369
477
|
}>;
|
|
478
|
+
/**
|
|
479
|
+
* Author-curated forms via <LiveLayerForm> / data-ll-form. The agent
|
|
480
|
+
* uses these to call `fill_form` / `submit_form`. Values NEVER included.
|
|
481
|
+
* (0.4.0)
|
|
482
|
+
*/
|
|
483
|
+
forms: Array<{
|
|
484
|
+
id: string;
|
|
485
|
+
intent?: string;
|
|
486
|
+
fields: Array<{
|
|
487
|
+
name: string;
|
|
488
|
+
label: string;
|
|
489
|
+
type: string;
|
|
490
|
+
}>;
|
|
491
|
+
}>;
|
|
370
492
|
/** Free-form metadata bag from the consumer's pageContextExtras prop. */
|
|
371
493
|
extras?: Record<string, unknown>;
|
|
372
494
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),n=require("react"),qt=require("@livelayer/sdk"),Ae=require("livekit-client");class xt extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,i){var s,o;(o=(s=this.props).onError)==null||o.call(s,r,i)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[e.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),e.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),e.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function vt(t){const[r,i]=n.useState("idle"),[s,o]=n.useState("idle"),[l,d]=n.useState([]),[f,u]=n.useState(null),[x,p]=n.useState(null),[a,c]=n.useState(null),[j,_]=n.useState(!1),[k,R]=n.useState(null),y=n.useRef(null),L=n.useRef(t.onDataMessage);L.current=t.onDataMessage,n.useEffect(()=>{const w={onConnectionStateChange:b=>{i(b),b==="connected"&&R(null)},onAgentStateChange:o,onTranscript:b=>d([...b]),onAgentConfig:u,onAudioTrack:b=>c(b),onVideoTrack:b=>p(b),onVideoTrackRemoved:()=>p(null),onError:b=>R(b),onDataMessage:b=>{var M;(M=L.current)==null||M.call(L,b)},onResumabilityChange:_},S=new qt.LiveKitSession({agentId:t.agentId,baseUrl:t.baseUrl,apiKey:t.apiKey,sessionEndpoint:t.sessionEndpoint,sessionBody:t.sessionBody},w);return y.current=S,i("idle"),o("idle"),d([]),u(null),p(null),c(null),_(!1),R(null),()=>{var b;(b=S.destroy)==null||b.call(S),y.current=null}},[t.agentId,t.baseUrl,t.apiKey,t.sessionEndpoint,JSON.stringify(t.sessionBody??{})]);const m=n.useCallback(async()=>{const w=y.current;if(w)try{await w.connect()}catch(S){throw R(S instanceof Error?S.message:String(S)),S}},[]),C=n.useCallback(()=>{const w=y.current;w&&w.disconnect()},[]),N=n.useCallback(()=>{var w;return((w=y.current)==null?void 0:w.getRoom())??null},[]);return{connectionState:r,agentState:s,transcript:l,agentConfig:f,videoElement:x,audioElement:a,canResume:j,error:k,connect:m,disconnect:C,getRoom:N,session:y.current}}function yt(){const t=n.useRef(null),r=n.useRef(null),i=n.useRef(null),s=n.useRef(null),o=n.useRef(new Set),l=n.useRef(null),d=n.useCallback(()=>{const a=r.current;if(!a){s.current=null;return}(!l.current||l.current.length!==a.frequencyBinCount)&&(l.current=new Uint8Array(new ArrayBuffer(a.frequencyBinCount)));const c=l.current;a.getByteFrequencyData(c);let j=0;for(let k=0;k<c.length;k++)j+=c[k];const _=j/c.length/255;for(const k of o.current)try{k(_)}catch(R){console.error("[useAudioLevel] subscriber threw:",R)}s.current=requestAnimationFrame(d)},[]),f=n.useCallback(()=>{if(t.current||typeof window>"u"||typeof AudioContext>"u")return;const a=new AudioContext,c=a.createAnalyser();c.fftSize=64,c.connect(a.destination),t.current=a,r.current=c},[]),u=n.useCallback(a=>{if(f(),!(!t.current||!r.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=t.current.createMediaElementSource(a);c.connect(r.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}s.current===null&&(s.current=requestAnimationFrame(d))}},[f,d]),x=n.useCallback(()=>{if(s.current!==null&&(cancelAnimationFrame(s.current),s.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),p=n.useCallback(a=>(o.current.add(a),()=>{o.current.delete(a)}),[]);return n.useEffect(()=>()=>{if(x(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(t.current){try{t.current.close()}catch{}t.current=null}o.current.clear(),l.current=null},[x]),{attach:u,detach:x,subscribe:p}}function bt(){const[t,r]=n.useState(!1),[i,s]=n.useState(null),o=n.useRef(null),l=n.useRef(null),d=n.useCallback(async p=>{if(o.current&&l.current){try{await l.current.localParticipant.unpublishTrack(o.current)}catch{}o.current.stop(),o.current=null}l.current=p,s(null);try{const a=await Ae.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await p.localParticipant.publishTrack(a),o.current=a,r(a.isMuted)}catch(a){const c=a instanceof Error&&a.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw s(c),a}},[]),f=n.useCallback(()=>{const p=o.current;p&&(p.isMuted?(p.unmute(),r(!1)):(p.mute(),r(!0)))},[]),u=n.useCallback(()=>{const p=o.current,a=l.current;if(p&&a){try{a.localParticipant.unpublishTrack(p)}catch{}p.stop()}o.current=null,l.current=null,r(!1)},[]),x=n.useCallback(()=>s(null),[]);return{isMuted:t,micError:i,toggleMute:f,setupMic:d,teardownMic:u,clearError:x}}const Gt={resolution:{width:640,height:480,frameRate:24}};function _t(){const[t,r]=n.useState(!1),[i,s]=n.useState(null),[o,l]=n.useState(null),[d,f]=n.useState(""),u=n.useRef(null),x=n.useRef(null),p=n.useCallback(y=>{u.current=y},[]),a=n.useCallback(()=>{const y=u.current,L=x.current;if(L&&y){const m=y.localParticipant.getTrackPublication(Ae.Track.Source.Camera);if(m!=null&&m.track){try{y.localParticipant.unpublishTrack(m.track)}catch{}m.track.stop()}else L.stop()}x.current=null,l(null),r(!1)},[]),c=n.useCallback(async y=>{const L=u.current;if(L){s(null);try{const m={...Gt};y&&(m.deviceId=y);const C=await Ae.createLocalVideoTrack(m);await L.localParticipant.publishTrack(C),x.current=C;const N=C.attach();l(N),r(!0),y&&f(y);try{L.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(m){const C=m instanceof Error&&m.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";s(C)}}},[]),j=n.useCallback(async()=>{t?a():await c(d||void 0)},[t,d,a,c]),_=n.useCallback(async y=>{a(),await c(y)},[a,c]),k=n.useCallback(()=>{a(),u.current=null,s(null),f("")},[a]),R=n.useCallback(()=>s(null),[]);return n.useEffect(()=>()=>{x.current&&x.current.stop()},[]),{isEnabled:t,error:i,previewEl:o,activeDeviceId:d,toggle:j,switchDevice:_,attachRoom:p,teardown:k,clearError:R}}function wt(){const[t,r]=n.useState(!1),[i,s]=n.useState(null),[o,l]=n.useState(null),d=n.useRef(null),f=n.useCallback(c=>{d.current=c},[]),u=n.useCallback(()=>l(null),[]),x=n.useCallback(async()=>{const c=d.current;if(c){if(t){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}s(null);try{await c.localParticipant.setScreenShareEnabled(!0);let j=0;const _=()=>{const k=c.localParticipant.getTrackPublication(Ae.Track.Source.ScreenShare);if(k!=null&&k.track){const R=k.track.attach();l(R),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}j++<10?setTimeout(_,100):r(!0)};_()}catch(j){const _=j instanceof Error?j.name:"";_!=="NotAllowedError"&&_!=="AbortError"&&s("Screen share unavailable. Try again."),r(!1)}}},[t,u]),p=n.useCallback(()=>{const c=d.current;if(c&&t)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),s(null),d.current=null},[t,u]),a=n.useCallback(()=>s(null),[]);return{isEnabled:t,error:i,previewEl:o,toggle:x,attachRoom:f,teardown:p,clearError:a}}function kt(){const[t,r]=n.useState([]),[i,s]=n.useState([]),o=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const l=await navigator.mediaDevices.enumerateDevices();r(l.filter(d=>d.kind==="audioinput")),s(l.filter(d=>d.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(o(),typeof navigator>"u"||!navigator.mediaDevices)return;const l=()=>void o();return navigator.mediaDevices.addEventListener("devicechange",l),()=>navigator.mediaDevices.removeEventListener("devicechange",l)},[o]),{mics:t,cameras:i,refresh:o}}function Ct(t,r,i=!1){const[s,o]=n.useState(null),[l,d]=n.useState(null),[f,u]=n.useState(!i&&!!t);return n.useEffect(()=>{if(i||!t){u(!1);return}const x=new AbortController,p=r||"https://app.livelayer.studio";return u(!0),d(null),fetch(`${p}/api/widget/agent/${encodeURIComponent(t)}`,{signal:x.signal}).then(async a=>{if(!a.ok){const c=await a.json().catch(()=>({}));throw new Error(c.error||`HTTP ${a.status}`)}return a.json()}).then(a=>{x.signal.aborted||(o(a),u(!1))}).catch(a=>{x.signal.aborted||(d(a instanceof Error?a.message:"Agent lookup failed"),u(!1))}),()=>x.abort()},[t,r,i]),{info:s,error:l,loading:f}}function Kt(t){if(typeof window>"u")return null;try{return window.localStorage.getItem(t)}catch{return null}}function Yt(t,r){if(!(typeof window>"u"))try{window.localStorage.setItem(t,r)}catch{}}function jt({value:t,defaultValue:r="expanded",onChange:i}={}){const s=t!==void 0,[o,l]=n.useState(r),d=s?t:o,f=n.useCallback(u=>{u!==d&&(s||l(u),i==null||i(u))},[d,s,i]);return[d,f]}const Xt=["hidden","minimized","expanded"];function Jt(t){return t&&Xt.includes(t)?t:null}function St({value:t,defaultValue:r="expanded",onChange:i,persistKey:s="ll-widget",disablePersistence:o=!1}={}){const l=`${s}:display-mode`,d=n.useRef(!1),[f,u]=jt({value:t,defaultValue:r,onChange:x=>{t===void 0&&!o&&Yt(l,x),i==null||i(x)}});return n.useEffect(()=>{if(d.current||(d.current=!0,o||t!==void 0))return;const x=Jt(Kt(l));x&&x!==f&&u(x)},[]),[f,u]}const Qt=640;function Et(t=Qt){const[r,i]=n.useState(!1);return n.useEffect(()=>{if(t===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const s=`(max-width: ${t-1}px)`,o=window.matchMedia(s),l=()=>i(o.matches);return l(),typeof o.addEventListener=="function"?(o.addEventListener("change",l),()=>o.removeEventListener("change",l)):(o.addListener(l),()=>{o.removeListener(l)})},[t]),r}const st="__llHistoryPatched",Me="ll:pathname";function Zt(){if(typeof window>"u"||window.history[st])return;const t=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...i){const s=t.apply(this,i);return window.dispatchEvent(new Event(Me)),s},window.history.replaceState=function(...i){const s=r.apply(this,i);return window.dispatchEvent(new Event(Me)),s},window.history[st]=!0}function ot(){return typeof window>"u"?"/":window.location.pathname||"/"}function Nt(t){const[r,i]=n.useState(()=>t??ot());return n.useEffect(()=>{if(t!==void 0)return;Zt();const s=()=>i(ot());return s(),window.addEventListener("popstate",s),window.addEventListener(Me,s),()=>{window.removeEventListener("popstate",s),window.removeEventListener(Me,s)}},[t]),t??r}const lt=new Map,en=/[\\^$+?.()|{}[\]]/g;function tn(t){return t.replace(en,"\\$&")}function nn(t){const r=lt.get(t);if(r)return r;const i=t.length>1&&t.endsWith("/")?t.slice(0,-1):t,s="",o="",l=i.replace(/\*\*/g,s).replace(/\*/g,o),f=tn(l).replace(new RegExp(`\\/${s}`,"g"),"(?:\\/.*)?").replace(new RegExp(s,"g"),".*").replace(new RegExp(o,"g"),"[^/]+"),u=new RegExp(`^${f}\\/?$`);return lt.set(t,u),u}function rn(t,r){const i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return nn(t).test(i)}function Lt(t,r){return typeof t=="function"?t(r):t instanceof RegExp?t.test(r):rn(t,r)}function at(t,r){if(!t||t.length===0)return!1;for(const i of t)if(Lt(i,r))return!0;return!1}function Rt(t,r,i){return t===void 0?!0:at(i,t)?!1:r&&r.length>0?at(r,t):!0}function At(t,r,i){return n.useMemo(()=>Rt(t,r,i),[t,r,i])}const ct=({muted:t=!1,className:r})=>t?e.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):e.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),ut=({className:t})=>e.jsx("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),sn=({className:t})=>e.jsx("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),on={left:180,right:0,up:-90,down:90},ln=({direction:t="right",className:r})=>e.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${on[t]}deg)`},"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function an(t){return t==="top-left"||t==="bottom-left"?"left":"right"}const Mt="ll-hidden-tab-center-y",cn=5,dt=16;function un(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Mt);if(!t)return null;const r=Number.parseFloat(t);return Number.isFinite(r)?r:null}catch{return null}}function ft(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Mt,String(t))}catch{}}const dn=({position:t,isMobile:r,isSpeaking:i,onExpand:s,label:o="Open widget"})=>{const l=an(t),d=l==="right"?"left":"right",f=r?80:72,[u,x]=n.useState(null),[p,a]=n.useState(!1),c=n.useRef(null),j=n.useRef(!1),_=n.useCallback(w=>{if(typeof window>"u")return w;const S=f/2,b=dt+S,M=window.innerHeight-dt-S;return M<b?Math.max(b,w):Math.max(b,Math.min(M,w))},[f]);n.useEffect(()=>{const w=un();x(_(w??window.innerHeight/2));const S=()=>{x(b=>b===null?null:_(b))};return window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[_]);const k=n.useCallback(w=>{if(!(w.pointerType==="mouse"&&w.button!==0)&&u!==null){try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}c.current={startClientY:w.clientY,startCenterY:u,moved:!1}}},[u]),R=n.useCallback(w=>{const S=c.current;if(!S)return;const b=w.clientY-S.startClientY;!S.moved&&Math.abs(b)>cn&&(S.moved=!0,a(!0)),S.moved&&x(_(S.startCenterY+b))},[_]),y=n.useCallback(w=>{const S=c.current;if(S){try{w.currentTarget.releasePointerCapture(w.pointerId)}catch{}c.current=null,S.moved&&(a(!1),j.current=!0,x(b=>(b!==null&&ft(b),b)))}},[]),L=n.useCallback(()=>{if(j.current){j.current=!1;return}s()},[s]),m=n.useCallback(w=>{if(w.key==="ArrowUp"||w.key==="ArrowDown"){w.preventDefault();const S=w.key==="ArrowUp"?-8:8;x(b=>{if(b===null)return b;const M=_(b+S);return ft(M),M})}},[_]),C=["ll-hidden",`ll-hidden--${l}`,r?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,p?"is-dragging":null].filter(Boolean).join(" "),N=u===null?void 0:{top:`${u-f/2}px`,transform:"none"};return e.jsx("button",{type:"button",className:C,onPointerDown:k,onPointerMove:R,onPointerUp:y,onPointerCancel:y,onClick:L,onKeyDown:m,"aria-label":o,"data-position":t,style:N,children:e.jsx(ln,{direction:d,className:"ll-hidden__chevron"})})},fn=({audioLevel:t,bars:r=20,maxHeight:i=20,minHeight:s=4,className:o,barClassName:l})=>{const d=n.useRef(null),f=n.useRef([]),u=n.useMemo(()=>{const p=(Math.sqrt(5)-1)/2;return Array.from({length:r},(a,c)=>.5+c*p%1*.5)},[r]);n.useEffect(()=>t.subscribe(a=>{for(let c=0;c<r;c++){const j=f.current[c];if(!j)continue;const _=Math.max(s,a*i*u[c]);j.style.height=`${_}px`}}),[t,r,i,s,u]);const x=["ll-waveform",o].filter(Boolean).join(" ");return e.jsx("div",{ref:d,className:x,"aria-hidden":"true",children:Array.from({length:r},(p,a)=>e.jsx("div",{ref:c=>{f.current[a]=c},className:["ll-waveform__bar",l].filter(Boolean).join(" "),style:{height:`${s}px`}},a))})},hn=({position:t,isMobile:r,agentName:i,avatarImageUrl:s,agentState:o,isMuted:l,audioLevel:d,onExpand:f,onToggleMute:u,onClose:x})=>r?e.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:e.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:f,"aria-label":`Expand ${i} widget`,children:[s?e.jsx("img",{src:s,alt:i,className:"ll-minimized__avatar"}):e.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),e.jsx(fn,{audioLevel:d,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),e.jsx("span",{className:"ll-minimized__name",children:i}),e.jsxs("div",{className:"ll-minimized__controls",children:[e.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:p=>{p.stopPropagation(),u()},onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.stopPropagation(),p.preventDefault(),u())},"aria-label":l?"Unmute microphone":"Mute microphone",children:e.jsx(ct,{muted:l,className:"ll-minimized__icon"})}),e.jsx(ut,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):e.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":t,role:"region","aria-label":`${i} widget`,children:e.jsxs("div",{className:"ll-minimized__surface",children:[s?e.jsx("img",{src:s,alt:i,className:"ll-minimized__avatar"}):e.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),e.jsxs("div",{className:"ll-minimized__meta",children:[e.jsx("span",{className:"ll-minimized__name",children:i}),e.jsx("span",{className:"ll-minimized__state",children:o==="speaking"?"Speaking":o==="thinking"?"Thinking":"Listening"})]}),e.jsxs("div",{className:"ll-minimized__controls",children:[e.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":l?"Unmute microphone":"Mute microphone",children:e.jsx(ct,{muted:l,className:"ll-minimized__icon"})}),e.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":`Expand ${i} widget`,children:e.jsx(ut,{className:"ll-minimized__icon"})}),e.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:x,"aria-label":"Close widget",children:e.jsx(sn,{className:"ll-minimized__icon"})})]})]})}),pn=({src:t,alt:r,preCannedPlaying:i=!1,className:s,style:o})=>{const[l,d]=n.useState(!1),f=n.useRef(t);if(n.useEffect(()=>{f.current!==t&&(f.current=t,d(!1))},[t]),!t)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:l?1:0,...o};return e.jsx("img",{src:t,alt:r,className:s,style:u,loading:"eager",fetchpriority:"high",onLoad:()=>d(!0)})},mn=({position:t,isMobile:r,agentName:i,avatarImageUrl:s,idleLoopUrl:o,greeting:l,branding:d,teamMembers:f,currentTeamMemberId:u,isSwitchingTeamMember:x,teamSwitcherOpen:p,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:j,onToggleLanguageMenu:_,connectionState:k,agentState:R,transcript:y,canResume:L,needsUserGesture:m,error:C,isMuted:N,micError:w,micDevices:S,isCameraEnabled:b,cameraPreviewEl:M,cameraDevices:_e,activeCameraId:Te,isScreenShareEnabled:V,screenPreviewEl:q,isSpeakerMuted:Y,allowCamera:we,allowScreenShare:te,allowTyping:ne,avatarVideoContainerRef:re,onConnect:X,onDisconnect:ie,onRetry:se,onResumeAudio:oe,onToggleMute:A,onToggleCamera:Ie,onSwitchCameraDevice:Pe,onToggleScreenShare:De,onToggleSpeaker:ke,onSendMessage:le,onMinimize:ae,onClose:Ce,onClearMicError:ze})=>{var Se;const U=y.length>0?y[y.length-1]:null,T=((f==null?void 0:f.length)??0)>1,J=k==="connecting"||k==="connected",O=k==="connected",G=k==="idle"||k==="disconnected"||k==="error",Q=n.useRef(null),ce=n.useRef(null);n.useEffect(()=>{const h=Q.current;h&&(h.innerHTML="",M&&(M.style.width="100%",M.style.height="100%",M.style.objectFit="cover",M.style.transform="scaleX(-1)",h.appendChild(M)))},[M]),n.useEffect(()=>{const h=ce.current;h&&(h.innerHTML="",q&&(q.style.width="100%",q.style.height="100%",q.style.objectFit="contain",h.appendChild(q)))},[q]);const[$,B]=n.useState(!1),[H,K]=n.useState(!1);n.useEffect(()=>{if(!$&&!H&&!j&&!p)return;const h=()=>{B(!1),K(!1),j&&_(),p&&a()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[$,H,j,p,_,a]);const[ue,de]=n.useState(""),ge=n.useCallback(h=>{h.preventDefault();const D=ue.trim();D&&(le(D),de(""))},[ue,le]),je=d.productName||"Live Layer",fe=O&&(U!=null&&U.text)?U.text:l||"",xe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return e.jsxs("div",{className:xe,"data-position":t,"data-state":O?"connected":J?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[e.jsxs("div",{className:"ll-expanded__bg",children:[s?e.jsx(pn,{src:s,alt:i,className:"ll-expanded__bg-img"}):e.jsx("div",{className:"ll-expanded__bg-fallback",children:e.jsx("span",{className:"ll-expanded__bg-initial",children:((Se=i==null?void 0:i.charAt(0))==null?void 0:Se.toUpperCase())||"A"})}),o&&!O&&e.jsx("video",{className:"ll-expanded__bg-idle",src:o,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),e.jsx("div",{ref:re,className:"ll-expanded__video"}),k==="connecting"&&e.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[e.jsx("div",{className:"ll-expanded__spinner"}),e.jsx("p",{className:"ll-expanded__overlay-text",children:x?"Switching...":"Connecting..."})]}),m&&O&&e.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:oe,children:[e.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:e.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),e.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),J?e.jsxs("div",{className:"ll-expanded__topbar",children:[e.jsxs("div",{className:"ll-expanded__topbar-left",children:[e.jsxs("div",{className:"ll-expanded__pill-wrap",children:[e.jsxs("button",{type:"button",className:"ll-hpill",onClick:h=>{T&&(h.stopPropagation(),a())},"aria-haspopup":T?"listbox":void 0,"aria-expanded":T?p:void 0,children:[e.jsx("span",{className:"ll-hpill__label",children:i}),T&&e.jsx(Le,{})]}),T&&p&&e.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:f==null?void 0:f.map(h=>e.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===u?"is-active":""}`,onClick:()=>c(h.id),role:"option","aria-selected":h.id===u,children:[h.avatarImageUrl&&e.jsx("img",{src:h.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),e.jsx("span",{className:"ll-hmenu__name",children:h.name}),h.role&&e.jsx("span",{className:"ll-hmenu__role",children:h.role})]},h.id))})]}),e.jsxs("div",{className:"ll-expanded__pill-wrap",children:[e.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:h=>{h.stopPropagation(),_()},"aria-haspopup":"listbox","aria-expanded":j,"aria-label":"Language: English",title:"Language: English",children:[e.jsx("span",{className:"ll-hpill__label",children:"EN"}),e.jsx(Le,{})]}),j&&e.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:e.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:e.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),e.jsx("span",{className:`ll-expanded__state ll-expanded__state--${R}`,children:R})]}),e.jsxs("div",{className:"ll-expanded__header-actions",children:[e.jsx("button",{type:"button",className:"ll-hbtn",onClick:ae,"aria-label":"Minimize widget",title:"Minimize",children:e.jsx(pt,{})}),e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ce,"aria-label":"End call",title:"End call",children:e.jsx(ht,{})})]})]}):e.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[e.jsx("span",{className:"ll-expanded__brand",children:je}),e.jsxs("div",{className:"ll-expanded__header-actions",children:[e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:ae,"aria-label":"Minimize widget",children:e.jsx(pt,{})}),e.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ce,"aria-label":"Close widget",children:e.jsx(ht,{})})]})]}),G&&(()=>{const h=L?"Restart paused session":k==="disconnected"?"Reconnect to agent":"Start video call",D=L?"Pick up where you left off":null,$e=k==="idle"&&!L&&!C;return e.jsxs(e.Fragment,{children:[$e&&e.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:X,"aria-label":h,children:[e.jsx("div",{className:"ll-expanded__play-circle",children:e.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:e.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),e.jsx("span",{className:"ll-expanded__play-label",children:h})]}),e.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[l&&e.jsx("div",{className:"ll-expanded__transcript",children:e.jsx("p",{className:"ll-expanded__transcript-text",children:l})}),D&&e.jsx("p",{className:"ll-expanded__cta-sublabel",children:D}),e.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:X,"aria-label":h,children:h})]})]})})(),e.jsxs("div",{className:`ll-expanded__pip ${J&&(b||V)?"is-visible":""}`,children:[e.jsx("div",{ref:ce,className:V?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),e.jsx("div",{ref:Q,className:!V&&b?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),J?e.jsxs("div",{className:"ll-expanded__bottom",children:[fe&&e.jsx("div",{className:"ll-expanded__transcript",children:e.jsx("p",{className:"ll-expanded__transcript-text",children:fe})}),e.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[te&&e.jsx("button",{type:"button",className:`ll-tool ${V?"is-on":""}`,onClick:De,"aria-label":V?"Stop sharing screen":"Share screen",title:V?"Stop sharing":"Share screen",children:e.jsx(gn,{})}),we&&e.jsxs("div",{className:"ll-tool-split",children:[e.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${b?"is-on":""}`,onClick:Ie,"aria-label":b?"Turn off camera":"Turn on camera",title:b?"Stop camera":"Start camera",children:e.jsx(xn,{})}),e.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${b?"is-on":""}`,onClick:h=>{h.stopPropagation(),K(D=>!D),B(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":H,children:e.jsx(Le,{})}),H&&_e.length>0&&e.jsx(mt,{label:"Camera",devices:_e,activeId:Te,onPick:h=>{K(!1),Pe(h)}})]}),e.jsxs("div",{className:"ll-tool-split",children:[e.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${N?"is-muted":""}`,onClick:A,"aria-label":N?"Unmute microphone":"Mute microphone",title:N?"Unmute":"Mute",children:e.jsx(vn,{muted:N})}),e.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${N?"is-muted":""}`,onClick:h=>{h.stopPropagation(),B(D=>!D),K(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":$,children:e.jsx(Le,{})}),$&&S.length>0&&e.jsx(mt,{label:"Microphone",devices:S,activeId:"",onPick:()=>B(!1)})]}),e.jsx("button",{type:"button",className:`ll-tool ${Y?"is-muted":""}`,onClick:ke,"aria-label":Y?"Unmute speaker":"Mute speaker",title:Y?"Unmute speaker":"Mute speaker",children:e.jsx(yn,{muted:Y})})]}),ne&&e.jsxs("form",{className:"ll-message-input",onSubmit:ge,children:[e.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:ue,onChange:h=>de(h.target.value),"aria-label":"Message the agent"}),ue.trim()&&e.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:e.jsx(bn,{})})]}),e.jsx("button",{type:"button",className:"ll-expanded__end",onClick:ie,children:"End conversation"})]}):null,(()=>{if(w&&k!=="error")return e.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[e.jsx("span",{children:w}),e.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:ze,"aria-label":"Dismiss",children:"×"})]});if(!C||k!=="error")return null;let h="Failed to connect",D="Try again";return C==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":C==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":C==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":C==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":C==="CONNECT_FAILED"?h="Connection failed. Check your network.":C.length<80&&(h=C),e.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:se,children:D})]})})()]})};function Le(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})}function ht(){return e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function pt(){return e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function gn(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),e.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),e.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function xn(){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),e.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function vn({muted:t}){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),t&&e.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function yn({muted:t}){return e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t?e.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),e.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function bn(){return e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),e.jsx("polyline",{points:"12 5 19 12 12 19"})]})}const mt=({label:t,devices:r,activeId:i,onPick:s})=>e.jsxs("div",{className:"ll-device-menu",onClick:o=>o.stopPropagation(),role:"listbox",children:[e.jsx("p",{className:"ll-device-menu__label",children:t}),r.map((o,l)=>{const d=i===o.deviceId;return e.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>s(o.deviceId),role:"option","aria-selected":d,children:[d&&e.jsx("span",{className:"ll-device-menu__dot",children:"●"}),e.jsx("span",{className:"ll-device-menu__name",children:o.label||`${t} ${l+1}`})]},o.deviceId||l)})]}),Re=4096,_n=20,wn=20,kn=10,gt=500,Cn=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function ye(t){if(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))return!0;let r=t;for(;r;){for(const i of Cn)if(r.matches(i))return!0;r=r.parentElement}return!1}function be(t){if(typeof window>"u")return!0;const r=t.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,s=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<i&&r.left<s}function jn(t){if(t.type==="password")return!0;const r=(t.getAttribute("autocomplete")||"").toLowerCase();return!!(r==="off"||r.startsWith("cc-"))}function Sn(t){const r=t.getAttribute("id");if(r){const l=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(l!=null&&l.textContent)return l.textContent.trim()}const i=t.getAttribute("aria-label");if(i)return i.trim();const s=t.getAttribute("placeholder");if(s)return s.trim();const o=t.closest("label");return o!=null&&o.textContent?o.textContent.trim():""}function he(t,r){return t.length<=r?t:t.slice(0,r-1)+"…"}function pe(t){return t.length}function Tt(t,r={}){const i=r.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],extras:t};const s=typeof window<"u"&&window.location.href||"",o=typeof window<"u"&&window.location.pathname||"/",l=i.title||"",d=Array.from(i.querySelectorAll("[data-ll-region]")),f=[];for(const m of d){if(f.length>=kn)break;if(ye(m)||!be(m))continue;const C=m.getAttribute("data-ll-region")??"",N=m.getAttribute("data-ll-intent")??void 0,w=he((m.innerText||m.textContent||"").trim(),gt*2);!C||!w||f.push({id:C,intent:N,text:w})}const u=[],x=["H1","H2","H3","H4","H5","H6"],p=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const m of p){if(ye(m)||!be(m))continue;const C=(m.textContent||"").trim();C&&u.push(`${m.tagName}: ${he(C,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const m of a){if(ye(m)||!be(m)||x.includes(m.tagName))continue;const C=(m.textContent||"").trim();C.length>10&&u.push(he(C,gt))}const c=u.join(`
|
|
2
|
-
`),j=[],_=Array.from(i.querySelectorAll("a[href]"));for(const m of _){if(j.length>=_n)break;if(ye(m)||!be(m))continue;const C=m.getAttribute("href")||"",N=(m.textContent||"").trim();!C||!N||j.push({href:C,text:he(N,100)})}const k=[],R=Array.from(i.querySelectorAll("input, textarea, select"));for(const m of R){if(k.length>=wn)break;if(ye(m)||m instanceof HTMLInputElement&&jn(m)||!be(m))continue;const C=Sn(m),N=m instanceof HTMLInputElement?m.type:m.tagName.toLowerCase();C&&k.push({label:he(C,100),type:N})}const y={url:s,title:l,pathname:o,regions:f,visibleText:c,visibleLinks:j,visibleFields:k,extras:t};let L=pe(JSON.stringify(y.regions))+pe(y.visibleText)+pe(JSON.stringify(y.visibleLinks))+pe(JSON.stringify(y.visibleFields));for(;L>Re&&y.visibleFields.length>0;)y.visibleFields.pop(),L=pe(JSON.stringify(y.visibleFields));for(;L>Re&&y.visibleLinks.length>0;)y.visibleLinks.pop(),L-=80;return pe(y.visibleText)>Re&&(y.visibleText=he(y.visibleText,Re-100)),y}let me=null;function Ve(t,r={}){const i=Date.now(),o=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(me&&me.key===o&&i-me.at<1e3)return me.ctx;const l=Tt(t,r);return me={key:o,at:i,ctx:l},l}function It(){me=null}const En=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context"]);function Nn(t){var Qe,Ze,et,tt,nt,rt;const{agentId:r,apiKey:i,baseUrl:s="https://app.livelayer.studio",sessionEndpoint:o,sessionBody:l,autoConnect:d=!1,displayMode:f,defaultDisplayMode:u="expanded",onDisplayModeChange:x,position:p="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:j=!1,teamMembers:_,currentTeamMemberId:k,onTeamMemberChange:R,idleLoopUrl:y,greeting:L,avatarImageUrl:m,agentName:C,branding:N={},allowCamera:w=!0,allowScreenShare:S=!0,allowTyping:b=!0,showOn:M,hideOn:_e,pathname:Te,onNavigate:V,onScrollToSelector:q,getPageContext:Y,pageContextExtras:we,onConnect:te,onDisconnect:ne,onTranscript:re,onAgentState:X,onConnectionStateChange:ie,onAgentEvent:se,onAgentCommand:oe,controlledSession:A,className:Ie,style:Pe,zIndex:De=2147483647}=t,ke=Nt(Te),le=At(ke,M,_e);n.useEffect(()=>{It()},[ke]);const ae=k!==void 0,[Ce,ze]=n.useState(()=>{var v;return k??((v=_==null?void 0:_[0])==null?void 0:v.id)}),U=ae?k:Ce,T=n.useMemo(()=>(_==null?void 0:_.find(v=>v.id===U))??null,[_,U]),J=(T==null?void 0:T.agentId)??r,[O,G]=St({value:f,defaultValue:u,onChange:x,persistKey:c,disablePersistence:j}),Q=Et(a),ce=yt(),$=bt(),B=_t(),H=wt(),K=kt(),[ue,de]=n.useState(!1),[ge,je]=n.useState(!1),[fe,xe]=n.useState(!1),[Se,h]=n.useState(!1),[D,$e]=n.useState(!1),Be=n.useRef(V),Ue=n.useRef(q),qe=n.useRef(Y),Ge=n.useRef(we),Ee=n.useRef(null);Be.current=V,Ue.current=q,qe.current=Y,Ge.current=we;const Oe=n.useCallback(v=>{var F;const E=v;if(!(!E.type||typeof E.type!="string")){if(se==null||se({eventName:E.type,data:v}),E.type==="navigate"){const z=typeof E.href=="string"?E.href:null;if(!z){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(Be.current){try{Be.current(z)}catch(P){console.warn(`[LiveLayer] onNavigate threw for "${z}". Falling back. Error:`,P)}return}if(typeof document<"u"){const P=document.querySelector(`a[href="${z.replace(/"/g,'\\"')}"]`);if(P){P.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",z),window.dispatchEvent(new PopStateEvent("popstate"))}catch(P){console.warn(`[LiveLayer] history.pushState fallback failed for "${z}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,P)}return}if(E.type==="scroll_to"){const z=typeof E.selector=="string"?E.selector:null;if(!z)return;const P=E.behavior==="instant"?"instant":"smooth";if(Ue.current){try{Ue.current(z,P)}catch(W){console.warn("[LiveLayer] onScrollToSelector threw.",W)}return}if(typeof document<"u"){let W=null;try{W=document.querySelector(z)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${z}".`);return}if(!W){console.warn(`[LiveLayer] scroll_to: no element matched "${z}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}W.scrollIntoView({behavior:P,block:"start"})}return}if(E.type==="request_page_context"){const z=(F=Ee.current)==null?void 0:F.call(Ee),P=Z=>{const ee=z,Ne=ee==null?void 0:ee.localParticipant;if(Ne!=null&&Ne.publishData)try{const We=new TextEncoder().encode(JSON.stringify(Z));Ne.publishData(We,{reliable:!0})}catch(We){console.warn("[LiveLayer] publishData failed.",We)}},W=Ge.current,it=qe.current;try{if(it){const Z=it(W);if(Z instanceof Promise){P({type:"page_context_pending"}),Z.then(ee=>P({type:"page_context",context:ee})).catch(ee=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",ee),P({type:"page_context",context:Ve(W)})});return}P({type:"page_context",context:Z});return}P({type:"page_context",context:Ve(W)})}catch(Z){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",Z),P({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],extras:W}})}return}En.has(E.type)||oe==null||oe(E)}},[oe,se]),I=vt({agentId:A?"__controlled__":J,baseUrl:s,apiKey:i,sessionEndpoint:o,sessionBody:l,onDataMessage:A?void 0:Oe});n.useEffect(()=>{if(A!=null&&A.subscribeToDataMessages)return A.subscribeToDataMessages(Oe)},[A,Oe]),Ee.current=()=>{var v;return(v=I.getRoom)==null?void 0:v.call(I)};const g=n.useMemo(()=>A?{connectionState:A.connectionState,agentState:A.agentState,transcript:A.transcript,videoElement:A.videoElement,audioElement:A.audioElement,canResume:A.canResume,error:A.error,agentConfig:null,connect:async()=>{await A.onConnect()},disconnect:()=>A.onDisconnect(),getRoom:I.getRoom,isControlled:!0}:{connectionState:I.connectionState,agentState:I.agentState,transcript:I.transcript,videoElement:I.videoElement,audioElement:I.audioElement,canResume:I.canResume,error:I.error,agentConfig:I.agentConfig,connect:I.connect,disconnect:I.disconnect,getRoom:I.getRoom,isControlled:!1},[A,I]),Ke=n.useRef(null);n.useEffect(()=>{const v=g.videoElement,E=Ke.current;if(!(!v||!E))return E.appendChild(v),()=>{v.parentNode===E&&E.removeChild(v)}},[g.videoElement]),n.useEffect(()=>{const v=g.audioElement;if(!v)return;ce.attach(v);const E=v.play();return E&&typeof E.catch=="function"&&E.catch(F=>{(F==null?void 0:F.name)==="NotAllowedError"&&de(!0)}),()=>{ce.detach()}},[g.audioElement]),n.useEffect(()=>{if(g.isControlled||g.connectionState!=="connected")return;const v=g.getRoom();if(v)return $.setupMic(v).catch(()=>{}),B.attachRoom(v),H.attachRoom(v),K.refresh(),()=>{$.teardownMic(),B.teardown(),H.teardown()}},[g.isControlled,g.connectionState]),n.useEffect(()=>{const v=g.audioElement;v&&(v.muted=D)},[g.audioElement,D]);const Pt=n.useCallback(v=>{const E=g.getRoom();if(E)try{const F=new TextEncoder().encode(JSON.stringify({type:"user_message",text:v}));E.localParticipant.publishData(F,{reliable:!0})}catch{}},[g]),Dt=n.useCallback(()=>{$e(v=>!v)},[]);n.useEffect(()=>{ie==null||ie(g.connectionState),g.connectionState==="connected"?te==null||te():g.connectionState==="disconnected"&&(ne==null||ne())},[g.connectionState,te,ne,ie]),n.useEffect(()=>{re==null||re(g.transcript)},[g.transcript,re]),n.useEffect(()=>{X==null||X(g.agentState)},[g.agentState,X]);const Ye=n.useRef(!1);n.useEffect(()=>{g.isControlled||!d||Ye.current||le&&g.connectionState==="idle"&&(Ye.current=!0,g.connect())},[d,g.connectionState,g,le]);const zt=n.useCallback(v=>{const E=_==null?void 0:_.find(F=>F.id===v);E&&(xe(!1),v!==U&&(je(!0),g.disconnect(),ae||ze(v),R==null||R(E)))},[_,U,g,ae,R]);n.useEffect(()=>{ge&&g.connectionState==="connected"&&je(!1)},[g.connectionState,ge]),n.useEffect(()=>{if(!fe)return;const v=E=>{E.key==="Escape"&&xe(!1)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[fe]);const $t=!!m||!!(T!=null&&T.avatarImageUrl)||g.isControlled,He=Ct(J,s,$t),Fe=(T==null?void 0:T.name)??C??((Qe=g.agentConfig)==null?void 0:Qe.name)??((Ze=He.info)==null?void 0:Ze.name)??"Live Layer",Xe=(T==null?void 0:T.avatarImageUrl)??m??((et=g.agentConfig)==null?void 0:et.avatarImageUrl)??((tt=He.info)==null?void 0:tt.avatarImageUrl)??null,Bt=y??((nt=g.agentConfig)==null?void 0:nt.idleLoopUrl)??((rt=He.info)==null?void 0:rt.idleLoopUrl)??null,Ut=L??null,Ot=n.useCallback(()=>G("expanded"),[G]),Ht=n.useCallback(()=>G("minimized"),[G]),Je=n.useCallback(()=>{g.disconnect(),G("hidden")},[g,G]),Ft=n.useCallback(()=>{const v=g.audioElement;v&&v.play().then(()=>de(!1)).catch(()=>{})},[g.audioElement]),Wt=n.useCallback(()=>{de(!1),g.connect()},[g]),ve={...Pe,zIndex:De};N.primaryColor&&(ve["--ll-color-primary"]=N.primaryColor),N.accentColor&&(ve["--ll-color-accent"]=N.accentColor),N.backgroundColor&&(ve["--ll-color-bg"]=N.backgroundColor),N.textColor&&(ve["--ll-color-fg"]=N.textColor);const Vt=["ll-widget",`ll-widget--${O}`,`ll-widget--${Q?"mobile":"desktop"}`,Ie].filter(Boolean).join(" ");return le?e.jsxs("div",{className:Vt,style:ve,"data-display-mode":O,"data-position":p,children:[O==="hidden"&&e.jsx(dn,{position:p,isMobile:Q,isSpeaking:g.agentState==="speaking",onExpand:()=>G("expanded"),label:`Open ${Fe} widget`}),O==="minimized"&&e.jsx(hn,{position:p,isMobile:Q,agentName:Fe,avatarImageUrl:Xe,agentState:g.agentState,isMuted:$.isMuted,audioLevel:ce,onExpand:Ot,onToggleMute:$.toggleMute,onClose:Je}),O==="expanded"&&e.jsx(mn,{position:p,isMobile:Q,agentName:Fe,avatarImageUrl:Xe,idleLoopUrl:Bt,greeting:Ut,branding:N,teamMembers:_,currentTeamMemberId:U,isSwitchingTeamMember:ge,teamSwitcherOpen:fe,onToggleTeamSwitcher:()=>xe(v=>!v),onSelectTeamMember:zt,connectionState:g.connectionState,agentState:g.agentState,transcript:g.transcript,isMuted:$.isMuted,micDevices:K.mics,isCameraEnabled:B.isEnabled,cameraPreviewEl:B.previewEl,cameraDevices:K.cameras,activeCameraId:B.activeDeviceId,isScreenShareEnabled:H.isEnabled,screenPreviewEl:H.previewEl,isSpeakerMuted:D,allowCamera:w,allowScreenShare:S,allowTyping:b,languageMenuOpen:Se,onToggleLanguageMenu:()=>h(v=>!v),needsUserGesture:ue,canResume:g.canResume,micError:$.micError,error:g.error,avatarVideoContainerRef:Ke,onConnect:()=>void g.connect(),onDisconnect:()=>g.disconnect(),onRetry:Wt,onResumeAudio:Ft,onToggleMute:$.toggleMute,onToggleCamera:()=>void B.toggle(),onSwitchCameraDevice:v=>void B.switchDevice(v),onToggleScreenShare:()=>void H.toggle(),onToggleSpeaker:Dt,onSendMessage:Pt,onMinimize:Ht,onClose:Je,onClearMicError:$.clearError})]}):null}function Ln(t){return e.jsx(xt,{children:e.jsx(Nn,{...t})})}const Rn=({agentId:t,baseUrl:r,apiKey:i,mode:s,onAgentEvent:o,className:l,style:d})=>{const f=n.useRef(null),u=n.useRef(null),x=n.useRef(o);x.current=o;const p=n.useCallback(a=>{var j;const c=a.detail;(j=x.current)==null||j.call(x,c)},[]);return n.useEffect(()=>{const a=f.current;if(!a)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",t),r&&c.setAttribute("base-url",r),i&&c.setAttribute("api-key",i),s&&c.setAttribute("mode",s),c.addEventListener("agent-event",p),a.appendChild(c),u.current=c,()=>{c.removeEventListener("agent-event",p),a.removeChild(c),u.current=null}},[t]),n.useEffect(()=>{u.current&&(s?u.current.setAttribute("mode",s):u.current.removeAttribute("mode"))},[s]),e.jsx("div",{ref:f,className:l,style:d})},An=n.forwardRef(function({id:r,intent:i,as:s="div",className:o,style:l,children:d},f){return n.createElement(s,{ref:f,"data-ll-region":r,"data-ll-intent":i,className:o,style:l},d)});function Mn(){const[t,r]=n.useState([]),i=n.useCallback(o=>{r(l=>{const d=l.findIndex(f=>f.id===o.id);if(d>=0){const f=l.slice();return f[d]=o,f}return[...l,o]})},[]),s=n.useCallback(()=>r([]),[]);return{entries:t,pushSegment:i,clear:s,latest:t.length>0?t[t.length-1]:null}}exports.AvatarWidget=Ln;exports.ErrorBoundary=xt;exports.LiveLayerRegion=An;exports.LiveLayerWidget=Rn;exports.clearPageContextCache=It;exports.extractPageContext=Tt;exports.getCachedPageContext=Ve;exports.matchesPattern=Lt;exports.shouldRenderAtPath=Rt;exports.useAgentInfo=Ct;exports.useAudioLevel=yt;exports.useCameraState=_t;exports.useDisplayMode=jt;exports.useDisplayModePersistence=St;exports.useIsMobile=Et;exports.useLiveKitSession=vt;exports.useMediaDevices=kt;exports.useMicrophoneState=bt;exports.usePathname=Nt;exports.useRouteMatch=At;exports.useScreenShareState=wt;exports.useTranscript=Mn;
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),r=require("react"),gn=require("@livelayer/sdk"),Fe=require("livekit-client");class It extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,i){var o,s;(s=(o=this.props).onError)==null||s.call(o,n,i)}render(){var n;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((n=this.state.error)==null?void 0:n.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Tt(e){const[n,i]=r.useState("idle"),[o,s]=r.useState("idle"),[l,u]=r.useState([]),[d,f]=r.useState(null),[y,h]=r.useState(null),[a,c]=r.useState(null),[S,k]=r.useState(!1),[j,T]=r.useState(null),N=r.useRef(null),M=r.useRef(e.onDataMessage);M.current=e.onDataMessage,r.useEffect(()=>{const v={onConnectionStateChange:w=>{i(w),w==="connected"&&T(null)},onAgentStateChange:s,onTranscript:w=>u([...w]),onAgentConfig:f,onAudioTrack:w=>c(w),onVideoTrack:w=>h(w),onVideoTrackRemoved:()=>h(null),onError:w=>T(w),onDataMessage:w=>{var P;(P=M.current)==null||P.call(M,w)},onResumabilityChange:k},C=new gn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},v);return N.current=C,i("idle"),s("idle"),u([]),f(null),h(null),c(null),k(!1),T(null),()=>{var w;(w=C.destroy)==null||w.call(C),N.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const L=r.useCallback(async()=>{const v=N.current;if(v)try{await v.connect()}catch(C){throw T(C instanceof Error?C.message:String(C)),C}},[]),A=r.useCallback(()=>{const v=N.current;v&&v.disconnect()},[]),g=r.useCallback(()=>{var v;return((v=N.current)==null?void 0:v.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:l,agentConfig:d,videoElement:y,audioElement:a,canResume:S,error:j,connect:L,disconnect:A,getRoom:g,session:N.current}}function Pt(){const e=r.useRef(null),n=r.useRef(null),i=r.useRef(null),o=r.useRef(null),s=r.useRef(new Set),l=r.useRef(null),u=r.useCallback(()=>{const a=n.current;if(!a){o.current=null;return}(!l.current||l.current.length!==a.frequencyBinCount)&&(l.current=new Uint8Array(new ArrayBuffer(a.frequencyBinCount)));const c=l.current;a.getByteFrequencyData(c);let S=0;for(let j=0;j<c.length;j++)S+=c[j];const k=S/c.length/255;for(const j of s.current)try{j(k)}catch(T){console.error("[useAudioLevel] subscriber threw:",T)}o.current=requestAnimationFrame(u)},[]),d=r.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const a=new AudioContext,c=a.createAnalyser();c.fftSize=64,c.connect(a.destination),e.current=a,n.current=c},[]),f=r.useCallback(a=>{if(d(),!(!e.current||!n.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(a);c.connect(n.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),y=r.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),h=r.useCallback(a=>(s.current.add(a),()=>{s.current.delete(a)}),[]);return r.useEffect(()=>()=>{if(y(),n.current){try{n.current.disconnect()}catch{}n.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),l.current=null},[y]),{attach:f,detach:y,subscribe:h}}function Dt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),s=r.useRef(null),l=r.useRef(null),u=r.useCallback(async h=>{if(s.current&&l.current){try{await l.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}l.current=h,o(null);try{const a=await Fe.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await h.localParticipant.publishTrack(a),s.current=a,n(a.isMuted)}catch(a){const c=a instanceof Error&&a.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),a}},[]),d=r.useCallback(()=>{const h=s.current;h&&(h.isMuted?(h.unmute(),n(!1)):(h.mute(),n(!0)))},[]),f=r.useCallback(()=>{const h=s.current,a=l.current;if(h&&a){try{a.localParticipant.unpublishTrack(h)}catch{}h.stop()}s.current=null,l.current=null,n(!1)},[]),y=r.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:y}}const yn={resolution:{width:640,height:480,frameRate:24}};function $t(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),[u,d]=r.useState(""),f=r.useRef(null),y=r.useRef(null),h=r.useCallback(N=>{f.current=N},[]),a=r.useCallback(()=>{const N=f.current,M=y.current;if(M&&N){const L=N.localParticipant.getTrackPublication(Fe.Track.Source.Camera);if(L!=null&&L.track){try{N.localParticipant.unpublishTrack(L.track)}catch{}L.track.stop()}else M.stop()}y.current=null,l(null),n(!1)},[]),c=r.useCallback(async N=>{const M=f.current;if(M){o(null);try{const L={...yn};N&&(L.deviceId=N);const A=await Fe.createLocalVideoTrack(L);await M.localParticipant.publishTrack(A),y.current=A;const g=A.attach();l(g),n(!0),N&&d(N);try{M.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(L){const A=L instanceof Error&&L.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(A)}}},[]),S=r.useCallback(async()=>{e?a():await c(u||void 0)},[e,u,a,c]),k=r.useCallback(async N=>{a(),await c(N)},[a,c]),j=r.useCallback(()=>{a(),f.current=null,o(null),d("")},[a]),T=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{y.current&&y.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:S,switchDevice:k,attachRoom:h,teardown:j,clearError:T}}function zt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),u=r.useRef(null),d=r.useCallback(c=>{u.current=c},[]),f=r.useCallback(()=>l(null),[]),y=r.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let S=0;const k=()=>{const j=c.localParticipant.getTrackPublication(Fe.Track.Source.ScreenShare);if(j!=null&&j.track){const T=j.track.attach();l(T),n(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}S++<10?setTimeout(k,100):n(!0)};k()}catch(S){const k=S instanceof Error?S.name:"";k!=="NotAllowedError"&&k!=="AbortError"&&o("Screen share unavailable. Try again."),n(!1)}}},[e,f]),h=r.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1),o(null),u.current=null},[e,f]),a=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:y,attachRoom:d,teardown:h,clearError:a}}function qt(){const[e,n]=r.useState([]),[i,o]=r.useState([]),s=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const l=await navigator.mediaDevices.enumerateDevices();n(l.filter(u=>u.kind==="audioinput")),o(l.filter(u=>u.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const l=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",l),()=>navigator.mediaDevices.removeEventListener("devicechange",l)},[s]),{mics:e,cameras:i,refresh:s}}function Ht(e,n,i=!1){const[o,s]=r.useState(null),[l,u]=r.useState(null),[d,f]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){f(!1);return}const y=new AbortController,h=n||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${h}/api/widget/agent/${encodeURIComponent(e)}`,{signal:y.signal}).then(async a=>{if(!a.ok){const c=await a.json().catch(()=>({}));throw new Error(c.error||`HTTP ${a.status}`)}return a.json()}).then(a=>{y.signal.aborted||(s(a),f(!1))}).catch(a=>{y.signal.aborted||(u(a instanceof Error?a.message:"Agent lookup failed"),f(!1))}),()=>y.abort()},[e,n,i]),{info:o,error:l,loading:d}}function vn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function xn(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function Ot({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[s,l]=r.useState(n),u=o?e:s,d=r.useCallback(f=>{f!==u&&(o||l(f),i==null||i(f))},[u,o,i]);return[u,d]}const bn=["hidden","minimized","expanded"];function wn(e){return e&&bn.includes(e)?e:null}function Ft({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const l=`${o}:display-mode`,u=r.useRef(!1),[d,f]=Ot({value:e,defaultValue:n,onChange:y=>{e===void 0&&!s&&xn(l,y),i==null||i(y)}});return r.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const y=wn(vn(l));y&&y!==d&&f(y)},[]),[d,f]}const _n=640;function Bt(e=_n){const[n,i]=r.useState(!1);return r.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,s=window.matchMedia(o),l=()=>i(s.matches);return l(),typeof s.addEventListener=="function"?(s.addEventListener("change",l),()=>s.removeEventListener("change",l)):(s.addListener(l),()=>{s.removeListener(l)})},[e]),n}const bt="__llHistoryPatched",Be="ll:pathname";function kn(){if(typeof window>"u"||window.history[bt])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(Be)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(Be)),o},window.history[bt]=!0}function wt(){return typeof window>"u"?"/":window.location.pathname||"/"}function Ut(e){const[n,i]=r.useState(()=>e??wt());return r.useEffect(()=>{if(e!==void 0)return;kn();const o=()=>i(wt());return o(),window.addEventListener("popstate",o),window.addEventListener(Be,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(Be,o)}},[e]),e??n}const _t=new Map,Cn=/[\\^$+?.()|{}[\]]/g;function Sn(e){return e.replace(Cn,"\\$&")}function jn(e){const n=_t.get(e);if(n)return n;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",l=i.replace(/\*\*/g,o).replace(/\*/g,s),d=Sn(l).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return _t.set(e,f),f}function En(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return jn(e).test(i)}function Wt(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):En(e,n)}function kt(e,n){if(!e||e.length===0)return!1;for(const i of e)if(Wt(i,n))return!0;return!1}function Vt(e,n,i){return e===void 0?!0:kt(i,e)?!1:n&&n.length>0?kt(n,e):!0}function Kt(e,n,i){return r.useMemo(()=>Vt(e,n,i),[e,n,i])}const Ct=({muted:e=!1,className:n})=>e?t.jsxs("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),St=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),Ln=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),Nn={left:180,right:0,up:-90,down:90},Rn=({direction:e="right",className:n})=>t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Nn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function An(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const Yt="ll-hidden-tab-center-y",Mn=5,jt=16;function In(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Yt);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function Et(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Yt,String(e))}catch{}}const Tn=({position:e,isMobile:n,isSpeaking:i,onExpand:o,label:s="Open widget"})=>{const l=An(e),u=l==="right"?"left":"right",d=n?80:72,[f,y]=r.useState(null),[h,a]=r.useState(!1),c=r.useRef(null),S=r.useRef(!1),k=r.useCallback(v=>{if(typeof window>"u")return v;const C=d/2,w=jt+C,P=window.innerHeight-jt-C;return P<w?Math.max(w,v):Math.max(w,Math.min(P,v))},[d]);r.useEffect(()=>{const v=In();y(k(v??window.innerHeight/2));const C=()=>{y(w=>w===null?null:k(w))};return window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[k]);const j=r.useCallback(v=>{if(!(v.pointerType==="mouse"&&v.button!==0)&&f!==null){try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}c.current={startClientY:v.clientY,startCenterY:f,moved:!1}}},[f]),T=r.useCallback(v=>{const C=c.current;if(!C)return;const w=v.clientY-C.startClientY;!C.moved&&Math.abs(w)>Mn&&(C.moved=!0,a(!0)),C.moved&&y(k(C.startCenterY+w))},[k]),N=r.useCallback(v=>{const C=c.current;if(C){try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}c.current=null,C.moved&&(a(!1),S.current=!0,y(w=>(w!==null&&Et(w),w)))}},[]),M=r.useCallback(()=>{if(S.current){S.current=!1;return}o()},[o]),L=r.useCallback(v=>{if(v.key==="ArrowUp"||v.key==="ArrowDown"){v.preventDefault();const C=v.key==="ArrowUp"?-8:8;y(w=>{if(w===null)return w;const P=k(w+C);return Et(P),P})}},[k]),A=["ll-hidden",`ll-hidden--${l}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,h?"is-dragging":null].filter(Boolean).join(" "),g=f===null?void 0:{top:`${f-d/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:A,onPointerDown:j,onPointerMove:T,onPointerUp:N,onPointerCancel:N,onClick:M,onKeyDown:L,"aria-label":s,"data-position":e,style:g,children:t.jsx(Rn,{direction:u,className:"ll-hidden__chevron"})})},Pn=({audioLevel:e,bars:n=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:l})=>{const u=r.useRef(null),d=r.useRef([]),f=r.useMemo(()=>{const h=(Math.sqrt(5)-1)/2;return Array.from({length:n},(a,c)=>.5+c*h%1*.5)},[n]);r.useEffect(()=>e.subscribe(a=>{for(let c=0;c<n;c++){const S=d.current[c];if(!S)continue;const k=Math.max(o,a*i*f[c]);S.style.height=`${k}px`}}),[e,n,i,o,f]);const y=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:y,"aria-hidden":"true",children:Array.from({length:n},(h,a)=>t.jsx("div",{ref:c=>{d.current[a]=c},className:["ll-waveform__bar",l].filter(Boolean).join(" "),style:{height:`${o}px`}},a))})},Dn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,agentState:s,isMuted:l,audioLevel:u,onExpand:d,onToggleMute:f,onClose:y})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:d,"aria-label":`Expand ${i} widget`,children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(Pn,{audioLevel:u,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:h=>{h.stopPropagation(),f()},onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.stopPropagation(),h.preventDefault(),f())},"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(Ct,{muted:l,className:"ll-minimized__icon"})}),t.jsx(St,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(Ct,{muted:l,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(St,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:y,"aria-label":"Close widget",children:t.jsx(Ln,{className:"ll-minimized__icon"})})]})]})}),$n=({src:e,alt:n,preCannedPlaying:i=!1,className:o,style:s})=>{const[l,u]=r.useState(!1),d=r.useRef(e);if(r.useEffect(()=>{d.current!==e&&(d.current=e,u(!1))},[e]),!e)return null;const f={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:l?1:0,...s};return t.jsx("img",{src:e,alt:n,className:o,style:f,loading:"eager",fetchpriority:"high",onLoad:()=>u(!0)})},zn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:l,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:y,teamSwitcherOpen:h,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:S,onToggleLanguageMenu:k,connectionState:j,agentState:T,transcript:N,canResume:M,needsUserGesture:L,error:A,isMuted:g,micError:v,micDevices:C,isCameraEnabled:w,cameraPreviewEl:P,cameraDevices:V,activeCameraId:se,isScreenShareEnabled:K,screenPreviewEl:Y,isSpeakerMuted:le,allowCamera:Pe,allowScreenShare:De,allowTyping:$e,avatarVideoContainerRef:Ce,onConnect:ae,onDisconnect:fe,onRetry:pe,onResumeAudio:he,onToggleMute:me,onToggleCamera:ge,onSwitchCameraDevice:ye,onToggleScreenShare:D,onToggleSpeaker:We,onSendMessage:ze,onMinimize:qe,onClose:Se,onClearMicError:je})=>{var Re;const ee=N.length>0?N[N.length-1]:null,ce=((d==null?void 0:d.length)??0)>1,ve=j==="connecting"||j==="connected",G=j==="connected",F=j==="idle"||j==="disconnected"||j==="error",Ee=r.useRef(null),te=r.useRef(null);r.useEffect(()=>{const m=Ee.current;m&&(m.innerHTML="",P&&(P.style.width="100%",P.style.height="100%",P.style.objectFit="cover",P.style.transform="scaleX(-1)",m.appendChild(P)))},[P]),r.useEffect(()=>{const m=te.current;m&&(m.innerHTML="",Y&&(Y.style.width="100%",Y.style.height="100%",Y.style.objectFit="contain",m.appendChild(Y)))},[Y]);const[U,Q]=r.useState(!1),[ne,B]=r.useState(!1);r.useEffect(()=>{if(!U&&!ne&&!S&&!h)return;const m=()=>{Q(!1),B(!1),S&&k(),h&&a()};return document.addEventListener("click",m),()=>document.removeEventListener("click",m)},[U,ne,S,h,k,a]);const[W,re]=r.useState(""),Le=r.useCallback(m=>{m.preventDefault();const H=W.trim();H&&(ze(H),re(""))},[W,ze]),Ve=u.productName||"Live Layer",xe=G&&(ee!=null&&ee.text)?ee.text:l||"",Ne=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Ne,"data-position":e,"data-state":G?"connected":ve?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx($n,{src:o,alt:i,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((Re=i==null?void 0:i.charAt(0))==null?void 0:Re.toUpperCase())||"A"})}),s&&!G&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:Ce,className:"ll-expanded__video"}),j==="connecting"&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:y?"Switching...":"Connecting..."})]}),L&&G&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:he,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),ve?t.jsxs("div",{className:"ll-expanded__topbar",children:[t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:m=>{ce&&(m.stopPropagation(),a())},"aria-haspopup":ce?"listbox":void 0,"aria-expanded":ce?h:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),ce&&t.jsx(He,{})]}),ce&&h&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(m=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${m.id===f?"is-active":""}`,onClick:()=>c(m.id),role:"option","aria-selected":m.id===f,children:[m.avatarImageUrl&&t.jsx("img",{src:m.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:m.name}),m.role&&t.jsx("span",{className:"ll-hmenu__role",children:m.role})]},m.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:m=>{m.stopPropagation(),k()},"aria-haspopup":"listbox","aria-expanded":S,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(He,{})]}),S&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${T}`,children:T})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:qe,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Nt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Se,"aria-label":"End call",title:"End call",children:t.jsx(Lt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Ve}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:qe,"aria-label":"Minimize widget",children:t.jsx(Nt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Se,"aria-label":"Close widget",children:t.jsx(Lt,{})})]})]}),F&&(()=>{const m=M?"Restart paused session":j==="disconnected"?"Reconnect to agent":"Start video call",H=M?"Pick up where you left off":null,Ke=j==="idle"&&!M&&!A;return t.jsxs(t.Fragment,{children:[Ke&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:ae,"aria-label":m,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),t.jsx("span",{className:"ll-expanded__play-label",children:m})]}),t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[l&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:l})}),H&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:H}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:ae,"aria-label":m,children:m})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${ve&&(w||K)?"is-visible":""}`,children:[t.jsx("div",{ref:te,className:K?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ee,className:!K&&w?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),ve?t.jsxs("div",{className:"ll-expanded__bottom",children:[xe&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:xe})}),t.jsxs("div",{className:"ll-toolbar",onClick:m=>m.stopPropagation(),children:[De&&t.jsx("button",{type:"button",className:`ll-tool ${K?"is-on":""}`,onClick:D,"aria-label":K?"Stop sharing screen":"Share screen",title:K?"Stop sharing":"Share screen",children:t.jsx(qn,{})}),Pe&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${w?"is-on":""}`,onClick:ge,"aria-label":w?"Turn off camera":"Turn on camera",title:w?"Stop camera":"Start camera",children:t.jsx(Hn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${w?"is-on":""}`,onClick:m=>{m.stopPropagation(),B(H=>!H),Q(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":ne,children:t.jsx(He,{})}),ne&&V.length>0&&t.jsx(Rt,{label:"Camera",devices:V,activeId:se,onPick:m=>{B(!1),ye(m)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${g?"is-muted":""}`,onClick:me,"aria-label":g?"Unmute microphone":"Mute microphone",title:g?"Unmute":"Mute",children:t.jsx(On,{muted:g})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${g?"is-muted":""}`,onClick:m=>{m.stopPropagation(),Q(H=>!H),B(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":U,children:t.jsx(He,{})}),U&&C.length>0&&t.jsx(Rt,{label:"Microphone",devices:C,activeId:"",onPick:()=>Q(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${le?"is-muted":""}`,onClick:We,"aria-label":le?"Unmute speaker":"Mute speaker",title:le?"Unmute speaker":"Mute speaker",children:t.jsx(Fn,{muted:le})})]}),$e&&t.jsxs("form",{className:"ll-message-input",onSubmit:Le,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:W,onChange:m=>re(m.target.value),"aria-label":"Message the agent"}),W.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Bn,{})})]}),t.jsx("button",{type:"button",className:"ll-expanded__end",onClick:fe,children:"End conversation"})]}):null,(()=>{if(v&&j!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:v}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:je,"aria-label":"Dismiss",children:"×"})]});if(!A||j!=="error")return null;let m="Failed to connect",H="Try again";return A==="MIC_PERMISSION_DENIED"?m="Microphone blocked. Allow access to talk.":A==="MIC_NOT_FOUND"?m="No microphone found. Plug one in + retry.":A==="MIC_UNAVAILABLE"?m="Mic unavailable. Check other apps using it.":A==="AGENT_TIMEOUT"?m="Agent didn't pick up. Try again.":A==="CONNECT_FAILED"?m="Connection failed. Check your network.":A.length<80&&(m=A),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:m}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:pe,children:H})]})})()]})};function He(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Lt(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Nt(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function qn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Hn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),t.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function On({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Fn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?t.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),t.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function Bn(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]})}const Rt=({label:e,devices:n,activeId:i,onPick:o})=>t.jsxs("div",{className:"ll-device-menu",onClick:s=>s.stopPropagation(),role:"listbox",children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),n.map((s,l)=>{const u=i===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${u?"is-active":""}`,onClick:()=>o(s.deviceId),role:"option","aria-selected":u,children:[u&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:s.label||`${e} ${l+1}`})]},s.deviceId||l)})]}),Un=['[data-ll-private="true"]',".ll-widget"];function rt(e){let n=e;for(;n;){for(const i of Un)if(n.matches(i))return!0;n=n.parentElement}return!1}function Ue(e){if(rt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const n=(e.getAttribute("autocomplete")||"").toLowerCase();if(n==="off"||n.startsWith("cc-"))return!1}return!0}const Oe=4096,Wn=20,Vn=20,Kn=10,Yn=10,Gn=30,At=500,Xn=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Ie(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const i of Xn)if(n.matches(i))return!0;n=n.parentElement}return!1}function Te(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<i&&n.left<o}function Mt(e){const n=e.getAttribute("id");if(n){const l=document.querySelector(`label[for="${CSS.escape(n)}"]`);if(l!=null&&l.textContent)return l.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.getAttribute("placeholder");if(o)return o.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function de(e,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function we(e){return e.length}function Gt(e,n={}){const i=n.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",l=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const g of u){if(d.length>=Kn)break;if(Ie(g)||!Te(g))continue;const v=g.getAttribute("data-ll-region")??"",C=g.getAttribute("data-ll-intent")??void 0,w=de((g.innerText||g.textContent||"").trim(),At*2);!v||!w||d.push({id:v,intent:C,text:w})}const f=[],y=["H1","H2","H3","H4","H5","H6"],h=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const g of h){if(Ie(g)||!Te(g))continue;const v=(g.textContent||"").trim();v&&f.push(`${g.tagName}: ${de(v,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const g of a){if(Ie(g)||!Te(g)||y.includes(g.tagName))continue;const v=(g.textContent||"").trim();v.length>10&&f.push(de(v,At))}const c=f.join(`
|
|
2
|
+
`),S=[],k=Array.from(i.querySelectorAll("a[href]"));for(const g of k){if(S.length>=Wn)break;if(Ie(g)||!Te(g))continue;const v=g.getAttribute("href")||"",C=(g.textContent||"").trim();!v||!C||S.push({href:v,text:de(C,100)})}const j=[],T=Array.from(i.querySelectorAll("input, textarea, select"));for(const g of T){if(j.length>=Vn)break;if(Ie(g)||!Ue(g)||!Te(g))continue;const v=Mt(g),C=g instanceof HTMLInputElement?g.type:g.tagName.toLowerCase();v&&j.push({label:de(v,100),type:C})}const N=Array.from(i.querySelectorAll("[data-ll-form]")),M=[];for(const g of N){if(M.length>=Yn)break;if(rt(g))continue;const v=g.getAttribute("data-ll-form")||"";if(!v)continue;const C=g.getAttribute("data-ll-intent")||void 0,w=Array.from(g.querySelectorAll("[data-ll-field]")),P=[];for(const V of w){if(P.length>=Gn)break;if(!Ue(V))continue;const se=V.getAttribute("data-ll-field")||"";if(!se)continue;const K=Mt(V)||se,Y=V instanceof HTMLInputElement?V.type:V.tagName.toLowerCase();P.push({name:se,label:de(K,100),type:Y})}M.push({id:v,intent:C,fields:P})}const L={url:o,title:l,pathname:s,regions:d,visibleText:c,visibleLinks:S,visibleFields:j,forms:M,extras:e};let A=we(JSON.stringify(L.regions))+we(L.visibleText)+we(JSON.stringify(L.visibleLinks))+we(JSON.stringify(L.visibleFields));for(;A>Oe&&L.visibleFields.length>0;)L.visibleFields.pop(),A=we(JSON.stringify(L.visibleFields));for(;A>Oe&&L.visibleLinks.length>0;)L.visibleLinks.pop(),A-=80;return we(L.visibleText)>Oe&&(L.visibleText=de(L.visibleText,Oe-100)),L}let _e=null;function nt(e,n={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(_e&&_e.key===s&&i-_e.at<1e3)return _e.ctx;const l=Gt(e,n);return _e={key:s,at:i,ctx:l},l}function Xt(){_e=null}const Jn=200;function Qn(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function Jt(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],l=Array.from(n.querySelectorAll("a[href]"));for(const u of l){if(s.length>=Jn)break;if(rt(u))continue;const d=u.getAttribute("href")||"";if(!Qn(d))continue;let f=d,y=!0;try{if(typeof window<"u"){const a=new URL(d,i);y=a.origin===i,y&&d.startsWith("http")&&(f=a.pathname+a.search+a.hash)}}catch{continue}if(o.has(f))continue;o.add(f);const h=(u.textContent||"").trim().slice(0,120);s.push({href:f,text:h,internal:y})}return s}let ke=null;const Zn=5e3;function Qt(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(ke&&ke.pathname===n&&e-ke.at<Zn)return ke.routes;const i=Jt();return ke={at:e,pathname:n,routes:i},i}function Zt(){ke=null}function er(e,n){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),s=o==null?void 0:o.set;s?s.call(e,n):e.value=n}function tr(e,n,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const l=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=l==null?void 0:l.set,d=n==="true"||n==="1"||n==="on";u?u.call(e,d):e.checked=d,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}er(e,n),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}const nr=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes"]);function rr(e){var ut,dt,ft,pt,ht,mt,gt;const{agentId:n,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:l,autoConnect:u=!1,displayMode:d,defaultDisplayMode:f="expanded",onDisplayModeChange:y,position:h="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:S=!1,teamMembers:k,currentTeamMemberId:j,onTeamMemberChange:T,idleLoopUrl:N,greeting:M,avatarImageUrl:L,agentName:A,branding:g={},allowCamera:v=!0,allowScreenShare:C=!0,allowTyping:w=!0,showOn:P,hideOn:V,pathname:se,onNavigate:K,onScrollToSelector:Y,getPageContext:le,pageContextExtras:Pe,onScrollPage:De,onClick:$e,capabilities:Ce,onConnect:ae,onDisconnect:fe,onTranscript:pe,onAgentState:he,onConnectionStateChange:me,onAgentEvent:ge,onAgentCommand:ye,controlledSession:D,className:We,style:ze,zIndex:qe=2147483647}=e,Se=Ut(se),je=Kt(Se,P,V);r.useEffect(()=>{Xt(),Zt()},[Se]);const ee=j!==void 0,[ce,ve]=r.useState(()=>{var x;return j??((x=k==null?void 0:k[0])==null?void 0:x.id)}),G=ee?j:ce,F=r.useMemo(()=>(k==null?void 0:k.find(x=>x.id===G))??null,[k,G]),Ee=(F==null?void 0:F.agentId)??n,[te,U]=Ft({value:d,defaultValue:f,onChange:y,persistKey:c,disablePersistence:S}),Q=Bt(a),ne=Pt(),B=Dt(),W=$t(),re=zt(),Le=qt(),[Ve,xe]=r.useState(!1),[Ne,Re]=r.useState(!1),[m,H]=r.useState(!1),[Ke,en]=r.useState(!1),[Ye,tn]=r.useState(!1),Ge=r.useRef(K),Xe=r.useRef(Y),Je=r.useRef(De),Qe=r.useRef($e),it=r.useRef(le),ot=r.useRef(Pe),Ze=r.useRef(Ce),X=r.useRef(null);Ge.current=K,Xe.current=Y,Je.current=De,Qe.current=$e,it.current=le,ot.current=Pe,Ze.current=Ce;function ie(x){const p=Ze.current;return p?p.includes(x):!0}function oe(x,p){console.warn(`[LiveLayer] Agent command "${x}" blocked — capability "${p}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const et=r.useCallback(x=>{var J,yt,vt,xt;const p=x;if(!(!p.type||typeof p.type!="string")){if(ge==null||ge({eventName:p.type,data:x}),p.type==="navigate"){if(!ie("navigate")){oe("navigate","navigate");return}const _=typeof p.href=="string"?p.href:null;if(!_){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(Ge.current){try{Ge.current(_)}catch(E){console.warn(`[LiveLayer] onNavigate threw for "${_}". Falling back. Error:`,E)}return}if(typeof document<"u"){const E=document.querySelector(`a[href="${_.replace(/"/g,'\\"')}"]`);if(E){E.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",_),window.dispatchEvent(new PopStateEvent("popstate"))}catch(E){console.warn(`[LiveLayer] history.pushState fallback failed for "${_}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,E)}return}if(p.type==="scroll_to"){if(!ie("scroll")){oe("scroll_to","scroll");return}const _=typeof p.selector=="string"?p.selector:null;if(!_)return;const E=p.behavior==="instant"?"instant":"smooth";if(Xe.current){try{Xe.current(_,E)}catch(R){console.warn("[LiveLayer] onScrollToSelector threw.",R)}return}if(typeof document<"u"){let R=null;try{R=document.querySelector(_)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${_}".`);return}if(!R){console.warn(`[LiveLayer] scroll_to: no element matched "${_}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}R.scrollIntoView({behavior:E,block:"start"})}return}if(p.type==="request_page_context"){if(!ie("read_page")){oe("request_page_context","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,E=(J=X.current)==null?void 0:J.call(X),R=z=>{const O=E,Z=O==null?void 0:O.localParticipant;if(Z!=null&&Z.publishData)try{const ue=_?{...z,requestId:_}:z,be=new TextEncoder().encode(JSON.stringify(ue));Z.publishData(be,{reliable:!0})}catch(ue){console.warn("[LiveLayer] publishData failed.",ue)}},I=ot.current,$=it.current;try{if($){const z=$(I);if(z instanceof Promise){R({type:"page_context_pending"}),z.then(O=>R({type:"page_context",context:O})).catch(O=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",O),R({type:"page_context",context:nt(I)})});return}R({type:"page_context",context:z});return}R({type:"page_context",context:nt(I)})}catch(z){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",z),R({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:I}})}return}if(p.type==="scroll_page"){if(!ie("scroll")){oe("scroll_page","scroll");return}const _=p.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const E=p.behavior==="instant"?"instant":"smooth";if(Je.current){try{Je.current(_,E)}catch(I){console.warn("[LiveLayer] onScrollPage threw.",I)}return}if(typeof window>"u")return;const R={behavior:E};_==="up"?window.scrollBy({top:-window.innerHeight,...R}):_==="down"?window.scrollBy({top:window.innerHeight,...R}):_==="top"?window.scrollTo({top:0,...R}):window.scrollTo({top:document.body.scrollHeight,...R});return}if(p.type==="click"){if(!ie("click")){oe("click","click");return}const _=typeof p.selector=="string"?p.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(Qe.current){try{Qe.current(_)}catch(R){console.warn("[LiveLayer] onClick threw.",R)}return}if(typeof document>"u")return;let E=null;try{E=document.querySelector(_)}catch{console.warn(`[LiveLayer] click: invalid selector "${_}".`);return}if(!E){console.warn(`[LiveLayer] click: no element matched "${_}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(E.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(yt=E.click)==null||yt.call(E);return}if(p.type==="fill_form"||p.type==="focus_field"){if(!ie("fill_forms")){oe(p.type,"fill_forms");return}if(typeof document>"u")return;const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn(`[LiveLayer] ${p.type}: missing formId.`);return}const E=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!E){console.warn(`[LiveLayer] ${p.type}: no form with data-ll-form="${_}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(E.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${p.type}: refusing to touch a form in a private subtree.`);return}if(p.type==="focus_field"){const I=typeof p.fieldName=="string"?p.fieldName:null;if(!I){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const $=E.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!$){console.warn(`[LiveLayer] focus_field: no field "${I}" in form "${_}".`);return}if(!Ue($)){console.warn(`[LiveLayer] focus_field: field "${I}" is privacy-protected and not focusable.`);return}$.focus();return}const R=p.values&&typeof p.values=="object"?p.values:null;if(!R){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[I,$]of Object.entries(R)){if(typeof $!="string")continue;const z=E.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!z){console.warn(`[LiveLayer] fill_form: no field "${I}" in form "${_}". Skipping.`);continue}if(!Ue(z)){console.warn(`[LiveLayer] fill_form: field "${I}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{tr(z,$)}catch(O){console.warn(`[LiveLayer] fill_form: failed to set "${I}".`,O)}}return}if(p.type==="submit_form"){if(!ie("submit_forms")){oe("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn("[LiveLayer] submit_form: missing formId.");return}const E=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!E){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${_}".`);return}if(E.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const R=typeof p.requestId=="string"?p.requestId:void 0,I=(vt=X.current)==null?void 0:vt.call(X),$=Z=>{const ue=I,be=ue==null?void 0:ue.localParticipant;if(be!=null&&be.publishData)try{const hn=R?{...Z,requestId:R}:Z,mn=new TextEncoder().encode(JSON.stringify(hn));be.publishData(mn,{reliable:!0})}catch{}};let z=!1;const O=()=>{z=!0,$({type:"form_submitted",formId:_})};E.addEventListener("submit",O,{once:!0});try{typeof E.requestSubmit=="function"?E.requestSubmit():E.submit()}catch(Z){console.warn("[LiveLayer] submit_form: requestSubmit threw.",Z),E.removeEventListener("submit",O),$({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{z||(E.removeEventListener("submit",O),$({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(p.type==="request_routes"){if(!ie("read_page")){oe("request_routes","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,R=(xt=X.current)==null?void 0:xt.call(X),I=R==null?void 0:R.localParticipant;if(!(I!=null&&I.publishData))return;try{const $=Qt(),z=_?{type:"routes",routes:$,requestId:_}:{type:"routes",routes:$},O=new TextEncoder().encode(JSON.stringify(z));I.publishData(O,{reliable:!0})}catch($){console.warn("[LiveLayer] request_routes: extractRoutes threw.",$)}return}nr.has(p.type)||ye==null||ye(p)}},[ye,ge]),q=Tt({agentId:D?"__controlled__":Ee,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:l,onDataMessage:D?void 0:et});r.useEffect(()=>{if(D!=null&&D.subscribeToDataMessages)return D.subscribeToDataMessages(et)},[D,et]),X.current=()=>{var x;return(x=q.getRoom)==null?void 0:x.call(q)};const b=r.useMemo(()=>D?{connectionState:D.connectionState,agentState:D.agentState,transcript:D.transcript,videoElement:D.videoElement,audioElement:D.audioElement,canResume:D.canResume,error:D.error,agentConfig:null,connect:async()=>{await D.onConnect()},disconnect:()=>D.onDisconnect(),getRoom:q.getRoom,isControlled:!0}:{connectionState:q.connectionState,agentState:q.agentState,transcript:q.transcript,videoElement:q.videoElement,audioElement:q.audioElement,canResume:q.canResume,error:q.error,agentConfig:q.agentConfig,connect:q.connect,disconnect:q.disconnect,getRoom:q.getRoom,isControlled:!1},[D,q]),st=r.useRef(null);r.useEffect(()=>{const x=b.videoElement,p=st.current;if(!(!x||!p))return p.appendChild(x),()=>{x.parentNode===p&&p.removeChild(x)}},[b.videoElement]),r.useEffect(()=>{const x=b.audioElement;if(!x)return;ne.attach(x);const p=x.play();return p&&typeof p.catch=="function"&&p.catch(J=>{(J==null?void 0:J.name)==="NotAllowedError"&&xe(!0)}),()=>{ne.detach()}},[b.audioElement]),r.useEffect(()=>{if(b.isControlled||b.connectionState!=="connected")return;const x=b.getRoom();if(x)return B.setupMic(x).catch(()=>{}),W.attachRoom(x),re.attachRoom(x),Le.refresh(),()=>{B.teardownMic(),W.teardown(),re.teardown()}},[b.isControlled,b.connectionState]),r.useEffect(()=>{const x=b.audioElement;x&&(x.muted=Ye)},[b.audioElement,Ye]);const nn=r.useCallback(x=>{const p=b.getRoom();if(p)try{const J=new TextEncoder().encode(JSON.stringify({type:"user_message",text:x}));p.localParticipant.publishData(J,{reliable:!0})}catch{}},[b]),rn=r.useCallback(()=>{tn(x=>!x)},[]);r.useEffect(()=>{me==null||me(b.connectionState),b.connectionState==="connected"?ae==null||ae():b.connectionState==="disconnected"&&(fe==null||fe())},[b.connectionState,ae,fe,me]),r.useEffect(()=>{pe==null||pe(b.transcript)},[b.transcript,pe]),r.useEffect(()=>{he==null||he(b.agentState)},[b.agentState,he]);const lt=r.useRef(!1);r.useEffect(()=>{b.isControlled||!u||lt.current||je&&b.connectionState==="idle"&&(lt.current=!0,b.connect())},[u,b.connectionState,b,je]);const on=r.useCallback(x=>{const p=k==null?void 0:k.find(J=>J.id===x);p&&(H(!1),x!==G&&(Re(!0),b.disconnect(),ee||ve(x),T==null||T(p)))},[k,G,b,ee,T]);r.useEffect(()=>{Ne&&b.connectionState==="connected"&&Re(!1)},[b.connectionState,Ne]),r.useEffect(()=>{if(!m)return;const x=p=>{p.key==="Escape"&&H(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[m]);const sn=!!L||!!(F!=null&&F.avatarImageUrl)||b.isControlled,Ae=Ht(Ee,o,sn);Ce===void 0&&((ut=Ae.info)!=null&&ut.capabilities)&&(Ze.current=Ae.info.capabilities);const tt=(F==null?void 0:F.name)??A??((dt=b.agentConfig)==null?void 0:dt.name)??((ft=Ae.info)==null?void 0:ft.name)??"Live Layer",at=(F==null?void 0:F.avatarImageUrl)??L??((pt=b.agentConfig)==null?void 0:pt.avatarImageUrl)??((ht=Ae.info)==null?void 0:ht.avatarImageUrl)??null,ln=N??((mt=b.agentConfig)==null?void 0:mt.idleLoopUrl)??((gt=Ae.info)==null?void 0:gt.idleLoopUrl)??null,an=M??null,cn=r.useCallback(()=>U("expanded"),[U]),un=r.useCallback(()=>U("minimized"),[U]),ct=r.useCallback(()=>{b.disconnect(),U("hidden")},[b,U]),dn=r.useCallback(()=>{const x=b.audioElement;x&&x.play().then(()=>xe(!1)).catch(()=>{})},[b.audioElement]),fn=r.useCallback(()=>{xe(!1),b.connect()},[b]),Me={...ze,zIndex:qe};g.primaryColor&&(Me["--ll-color-primary"]=g.primaryColor),g.accentColor&&(Me["--ll-color-accent"]=g.accentColor),g.backgroundColor&&(Me["--ll-color-bg"]=g.backgroundColor),g.textColor&&(Me["--ll-color-fg"]=g.textColor);const pn=["ll-widget",`ll-widget--${te}`,`ll-widget--${Q?"mobile":"desktop"}`,We].filter(Boolean).join(" ");return je?t.jsxs("div",{className:pn,style:Me,"data-display-mode":te,"data-position":h,children:[te==="hidden"&&t.jsx(Tn,{position:h,isMobile:Q,isSpeaking:b.agentState==="speaking",onExpand:()=>U("expanded"),label:`Open ${tt} widget`}),te==="minimized"&&t.jsx(Dn,{position:h,isMobile:Q,agentName:tt,avatarImageUrl:at,agentState:b.agentState,isMuted:B.isMuted,audioLevel:ne,onExpand:cn,onToggleMute:B.toggleMute,onClose:ct}),te==="expanded"&&t.jsx(zn,{position:h,isMobile:Q,agentName:tt,avatarImageUrl:at,idleLoopUrl:ln,greeting:an,branding:g,teamMembers:k,currentTeamMemberId:G,isSwitchingTeamMember:Ne,teamSwitcherOpen:m,onToggleTeamSwitcher:()=>H(x=>!x),onSelectTeamMember:on,connectionState:b.connectionState,agentState:b.agentState,transcript:b.transcript,isMuted:B.isMuted,micDevices:Le.mics,isCameraEnabled:W.isEnabled,cameraPreviewEl:W.previewEl,cameraDevices:Le.cameras,activeCameraId:W.activeDeviceId,isScreenShareEnabled:re.isEnabled,screenPreviewEl:re.previewEl,isSpeakerMuted:Ye,allowCamera:v,allowScreenShare:C,allowTyping:w,languageMenuOpen:Ke,onToggleLanguageMenu:()=>en(x=>!x),needsUserGesture:Ve,canResume:b.canResume,micError:B.micError,error:b.error,avatarVideoContainerRef:st,onConnect:()=>void b.connect(),onDisconnect:()=>b.disconnect(),onRetry:fn,onResumeAudio:dn,onToggleMute:B.toggleMute,onToggleCamera:()=>void W.toggle(),onSwitchCameraDevice:x=>void W.switchDevice(x),onToggleScreenShare:()=>void re.toggle(),onToggleSpeaker:rn,onSendMessage:nn,onMinimize:un,onClose:ct,onClearMicError:B.clearError})]}):null}function ir(e){return t.jsx(It,{children:t.jsx(rr,{...e})})}const or=({agentId:e,baseUrl:n,apiKey:i,mode:o,onAgentEvent:s,className:l,style:u})=>{const d=r.useRef(null),f=r.useRef(null),y=r.useRef(s);y.current=s;const h=r.useCallback(a=>{var S;const c=a.detail;(S=y.current)==null||S.call(y,c)},[]);return r.useEffect(()=>{const a=d.current;if(!a)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),n&&c.setAttribute("base-url",n),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",h),a.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",h),a.removeChild(c),f.current=null}},[e]),r.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:l,style:u})},sr=r.forwardRef(function({id:n,intent:i,as:o="div",className:s,style:l,children:u},d){return r.createElement(o,{ref:d,"data-ll-region":n,"data-ll-intent":i,className:s,style:l},u)}),lr=r.forwardRef(function({id:n,intent:i,children:o,...s},l){return t.jsx("form",{ref:l,"data-ll-form":n,"data-ll-intent":i,...s,children:o})}),ar=r.forwardRef(function(n,i){const{name:o,label:s,labelClassName:l}=n,u={name:o,"data-ll-field":o};let d;if("as"in n&&n.as==="textarea"){const{name:f,label:y,labelClassName:h,as:a,...c}=n;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in n&&n.as==="select"){const{name:f,label:y,labelClassName:h,as:a,children:c,...S}=n;d=t.jsx("select",{ref:i,...u,...S,children:c})}else{const{name:f,label:y,labelClassName:h,as:a,...c}=n;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:l,children:[s,d]})});function cr(){const[e,n]=r.useState([]),i=r.useCallback(s=>{n(l=>{const u=l.findIndex(d=>d.id===s.id);if(u>=0){const d=l.slice();return d[u]=s,d}return[...l,s]})},[]),o=r.useCallback(()=>n([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=ir;exports.ErrorBoundary=It;exports.LiveLayerField=ar;exports.LiveLayerForm=lr;exports.LiveLayerRegion=sr;exports.LiveLayerWidget=or;exports.clearPageContextCache=Xt;exports.clearRoutesCache=Zt;exports.extractPageContext=Gt;exports.extractRoutes=Jt;exports.getCachedPageContext=nt;exports.getCachedRoutes=Qt;exports.matchesPattern=Wt;exports.shouldRenderAtPath=Vt;exports.useAgentInfo=Ht;exports.useAudioLevel=Pt;exports.useCameraState=$t;exports.useDisplayMode=Ot;exports.useDisplayModePersistence=Ft;exports.useIsMobile=Bt;exports.useLiveKitSession=Tt;exports.useMediaDevices=qt;exports.useMicrophoneState=Dt;exports.usePathname=Ut;exports.useRouteMatch=Kt;exports.useScreenShareState=zt;exports.useTranscript=cr;
|