@d-id/client-sdk 1.1.51-staging.227 → 1.1.51-staging.229
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 +105 -57
- package/dist/index.js +1 -1
- package/dist/index.umd.cjs +1 -1
- package/dist/src/types/auth.d.ts +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,6 +13,12 @@ The D-ID Agents SDK provides a seamless integration pathway for embedding your c
|
|
|
13
13
|
|
|
14
14
|
With a streamlined and user-friendly workflow, you can easily harness the capabilities of the D-ID Agents and Streams API right out of the box.
|
|
15
15
|
|
|
16
|
+
The SDK supports three avatar types:
|
|
17
|
+
|
|
18
|
+
- **Talks (V2)** — Photo-based presenters using WebRTC streaming.
|
|
19
|
+
- **Clips (V3)** — Pre-built presenter avatars using WebRTC streaming.
|
|
20
|
+
- **Expressives (V4)** — Next-generation avatars using LiveKit-based streaming, supporting microphone input and always-on fluent mode.
|
|
21
|
+
|
|
16
22
|
**Please note:** This SDK is designed for front-end development only. The creation of Agents and Knowledge bases should be handled through the [Agents API](https://docs.d-id.com/reference/agents-overview) or directly within the [D-ID Studio](https://studio.d-id.com/agents).
|
|
17
23
|
|
|
18
24
|
## ✴️ Getting Started
|
|
@@ -25,7 +31,7 @@ Follow these steps:
|
|
|
25
31
|
2. Create a new Agent with the required options - Image, voice, etc.
|
|
26
32
|
3. In the [Agents gallery](https://studio.d-id.com/agents), hover with your mouse over the created Agent, then click on the `[...]` button
|
|
27
33
|
4. Click on `</> Embed` button
|
|
28
|
-
5. Set the list of allowed domains for your Agent, for example: `http://localhost`
|
|
34
|
+
5. Set the list of allowed domains for your Agent, for example: `http://localhost`
|
|
29
35
|
This is an additional security measurement: your Agent can be accessed only from the domains allowed by you.
|
|
30
36
|
6. In the code snippet section, fetch the `data-client-key` and the `data-agent-id`, these will be used later to access your Agent.
|
|
31
37
|
|
|
@@ -46,11 +52,11 @@ In your front-end application,
|
|
|
46
52
|
1. Import the Agents SDK library
|
|
47
53
|
2. Paste the `data-agent-id` obtained in the prerequisites step in the `agentId` variable
|
|
48
54
|
3. Paste the `data-client-key` obtained in the prerequisites step in the `auth.clientKey` variable
|
|
49
|
-
4. Define an object called `callbacks`.
|
|
55
|
+
4. Define an object called `callbacks`.
|
|
50
56
|
This will be explained in the [Usage section](#➤-%EF%B8%8F-callback-functions) in this guide.
|
|
51
|
-
5. Define an object called `streamOptions` [optional]
|
|
57
|
+
5. Define an object called `streamOptions` [optional — v2/v3 avatars only]
|
|
52
58
|
This will be explained in the [Usage section](#➤-%EF%B8%8F-stream-options) in this guide.
|
|
53
|
-
6. Create an instance of the `createAgentManger` object called `agentManager` with the values created above.
|
|
59
|
+
6. Create an instance of the `createAgentManger` object called `agentManager` with the values created above.
|
|
54
60
|
This will be explained later in the [Usage section](#➤-%EF%B8%8F-agent-manager) in this guide.
|
|
55
61
|
|
|
56
62
|
Example:
|
|
@@ -68,7 +74,7 @@ let auth = { type: 'key', clientKey: 'Z3123asdaczxSXSAasdcxzcashDY6MGSASFsafxSDd
|
|
|
68
74
|
// 4. Define the SDK callbacks functions in this object
|
|
69
75
|
const callbacks = {};
|
|
70
76
|
|
|
71
|
-
// 5. Define the Stream Options object (Optional)
|
|
77
|
+
// 5. Define the Stream Options object (Optional — v2/v3 avatars only)
|
|
72
78
|
let streamOptions = { compatibilityMode: 'auto', streamWarmup: true };
|
|
73
79
|
|
|
74
80
|
//....Rest of the APP's code here....//
|
|
@@ -86,21 +92,21 @@ let agentManager = await sdk.createAgentManager(agentId, { auth, callbacks, stre
|
|
|
86
92
|
|
|
87
93
|
The `agentManager` object created during initialization has several built-in parameters that might come in handy.
|
|
88
94
|
|
|
89
|
-
-
|
|
90
|
-
|
|
91
|
-
-
|
|
92
|
-
|
|
95
|
+
- **`agentManager.agent`**
|
|
96
|
+
Displaying all of the Agent's saved information (Same as the following [endpoint](/reference/getagent))
|
|
97
|
+
- **`agentManager.starterMessages`**
|
|
98
|
+
Displaying the Agent's defined Starter Messages.
|
|
93
99
|
|
|
94
100
|
#### **Built-in Methods**
|
|
95
101
|
|
|
96
102
|
The `agentManager` object created during initialization has several built-in methods that allow you to interact with your Agent.
|
|
97
103
|
|
|
98
|
-
-
|
|
99
|
-
|
|
104
|
+
- **`agentManager.connect()`**
|
|
105
|
+
Method to create a new connection with an Agent (new WebRTC connection, web-socket, new Agent chat ID)
|
|
100
106
|
|
|
101
|
-
-
|
|
102
|
-
|
|
103
|
-
|
|
107
|
+
- **`agentManager.speak({type, input})`**
|
|
108
|
+
Method to make your Agent stream back a video based on a text or audio file.
|
|
109
|
+
(Similar to [Talks Streams](https://docs.d-id.com/reference/talks-streams-overview) / [Clips Streams API](https://docs.d-id.com/reference/clips-streams-overview))
|
|
104
110
|
|
|
105
111
|
```javascript Text - JavaScript
|
|
106
112
|
let speak = agentManager.speak({
|
|
@@ -118,30 +124,51 @@ The `agentManager` object created during initialization has several built-in met
|
|
|
118
124
|
)
|
|
119
125
|
```
|
|
120
126
|
|
|
121
|
-
-
|
|
122
|
-
|
|
127
|
+
- **`agentManager.chat(string)`**
|
|
128
|
+
Method to send a message to your Agent and get a streamed video based on its answer (LLM)
|
|
123
129
|
|
|
124
130
|
```javascript JavaScript
|
|
125
131
|
let chat = agentManager.chat('What is the distance to the moon?');
|
|
126
132
|
```
|
|
127
133
|
|
|
128
|
-
-
|
|
129
|
-
|
|
134
|
+
- **`agentManager.rate(messageID, score)`**
|
|
135
|
+
Method to rate the Agent's answer in the chat - for future analytics and insights.
|
|
136
|
+
|
|
137
|
+
- **`agentManager.reconnect()`**
|
|
138
|
+
Method to reconnect to the Agent when the session expires and continue the conversation on the same chat ID.
|
|
139
|
+
|
|
140
|
+
- **`agentManager.disconnect()`**
|
|
141
|
+
Method to close the existing connection and chat with the Agent.
|
|
142
|
+
|
|
143
|
+
- **`agentManager.interrupt(interrupt)`**
|
|
144
|
+
Method to interrupt the current video stream mid-playback.
|
|
145
|
+
Supported for Fluent streams (V3 Pro Avatars) and all Expressive (V4) agents.
|
|
130
146
|
|
|
131
|
-
-
|
|
132
|
-
|
|
147
|
+
- **`agentManager.publishMicrophoneStream(stream)`**
|
|
148
|
+
**Supported only with Expressive (V4) agents.**
|
|
149
|
+
Method to publish a microphone audio track to the session. Call after `connect()` to enable voice input.
|
|
133
150
|
|
|
134
|
-
|
|
135
|
-
|
|
151
|
+
```javascript
|
|
152
|
+
const micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
153
|
+
await agentManager.publishMicrophoneStream(micStream);
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
- **`agentManager.unpublishMicrophoneStream()`**
|
|
157
|
+
**Supported only with Expressive (V4) agents.**
|
|
158
|
+
Method to stop and remove the currently published microphone track from the session.
|
|
159
|
+
|
|
160
|
+
```javascript
|
|
161
|
+
await agentManager.unpublishMicrophoneStream();
|
|
162
|
+
```
|
|
136
163
|
|
|
137
164
|
### ➤ ✴️ Callback Functions
|
|
138
165
|
|
|
139
166
|
Callback functions enable you to manage various events throughout the SDK lifecycle. Each function is linked to one or more methods within the built-in `agentManager` and triggers automatically to handle specific events efficiently
|
|
140
167
|
|
|
141
|
-
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
168
|
+
- **`onSrcObjectReady(value)`:**
|
|
169
|
+
[**MANDATORY for using the SDK**] - Linking the Streamed video and audio to the HTML element.
|
|
170
|
+
The `value` of this callback function is passed to the HTML video element in the following function.
|
|
171
|
+
Triggered when `agentManager.connect(), agentManager.reconnect(), agentManager.disconnect()` are called.
|
|
145
172
|
|
|
146
173
|
```javascript
|
|
147
174
|
onSrcObjectReady(value) {
|
|
@@ -151,9 +178,9 @@ Callback functions enable you to manage various events throughout the SDK lifecy
|
|
|
151
178
|
}
|
|
152
179
|
```
|
|
153
180
|
|
|
154
|
-
-
|
|
155
|
-
|
|
156
|
-
|
|
181
|
+
- **`onVideoStateChange(state)`:**
|
|
182
|
+
Displaying the state of the streamed video, used for switching the HTML element's source between the idle and streamed videos.
|
|
183
|
+
Triggered when `agentManager.chat() and agentManager.speak()` are called.
|
|
157
184
|
|
|
158
185
|
```javascript
|
|
159
186
|
onVideoStateChange(state) {
|
|
@@ -170,9 +197,9 @@ Callback functions enable you to manage various events throughout the SDK lifecy
|
|
|
170
197
|
}
|
|
171
198
|
```
|
|
172
199
|
|
|
173
|
-
-
|
|
174
|
-
|
|
175
|
-
|
|
200
|
+
- **`onConnectionStateChange(state):`**
|
|
201
|
+
Displaying the different connection states with the Agent's WebRTC stream connection
|
|
202
|
+
Triggered when `agentManager.connect(), agentManager.reconnect(), agentManager.disconnect()` are called.
|
|
176
203
|
|
|
177
204
|
```javascript
|
|
178
205
|
onConnectionStateChange(state) {
|
|
@@ -187,10 +214,10 @@ Callback functions enable you to manage various events throughout the SDK lifecy
|
|
|
187
214
|
state: ['new', 'fail', 'connecting', 'connected', 'disconnected', 'closed'];
|
|
188
215
|
```
|
|
189
216
|
|
|
190
|
-
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
217
|
+
- **`onNewMessage(messages, type)`:**
|
|
218
|
+
Displaying the chat messages array when a new message is sent to the chat.
|
|
219
|
+
`type`: `answer` indicates the full answer replied in the streamed video.
|
|
220
|
+
`role`: `user`, `assistant`(Agent)
|
|
194
221
|
|
|
195
222
|
Triggered when `agentManager.chat()` is called:
|
|
196
223
|
|
|
@@ -227,8 +254,21 @@ Callback functions enable you to manage various events throughout the SDK lifecy
|
|
|
227
254
|
];
|
|
228
255
|
```
|
|
229
256
|
|
|
230
|
-
-
|
|
231
|
-
|
|
257
|
+
- **`onConnectivityStateChange(state)`:**
|
|
258
|
+
Triggered when the user's internet connectivity state changes, estimated by real-time bitrate.
|
|
259
|
+
|
|
260
|
+
```javascript
|
|
261
|
+
onConnectivityStateChange(state) {
|
|
262
|
+
console.log("onConnectivityStateChange(): ", state)
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
```javascript Example Values
|
|
267
|
+
state: ['STRONG', 'WEAK', 'UNKNOWN'];
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
- **`onError(error, errorData)`:**
|
|
271
|
+
Throwing an error and displaying the error message when things go badly.
|
|
232
272
|
|
|
233
273
|
```javascript
|
|
234
274
|
onError(error, errorData) {
|
|
@@ -236,33 +276,41 @@ Callback functions enable you to manage various events throughout the SDK lifecy
|
|
|
236
276
|
}
|
|
237
277
|
```
|
|
238
278
|
|
|
239
|
-
### ➤ ✴️ Stream Options
|
|
279
|
+
### ➤ ✴️ Stream Options (v2/v3 avatars only)
|
|
240
280
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
When set to `"
|
|
281
|
+
> **Note:** `streamOptions` apply only to Talks (V2) and Clips (V3) agents. Expressive (V4) avatars manage transport settings automatically and do not use these options.
|
|
282
|
+
|
|
283
|
+
- **`compatibilityMode`**:
|
|
284
|
+
Defines the video codec to be used in the stream.
|
|
285
|
+
When set to `"on"`: VP8 will be used.
|
|
286
|
+
When set to `"off"`: H264 will be used
|
|
287
|
+
When set to `"auto"` - the codec will be selected according to the browser [Default]
|
|
246
288
|
<br />
|
|
247
|
-
- **`streamWarmup`**:
|
|
248
|
-
Allowed values:
|
|
249
|
-
`true` -
|
|
250
|
-
`false` - no warmup video [Default]
|
|
289
|
+
- **`streamWarmup`**:
|
|
290
|
+
Allowed values:
|
|
291
|
+
`true` - warmup video will be streamed when the connection is established.
|
|
292
|
+
`false` - no warmup video [Default]
|
|
251
293
|
<br />
|
|
252
|
-
- **`sessionTimeout`**:
|
|
253
|
-
**Can only be used with proper permissions**
|
|
254
|
-
Maximum duration (in seconds) between messages before the session times out.
|
|
255
|
-
Max value: `300`
|
|
294
|
+
- **`sessionTimeout`**:
|
|
295
|
+
**Can only be used with proper permissions**
|
|
296
|
+
Maximum duration (in seconds) between messages before the session times out.
|
|
297
|
+
Max value: `300`
|
|
256
298
|
<br />
|
|
257
|
-
- **`outputResolution`**:
|
|
258
|
-
**Supported only with Talk presenters (photo-based).**
|
|
259
|
-
The output resolution sets the maximum height or width pixels of the streamed video.
|
|
260
|
-
When resolution is not configured, it defaults to the agent output resolution.
|
|
299
|
+
- **`outputResolution`**:
|
|
300
|
+
**Supported only with Talk presenters (photo-based).**
|
|
301
|
+
The output resolution sets the maximum height or width pixels of the streamed video.
|
|
302
|
+
When resolution is not configured, it defaults to the agent output resolution.
|
|
261
303
|
Allowed values: `150 - 1080`
|
|
262
304
|
|
|
305
|
+
- **`fluent`**:
|
|
306
|
+
**Supported with Agents created with V3 Pro Avatars. Always enabled for V4 Avatars.**
|
|
307
|
+
Allowed values:
|
|
308
|
+
`true` - Fluent streaming (one video for Idle/Talking states)
|
|
309
|
+
`false` - Legacy streaming mode (2 video elements)
|
|
310
|
+
|
|
263
311
|
## ✴️ See it in Action
|
|
264
312
|
|
|
265
|
-
Explore our demo repository on GitHub to see the Agents SDK in action!
|
|
313
|
+
Explore our demo repository on GitHub to see the Agents SDK in action!
|
|
266
314
|
This repository features a sample project crafted in Vanilla JavaScript and Vite, utilizing the Agents SDK to help you get started swiftly.
|
|
267
315
|
|
|
268
316
|
[GitHub Demo Repository](https://github.com/de-id/Agents-SDK-Demo)
|
package/dist/index.js
CHANGED
|
@@ -102,7 +102,7 @@ function Ge(e, n) {
|
|
|
102
102
|
if (e.type === "bearer")
|
|
103
103
|
return `Bearer ${e.token}`;
|
|
104
104
|
if (e.type === "basic")
|
|
105
|
-
return `Basic ${btoa(`${e.username}:${e.password}`)}`;
|
|
105
|
+
return `Basic ${"token" in e ? e.token : btoa(`${e.username}:${e.password}`)}`;
|
|
106
106
|
if (e.type === "key")
|
|
107
107
|
return `Client-Key ${e.clientKey}.${Ae(n)}_${It}`;
|
|
108
108
|
throw new Error(`Unknown auth type: ${e}`);
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(G,Ie){typeof exports=="object"&&typeof module<"u"?Ie(exports):typeof define=="function"&&define.amd?define(["exports"],Ie):(G=typeof globalThis<"u"?globalThis:G||self,Ie(G.index={}))})(this,function(G){"use strict";var _g=Object.defineProperty;var Rg=(G,Ie,Kt)=>Ie in G?_g(G,Ie,{enumerable:!0,configurable:!0,writable:!0,value:Kt}):G[Ie]=Kt;var si=(G,Ie,Kt)=>Rg(G,typeof Ie!="symbol"?Ie+"":Ie,Kt);class Ie extends Error{constructor({kind:t,description:i,error:r}){super(JSON.stringify({kind:t,description:i}));si(this,"kind");si(this,"description");si(this,"error");this.kind=t,this.description=i,this.error=r}}class Kt extends Ie{constructor(e,t){super({kind:"ChatCreationFailed",description:`Failed to create ${t?"persistent":""} chat, mode: ${e}`})}}class js extends Ie{constructor(e){super({kind:"ChatModeDowngraded",description:`Chat mode downgraded to ${e}`})}}class Wt extends Ie{constructor(t,i){super({kind:"ValidationError",description:t});si(this,"key");this.key=i}}class Vs extends Ie{constructor(e){super({kind:"WSError",description:e})}}var qs=(n=>(n.TRIAL="trial",n.BASIC="basic",n.ENTERPRISE="enterprise",n.LITE="lite",n.ADVANCED="advanced",n))(qs||{}),Ks=(n=>(n.TRIAL="deid-trial",n.PRO="deid-pro",n.ENTERPRISE="deid-enterprise",n.LITE="deid-lite",n.ADVANCED="deid-advanced",n.BUILD="deid-api-build",n.LAUNCH="deid-api-launch",n.SCALE="deid-api-scale",n))(Ks||{}),Ws=(n=>(n.Created="created",n.Started="started",n.Done="done",n.Error="error",n.Rejected="rejected",n.Ready="ready",n))(Ws||{}),Hs=(n=>(n.Unrated="Unrated",n.Positive="Positive",n.Negative="Negative",n))(Hs||{}),ke=(n=>(n.Functional="Functional",n.TextOnly="TextOnly",n.Maintenance="Maintenance",n.Playground="Playground",n.DirectPlayback="DirectPlayback",n.Off="Off",n))(ke||{}),Be=(n=>(n.Embed="embed",n.Query="query",n.Partial="partial",n.Answer="answer",n.Transcribe="transcribe",n.Complete="done",n))(Be||{}),Js=(n=>(n.KnowledgeProcessing="knowledge/processing",n.KnowledgeIndexing="knowledge/indexing",n.KnowledgeFailed="knowledge/error",n.KnowledgeDone="knowledge/done",n))(Js||{}),Gs=(n=>(n.Knowledge="knowledge",n.Document="document",n.Record="record",n))(Gs||{}),zs=(n=>(n.Pdf="pdf",n.Text="text",n.Html="html",n.Word="word",n.Json="json",n.Markdown="markdown",n.Csv="csv",n.Excel="excel",n.Powerpoint="powerpoint",n.Archive="archive",n.Image="image",n.Audio="audio",n.Video="video",n))(zs||{}),Zi=(n=>(n.Clip="clip",n.Talk="talk",n.Expressive="expressive",n))(Zi||{});const ou=n=>{switch(n){case"clip":return"clip";case"talk":return"talk";case"expressive":return"expressive";default:throw new Error(`Unknown video type: ${n}`)}};var z=(n=>(n.Start="START",n.Stop="STOP",n))(z||{}),et=(n=>(n.Strong="STRONG",n.Weak="WEAK",n.Unknown="UNKNOWN",n))(et||{}),xe=(n=>(n.Idle="IDLE",n.Loading="LOADING",n.Talking="TALKING",n))(xe||{}),oe=(n=>(n.ChatAnswer="chat/answer",n.ChatPartial="chat/partial",n.ChatAudioTranscribed="chat/audio-transcribed",n.StreamDone="stream/done",n.StreamStarted="stream/started",n.StreamFailed="stream/error",n.StreamReady="stream/ready",n.StreamCreated="stream/created",n.StreamInterrupt="stream/interrupt",n.StreamVideoCreated="stream-video/started",n.StreamVideoDone="stream-video/done",n.StreamVideoError="stream-video/error",n.StreamVideoRejected="stream-video/rejected",n))(oe||{}),se=(n=>(n.New="new",n.Fail="fail",n.Connected="connected",n.Connecting="connecting",n.Closed="closed",n.Completed="completed",n.Disconnecting="disconnecting",n.Disconnected="disconnected",n))(se||{}),tt=(n=>(n.Legacy="legacy",n.Fluent="fluent",n))(tt||{}),Rn=(n=>(n.Livekit="livekit",n))(Rn||{}),$s=(n=>(n.Amazon="amazon",n.AzureOpenAi="azure-openai",n.Microsoft="microsoft",n.Afflorithmics="afflorithmics",n.Elevenlabs="elevenlabs",n))($s||{}),Qs=(n=>(n.Public="public",n.Premium="premium",n.Private="private",n))(Qs||{});const cu=45*1e3,du="X-Playground-Chat",Pn="https://api.d-id.com",uu="wss://notifications.d-id.com",lu="79f81a83a67430be2bc0fd61042b8faa",hu=(...n)=>{},Ys=n=>new Promise(e=>setTimeout(e,n)),an=(n=16)=>{const e=new Uint8Array(n);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,13)},Xs=n=>n.type==="clip"&&n.presenter_id.startsWith("v2_")?"clip_v2":n.type,er=n=>n===Zi.Expressive,mu=n=>[ke.TextOnly,ke.Playground,ke.Maintenance].includes(n),Zs=n=>n&&[ke.DirectPlayback,ke.Off].includes(n);function fu(n,e){let t;return{promise:new Promise((r,s)=>{t=setTimeout(()=>s(new Error(e)),n)}),clear:()=>clearTimeout(t)}}async function tr(n,e){const t={limit:(e==null?void 0:e.limit)??3,delayMs:(e==null?void 0:e.delayMs)??0,timeout:(e==null?void 0:e.timeout)??3e4,timeoutErrorMessage:(e==null?void 0:e.timeoutErrorMessage)||"Timeout error",shouldRetryFn:(e==null?void 0:e.shouldRetryFn)??(()=>!0),onRetry:(e==null?void 0:e.onRetry)??(()=>{})};let i;for(let r=1;r<=t.limit;r++)try{if(!t.timeout)return await n();const{promise:s,clear:c}=fu(t.timeout,t.timeoutErrorMessage),a=n().finally(c);return await Promise.race([a,s])}catch(s){if(i=s,!t.shouldRetryFn(s)||r>=t.limit)throw s;await Ys(t.delayMs),t.onRetry(s)}throw i}function nr(n){if(n!==void 0)return window.localStorage.setItem("did_external_key_id",n),n;let e=window.localStorage.getItem("did_external_key_id");if(!e){let t=an();window.localStorage.setItem("did_external_key_id",t),e=t}return e}let pu=an();function ea(n,e){if(n.type==="bearer")return`Bearer ${n.token}`;if(n.type==="basic")return`Basic ${btoa(`${n.username}:${n.password}`)}`;if(n.type==="key")return`Client-Key ${n.clientKey}.${nr(e)}_${pu}`;throw new Error(`Unknown auth type: ${n}`)}const gu=n=>tr(n,{limit:3,delayMs:1e3,timeout:0,shouldRetryFn:e=>e.status===429});function ir(n,e=Pn,t,i){const r=async(s,c)=>{const{skipErrorHandler:a,...o}=c||{},d=await gu(()=>fetch(e+(s!=null&&s.startsWith("/")?s:`/${s}`),{...o,headers:{...o.headers,Authorization:ea(n,i),"Content-Type":"application/json"}}));if(!d.ok){let u=await d.text().catch(()=>`Failed to fetch with status ${d.status}`);const l=new Error(u);throw t&&!a&&t(l,{url:s,options:o,headers:d.headers}),l}return d.json()};return{get(s,c){return r(s,{...c,method:"GET"})},post(s,c,a){return r(s,{...a,body:JSON.stringify(c),method:"POST"})},delete(s,c,a){return r(s,{...a,body:JSON.stringify(c),method:"DELETE"})},patch(s,c,a){return r(s,{...a,body:JSON.stringify(c),method:"PATCH"})}}}function vu(n,e=Pn,t,i){const r=ir(n,`${e}/agents`,t,i);return{create(s,c){return r.post("/",s,c)},getAgents(s,c){return r.get(`/${s?`?tag=${s}`:""}`,c).then(a=>a??[])},getById(s,c){return r.get(`/${s}`,c)},delete(s,c){return r.delete(`/${s}`,void 0,c)},update(s,c,a){return r.patch(`/${s}`,c,a)},newChat(s,c,a){return r.post(`/${s}/chat`,c,a)},chat(s,c,a,o){return r.post(`/${s}/chat/${c}`,a,o)},createRating(s,c,a,o){return r.post(`/${s}/chat/${c}/ratings`,a,o)},updateRating(s,c,a,o,d){return r.patch(`/${s}/chat/${c}/ratings/${a}`,o,d)},deleteRating(s,c,a,o){return r.delete(`/${s}/chat/${c}/ratings/${a}`,o)},getSTTToken(s,c){return r.get(`/${s}/stt-token`,c)}}}function yu(n){var r,s,c,a;const e=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",t=()=>{const o=navigator.platform;return o.toLowerCase().includes("win")?"Windows":o.toLowerCase().includes("mac")?"Mac OS X":o.toLowerCase().includes("linux")?"Linux":"Unknown"},i=n.presenter;return{$os:`${t()}`,isMobile:`${e()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:Xs(i),agentVoice:{voiceId:(s=(r=n.presenter)==null?void 0:r.voice)==null?void 0:s.voice_id,provider:(a=(c=n.presenter)==null?void 0:c.voice)==null?void 0:a.type}}}function bu(n){var t,i,r,s,c,a;const e=(t=n.llm)==null?void 0:t.prompt_customization;return{agentType:Xs(n.presenter),owner_id:n.owner_id??"",promptVersion:(i=n.llm)==null?void 0:i.prompt_version,behavior:{role:e==null?void 0:e.role,personality:e==null?void 0:e.personality,instructions:(r=n.llm)==null?void 0:r.instructions},temperature:(s=n.llm)==null?void 0:s.temperature,knowledgeSource:e==null?void 0:e.knowledge_source,starterQuestionsCount:(a=(c=n.knowledge)==null?void 0:c.starter_message)==null?void 0:a.length,topicsToAvoid:e==null?void 0:e.topics_to_avoid,maxResponseLength:e==null?void 0:e.max_response_length,agentId:n.id,access:n.access,name:n.preview_name,...n.access==="public"?{from:"agent-template"}:{}}}const ku=n=>n.reduce((e,t)=>e+t,0),ta=n=>ku(n)/n.length;function Tu(n,e,t){var o,d,u;const{event:i,...r}=n,{template:s}=(e==null?void 0:e.llm)||{},{language:c}=((o=e==null?void 0:e.presenter)==null?void 0:o.voice)||{};return{...r,llm:{...r.llm,template:s},script:{...r.script,provider:{...(d=r==null?void 0:r.script)==null?void 0:d.provider,language:c}},stitch:(e==null?void 0:e.presenter.type)==="talk"?(u=e==null?void 0:e.presenter)==null?void 0:u.stitch:void 0,...t}}function na(n){"requestIdleCallback"in window?requestIdleCallback(n,{timeout:2e3}):setTimeout(n,0)}const Su="https://api-js.mixpanel.com/track/?verbose=1&ip=1";function Cu(n){const e=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={};return{token:n.token||"testKey",distinct_id:nr(n.externalId),agentId:n.agentId,additionalProperties:{id:nr(n.externalId),...n.mixpanelAdditionalProperties||{}},isEnabled:n.isEnabled??!0,getRandom:an,enrich(i){this.additionalProperties={...this.additionalProperties,...i}},async track(i,r,s){if(!this.isEnabled)return Promise.resolve();const{audioPath:c,...a}=r||{},o=s||Date.now(),d={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:i,properties:{...this.additionalProperties,...a,agentId:this.agentId,source:e,token:this.token,time:o,$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};return fetch(Su,d).catch(u=>console.error("Analytics tracking error:",u)),Promise.resolve()},linkTrack(i,r,s,c){t[i]||(t[i]={events:{},resolvedDependencies:[]}),c.includes(s)||c.push(s);const a=t[i];if(a.events[s]={props:r},a.resolvedDependencies.push(s),c.every(d=>a.resolvedDependencies.includes(d))){const d=c.reduce((u,l)=>a.events[l]?{...u,...a.events[l].props}:u,{});this.track(i,d),a.resolvedDependencies=a.resolvedDependencies.filter(u=>!c.includes(u)),c.forEach(u=>{delete a.events[u]})}}}}function rr(){let n=0;return{reset:()=>n=0,update:()=>n=Date.now(),get:(e=!1)=>e?Date.now()-n:n}}const nt=rr(),sr=rr(),ia=rr();function ra(n){return n===ke.Playground?{headers:{[du]:"true"}}:{}}async function sa(n,e,t,i,r=!1,s){try{return!s&&!Zs(i)&&(s=await e.newChat(n.id,{persist:r},ra(i)),t.track("agent-chat",{event:"created",chatId:s.id,mode:i})),{chat:s,chatMode:(s==null?void 0:s.chat_mode)??i}}catch(c){throw Eu(c)==="InsufficientCreditsError"?new Error("InsufficientCreditsError"):new Error("Cannot create new chat")}}const Eu=n=>{try{const e=JSON.parse(n.message);return e==null?void 0:e.kind}catch{return"UnknownError"}};function wu(n){return n&&n.length>0?n:[]}function _u(n,e,t,i){const r=ir(n,`${e}/v2/agents/${t}`,i);return{async createStream(s){return r.post("/sessions",s)}}}const aa=(n,e)=>(t,i)=>n&&console.log(`[${e}] ${t}`,i??"");function Ru(n,e,t){const i=(e.timestamp-n.timestamp)/1e3;return{duration:i,bytesReceived:e.bytesReceived-n.bytesReceived,bitrate:Math.round((e.bytesReceived-n.bytesReceived)*8/i),packetsReceived:e.packetsReceived-n.packetsReceived,packetsLost:e.packetsLost-n.packetsLost,framesDropped:e.framesDropped-n.framesDropped,framesDecoded:e.framesDecoded-n.framesDecoded,jitter:e.jitter,avgJitterDelayInInterval:(e.jitterBufferDelay-n.jitterBufferDelay)/(e.jitterBufferEmittedCount-n.jitterBufferEmittedCount),jitterBufferEmittedCount:e.jitterBufferEmittedCount-n.jitterBufferEmittedCount,jitterBufferDelay:(e.jitterBufferDelay-n.jitterBufferDelay)/i,framesPerSecond:e.framesPerSecond,freezeCount:e.freezeCount-n.freezeCount,freezeDuration:e.freezeDuration-n.freezeDuration,lowFpsCount:t}}function Pu(n){return n.filter(e=>e.freezeCount>0||e.framesPerSecond<21||e.framesDropped>0||e.packetsLost>0).map(e=>{const{timestamp:t,...i}=e,r=[];return e.freezeCount>0&&r.push("freeze"),e.framesPerSecond<21&&r.push("low fps"),e.framesDropped>0&&r.push("frames dropped"),e.packetsLost>0&&r.push("packet loss"),{...i,causes:r}})}function Iu(n){let e="",t=0;for(const i of n.values()){if(i&&i.type==="codec"&&i.mimeType.startsWith("video")&&(e=i.mimeType.split("/")[1]),i&&i.type==="candidate-pair"){const r=i.currentRoundTripTime,c=i.nominated===!0;r>0&&(c||t===0)&&(t=r)}if(i&&i.type==="inbound-rtp"&&i.kind==="video")return{codec:e,rtt:t,timestamp:i.timestamp,bytesReceived:i.bytesReceived,packetsReceived:i.packetsReceived,packetsLost:i.packetsLost,framesDropped:i.framesDropped,framesDecoded:i.framesDecoded,jitter:i.jitter,jitterBufferDelay:i.jitterBufferDelay,jitterBufferEmittedCount:i.jitterBufferEmittedCount,avgJitterDelayInInterval:i.jitterBufferDelay/i.jitterBufferEmittedCount,frameWidth:i.frameWidth,frameHeight:i.frameHeight,framesPerSecond:i.framesPerSecond,freezeCount:i.freezeCount,freezeDuration:i.totalFreezesDuration}}return{}}function oa(n,e,t){const i=n.map((o,d)=>d===0?t?{timestamp:o.timestamp,duration:0,rtt:o.rtt,bytesReceived:o.bytesReceived-t.bytesReceived,bitrate:(o.bytesReceived-t.bytesReceived)*8/(e/1e3),packetsReceived:o.packetsReceived-t.packetsReceived,packetsLost:o.packetsLost-t.packetsLost,framesDropped:o.framesDropped-t.framesDropped,framesDecoded:o.framesDecoded-t.framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay-t.jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount-t.jitterBufferEmittedCount,avgJitterDelayInInterval:(o.jitterBufferDelay-t.jitterBufferDelay)/(o.jitterBufferEmittedCount-t.jitterBufferEmittedCount),framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount-t.freezeCount,freezeDuration:o.freezeDuration-t.freezeDuration}:{timestamp:o.timestamp,rtt:o.rtt,duration:0,bytesReceived:o.bytesReceived,bitrate:o.bytesReceived*8/(e/1e3),packetsReceived:o.packetsReceived,packetsLost:o.packetsLost,framesDropped:o.framesDropped,framesDecoded:o.framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount,avgJitterDelayInInterval:o.jitterBufferDelay/o.jitterBufferEmittedCount,framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount,freezeDuration:o.freezeDuration}:{timestamp:o.timestamp,duration:e*d/1e3,rtt:o.rtt,bytesReceived:o.bytesReceived-n[d-1].bytesReceived,bitrate:(o.bytesReceived-n[d-1].bytesReceived)*8/(e/1e3),packetsReceived:o.packetsReceived-n[d-1].packetsReceived,packetsLost:o.packetsLost-n[d-1].packetsLost,framesDropped:o.framesDropped-n[d-1].framesDropped,framesDecoded:o.framesDecoded-n[d-1].framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay-n[d-1].jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount,avgJitterDelayInInterval:(o.jitterBufferDelay-n[d-1].jitterBufferDelay)/(o.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount),framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount-n[d-1].freezeCount,freezeDuration:o.freezeDuration-n[d-1].freezeDuration}),r=Pu(i),s=r.reduce((o,d)=>o+(d.causes.includes("low fps")?1:0),0),c=i.filter(o=>!!o.avgJitterDelayInInterval).map(o=>o.avgJitterDelayInInterval),a=i.filter(o=>!!o.rtt).map(o=>o.rtt);return{webRTCStats:{anomalies:r,minRtt:Math.min(...a),avgRtt:ta(a),maxRtt:Math.max(...a),aggregateReport:Ru(n[0],n[n.length-1],s),minJitterDelayInInterval:Math.min(...c),maxJitterDelayInInterval:Math.max(...c),avgJitterDelayInInterval:ta(c)},codec:n[0].codec,resolution:`${n[0].frameWidth}x${n[0].frameHeight}`}}const ai=100,Ou=Math.max(Math.ceil(400/ai),1),Mu=.25,Du=.28;function Au(){let n=0,e,t,i=0;return r=>{for(const s of r.values())if(s&&s.type==="inbound-rtp"&&s.kind==="video"){const c=s.jitterBufferDelay,a=s.jitterBufferEmittedCount;if(t&&a>t){const u=c-e,l=a-t;i=u/l}e=c,t=a;const o=s.framesDecoded,d=o-n>0;return n=o,{isReceiving:d,avgJitterDelayInInterval:i,freezeCount:s.freezeCount}}return{isReceiving:!1,avgJitterDelayInInterval:i}}}function ca(n,e,t,i,r){let s=null,c=[],a,o=0,d=!1,u=et.Unknown,l=et.Unknown,h=0,f=0;const y=Au();async function g(){const C=await n();if(!C)return;const{isReceiving:T,avgJitterDelayInInterval:_,freezeCount:I}=y(C),v=Iu(C);if(T)o=0,h=I-f,l=_<Mu?et.Strong:_>Du&&h>1?et.Weak:u,l!==u&&(r==null||r(l),u=l,f+=h,h=0),d||(i==null||i(z.Start),a=c[c.length-1],c=[],d=!0),c.push(v);else if(d&&(o++,o>=Ou)){const b=oa(c,ai,a);i==null||i(z.Stop,b),e()||t(),f=I,d=!1}}return{start:()=>{s||(s=setInterval(g,ai))},stop:()=>{s&&(clearInterval(s),s=null)},getReport:()=>oa(c,ai,a)}}const da=2e4;async function xu(){try{return await Promise.resolve().then(()=>Sg)}catch{throw new Error("LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client")}}const Lu={excellent:et.Strong,good:et.Strong,poor:et.Weak,lost:et.Unknown,unknown:et.Unknown},In=JSON.stringify({kind:"InternalServerError",description:"Stream Error"});var ar=(n=>(n.Chat="lk.chat",n.Speak="did.speak",n.Interrupt="did.interrupt",n))(ar||{});function or(n,e,t){var i,r;throw e("Failed to connect to LiveKit room:",n),(i=t.onConnectionStateChange)==null||i.call(t,se.Fail,"internal:init-error"),(r=t.onError)==null||r.call(t,n,{sessionId:""}),n}async function Nu(n,e,t){var su;const i=aa(t.debug||!1,"LiveKitStreamingManager"),{Room:r,RoomEvent:s,ConnectionState:c,Track:a}=await xu(),{callbacks:o,auth:d,baseURL:u,analytics:l}=t;let h=null,f=!1;const y=tt.Fluent;let g=null;const C={isPublishing:!1,publication:null},T={isPublishing:!1,publication:null};let _=null,I=null,v=!1;h=new r({adaptiveStream:!1,dynacast:!0});let b=null,S=xe.Idle;const L=_u(d,u||Pn,n,o.onError);let N,x,k;try{const D=await L.createStream({transport_provider:Rn.Livekit,chat_persist:e.chat_persist??!0}),{id:V,session_token:$,session_url:ne}=D;(su=o.onStreamCreated)==null||su.call(o,{session_id:V,stream_id:V,agent_id:n}),N=V,x=$,k=ne,await h.prepareConnection(k,x)}catch(D){or(D,i,o)}if(!k||!x||!N)return Promise.reject(new Error("Failed to initialize LiveKit stream"));h.on(s.ConnectionStateChanged,U).on(s.ConnectionQualityChanged,K).on(s.ParticipantConnected,Q).on(s.ParticipantDisconnected,ee).on(s.TrackSubscribed,Re).on(s.TrackUnsubscribed,de).on(s.DataReceived,me).on(s.MediaDevicesError,De).on(s.TranscriptionReceived,O).on(s.EncryptionError,Ze).on(s.TrackSubscriptionFailed,B);function O(D,V){var $;V!=null&&V.isLocal&&(nt.update(),S===xe.Talking&&(($=o.onInterruptDetected)==null||$.call(o,{type:"audio"}),S=xe.Idle))}try{await h.connect(k,x),i("LiveKit room joined successfully"),b=setTimeout(()=>{var D;i(`Track subscription timeout - no track subscribed within ${da/1e3} seconds after connect`),b=null,l.track("connectivity-error",{error:"Track subscription timeout",sessionId:N}),(D=o.onError)==null||D.call(o,new Error("Track subscription timeout"),{sessionId:N}),Bs("internal:track-subscription-timeout")},da)}catch(D){or(D,i,o)}l.enrich({"stream-type":y});function U(D){var V,$,ne,Ee;switch(i("Connection state changed:",D),D){case c.Connecting:i("CALLBACK: onConnectionStateChange(Connecting)"),(V=o.onConnectionStateChange)==null||V.call(o,se.Connecting,"livekit:connecting");break;case c.Connected:i("LiveKit room connected successfully"),f=!0;break;case c.Disconnected:i("LiveKit room disconnected"),f=!1,v=!1,C.publication=null,T.publication=null,($=o.onConnectionStateChange)==null||$.call(o,se.Disconnected,"livekit:disconnected");break;case c.Reconnecting:i("LiveKit room reconnecting..."),(ne=o.onConnectionStateChange)==null||ne.call(o,se.Connecting,"livekit:reconnecting");break;case c.SignalReconnecting:i("LiveKit room signal reconnecting..."),(Ee=o.onConnectionStateChange)==null||Ee.call(o,se.Connecting,"livekit:signal-reconnecting");break}}function K(D,V){var $;i("Connection quality:",D),V!=null&&V.isLocal&&(($=o.onConnectivityStateChange)==null||$.call(o,Lu[D]))}function Q(D){i("Participant connected:",D.identity)}function ee(D){i("Participant disconnected:",D.identity),Bs("livekit:participant-disconnected")}function X(){var D;I!==z.Start&&(i("CALLBACK: onVideoStateChange(Start)"),I=z.Start,(D=o.onVideoStateChange)==null||D.call(o,z.Start))}function he(D){var V;I!==z.Stop&&(i("CALLBACK: onVideoStateChange(Stop)"),I=z.Stop,(V=o.onVideoStateChange)==null||V.call(o,z.Stop,D))}function Re(D,V,$){var Ee,Ae,Vt;i(`Track subscribed: ${D.kind} from ${$.identity}`);const ne=D.mediaStreamTrack;if(!ne){i(`No mediaStreamTrack available for ${D.kind}`);return}g?(g.addTrack(ne),i(`Added ${D.kind} track to shared MediaStream`)):(g=new MediaStream([ne]),i(`Created shared MediaStream with ${D.kind} track`)),D.kind==="video"&&((Ee=o.onStreamReady)==null||Ee.call(o),i("CALLBACK: onSrcObjectReady"),(Ae=o.onSrcObjectReady)==null||Ae.call(o,g),v||(v=!0,i("CALLBACK: onConnectionStateChange(Connected)"),(Vt=o.onConnectionStateChange)==null||Vt.call(o,se.Connected,"livekit:track-subscribed")),_=ca(()=>D.getRTCStatsReport(),()=>f,hu,(He,qt)=>{i(`Video state change: ${He}`),He===z.Start?(b&&(clearTimeout(b),b=null,i("Track subscription timeout cleared")),X()):He===z.Stop&&he(qt)}),_.start())}function de(D,V,$){i(`Track unsubscribed: ${D.kind} from ${$.identity}`),D.kind==="video"&&(he(_==null?void 0:_.getReport()),_==null||_.stop(),_=null)}function me(D,V,$,ne){var Ae,Vt,He,qt,ni,ii,ri,kt;const Ee=new TextDecoder().decode(D);try{const Je=JSON.parse(Ee),sn=ne||Je.subject;if(i("Data received:",{subject:sn,data:Je}),sn===oe.ChatAnswer){const ut=Be.Answer;(Ae=o.onMessage)==null||Ae.call(o,ut,{event:ut,...Je})}else if(sn===oe.ChatPartial){const ut=Be.Partial;(Vt=o.onMessage)==null||Vt.call(o,ut,{event:ut,...Je})}else if([oe.StreamVideoCreated,oe.StreamVideoDone,oe.StreamVideoError,oe.StreamVideoRejected].includes(sn)){S=sn===oe.StreamVideoCreated?xe.Talking:xe.Idle,(He=o.onAgentActivityStateChange)==null||He.call(o,S);const ut=((ni=(qt=_==null?void 0:_.getReport())==null?void 0:qt.webRTCStats)==null?void 0:ni.avgRtt)??0,Xi=ut>0?Math.round(ut/2*1e3):0,au={...Je,downstreamNetworkLatency:Xi};t.debug&&((ii=Je==null?void 0:Je.metadata)!=null&&ii.sentiment)&&(au.sentiment={id:Je.metadata.sentiment.id,name:Je.metadata.sentiment.sentiment}),(ri=o.onMessage)==null||ri.call(o,sn,au)}else if(sn===oe.ChatAudioTranscribed){const ut=Be.Transcribe;(kt=o.onMessage)==null||kt.call(o,ut,{event:ut,...Je}),queueMicrotask(()=>{var Xi;(Xi=o.onAgentActivityStateChange)==null||Xi.call(o,xe.Loading)})}}catch(Je){i("Failed to parse data channel message:",Je)}}function De(D){var V;i("Media devices error:",D),(V=o.onError)==null||V.call(o,new Error(In),{sessionId:N})}function Ze(D){var V;i("Encryption error:",D),(V=o.onError)==null||V.call(o,new Error(In),{sessionId:N})}function B(D,V,$){i("Track subscription failed:",{trackSid:D,participant:V,reason:$})}function F(D,V,$){for(const[ne,Ee]of $)if(Ee.source===V&&Ee.track){const Ae=Ee.track.mediaStreamTrack;if(Ae===D||(Ae==null?void 0:Ae.id)===D.id)return Ee}return null}async function te(D,V,$,ne,Ee,Ae){var ni,ii,ri;if(!f||!h)throw i(`Room is not connected, cannot publish ${ne} stream`),new Error("Room is not connected");if(D.isPublishing){i(`${ne} publish already in progress, skipping`);return}const Vt=$(V);if(Vt.length===0)throw new Error(`No ${ne} track found in the provided MediaStream`);const He=Vt[0],qt=F(He,ne,Ee());if(qt){i(`${ne} track is already published, skipping`,{trackId:He.id,publishedTrackId:(ii=(ni=qt.track)==null?void 0:ni.mediaStreamTrack)==null?void 0:ii.id}),D.publication=qt;return}if((ri=D.publication)!=null&&ri.track){const kt=D.publication.track.mediaStreamTrack;kt!==He&&(kt==null?void 0:kt.id)!==He.id&&(i(`Unpublishing existing ${ne} track before publishing new one`),await Ae())}i(`Publishing ${ne} track from provided MediaStream`,{trackId:He.id}),D.isPublishing=!0;try{D.publication=await h.localParticipant.publishTrack(He,{source:ne}),i(`${ne} track published successfully`,{trackSid:D.publication.trackSid})}catch(kt){throw i(`Failed to publish ${ne} track:`,kt),kt}finally{D.isPublishing=!1}}async function Pe(D,V){if(!(!D.publication||!D.publication.track))try{h&&(await h.localParticipant.unpublishTrack(D.publication.track,!1),i(`${V} track unpublished`))}catch($){i(`Error unpublishing ${V} track:`,$)}finally{D.publication=null}}async function En(D){return te(C,D,V=>V.getAudioTracks(),a.Source.Microphone,()=>h.localParticipant.audioTrackPublications,wn)}async function wn(){return Pe(C,"Microphone")}async function Yi(D){return te(T,D,V=>V.getVideoTracks(),a.Source.Camera,()=>h.localParticipant.videoTrackPublications,_n)}async function _n(){return Pe(T,"Camera")}function Cg(){g&&(g.getTracks().forEach(D=>D.stop()),g=null)}async function Fs(D,V){var $,ne;if(!f||!h){i("Room is not connected for sending messages"),($=o.onError)==null||$.call(o,new Error(In),{sessionId:N});return}try{await h.localParticipant.sendText(D,{topic:V}),i("Message sent successfully:",D)}catch(Ee){i("Failed to send message:",Ee),(ne=o.onError)==null||ne.call(o,new Error(In),{sessionId:N})}}async function Eg(D){var V;try{const ne=JSON.parse(D).topic;return Fs("",ne)}catch($){i("Failed to send data channel message:",$),(V=o.onError)==null||V.call(o,new Error(In),{sessionId:N})}}function wg(D){return Fs(D,"lk.chat")}async function Bs(D){var V,$;b&&(clearTimeout(b),b=null),h&&((V=o.onConnectionStateChange)==null||V.call(o,se.Disconnecting,D),await Promise.all([wn(),_n()]),await h.disconnect()),Cg(),f=!1,v=!1,($=o.onAgentActivityStateChange)==null||$.call(o,xe.Idle),S=xe.Idle}return{speak(D){const V=typeof D=="string"?D:JSON.stringify(D);return Fs(V,"did.speak")},disconnect:()=>Bs("user:disconnect"),async reconnect(){var D,V;if((h==null?void 0:h.state)===c.Connected){i("Room is already connected");return}if(!h||!k||!x)throw i("Cannot reconnect: missing room, URL or token"),new Error("Cannot reconnect: session not available");i("Reconnecting to LiveKit room, state:",h.state),v=!1,(D=o.onConnectionStateChange)==null||D.call(o,se.Connecting,"user:reconnect");try{if(await h.connect(k,x),i("Room reconnected"),f=!0,h.remoteParticipants.size===0){if(i("Waiting for agent to join..."),!await new Promise(ne=>{const Ee=setTimeout(()=>{h==null||h.off(s.ParticipantConnected,Ae),ne(!1)},5e3),Ae=()=>{clearTimeout(Ee),h==null||h.off(s.ParticipantConnected,Ae),ne(!0)};h==null||h.on(s.ParticipantConnected,Ae)}))throw i("Agent did not join within timeout"),await h.disconnect(),new Error("Agent did not rejoin the room");i("Agent joined, reconnection successful")}}catch($){throw i("Failed to reconnect:",$),(V=o.onConnectionStateChange)==null||V.call(o,se.Fail,"user:reconnect-failed"),$}},sendDataChannelMessage:Eg,sendTextMessage:wg,publishMicrophoneStream:En,unpublishMicrophoneStream:wn,publishCameraStream:Yi,unpublishCameraStream:_n,sessionId:N,streamId:N,streamType:y,interruptAvailable:!0,triggersAvailable:!1}}const Uu=Object.freeze(Object.defineProperty({__proto__:null,DataChannelTopic:ar,createLiveKitStreamingManager:Nu,handleInitError:or},Symbol.toStringTag,{value:"Module"}));function Fu(n,e,t){if(!n)throw new Error("Please connect to the agent first");if(!n.interruptAvailable)throw new Error("Interrupt is not enabled for this stream");if(e!==tt.Fluent)throw new Error("Interrupt only available for Fluent streams");if(!t)throw new Error("No active video to interrupt")}async function Bu(n,e){const t={type:oe.StreamInterrupt,videoId:e,timestamp:Date.now()};n.sendDataChannelMessage(JSON.stringify(t))}async function ju(n){const e={topic:ar.Interrupt};n.sendDataChannelMessage(JSON.stringify(e))}function Vu(n){return new Promise((e,t)=>{const{callbacks:i,host:r,auth:s,externalId:c}=n,{onMessage:a=null,onOpen:o=null,onClose:d=null,onError:u=null}=i||{},l=new WebSocket(`${r}?authorization=${encodeURIComponent(ea(s,c))}`);l.onmessage=a,l.onclose=d,l.onerror=h=>{console.error(h),u==null||u("Websocket failed to connect",h),t(h)},l.onopen=h=>{o==null||o(h),e(l)}})}async function qu(n){const{retries:e=1}=n;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await Vu(n)}catch(r){if(i===e)throw r;await Ys(i*500)}return t}async function Ku(n,e,t,i){const r=t!=null&&t.onMessage?[t.onMessage]:[],s=await qu({auth:n,host:e,externalId:i,callbacks:{onError:c=>{var a;return(a=t.onError)==null?void 0:a.call(t,new Vs(c))},onMessage(c){const a=JSON.parse(c.data);r.forEach(o=>o(a.event,a))}}});return{socket:s,disconnect:()=>s.close(),subscribeToEvents:c=>r.push(c)}}function Wu(n){if(n.answer!==void 0)return n.answer;let e=0,t="";for(;e in n;)t+=n[e++];return t}function Hu(n,e,t){if(!n.content)return;const i=e.messages[e.messages.length-1];(i==null?void 0:i.role)==="assistant"&&!i.interrupted&&(i.interrupted=!0);const r={id:n.id||`user-${Date.now()}`,role:n.role,content:n.content,created_at:n.created_at||new Date().toISOString(),transcribed:!0};e.messages.push(r),t==null||t([...e.messages],"user")}function Ju(n,e,t,i,r){if(n===Be.Transcribe&&e.content){Hu(e,i,r);return}if(!(n===Be.Partial||n===Be.Answer))return;const s=i.messages[i.messages.length-1];let c;if(s!=null&&s.transcribed&&s.role==="user")n===Be.Answer&&e.content,c={id:e.id||`assistant-${Date.now()}`,role:e.role||"assistant",content:e.content||"",created_at:e.created_at||new Date().toISOString()},i.messages.push(c);else if((s==null?void 0:s.role)==="assistant")c=s;else return;const{content:a,sequence:o}=e;n===Be.Partial?t[o]=a:t.answer=a;const d=Wu(t);(c.content!==d||n===Be.Answer)&&(c.content=d,r==null||r([...i.messages],n))}function Gu(n,e,t,i,r){let s={};const c=()=>s={};let a="answer";const o=(d,u)=>{var l,h;u==="user"&&c(),a=u,(h=(l=t.callbacks).onNewMessage)==null||h.call(l,d,u)};return{clearQueue:c,onMessage:(d,u)=>{var l,h;if("content"in u){const f=d===oe.ChatAnswer?Be.Answer:d===oe.ChatAudioTranscribed?Be.Transcribe:d;Ju(f,u,s,e,o),f===Be.Answer&&n.track("agent-message-received",{content:u.content,messages:e.messages.length,mode:e.chatMode})}else{const f=oe,y=[f.StreamVideoDone,f.StreamVideoError,f.StreamVideoRejected],g=[f.StreamFailed,f.StreamVideoError,f.StreamVideoRejected],C=Tu(u,i,{mode:e.chatMode});if(d=d,d===f.StreamVideoCreated&&(n.linkTrack("agent-video",C,f.StreamVideoCreated,["start"]),u.sentiment)){const T=e.messages[e.messages.length-1];if((T==null?void 0:T.role)==="assistant"){const _={...T,sentiment:u.sentiment};e.messages[e.messages.length-1]=_,o==null||o([...e.messages],a)}}if(y.includes(d)){const T=d.split("/")[1];g.includes(d)?n.track("agent-video",{...C,event:T}):n.linkTrack("agent-video",{...C,event:T},d,["done"])}g.includes(d)&&((h=(l=t.callbacks).onError)==null||h.call(l,new Error(`Stream failed with event ${d}`),{data:u})),u.event===f.StreamDone&&r()}}}}function zu(n,e,t,i){const r=ir(n,`${e}/agents/${t}`,i);return{createStream(s,c){return r.post("/streams",s,{signal:c})},startConnection(s,c,a,o){return r.post(`/streams/${s}/sdp`,{session_id:a,answer:c},{signal:o})},addIceCandidate(s,c,a,o){return r.post(`/streams/${s}/ice`,{session_id:a,...c},{signal:o})},sendStreamRequest(s,c,a){return r.post(`/streams/${s}`,{session_id:c,...a})},close(s,c){return r.delete(`/streams/${s}`,{session_id:c})}}}const $u=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function ua(n){switch(n){case"connected":return se.Connected;case"checking":return se.Connecting;case"failed":return se.Fail;case"new":return se.New;case"closed":return se.Closed;case"disconnected":return se.Disconnected;case"completed":return se.Completed;default:return se.New}}const Qu=n=>e=>{const[t,i=""]=e.split(/:(.+)/);try{const r=JSON.parse(i);return n("parsed data channel message",{subject:t,data:r}),{subject:t,data:r}}catch(r){return n("Failed to parse data channel message, returning data as string",{subject:t,rawData:i,error:r}),{subject:t,data:i}}};function Yu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:i,log:r}){n===z.Start&&e===z.Start?(r("CALLBACK: onVideoStateChange(Start)"),t==null||t(z.Start)):n===z.Stop&&e===z.Stop&&(r("CALLBACK: onVideoStateChange(Stop)"),t==null||t(z.Stop,i))}function Xu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:r,log:s}){n===z.Start?(s("CALLBACK: onVideoStateChange(Start)"),t==null||t(z.Start)):n===z.Stop&&(s("CALLBACK: onVideoStateChange(Stop)"),t==null||t(z.Stop,r)),e===z.Start?i==null||i(xe.Talking):e===z.Stop&&(i==null||i(xe.Idle))}function la({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,streamType:r,report:s,log:c}){r===tt.Legacy?Yu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:s,log:c}):r===tt.Fluent&&Xu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:s,log:c})}async function Zu(n,e,{debug:t=!1,callbacks:i,auth:r,baseURL:s=Pn,analytics:c},a){var Ze;const o=aa(t,"WebRTCStreamingManager"),d=Qu(o);let u=!1,l=!1,h=z.Stop,f=z.Stop;const{startConnection:y,sendStreamRequest:g,close:C,createStream:T,addIceCandidate:_}=zu(r,s,n,i.onError),{id:I,offer:v,ice_servers:b,session_id:S,fluent:L,interrupt_enabled:N,triggers_enabled:x}=await T(e,a);(Ze=i.onStreamCreated)==null||Ze.call(i,{stream_id:I,session_id:S,agent_id:n});const k=new $u({iceServers:b}),O=k.createDataChannel("JanusDataChannel");if(!S)throw new Error("Could not create session_id");const U=L?tt.Fluent:tt.Legacy;c.enrich({"stream-type":U});const K=e.stream_warmup&&!L,Q=()=>u,ee=()=>{var B;u=!0,l&&(o("CALLBACK: onConnectionStateChange(Connected)"),(B=i.onConnectionStateChange)==null||B.call(i,se.Connected))},X=ca(()=>k.getStats(),Q,ee,(B,F)=>la({statsSignal:f=B,dataChannelSignal:U===tt.Legacy?h:void 0,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,report:F,streamType:U,log:o}),B=>{var F;return(F=i.onConnectivityStateChange)==null?void 0:F.call(i,B)});X.start(),k.onicecandidate=B=>{var F;o("peerConnection.onicecandidate",B);try{B.candidate&&B.candidate.sdpMid&&B.candidate.sdpMLineIndex!==null?_(I,{candidate:B.candidate.candidate,sdpMid:B.candidate.sdpMid,sdpMLineIndex:B.candidate.sdpMLineIndex},S,a):_(I,{candidate:null},S,a)}catch(te){(F=i.onError)==null||F.call(i,te,{streamId:I})}},O.onopen=()=>{l=!0,(!K||u)&&ee()};const he=B=>{var F;(F=i.onVideoIdChange)==null||F.call(i,B)};function Re(B,F){if(B===oe.StreamStarted&&typeof F=="object"&&"metadata"in F){const te=F.metadata;he(te.videoId)}B===oe.StreamDone&&he(null),h=B===oe.StreamStarted?z.Start:z.Stop,la({statsSignal:U===tt.Legacy?f:void 0,dataChannelSignal:h,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,streamType:U,log:o})}function de(B,F){var Pe;const te=typeof F=="string"?F:F==null?void 0:F.metadata;te&&c.enrich({streamMetadata:te}),(Pe=i.onStreamReady)==null||Pe.call(i)}const me={[oe.StreamStarted]:Re,[oe.StreamDone]:Re,[oe.StreamReady]:de};O.onmessage=B=>{var Pe;const{subject:F,data:te}=d(B.data);(Pe=me[F])==null||Pe.call(me,F,te)},k.oniceconnectionstatechange=()=>{var F;o("peerConnection.oniceconnectionstatechange => "+k.iceConnectionState);const B=ua(k.iceConnectionState);B!==se.Connected&&((F=i.onConnectionStateChange)==null||F.call(i,B))},k.ontrack=B=>{var F;o("peerConnection.ontrack",B),o("CALLBACK: onSrcObjectReady"),(F=i.onSrcObjectReady)==null||F.call(i,B.streams[0])},await k.setRemoteDescription(v),o("set remote description OK");const De=await k.createAnswer();return o("create answer OK"),await k.setLocalDescription(De),o("set local description OK"),await y(I,De,S,a),o("start connection OK"),{speak(B){return g(I,S,B)},async disconnect(){var B;if(I){const F=ua(k.iceConnectionState);if(k){if(F===se.New){X.stop();return}k.close(),k.oniceconnectionstatechange=null,k.onnegotiationneeded=null,k.onicecandidate=null,k.ontrack=null}try{F===se.Connected&&await C(I,S).catch(te=>{})}catch(te){o("Error on close stream connection",te)}(B=i.onAgentActivityStateChange)==null||B.call(i,xe.Idle),X.stop()}},sendDataChannelMessage(B){var F,te;if(!u||O.readyState!=="open"){o("Data channel is not ready for sending messages"),(F=i.onError)==null||F.call(i,new Error("Data channel is not ready for sending messages"),{streamId:I});return}try{O.send(B)}catch(Pe){o("Error sending data channel message",Pe),(te=i.onError)==null||te.call(i,Pe,{streamId:I})}},sessionId:S,streamId:I,streamType:U,interruptAvailable:N??!1,triggersAvailable:x??!1}}var cr=(n=>(n.V1="v1",n.V2="v2",n))(cr||{});async function el(n,e,t,i){const r=n.id;switch(e.version){case"v1":{const{version:s,...c}=e;return Zu(r,c,t,i)}case"v2":{const{version:s,...c}=e;switch(c.transport_provider){case Rn.Livekit:const{createLiveKitStreamingManager:a}=await Promise.resolve().then(()=>Uu);return a(r,c,t);default:throw new Error(`Unsupported transport provider: ${c.transport_provider}`)}}default:throw new Error(`Invalid stream version: ${e.version}`)}}const tl="cht";function nl(){return{transport_provider:Rn.Livekit}}function il(n){var r,s;const{streamOptions:e}=n??{},t=((r=n==null?void 0:n.mixpanelAdditionalProperties)==null?void 0:r.plan)!==void 0?{plan:(s=n.mixpanelAdditionalProperties)==null?void 0:s.plan}:void 0;return{...{output_resolution:e==null?void 0:e.outputResolution,session_timeout:e==null?void 0:e.sessionTimeout,stream_warmup:e==null?void 0:e.streamWarmup,compatibility_mode:e==null?void 0:e.compatibilityMode,fluent:e==null?void 0:e.fluent},...t&&{end_user_data:t}}}function rl(n,e){return er(n.presenter.type)?{version:cr.V2,...nl()}:{version:cr.V1,...il(e)}}function sl(n,e,t){t.track("agent-connection-state-change",{state:n,...e&&{reason:e}})}function al(n,e,t,i,r){r===tt.Fluent?ol(n,e,t,i,r):dl(n,e,t,i,r)}function ol(n,e,t,i,r){n===z.Start?i.track("stream-session",{event:"start","stream-type":r}):n===z.Stop&&i.track("stream-session",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t})}function cl(n,e,t,i){nt.get()<=0||(n===z.Start?t.linkTrack("agent-video",{event:"start",latency:nt.get(!0),"stream-type":i},"start",[oe.StreamVideoCreated]):n===z.Stop&&t.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":i},"done",[oe.StreamVideoDone]))}function dl(n,e,t,i,r){nt.get()<=0||(n===z.Start?i.linkTrack("agent-video",{event:"start",latency:nt.get(!0),"stream-type":r},"start",[oe.StreamVideoCreated]):n===z.Stop&&i.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t},"done",[oe.StreamVideoDone]))}function ha(n,e,t,i){return nt.reset(),ia.update(),new Promise(async(r,s)=>{try{let c,a=!1;const o=rl(n,e);t.enrich({"stream-version":o.version.toString()}),c=await el(n,o,{...e,analytics:t,callbacks:{...e.callbacks,onConnectionStateChange:(d,u)=>{var l,h;(h=(l=e.callbacks).onConnectionStateChange)==null||h.call(l,d),sl(d,u,t),d===se.Connected&&(c?r(c):a=!0)},onVideoStateChange:(d,u)=>{var l,h;(h=(l=e.callbacks).onVideoStateChange)==null||h.call(l,d),al(d,n,u,t,c.streamType)},onAgentActivityStateChange:d=>{var u,l;(l=(u=e.callbacks).onAgentActivityStateChange)==null||l.call(u,d),d===xe.Talking?sr.update():sr.reset(),cl(d===xe.Talking?z.Start:z.Stop,n,t,c.streamType)},onStreamReady:()=>{const d=ia.get(!0);t.track("agent-chat",{event:"ready",latency:d})}}},i),a&&r(c)}catch(c){s(c)}})}async function ul(n,e,t,i,r){var u,l,h,f;const s=async()=>{if(er(n.presenter.type)){const y=await ha(n,e,i),g=`${tl}_${y.sessionId}`,C=new Date().toISOString();return{chatResult:{chatMode:ke.Functional,chat:{id:g,agent_id:n.id,owner_id:n.owner_id??"",created:C,modified:C,agent_id__created_at:C,agent_id__modified_at:C,chat_mode:ke.Functional,messages:[]}},streamingManager:y}}else{const y=new AbortController,g=y.signal;let C;try{const T=sa(n,t,i,e.mode,e.persistentChat,r),_=ha(n,e,i,g).then(b=>(C=b,b)),[I,v]=await Promise.all([T,_]);return{chatResult:I,streamingManager:v}}catch(T){throw y.abort(),C&&await C.disconnect().catch(()=>{}),T}}},{chatResult:c,streamingManager:a}=await s(),{chat:o,chatMode:d}=c;return d&&e.mode!==void 0&&d!==e.mode&&(e.mode=d,(l=(u=e.callbacks).onModeChange)==null||l.call(u,d),d!==ke.Functional)?((f=(h=e.callbacks).onError)==null||f.call(h,new js(d)),a==null||a.disconnect(),{chat:o}):{chat:o,streamingManager:a}}async function ll(n,e){var S,L,N,x;let t=!0,i=null;const r=e.mixpanelKey||lu,s=e.wsURL||uu,c=e.baseURL||Pn,a=e.mode||ke.Functional,o={messages:[],chatMode:a},d=Cu({token:r,agentId:n,isEnabled:e.enableAnalitics,externalId:e.externalId,mixpanelAdditionalProperties:e.mixpanelAdditionalProperties}),u=Date.now();na(()=>{d.track("agent-sdk",{event:"init"},u)});const l=vu(e.auth,c,e.callbacks.onError,e.externalId),h=await l.getById(n);e.debug=e.debug||((S=h==null?void 0:h.advanced_settings)==null?void 0:S.ui_debug_mode);const f=er(h.presenter.type);d.enrich(bu(h));const{onMessage:y,clearQueue:g}=Gu(d,o,e,h,()=>{var k;return(k=o.socketManager)==null?void 0:k.disconnect()});o.messages=wu(e.initialMessages),(N=(L=e.callbacks).onNewMessage)==null||N.call(L,[...o.messages],"answer");const C=k=>{i=k},T=({type:k})=>{var U,K,Q;const O=o.messages[o.messages.length-1];d.track("agent-video-interrupt",{type:k||"click",video_duration_to_interrupt:sr.get(!0),message_duration_to_interrupt:nt.get(!0)}),O.interrupted=!0,(K=(U=e.callbacks).onNewMessage)==null||K.call(U,[...o.messages],"answer"),f?ju(o.streamingManager):(Fu(o.streamingManager,(Q=o.streamingManager)==null?void 0:Q.streamType,i),Bu(o.streamingManager,i))},_=Date.now();na(()=>{d.track("agent-sdk",{event:"loaded",...yu(h)},_)});async function I(k){var X,he,Re,de,me,De,Ze;(he=(X=e.callbacks).onConnectionStateChange)==null||he.call(X,se.Connecting),nt.reset(),k&&!t&&(delete o.chat,(de=(Re=e.callbacks).onNewMessage)==null||de.call(Re,[...o.messages],"answer"));const O=a===ke.DirectPlayback||f?Promise.resolve(void 0):Ku(e.auth,s,{onMessage:y,onError:e.callbacks.onError},e.externalId),U=tr(()=>ul(h,{...e,mode:a,callbacks:{...e.callbacks,onVideoIdChange:C,onMessage:y,onInterruptDetected:T}},l,d,o.chat),{limit:3,timeout:cu,timeoutErrorMessage:"Timeout initializing the stream",shouldRetryFn:B=>(B==null?void 0:B.message)!=="Could not connect"&&B.status!==429&&(B==null?void 0:B.message)!=="InsufficientCreditsError",delayMs:1e3}).catch(B=>{var F,te;throw b(ke.Maintenance),(te=(F=e.callbacks).onConnectionStateChange)==null||te.call(F,se.Fail),B}),[K,{streamingManager:Q,chat:ee}]=await Promise.all([O,U]);ee&&ee.id!==((me=o.chat)==null?void 0:me.id)&&((Ze=(De=e.callbacks).onNewChat)==null||Ze.call(De,ee.id)),o.streamingManager=Q,o.socketManager=K,o.chat=ee,t=!1,d.enrich({chatId:ee==null?void 0:ee.id,streamId:Q==null?void 0:Q.streamId,mode:o.chatMode}),b((ee==null?void 0:ee.chat_mode)??a)}async function v(){var k,O,U,K;(k=o.socketManager)==null||k.disconnect(),await((O=o.streamingManager)==null?void 0:O.disconnect()),delete o.streamingManager,delete o.socketManager,(K=(U=e.callbacks).onConnectionStateChange)==null||K.call(U,se.Disconnected)}async function b(k){var O,U;k!==o.chatMode&&(d.track("agent-mode-change",{mode:k}),o.chatMode=k,o.chatMode!==ke.Functional&&await v(),(U=(O=e.callbacks).onModeChange)==null||U.call(O,k))}return{agent:h,getStreamType:()=>{var k;return(k=o.streamingManager)==null?void 0:k.streamType},getIsInterruptAvailable:()=>{var k;return((k=o.streamingManager)==null?void 0:k.interruptAvailable)??!1},getIsTriggersAvailable:()=>{var k;return((k=o.streamingManager)==null?void 0:k.triggersAvailable)??!1},starterMessages:((x=h.knowledge)==null?void 0:x.starter_message)||[],getSTTToken:()=>l.getSTTToken(h.id),changeMode:b,enrichAnalytics:d.enrich,async connect(){await I(!0),d.track("agent-chat",{event:"connect",mode:o.chatMode})},async reconnect(){const k=o.streamingManager;if(f&&(k!=null&&k.reconnect)){try{await k.reconnect(),d.track("agent-chat",{event:"reconnect",mode:o.chatMode})}catch{await v(),await I(!1)}return}await v(),await I(!1),d.track("agent-chat",{event:"reconnect",mode:o.chatMode})},async disconnect(){await v(),d.track("agent-chat",{event:"disconnect",mode:o.chatMode})},async publishMicrophoneStream(k){var O;if(!((O=o.streamingManager)!=null&&O.publishMicrophoneStream))throw new Error("publishMicrophoneStream is not available for this streaming manager");return o.streamingManager.publishMicrophoneStream(k)},async unpublishMicrophoneStream(){var k;if(!((k=o.streamingManager)!=null&&k.unpublishMicrophoneStream))throw new Error("unpublishMicrophoneStream is not available for this streaming manager");return o.streamingManager.unpublishMicrophoneStream()},async publishCameraStream(k){var O;if(!((O=o.streamingManager)!=null&&O.publishCameraStream))throw new Error("publishCameraStream is not available for this streaming manager");return o.streamingManager.publishCameraStream(k)},async unpublishCameraStream(){var k;if(!((k=o.streamingManager)!=null&&k.unpublishCameraStream))throw new Error("unpublishCameraStream is not available for this streaming manager");return o.streamingManager.unpublishCameraStream()},async chat(k){var Q,ee,X,he,Re;const O=()=>{if(Zs(a))throw new Wt(`${a} is enabled, chat is disabled`);if(k.length>=800)throw new Wt("Message cannot be more than 800 characters");if(k.length===0)throw new Wt("Message cannot be empty");if(o.chatMode===ke.Maintenance)throw new Wt("Chat is in maintenance mode");if(![ke.TextOnly,ke.Playground].includes(o.chatMode)){if(!o.streamingManager)throw new Wt("Streaming manager is not initialized");if(!o.chat)throw new Wt("Chat is not initialized")}},U=async()=>{var de,me;if(!o.chat){const De=await sa(h,l,d,o.chatMode,e.persistentChat);if(!De.chat)throw new Kt(o.chatMode,!!e.persistentChat);o.chat=De.chat,(me=(de=e.callbacks).onNewChat)==null||me.call(de,o.chat.id)}return o.chat.id},K=async(de,me)=>{const De=o.chatMode===ke.Playground;return tr(f&&!De?async()=>{var F,te;return await((te=(F=o.streamingManager)==null?void 0:F.sendTextMessage)==null?void 0:te.call(F,k)),Promise.resolve({})}:async()=>{var F,te;return l.chat(h.id,me,{chatMode:o.chatMode,streamId:(F=o.streamingManager)==null?void 0:F.streamId,sessionId:(te=o.streamingManager)==null?void 0:te.sessionId,messages:de.map(({matches:Pe,...En})=>En)},{...ra(o.chatMode),skipErrorHandler:!0})},{limit:2,shouldRetryFn:F=>{var En,wn,Yi,_n;const te=(En=F==null?void 0:F.message)==null?void 0:En.includes("missing or invalid session_id");return!((wn=F==null?void 0:F.message)==null?void 0:wn.includes("Stream Error"))&&!te?((_n=(Yi=e.callbacks).onError)==null||_n.call(Yi,F),!1):!0},onRetry:async()=>{await v(),await I(!1)}})};try{g(),O(),o.messages.push({id:an(),role:"user",content:k,created_at:new Date(nt.update()).toISOString()}),(ee=(Q=e.callbacks).onNewMessage)==null||ee.call(Q,[...o.messages],"user");const de=await U(),me=await K([...o.messages],de);return o.messages.push({id:an(),role:"assistant",content:me.result||"",created_at:new Date().toISOString(),context:me.context,matches:me.matches}),d.track("agent-message-send",{event:"success",messages:o.messages.length+1}),me.result&&((he=(X=e.callbacks).onNewMessage)==null||he.call(X,[...o.messages],"answer"),d.track("agent-message-received",{latency:nt.get(!0),messages:o.messages.length})),me}catch(de){throw((Re=o.messages[o.messages.length-1])==null?void 0:Re.role)==="assistant"&&o.messages.pop(),d.track("agent-message-send",{event:"error",messages:o.messages.length}),de}},rate(k,O,U){var ee,X,he,Re;const K=o.messages.find(de=>de.id===k);if(o.chat){if(!K)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const Q=((ee=K.matches)==null?void 0:ee.map(de=>[de.document_id,de.id]))??[];return d.track("agent-rate",{event:U?"update":"create",thumb:O===1?"up":"down",knowledge_id:((X=h.knowledge)==null?void 0:X.id)??"",matches:Q,score:O}),U?l.updateRating(h.id,o.chat.id,U,{knowledge_id:((he=h.knowledge)==null?void 0:he.id)??"",message_id:k,matches:Q,score:O}):l.createRating(h.id,o.chat.id,{knowledge_id:((Re=h.knowledge)==null?void 0:Re.id)??"",message_id:k,matches:Q,score:O})},deleteRate(k){if(!o.chat)throw new Error("Chat is not initialized");return d.track("agent-rate-delete",{type:"text"}),l.deleteRating(h.id,o.chat.id,k)},async speak(k){var Q,ee,X;function O(){if(typeof k=="string"){if(!h.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:k,ssml:!1}}if(k.type==="text"&&!k.provider){if(!h.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:k.input,ssml:k.ssml}}return k}const U=O();if(d.track("agent-speak",U),nt.update(),o.messages&&U.type==="text"&&(o.messages.push({id:an(),role:"assistant",content:U.input,created_at:new Date().toISOString()}),(ee=(Q=e.callbacks).onNewMessage)==null||ee.call(Q,[...o.messages],"answer")),mu(o.chatMode))return{duration:0,video_id:"",status:"success"};if(!o.streamingManager)throw new Error("Please connect to the agent first");return o.streamingManager.speak({script:U,metadata:{chat_id:(X=o.chat)==null?void 0:X.id,agent_id:h.id}})},interrupt:T}}function hl(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var ml=Object.defineProperty,fl=(n,e,t)=>e in n?ml(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ma=(n,e,t)=>fl(n,typeof e!="symbol"?e+"":e,t);class we{constructor(){ma(this,"_locking"),ma(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function fe(n,e){if(!n)throw new Error(e)}const pl=34028234663852886e22,gl=-34028234663852886e22,vl=4294967295,yl=2147483647,bl=-2147483648;function oi(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>yl||n<bl)throw new Error("invalid int 32: "+n)}function dr(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>vl||n<0)throw new Error("invalid uint 32: "+n)}function fa(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>pl||n<gl))throw new Error("invalid float 32: "+n)}const pa=Symbol("@bufbuild/protobuf/enum-type");function kl(n){const e=n[pa];return fe(e,"missing enum type on enum object"),e}function ga(n,e,t,i){n[pa]=va(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function va(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const c of e){const a=ya(c);s.push(a),i[c.name]=a,r[c.no]=a}return{typeName:n,values:s,findName(c){return i[c]},findNumber(c){return r[c]}}}function Tl(n,e,t){const i={};for(const r of e){const s=ya(r);i[s.localName]=s.no,i[s.no]=s.localName}return ga(i,n,e),i}function ya(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class ur{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Sl(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),c={[s]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(c.prototype,new ur),Object.assign(c,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(a,o){return new c().fromBinary(a,o)},fromJson(a,o){return new c().fromJson(a,o)},fromJsonString(a,o){return new c().fromJsonString(a,o)},equals(a,o){return n.util.equals(c,a,o)}}),c}function Cl(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function lr(n,e,t){for(let s=0;s<28;s=s+7){const c=n>>>s,a=!(!(c>>>7)&&e==0),o=(a?c|128:c)&255;if(t.push(o),!a)return}const i=n>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const c=e>>>s,a=!!(c>>>7),o=(a?c|128:c)&255;if(t.push(o),!a)return}t.push(e>>>31&1)}}const ci=4294967296;function ba(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(c,a){const o=Number(n.slice(c,a));r*=t,i=i*t+o,i>=ci&&(r=r+(i/ci|0),i=i%ci)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Ta(i,r):hr(i,r)}function El(n,e){let t=hr(n,e);const i=t.hi&2147483648;i&&(t=Ta(t.lo,t.hi));const r=ka(t.lo,t.hi);return i?"-"+r:r}function ka(n,e){if({lo:n,hi:e}=wl(n,e),e<=2097151)return String(ci*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,c=i+r*8147497,a=r*2;const o=1e7;return s>=o&&(c+=Math.floor(s/o),s%=o),c>=o&&(a+=Math.floor(c/o),c%=o),a.toString()+Sa(c)+Sa(s)}function wl(n,e){return{lo:n>>>0,hi:e>>>0}}function hr(n,e){return{lo:n|0,hi:e|0}}function Ta(n,e){return e=~e,n?n=~n+1:e+=1,hr(n,e)}const Sa=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Ca(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function _l(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Rl(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),c=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(o){const d=typeof o=="bigint"?o:BigInt(o);if(d>s||d<r)throw new Error("int64 invalid: ".concat(o));return d},uParse(o){const d=typeof o=="bigint"?o:BigInt(o);if(d>a||d<c)throw new Error("uint64 invalid: ".concat(o));return d},enc(o){return n.setBigInt64(0,this.parse(o),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(o){return n.setBigInt64(0,this.uParse(o),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(o,d){return n.setInt32(0,o,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(o,d){return n.setInt32(0,o,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=r=>fe(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>fe(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),ba(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),ba(r)},dec(r,s){return El(r,s)},uDec(r,s){return ka(r,s)}}}const ce=Rl();var w;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(w||(w={}));var Mt;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Mt||(Mt={}));function Dt(n,e,t){if(e===t)return!0;if(n==w.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==t}return!1}function on(n,e){switch(n){case w.BOOL:return!1;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==0?ce.zero:"0";case w.DOUBLE:case w.FLOAT:return 0;case w.BYTES:return new Uint8Array(0);case w.STRING:return"";default:return 0}}function Ea(n,e){switch(n){case w.BOOL:return e===!1;case w.STRING:return e==="";case w.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ve;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ve||(ve={}));class Pl{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(dr(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return oi(e),Ca(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){fa(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){dr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){oi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return oi(e),e=(e<<1^e>>31)>>>0,Ca(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=ce.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=ce.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ce.enc(e);return lr(t.lo,t.hi,this.buf),this}sint64(e){let t=ce.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return lr(r,s,this.buf),this}uint64(e){let t=ce.uEnc(e);return lr(t.lo,t.hi,this.buf),this}}class Il{constructor(e,t){this.varint64=Cl,this.uint32=_l,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ve.Varint:for(;this.buf[this.pos++]&128;);break;case ve.Bit64:this.pos+=4;case ve.Bit32:this.pos+=4;break;case ve.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ve.StartGroup:for(;;){const[s,c]=this.tag();if(c===ve.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(c,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ce.dec(...this.varint64())}uint64(){return ce.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,ce.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ce.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ce.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Ol(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function wa(n){const e=n.field.localName,t=Object.create(null);return t[e]=Ml(n),[t,()=>t[e]]}function Ml(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return on(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function Dl(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),di=[];for(let n=0;n<Tt.length;n++)di[Tt[n].charCodeAt(0)]=n;di[45]=Tt.indexOf("+"),di[95]=Tt.indexOf("/");const _a={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,c=0;for(let a=0;a<n.length;a++){if(s=di[n.charCodeAt(a)],s===void 0)switch(n[a]){case"=":r=0;case`
|
|
1
|
+
(function(G,Ie){typeof exports=="object"&&typeof module<"u"?Ie(exports):typeof define=="function"&&define.amd?define(["exports"],Ie):(G=typeof globalThis<"u"?globalThis:G||self,Ie(G.index={}))})(this,function(G){"use strict";var _g=Object.defineProperty;var Rg=(G,Ie,Kt)=>Ie in G?_g(G,Ie,{enumerable:!0,configurable:!0,writable:!0,value:Kt}):G[Ie]=Kt;var si=(G,Ie,Kt)=>Rg(G,typeof Ie!="symbol"?Ie+"":Ie,Kt);class Ie extends Error{constructor({kind:t,description:i,error:r}){super(JSON.stringify({kind:t,description:i}));si(this,"kind");si(this,"description");si(this,"error");this.kind=t,this.description=i,this.error=r}}class Kt extends Ie{constructor(e,t){super({kind:"ChatCreationFailed",description:`Failed to create ${t?"persistent":""} chat, mode: ${e}`})}}class js extends Ie{constructor(e){super({kind:"ChatModeDowngraded",description:`Chat mode downgraded to ${e}`})}}class Wt extends Ie{constructor(t,i){super({kind:"ValidationError",description:t});si(this,"key");this.key=i}}class Vs extends Ie{constructor(e){super({kind:"WSError",description:e})}}var qs=(n=>(n.TRIAL="trial",n.BASIC="basic",n.ENTERPRISE="enterprise",n.LITE="lite",n.ADVANCED="advanced",n))(qs||{}),Ks=(n=>(n.TRIAL="deid-trial",n.PRO="deid-pro",n.ENTERPRISE="deid-enterprise",n.LITE="deid-lite",n.ADVANCED="deid-advanced",n.BUILD="deid-api-build",n.LAUNCH="deid-api-launch",n.SCALE="deid-api-scale",n))(Ks||{}),Ws=(n=>(n.Created="created",n.Started="started",n.Done="done",n.Error="error",n.Rejected="rejected",n.Ready="ready",n))(Ws||{}),Hs=(n=>(n.Unrated="Unrated",n.Positive="Positive",n.Negative="Negative",n))(Hs||{}),ke=(n=>(n.Functional="Functional",n.TextOnly="TextOnly",n.Maintenance="Maintenance",n.Playground="Playground",n.DirectPlayback="DirectPlayback",n.Off="Off",n))(ke||{}),Be=(n=>(n.Embed="embed",n.Query="query",n.Partial="partial",n.Answer="answer",n.Transcribe="transcribe",n.Complete="done",n))(Be||{}),Js=(n=>(n.KnowledgeProcessing="knowledge/processing",n.KnowledgeIndexing="knowledge/indexing",n.KnowledgeFailed="knowledge/error",n.KnowledgeDone="knowledge/done",n))(Js||{}),Gs=(n=>(n.Knowledge="knowledge",n.Document="document",n.Record="record",n))(Gs||{}),zs=(n=>(n.Pdf="pdf",n.Text="text",n.Html="html",n.Word="word",n.Json="json",n.Markdown="markdown",n.Csv="csv",n.Excel="excel",n.Powerpoint="powerpoint",n.Archive="archive",n.Image="image",n.Audio="audio",n.Video="video",n))(zs||{}),Zi=(n=>(n.Clip="clip",n.Talk="talk",n.Expressive="expressive",n))(Zi||{});const ou=n=>{switch(n){case"clip":return"clip";case"talk":return"talk";case"expressive":return"expressive";default:throw new Error(`Unknown video type: ${n}`)}};var z=(n=>(n.Start="START",n.Stop="STOP",n))(z||{}),et=(n=>(n.Strong="STRONG",n.Weak="WEAK",n.Unknown="UNKNOWN",n))(et||{}),xe=(n=>(n.Idle="IDLE",n.Loading="LOADING",n.Talking="TALKING",n))(xe||{}),oe=(n=>(n.ChatAnswer="chat/answer",n.ChatPartial="chat/partial",n.ChatAudioTranscribed="chat/audio-transcribed",n.StreamDone="stream/done",n.StreamStarted="stream/started",n.StreamFailed="stream/error",n.StreamReady="stream/ready",n.StreamCreated="stream/created",n.StreamInterrupt="stream/interrupt",n.StreamVideoCreated="stream-video/started",n.StreamVideoDone="stream-video/done",n.StreamVideoError="stream-video/error",n.StreamVideoRejected="stream-video/rejected",n))(oe||{}),se=(n=>(n.New="new",n.Fail="fail",n.Connected="connected",n.Connecting="connecting",n.Closed="closed",n.Completed="completed",n.Disconnecting="disconnecting",n.Disconnected="disconnected",n))(se||{}),tt=(n=>(n.Legacy="legacy",n.Fluent="fluent",n))(tt||{}),Rn=(n=>(n.Livekit="livekit",n))(Rn||{}),$s=(n=>(n.Amazon="amazon",n.AzureOpenAi="azure-openai",n.Microsoft="microsoft",n.Afflorithmics="afflorithmics",n.Elevenlabs="elevenlabs",n))($s||{}),Qs=(n=>(n.Public="public",n.Premium="premium",n.Private="private",n))(Qs||{});const cu=45*1e3,du="X-Playground-Chat",Pn="https://api.d-id.com",uu="wss://notifications.d-id.com",lu="79f81a83a67430be2bc0fd61042b8faa",hu=(...n)=>{},Ys=n=>new Promise(e=>setTimeout(e,n)),an=(n=16)=>{const e=new Uint8Array(n);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,13)},Xs=n=>n.type==="clip"&&n.presenter_id.startsWith("v2_")?"clip_v2":n.type,er=n=>n===Zi.Expressive,mu=n=>[ke.TextOnly,ke.Playground,ke.Maintenance].includes(n),Zs=n=>n&&[ke.DirectPlayback,ke.Off].includes(n);function fu(n,e){let t;return{promise:new Promise((r,s)=>{t=setTimeout(()=>s(new Error(e)),n)}),clear:()=>clearTimeout(t)}}async function tr(n,e){const t={limit:(e==null?void 0:e.limit)??3,delayMs:(e==null?void 0:e.delayMs)??0,timeout:(e==null?void 0:e.timeout)??3e4,timeoutErrorMessage:(e==null?void 0:e.timeoutErrorMessage)||"Timeout error",shouldRetryFn:(e==null?void 0:e.shouldRetryFn)??(()=>!0),onRetry:(e==null?void 0:e.onRetry)??(()=>{})};let i;for(let r=1;r<=t.limit;r++)try{if(!t.timeout)return await n();const{promise:s,clear:c}=fu(t.timeout,t.timeoutErrorMessage),a=n().finally(c);return await Promise.race([a,s])}catch(s){if(i=s,!t.shouldRetryFn(s)||r>=t.limit)throw s;await Ys(t.delayMs),t.onRetry(s)}throw i}function nr(n){if(n!==void 0)return window.localStorage.setItem("did_external_key_id",n),n;let e=window.localStorage.getItem("did_external_key_id");if(!e){let t=an();window.localStorage.setItem("did_external_key_id",t),e=t}return e}let pu=an();function ea(n,e){if(n.type==="bearer")return`Bearer ${n.token}`;if(n.type==="basic")return`Basic ${"token"in n?n.token:btoa(`${n.username}:${n.password}`)}`;if(n.type==="key")return`Client-Key ${n.clientKey}.${nr(e)}_${pu}`;throw new Error(`Unknown auth type: ${n}`)}const gu=n=>tr(n,{limit:3,delayMs:1e3,timeout:0,shouldRetryFn:e=>e.status===429});function ir(n,e=Pn,t,i){const r=async(s,c)=>{const{skipErrorHandler:a,...o}=c||{},d=await gu(()=>fetch(e+(s!=null&&s.startsWith("/")?s:`/${s}`),{...o,headers:{...o.headers,Authorization:ea(n,i),"Content-Type":"application/json"}}));if(!d.ok){let u=await d.text().catch(()=>`Failed to fetch with status ${d.status}`);const l=new Error(u);throw t&&!a&&t(l,{url:s,options:o,headers:d.headers}),l}return d.json()};return{get(s,c){return r(s,{...c,method:"GET"})},post(s,c,a){return r(s,{...a,body:JSON.stringify(c),method:"POST"})},delete(s,c,a){return r(s,{...a,body:JSON.stringify(c),method:"DELETE"})},patch(s,c,a){return r(s,{...a,body:JSON.stringify(c),method:"PATCH"})}}}function vu(n,e=Pn,t,i){const r=ir(n,`${e}/agents`,t,i);return{create(s,c){return r.post("/",s,c)},getAgents(s,c){return r.get(`/${s?`?tag=${s}`:""}`,c).then(a=>a??[])},getById(s,c){return r.get(`/${s}`,c)},delete(s,c){return r.delete(`/${s}`,void 0,c)},update(s,c,a){return r.patch(`/${s}`,c,a)},newChat(s,c,a){return r.post(`/${s}/chat`,c,a)},chat(s,c,a,o){return r.post(`/${s}/chat/${c}`,a,o)},createRating(s,c,a,o){return r.post(`/${s}/chat/${c}/ratings`,a,o)},updateRating(s,c,a,o,d){return r.patch(`/${s}/chat/${c}/ratings/${a}`,o,d)},deleteRating(s,c,a,o){return r.delete(`/${s}/chat/${c}/ratings/${a}`,o)},getSTTToken(s,c){return r.get(`/${s}/stt-token`,c)}}}function yu(n){var r,s,c,a;const e=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",t=()=>{const o=navigator.platform;return o.toLowerCase().includes("win")?"Windows":o.toLowerCase().includes("mac")?"Mac OS X":o.toLowerCase().includes("linux")?"Linux":"Unknown"},i=n.presenter;return{$os:`${t()}`,isMobile:`${e()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:Xs(i),agentVoice:{voiceId:(s=(r=n.presenter)==null?void 0:r.voice)==null?void 0:s.voice_id,provider:(a=(c=n.presenter)==null?void 0:c.voice)==null?void 0:a.type}}}function bu(n){var t,i,r,s,c,a;const e=(t=n.llm)==null?void 0:t.prompt_customization;return{agentType:Xs(n.presenter),owner_id:n.owner_id??"",promptVersion:(i=n.llm)==null?void 0:i.prompt_version,behavior:{role:e==null?void 0:e.role,personality:e==null?void 0:e.personality,instructions:(r=n.llm)==null?void 0:r.instructions},temperature:(s=n.llm)==null?void 0:s.temperature,knowledgeSource:e==null?void 0:e.knowledge_source,starterQuestionsCount:(a=(c=n.knowledge)==null?void 0:c.starter_message)==null?void 0:a.length,topicsToAvoid:e==null?void 0:e.topics_to_avoid,maxResponseLength:e==null?void 0:e.max_response_length,agentId:n.id,access:n.access,name:n.preview_name,...n.access==="public"?{from:"agent-template"}:{}}}const ku=n=>n.reduce((e,t)=>e+t,0),ta=n=>ku(n)/n.length;function Tu(n,e,t){var o,d,u;const{event:i,...r}=n,{template:s}=(e==null?void 0:e.llm)||{},{language:c}=((o=e==null?void 0:e.presenter)==null?void 0:o.voice)||{};return{...r,llm:{...r.llm,template:s},script:{...r.script,provider:{...(d=r==null?void 0:r.script)==null?void 0:d.provider,language:c}},stitch:(e==null?void 0:e.presenter.type)==="talk"?(u=e==null?void 0:e.presenter)==null?void 0:u.stitch:void 0,...t}}function na(n){"requestIdleCallback"in window?requestIdleCallback(n,{timeout:2e3}):setTimeout(n,0)}const Su="https://api-js.mixpanel.com/track/?verbose=1&ip=1";function Cu(n){const e=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={};return{token:n.token||"testKey",distinct_id:nr(n.externalId),agentId:n.agentId,additionalProperties:{id:nr(n.externalId),...n.mixpanelAdditionalProperties||{}},isEnabled:n.isEnabled??!0,getRandom:an,enrich(i){this.additionalProperties={...this.additionalProperties,...i}},async track(i,r,s){if(!this.isEnabled)return Promise.resolve();const{audioPath:c,...a}=r||{},o=s||Date.now(),d={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:i,properties:{...this.additionalProperties,...a,agentId:this.agentId,source:e,token:this.token,time:o,$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};return fetch(Su,d).catch(u=>console.error("Analytics tracking error:",u)),Promise.resolve()},linkTrack(i,r,s,c){t[i]||(t[i]={events:{},resolvedDependencies:[]}),c.includes(s)||c.push(s);const a=t[i];if(a.events[s]={props:r},a.resolvedDependencies.push(s),c.every(d=>a.resolvedDependencies.includes(d))){const d=c.reduce((u,l)=>a.events[l]?{...u,...a.events[l].props}:u,{});this.track(i,d),a.resolvedDependencies=a.resolvedDependencies.filter(u=>!c.includes(u)),c.forEach(u=>{delete a.events[u]})}}}}function rr(){let n=0;return{reset:()=>n=0,update:()=>n=Date.now(),get:(e=!1)=>e?Date.now()-n:n}}const nt=rr(),sr=rr(),ia=rr();function ra(n){return n===ke.Playground?{headers:{[du]:"true"}}:{}}async function sa(n,e,t,i,r=!1,s){try{return!s&&!Zs(i)&&(s=await e.newChat(n.id,{persist:r},ra(i)),t.track("agent-chat",{event:"created",chatId:s.id,mode:i})),{chat:s,chatMode:(s==null?void 0:s.chat_mode)??i}}catch(c){throw Eu(c)==="InsufficientCreditsError"?new Error("InsufficientCreditsError"):new Error("Cannot create new chat")}}const Eu=n=>{try{const e=JSON.parse(n.message);return e==null?void 0:e.kind}catch{return"UnknownError"}};function wu(n){return n&&n.length>0?n:[]}function _u(n,e,t,i){const r=ir(n,`${e}/v2/agents/${t}`,i);return{async createStream(s){return r.post("/sessions",s)}}}const aa=(n,e)=>(t,i)=>n&&console.log(`[${e}] ${t}`,i??"");function Ru(n,e,t){const i=(e.timestamp-n.timestamp)/1e3;return{duration:i,bytesReceived:e.bytesReceived-n.bytesReceived,bitrate:Math.round((e.bytesReceived-n.bytesReceived)*8/i),packetsReceived:e.packetsReceived-n.packetsReceived,packetsLost:e.packetsLost-n.packetsLost,framesDropped:e.framesDropped-n.framesDropped,framesDecoded:e.framesDecoded-n.framesDecoded,jitter:e.jitter,avgJitterDelayInInterval:(e.jitterBufferDelay-n.jitterBufferDelay)/(e.jitterBufferEmittedCount-n.jitterBufferEmittedCount),jitterBufferEmittedCount:e.jitterBufferEmittedCount-n.jitterBufferEmittedCount,jitterBufferDelay:(e.jitterBufferDelay-n.jitterBufferDelay)/i,framesPerSecond:e.framesPerSecond,freezeCount:e.freezeCount-n.freezeCount,freezeDuration:e.freezeDuration-n.freezeDuration,lowFpsCount:t}}function Pu(n){return n.filter(e=>e.freezeCount>0||e.framesPerSecond<21||e.framesDropped>0||e.packetsLost>0).map(e=>{const{timestamp:t,...i}=e,r=[];return e.freezeCount>0&&r.push("freeze"),e.framesPerSecond<21&&r.push("low fps"),e.framesDropped>0&&r.push("frames dropped"),e.packetsLost>0&&r.push("packet loss"),{...i,causes:r}})}function Iu(n){let e="",t=0;for(const i of n.values()){if(i&&i.type==="codec"&&i.mimeType.startsWith("video")&&(e=i.mimeType.split("/")[1]),i&&i.type==="candidate-pair"){const r=i.currentRoundTripTime,c=i.nominated===!0;r>0&&(c||t===0)&&(t=r)}if(i&&i.type==="inbound-rtp"&&i.kind==="video")return{codec:e,rtt:t,timestamp:i.timestamp,bytesReceived:i.bytesReceived,packetsReceived:i.packetsReceived,packetsLost:i.packetsLost,framesDropped:i.framesDropped,framesDecoded:i.framesDecoded,jitter:i.jitter,jitterBufferDelay:i.jitterBufferDelay,jitterBufferEmittedCount:i.jitterBufferEmittedCount,avgJitterDelayInInterval:i.jitterBufferDelay/i.jitterBufferEmittedCount,frameWidth:i.frameWidth,frameHeight:i.frameHeight,framesPerSecond:i.framesPerSecond,freezeCount:i.freezeCount,freezeDuration:i.totalFreezesDuration}}return{}}function oa(n,e,t){const i=n.map((o,d)=>d===0?t?{timestamp:o.timestamp,duration:0,rtt:o.rtt,bytesReceived:o.bytesReceived-t.bytesReceived,bitrate:(o.bytesReceived-t.bytesReceived)*8/(e/1e3),packetsReceived:o.packetsReceived-t.packetsReceived,packetsLost:o.packetsLost-t.packetsLost,framesDropped:o.framesDropped-t.framesDropped,framesDecoded:o.framesDecoded-t.framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay-t.jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount-t.jitterBufferEmittedCount,avgJitterDelayInInterval:(o.jitterBufferDelay-t.jitterBufferDelay)/(o.jitterBufferEmittedCount-t.jitterBufferEmittedCount),framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount-t.freezeCount,freezeDuration:o.freezeDuration-t.freezeDuration}:{timestamp:o.timestamp,rtt:o.rtt,duration:0,bytesReceived:o.bytesReceived,bitrate:o.bytesReceived*8/(e/1e3),packetsReceived:o.packetsReceived,packetsLost:o.packetsLost,framesDropped:o.framesDropped,framesDecoded:o.framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount,avgJitterDelayInInterval:o.jitterBufferDelay/o.jitterBufferEmittedCount,framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount,freezeDuration:o.freezeDuration}:{timestamp:o.timestamp,duration:e*d/1e3,rtt:o.rtt,bytesReceived:o.bytesReceived-n[d-1].bytesReceived,bitrate:(o.bytesReceived-n[d-1].bytesReceived)*8/(e/1e3),packetsReceived:o.packetsReceived-n[d-1].packetsReceived,packetsLost:o.packetsLost-n[d-1].packetsLost,framesDropped:o.framesDropped-n[d-1].framesDropped,framesDecoded:o.framesDecoded-n[d-1].framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay-n[d-1].jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount,avgJitterDelayInInterval:(o.jitterBufferDelay-n[d-1].jitterBufferDelay)/(o.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount),framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount-n[d-1].freezeCount,freezeDuration:o.freezeDuration-n[d-1].freezeDuration}),r=Pu(i),s=r.reduce((o,d)=>o+(d.causes.includes("low fps")?1:0),0),c=i.filter(o=>!!o.avgJitterDelayInInterval).map(o=>o.avgJitterDelayInInterval),a=i.filter(o=>!!o.rtt).map(o=>o.rtt);return{webRTCStats:{anomalies:r,minRtt:Math.min(...a),avgRtt:ta(a),maxRtt:Math.max(...a),aggregateReport:Ru(n[0],n[n.length-1],s),minJitterDelayInInterval:Math.min(...c),maxJitterDelayInInterval:Math.max(...c),avgJitterDelayInInterval:ta(c)},codec:n[0].codec,resolution:`${n[0].frameWidth}x${n[0].frameHeight}`}}const ai=100,Ou=Math.max(Math.ceil(400/ai),1),Mu=.25,Du=.28;function Au(){let n=0,e,t,i=0;return r=>{for(const s of r.values())if(s&&s.type==="inbound-rtp"&&s.kind==="video"){const c=s.jitterBufferDelay,a=s.jitterBufferEmittedCount;if(t&&a>t){const u=c-e,l=a-t;i=u/l}e=c,t=a;const o=s.framesDecoded,d=o-n>0;return n=o,{isReceiving:d,avgJitterDelayInInterval:i,freezeCount:s.freezeCount}}return{isReceiving:!1,avgJitterDelayInInterval:i}}}function ca(n,e,t,i,r){let s=null,c=[],a,o=0,d=!1,u=et.Unknown,l=et.Unknown,h=0,f=0;const y=Au();async function g(){const C=await n();if(!C)return;const{isReceiving:T,avgJitterDelayInInterval:_,freezeCount:I}=y(C),v=Iu(C);if(T)o=0,h=I-f,l=_<Mu?et.Strong:_>Du&&h>1?et.Weak:u,l!==u&&(r==null||r(l),u=l,f+=h,h=0),d||(i==null||i(z.Start),a=c[c.length-1],c=[],d=!0),c.push(v);else if(d&&(o++,o>=Ou)){const b=oa(c,ai,a);i==null||i(z.Stop,b),e()||t(),f=I,d=!1}}return{start:()=>{s||(s=setInterval(g,ai))},stop:()=>{s&&(clearInterval(s),s=null)},getReport:()=>oa(c,ai,a)}}const da=2e4;async function xu(){try{return await Promise.resolve().then(()=>Sg)}catch{throw new Error("LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client")}}const Lu={excellent:et.Strong,good:et.Strong,poor:et.Weak,lost:et.Unknown,unknown:et.Unknown},In=JSON.stringify({kind:"InternalServerError",description:"Stream Error"});var ar=(n=>(n.Chat="lk.chat",n.Speak="did.speak",n.Interrupt="did.interrupt",n))(ar||{});function or(n,e,t){var i,r;throw e("Failed to connect to LiveKit room:",n),(i=t.onConnectionStateChange)==null||i.call(t,se.Fail,"internal:init-error"),(r=t.onError)==null||r.call(t,n,{sessionId:""}),n}async function Nu(n,e,t){var su;const i=aa(t.debug||!1,"LiveKitStreamingManager"),{Room:r,RoomEvent:s,ConnectionState:c,Track:a}=await xu(),{callbacks:o,auth:d,baseURL:u,analytics:l}=t;let h=null,f=!1;const y=tt.Fluent;let g=null;const C={isPublishing:!1,publication:null},T={isPublishing:!1,publication:null};let _=null,I=null,v=!1;h=new r({adaptiveStream:!1,dynacast:!0});let b=null,S=xe.Idle;const L=_u(d,u||Pn,n,o.onError);let N,x,k;try{const D=await L.createStream({transport_provider:Rn.Livekit,chat_persist:e.chat_persist??!0}),{id:V,session_token:$,session_url:ne}=D;(su=o.onStreamCreated)==null||su.call(o,{session_id:V,stream_id:V,agent_id:n}),N=V,x=$,k=ne,await h.prepareConnection(k,x)}catch(D){or(D,i,o)}if(!k||!x||!N)return Promise.reject(new Error("Failed to initialize LiveKit stream"));h.on(s.ConnectionStateChanged,U).on(s.ConnectionQualityChanged,K).on(s.ParticipantConnected,Q).on(s.ParticipantDisconnected,ee).on(s.TrackSubscribed,Re).on(s.TrackUnsubscribed,de).on(s.DataReceived,me).on(s.MediaDevicesError,De).on(s.TranscriptionReceived,O).on(s.EncryptionError,Ze).on(s.TrackSubscriptionFailed,B);function O(D,V){var $;V!=null&&V.isLocal&&(nt.update(),S===xe.Talking&&(($=o.onInterruptDetected)==null||$.call(o,{type:"audio"}),S=xe.Idle))}try{await h.connect(k,x),i("LiveKit room joined successfully"),b=setTimeout(()=>{var D;i(`Track subscription timeout - no track subscribed within ${da/1e3} seconds after connect`),b=null,l.track("connectivity-error",{error:"Track subscription timeout",sessionId:N}),(D=o.onError)==null||D.call(o,new Error("Track subscription timeout"),{sessionId:N}),Bs("internal:track-subscription-timeout")},da)}catch(D){or(D,i,o)}l.enrich({"stream-type":y});function U(D){var V,$,ne,Ee;switch(i("Connection state changed:",D),D){case c.Connecting:i("CALLBACK: onConnectionStateChange(Connecting)"),(V=o.onConnectionStateChange)==null||V.call(o,se.Connecting,"livekit:connecting");break;case c.Connected:i("LiveKit room connected successfully"),f=!0;break;case c.Disconnected:i("LiveKit room disconnected"),f=!1,v=!1,C.publication=null,T.publication=null,($=o.onConnectionStateChange)==null||$.call(o,se.Disconnected,"livekit:disconnected");break;case c.Reconnecting:i("LiveKit room reconnecting..."),(ne=o.onConnectionStateChange)==null||ne.call(o,se.Connecting,"livekit:reconnecting");break;case c.SignalReconnecting:i("LiveKit room signal reconnecting..."),(Ee=o.onConnectionStateChange)==null||Ee.call(o,se.Connecting,"livekit:signal-reconnecting");break}}function K(D,V){var $;i("Connection quality:",D),V!=null&&V.isLocal&&(($=o.onConnectivityStateChange)==null||$.call(o,Lu[D]))}function Q(D){i("Participant connected:",D.identity)}function ee(D){i("Participant disconnected:",D.identity),Bs("livekit:participant-disconnected")}function X(){var D;I!==z.Start&&(i("CALLBACK: onVideoStateChange(Start)"),I=z.Start,(D=o.onVideoStateChange)==null||D.call(o,z.Start))}function he(D){var V;I!==z.Stop&&(i("CALLBACK: onVideoStateChange(Stop)"),I=z.Stop,(V=o.onVideoStateChange)==null||V.call(o,z.Stop,D))}function Re(D,V,$){var Ee,Ae,Vt;i(`Track subscribed: ${D.kind} from ${$.identity}`);const ne=D.mediaStreamTrack;if(!ne){i(`No mediaStreamTrack available for ${D.kind}`);return}g?(g.addTrack(ne),i(`Added ${D.kind} track to shared MediaStream`)):(g=new MediaStream([ne]),i(`Created shared MediaStream with ${D.kind} track`)),D.kind==="video"&&((Ee=o.onStreamReady)==null||Ee.call(o),i("CALLBACK: onSrcObjectReady"),(Ae=o.onSrcObjectReady)==null||Ae.call(o,g),v||(v=!0,i("CALLBACK: onConnectionStateChange(Connected)"),(Vt=o.onConnectionStateChange)==null||Vt.call(o,se.Connected,"livekit:track-subscribed")),_=ca(()=>D.getRTCStatsReport(),()=>f,hu,(He,qt)=>{i(`Video state change: ${He}`),He===z.Start?(b&&(clearTimeout(b),b=null,i("Track subscription timeout cleared")),X()):He===z.Stop&&he(qt)}),_.start())}function de(D,V,$){i(`Track unsubscribed: ${D.kind} from ${$.identity}`),D.kind==="video"&&(he(_==null?void 0:_.getReport()),_==null||_.stop(),_=null)}function me(D,V,$,ne){var Ae,Vt,He,qt,ni,ii,ri,kt;const Ee=new TextDecoder().decode(D);try{const Je=JSON.parse(Ee),sn=ne||Je.subject;if(i("Data received:",{subject:sn,data:Je}),sn===oe.ChatAnswer){const ut=Be.Answer;(Ae=o.onMessage)==null||Ae.call(o,ut,{event:ut,...Je})}else if(sn===oe.ChatPartial){const ut=Be.Partial;(Vt=o.onMessage)==null||Vt.call(o,ut,{event:ut,...Je})}else if([oe.StreamVideoCreated,oe.StreamVideoDone,oe.StreamVideoError,oe.StreamVideoRejected].includes(sn)){S=sn===oe.StreamVideoCreated?xe.Talking:xe.Idle,(He=o.onAgentActivityStateChange)==null||He.call(o,S);const ut=((ni=(qt=_==null?void 0:_.getReport())==null?void 0:qt.webRTCStats)==null?void 0:ni.avgRtt)??0,Xi=ut>0?Math.round(ut/2*1e3):0,au={...Je,downstreamNetworkLatency:Xi};t.debug&&((ii=Je==null?void 0:Je.metadata)!=null&&ii.sentiment)&&(au.sentiment={id:Je.metadata.sentiment.id,name:Je.metadata.sentiment.sentiment}),(ri=o.onMessage)==null||ri.call(o,sn,au)}else if(sn===oe.ChatAudioTranscribed){const ut=Be.Transcribe;(kt=o.onMessage)==null||kt.call(o,ut,{event:ut,...Je}),queueMicrotask(()=>{var Xi;(Xi=o.onAgentActivityStateChange)==null||Xi.call(o,xe.Loading)})}}catch(Je){i("Failed to parse data channel message:",Je)}}function De(D){var V;i("Media devices error:",D),(V=o.onError)==null||V.call(o,new Error(In),{sessionId:N})}function Ze(D){var V;i("Encryption error:",D),(V=o.onError)==null||V.call(o,new Error(In),{sessionId:N})}function B(D,V,$){i("Track subscription failed:",{trackSid:D,participant:V,reason:$})}function F(D,V,$){for(const[ne,Ee]of $)if(Ee.source===V&&Ee.track){const Ae=Ee.track.mediaStreamTrack;if(Ae===D||(Ae==null?void 0:Ae.id)===D.id)return Ee}return null}async function te(D,V,$,ne,Ee,Ae){var ni,ii,ri;if(!f||!h)throw i(`Room is not connected, cannot publish ${ne} stream`),new Error("Room is not connected");if(D.isPublishing){i(`${ne} publish already in progress, skipping`);return}const Vt=$(V);if(Vt.length===0)throw new Error(`No ${ne} track found in the provided MediaStream`);const He=Vt[0],qt=F(He,ne,Ee());if(qt){i(`${ne} track is already published, skipping`,{trackId:He.id,publishedTrackId:(ii=(ni=qt.track)==null?void 0:ni.mediaStreamTrack)==null?void 0:ii.id}),D.publication=qt;return}if((ri=D.publication)!=null&&ri.track){const kt=D.publication.track.mediaStreamTrack;kt!==He&&(kt==null?void 0:kt.id)!==He.id&&(i(`Unpublishing existing ${ne} track before publishing new one`),await Ae())}i(`Publishing ${ne} track from provided MediaStream`,{trackId:He.id}),D.isPublishing=!0;try{D.publication=await h.localParticipant.publishTrack(He,{source:ne}),i(`${ne} track published successfully`,{trackSid:D.publication.trackSid})}catch(kt){throw i(`Failed to publish ${ne} track:`,kt),kt}finally{D.isPublishing=!1}}async function Pe(D,V){if(!(!D.publication||!D.publication.track))try{h&&(await h.localParticipant.unpublishTrack(D.publication.track,!1),i(`${V} track unpublished`))}catch($){i(`Error unpublishing ${V} track:`,$)}finally{D.publication=null}}async function En(D){return te(C,D,V=>V.getAudioTracks(),a.Source.Microphone,()=>h.localParticipant.audioTrackPublications,wn)}async function wn(){return Pe(C,"Microphone")}async function Yi(D){return te(T,D,V=>V.getVideoTracks(),a.Source.Camera,()=>h.localParticipant.videoTrackPublications,_n)}async function _n(){return Pe(T,"Camera")}function Cg(){g&&(g.getTracks().forEach(D=>D.stop()),g=null)}async function Fs(D,V){var $,ne;if(!f||!h){i("Room is not connected for sending messages"),($=o.onError)==null||$.call(o,new Error(In),{sessionId:N});return}try{await h.localParticipant.sendText(D,{topic:V}),i("Message sent successfully:",D)}catch(Ee){i("Failed to send message:",Ee),(ne=o.onError)==null||ne.call(o,new Error(In),{sessionId:N})}}async function Eg(D){var V;try{const ne=JSON.parse(D).topic;return Fs("",ne)}catch($){i("Failed to send data channel message:",$),(V=o.onError)==null||V.call(o,new Error(In),{sessionId:N})}}function wg(D){return Fs(D,"lk.chat")}async function Bs(D){var V,$;b&&(clearTimeout(b),b=null),h&&((V=o.onConnectionStateChange)==null||V.call(o,se.Disconnecting,D),await Promise.all([wn(),_n()]),await h.disconnect()),Cg(),f=!1,v=!1,($=o.onAgentActivityStateChange)==null||$.call(o,xe.Idle),S=xe.Idle}return{speak(D){const V=typeof D=="string"?D:JSON.stringify(D);return Fs(V,"did.speak")},disconnect:()=>Bs("user:disconnect"),async reconnect(){var D,V;if((h==null?void 0:h.state)===c.Connected){i("Room is already connected");return}if(!h||!k||!x)throw i("Cannot reconnect: missing room, URL or token"),new Error("Cannot reconnect: session not available");i("Reconnecting to LiveKit room, state:",h.state),v=!1,(D=o.onConnectionStateChange)==null||D.call(o,se.Connecting,"user:reconnect");try{if(await h.connect(k,x),i("Room reconnected"),f=!0,h.remoteParticipants.size===0){if(i("Waiting for agent to join..."),!await new Promise(ne=>{const Ee=setTimeout(()=>{h==null||h.off(s.ParticipantConnected,Ae),ne(!1)},5e3),Ae=()=>{clearTimeout(Ee),h==null||h.off(s.ParticipantConnected,Ae),ne(!0)};h==null||h.on(s.ParticipantConnected,Ae)}))throw i("Agent did not join within timeout"),await h.disconnect(),new Error("Agent did not rejoin the room");i("Agent joined, reconnection successful")}}catch($){throw i("Failed to reconnect:",$),(V=o.onConnectionStateChange)==null||V.call(o,se.Fail,"user:reconnect-failed"),$}},sendDataChannelMessage:Eg,sendTextMessage:wg,publishMicrophoneStream:En,unpublishMicrophoneStream:wn,publishCameraStream:Yi,unpublishCameraStream:_n,sessionId:N,streamId:N,streamType:y,interruptAvailable:!0,triggersAvailable:!1}}const Uu=Object.freeze(Object.defineProperty({__proto__:null,DataChannelTopic:ar,createLiveKitStreamingManager:Nu,handleInitError:or},Symbol.toStringTag,{value:"Module"}));function Fu(n,e,t){if(!n)throw new Error("Please connect to the agent first");if(!n.interruptAvailable)throw new Error("Interrupt is not enabled for this stream");if(e!==tt.Fluent)throw new Error("Interrupt only available for Fluent streams");if(!t)throw new Error("No active video to interrupt")}async function Bu(n,e){const t={type:oe.StreamInterrupt,videoId:e,timestamp:Date.now()};n.sendDataChannelMessage(JSON.stringify(t))}async function ju(n){const e={topic:ar.Interrupt};n.sendDataChannelMessage(JSON.stringify(e))}function Vu(n){return new Promise((e,t)=>{const{callbacks:i,host:r,auth:s,externalId:c}=n,{onMessage:a=null,onOpen:o=null,onClose:d=null,onError:u=null}=i||{},l=new WebSocket(`${r}?authorization=${encodeURIComponent(ea(s,c))}`);l.onmessage=a,l.onclose=d,l.onerror=h=>{console.error(h),u==null||u("Websocket failed to connect",h),t(h)},l.onopen=h=>{o==null||o(h),e(l)}})}async function qu(n){const{retries:e=1}=n;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await Vu(n)}catch(r){if(i===e)throw r;await Ys(i*500)}return t}async function Ku(n,e,t,i){const r=t!=null&&t.onMessage?[t.onMessage]:[],s=await qu({auth:n,host:e,externalId:i,callbacks:{onError:c=>{var a;return(a=t.onError)==null?void 0:a.call(t,new Vs(c))},onMessage(c){const a=JSON.parse(c.data);r.forEach(o=>o(a.event,a))}}});return{socket:s,disconnect:()=>s.close(),subscribeToEvents:c=>r.push(c)}}function Wu(n){if(n.answer!==void 0)return n.answer;let e=0,t="";for(;e in n;)t+=n[e++];return t}function Hu(n,e,t){if(!n.content)return;const i=e.messages[e.messages.length-1];(i==null?void 0:i.role)==="assistant"&&!i.interrupted&&(i.interrupted=!0);const r={id:n.id||`user-${Date.now()}`,role:n.role,content:n.content,created_at:n.created_at||new Date().toISOString(),transcribed:!0};e.messages.push(r),t==null||t([...e.messages],"user")}function Ju(n,e,t,i,r){if(n===Be.Transcribe&&e.content){Hu(e,i,r);return}if(!(n===Be.Partial||n===Be.Answer))return;const s=i.messages[i.messages.length-1];let c;if(s!=null&&s.transcribed&&s.role==="user")n===Be.Answer&&e.content,c={id:e.id||`assistant-${Date.now()}`,role:e.role||"assistant",content:e.content||"",created_at:e.created_at||new Date().toISOString()},i.messages.push(c);else if((s==null?void 0:s.role)==="assistant")c=s;else return;const{content:a,sequence:o}=e;n===Be.Partial?t[o]=a:t.answer=a;const d=Wu(t);(c.content!==d||n===Be.Answer)&&(c.content=d,r==null||r([...i.messages],n))}function Gu(n,e,t,i,r){let s={};const c=()=>s={};let a="answer";const o=(d,u)=>{var l,h;u==="user"&&c(),a=u,(h=(l=t.callbacks).onNewMessage)==null||h.call(l,d,u)};return{clearQueue:c,onMessage:(d,u)=>{var l,h;if("content"in u){const f=d===oe.ChatAnswer?Be.Answer:d===oe.ChatAudioTranscribed?Be.Transcribe:d;Ju(f,u,s,e,o),f===Be.Answer&&n.track("agent-message-received",{content:u.content,messages:e.messages.length,mode:e.chatMode})}else{const f=oe,y=[f.StreamVideoDone,f.StreamVideoError,f.StreamVideoRejected],g=[f.StreamFailed,f.StreamVideoError,f.StreamVideoRejected],C=Tu(u,i,{mode:e.chatMode});if(d=d,d===f.StreamVideoCreated&&(n.linkTrack("agent-video",C,f.StreamVideoCreated,["start"]),u.sentiment)){const T=e.messages[e.messages.length-1];if((T==null?void 0:T.role)==="assistant"){const _={...T,sentiment:u.sentiment};e.messages[e.messages.length-1]=_,o==null||o([...e.messages],a)}}if(y.includes(d)){const T=d.split("/")[1];g.includes(d)?n.track("agent-video",{...C,event:T}):n.linkTrack("agent-video",{...C,event:T},d,["done"])}g.includes(d)&&((h=(l=t.callbacks).onError)==null||h.call(l,new Error(`Stream failed with event ${d}`),{data:u})),u.event===f.StreamDone&&r()}}}}function zu(n,e,t,i){const r=ir(n,`${e}/agents/${t}`,i);return{createStream(s,c){return r.post("/streams",s,{signal:c})},startConnection(s,c,a,o){return r.post(`/streams/${s}/sdp`,{session_id:a,answer:c},{signal:o})},addIceCandidate(s,c,a,o){return r.post(`/streams/${s}/ice`,{session_id:a,...c},{signal:o})},sendStreamRequest(s,c,a){return r.post(`/streams/${s}`,{session_id:c,...a})},close(s,c){return r.delete(`/streams/${s}`,{session_id:c})}}}const $u=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function ua(n){switch(n){case"connected":return se.Connected;case"checking":return se.Connecting;case"failed":return se.Fail;case"new":return se.New;case"closed":return se.Closed;case"disconnected":return se.Disconnected;case"completed":return se.Completed;default:return se.New}}const Qu=n=>e=>{const[t,i=""]=e.split(/:(.+)/);try{const r=JSON.parse(i);return n("parsed data channel message",{subject:t,data:r}),{subject:t,data:r}}catch(r){return n("Failed to parse data channel message, returning data as string",{subject:t,rawData:i,error:r}),{subject:t,data:i}}};function Yu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:i,log:r}){n===z.Start&&e===z.Start?(r("CALLBACK: onVideoStateChange(Start)"),t==null||t(z.Start)):n===z.Stop&&e===z.Stop&&(r("CALLBACK: onVideoStateChange(Stop)"),t==null||t(z.Stop,i))}function Xu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:r,log:s}){n===z.Start?(s("CALLBACK: onVideoStateChange(Start)"),t==null||t(z.Start)):n===z.Stop&&(s("CALLBACK: onVideoStateChange(Stop)"),t==null||t(z.Stop,r)),e===z.Start?i==null||i(xe.Talking):e===z.Stop&&(i==null||i(xe.Idle))}function la({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,streamType:r,report:s,log:c}){r===tt.Legacy?Yu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:s,log:c}):r===tt.Fluent&&Xu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:s,log:c})}async function Zu(n,e,{debug:t=!1,callbacks:i,auth:r,baseURL:s=Pn,analytics:c},a){var Ze;const o=aa(t,"WebRTCStreamingManager"),d=Qu(o);let u=!1,l=!1,h=z.Stop,f=z.Stop;const{startConnection:y,sendStreamRequest:g,close:C,createStream:T,addIceCandidate:_}=zu(r,s,n,i.onError),{id:I,offer:v,ice_servers:b,session_id:S,fluent:L,interrupt_enabled:N,triggers_enabled:x}=await T(e,a);(Ze=i.onStreamCreated)==null||Ze.call(i,{stream_id:I,session_id:S,agent_id:n});const k=new $u({iceServers:b}),O=k.createDataChannel("JanusDataChannel");if(!S)throw new Error("Could not create session_id");const U=L?tt.Fluent:tt.Legacy;c.enrich({"stream-type":U});const K=e.stream_warmup&&!L,Q=()=>u,ee=()=>{var B;u=!0,l&&(o("CALLBACK: onConnectionStateChange(Connected)"),(B=i.onConnectionStateChange)==null||B.call(i,se.Connected))},X=ca(()=>k.getStats(),Q,ee,(B,F)=>la({statsSignal:f=B,dataChannelSignal:U===tt.Legacy?h:void 0,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,report:F,streamType:U,log:o}),B=>{var F;return(F=i.onConnectivityStateChange)==null?void 0:F.call(i,B)});X.start(),k.onicecandidate=B=>{var F;o("peerConnection.onicecandidate",B);try{B.candidate&&B.candidate.sdpMid&&B.candidate.sdpMLineIndex!==null?_(I,{candidate:B.candidate.candidate,sdpMid:B.candidate.sdpMid,sdpMLineIndex:B.candidate.sdpMLineIndex},S,a):_(I,{candidate:null},S,a)}catch(te){(F=i.onError)==null||F.call(i,te,{streamId:I})}},O.onopen=()=>{l=!0,(!K||u)&&ee()};const he=B=>{var F;(F=i.onVideoIdChange)==null||F.call(i,B)};function Re(B,F){if(B===oe.StreamStarted&&typeof F=="object"&&"metadata"in F){const te=F.metadata;he(te.videoId)}B===oe.StreamDone&&he(null),h=B===oe.StreamStarted?z.Start:z.Stop,la({statsSignal:U===tt.Legacy?f:void 0,dataChannelSignal:h,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,streamType:U,log:o})}function de(B,F){var Pe;const te=typeof F=="string"?F:F==null?void 0:F.metadata;te&&c.enrich({streamMetadata:te}),(Pe=i.onStreamReady)==null||Pe.call(i)}const me={[oe.StreamStarted]:Re,[oe.StreamDone]:Re,[oe.StreamReady]:de};O.onmessage=B=>{var Pe;const{subject:F,data:te}=d(B.data);(Pe=me[F])==null||Pe.call(me,F,te)},k.oniceconnectionstatechange=()=>{var F;o("peerConnection.oniceconnectionstatechange => "+k.iceConnectionState);const B=ua(k.iceConnectionState);B!==se.Connected&&((F=i.onConnectionStateChange)==null||F.call(i,B))},k.ontrack=B=>{var F;o("peerConnection.ontrack",B),o("CALLBACK: onSrcObjectReady"),(F=i.onSrcObjectReady)==null||F.call(i,B.streams[0])},await k.setRemoteDescription(v),o("set remote description OK");const De=await k.createAnswer();return o("create answer OK"),await k.setLocalDescription(De),o("set local description OK"),await y(I,De,S,a),o("start connection OK"),{speak(B){return g(I,S,B)},async disconnect(){var B;if(I){const F=ua(k.iceConnectionState);if(k){if(F===se.New){X.stop();return}k.close(),k.oniceconnectionstatechange=null,k.onnegotiationneeded=null,k.onicecandidate=null,k.ontrack=null}try{F===se.Connected&&await C(I,S).catch(te=>{})}catch(te){o("Error on close stream connection",te)}(B=i.onAgentActivityStateChange)==null||B.call(i,xe.Idle),X.stop()}},sendDataChannelMessage(B){var F,te;if(!u||O.readyState!=="open"){o("Data channel is not ready for sending messages"),(F=i.onError)==null||F.call(i,new Error("Data channel is not ready for sending messages"),{streamId:I});return}try{O.send(B)}catch(Pe){o("Error sending data channel message",Pe),(te=i.onError)==null||te.call(i,Pe,{streamId:I})}},sessionId:S,streamId:I,streamType:U,interruptAvailable:N??!1,triggersAvailable:x??!1}}var cr=(n=>(n.V1="v1",n.V2="v2",n))(cr||{});async function el(n,e,t,i){const r=n.id;switch(e.version){case"v1":{const{version:s,...c}=e;return Zu(r,c,t,i)}case"v2":{const{version:s,...c}=e;switch(c.transport_provider){case Rn.Livekit:const{createLiveKitStreamingManager:a}=await Promise.resolve().then(()=>Uu);return a(r,c,t);default:throw new Error(`Unsupported transport provider: ${c.transport_provider}`)}}default:throw new Error(`Invalid stream version: ${e.version}`)}}const tl="cht";function nl(){return{transport_provider:Rn.Livekit}}function il(n){var r,s;const{streamOptions:e}=n??{},t=((r=n==null?void 0:n.mixpanelAdditionalProperties)==null?void 0:r.plan)!==void 0?{plan:(s=n.mixpanelAdditionalProperties)==null?void 0:s.plan}:void 0;return{...{output_resolution:e==null?void 0:e.outputResolution,session_timeout:e==null?void 0:e.sessionTimeout,stream_warmup:e==null?void 0:e.streamWarmup,compatibility_mode:e==null?void 0:e.compatibilityMode,fluent:e==null?void 0:e.fluent},...t&&{end_user_data:t}}}function rl(n,e){return er(n.presenter.type)?{version:cr.V2,...nl()}:{version:cr.V1,...il(e)}}function sl(n,e,t){t.track("agent-connection-state-change",{state:n,...e&&{reason:e}})}function al(n,e,t,i,r){r===tt.Fluent?ol(n,e,t,i,r):dl(n,e,t,i,r)}function ol(n,e,t,i,r){n===z.Start?i.track("stream-session",{event:"start","stream-type":r}):n===z.Stop&&i.track("stream-session",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t})}function cl(n,e,t,i){nt.get()<=0||(n===z.Start?t.linkTrack("agent-video",{event:"start",latency:nt.get(!0),"stream-type":i},"start",[oe.StreamVideoCreated]):n===z.Stop&&t.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":i},"done",[oe.StreamVideoDone]))}function dl(n,e,t,i,r){nt.get()<=0||(n===z.Start?i.linkTrack("agent-video",{event:"start",latency:nt.get(!0),"stream-type":r},"start",[oe.StreamVideoCreated]):n===z.Stop&&i.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t},"done",[oe.StreamVideoDone]))}function ha(n,e,t,i){return nt.reset(),ia.update(),new Promise(async(r,s)=>{try{let c,a=!1;const o=rl(n,e);t.enrich({"stream-version":o.version.toString()}),c=await el(n,o,{...e,analytics:t,callbacks:{...e.callbacks,onConnectionStateChange:(d,u)=>{var l,h;(h=(l=e.callbacks).onConnectionStateChange)==null||h.call(l,d),sl(d,u,t),d===se.Connected&&(c?r(c):a=!0)},onVideoStateChange:(d,u)=>{var l,h;(h=(l=e.callbacks).onVideoStateChange)==null||h.call(l,d),al(d,n,u,t,c.streamType)},onAgentActivityStateChange:d=>{var u,l;(l=(u=e.callbacks).onAgentActivityStateChange)==null||l.call(u,d),d===xe.Talking?sr.update():sr.reset(),cl(d===xe.Talking?z.Start:z.Stop,n,t,c.streamType)},onStreamReady:()=>{const d=ia.get(!0);t.track("agent-chat",{event:"ready",latency:d})}}},i),a&&r(c)}catch(c){s(c)}})}async function ul(n,e,t,i,r){var u,l,h,f;const s=async()=>{if(er(n.presenter.type)){const y=await ha(n,e,i),g=`${tl}_${y.sessionId}`,C=new Date().toISOString();return{chatResult:{chatMode:ke.Functional,chat:{id:g,agent_id:n.id,owner_id:n.owner_id??"",created:C,modified:C,agent_id__created_at:C,agent_id__modified_at:C,chat_mode:ke.Functional,messages:[]}},streamingManager:y}}else{const y=new AbortController,g=y.signal;let C;try{const T=sa(n,t,i,e.mode,e.persistentChat,r),_=ha(n,e,i,g).then(b=>(C=b,b)),[I,v]=await Promise.all([T,_]);return{chatResult:I,streamingManager:v}}catch(T){throw y.abort(),C&&await C.disconnect().catch(()=>{}),T}}},{chatResult:c,streamingManager:a}=await s(),{chat:o,chatMode:d}=c;return d&&e.mode!==void 0&&d!==e.mode&&(e.mode=d,(l=(u=e.callbacks).onModeChange)==null||l.call(u,d),d!==ke.Functional)?((f=(h=e.callbacks).onError)==null||f.call(h,new js(d)),a==null||a.disconnect(),{chat:o}):{chat:o,streamingManager:a}}async function ll(n,e){var S,L,N,x;let t=!0,i=null;const r=e.mixpanelKey||lu,s=e.wsURL||uu,c=e.baseURL||Pn,a=e.mode||ke.Functional,o={messages:[],chatMode:a},d=Cu({token:r,agentId:n,isEnabled:e.enableAnalitics,externalId:e.externalId,mixpanelAdditionalProperties:e.mixpanelAdditionalProperties}),u=Date.now();na(()=>{d.track("agent-sdk",{event:"init"},u)});const l=vu(e.auth,c,e.callbacks.onError,e.externalId),h=await l.getById(n);e.debug=e.debug||((S=h==null?void 0:h.advanced_settings)==null?void 0:S.ui_debug_mode);const f=er(h.presenter.type);d.enrich(bu(h));const{onMessage:y,clearQueue:g}=Gu(d,o,e,h,()=>{var k;return(k=o.socketManager)==null?void 0:k.disconnect()});o.messages=wu(e.initialMessages),(N=(L=e.callbacks).onNewMessage)==null||N.call(L,[...o.messages],"answer");const C=k=>{i=k},T=({type:k})=>{var U,K,Q;const O=o.messages[o.messages.length-1];d.track("agent-video-interrupt",{type:k||"click",video_duration_to_interrupt:sr.get(!0),message_duration_to_interrupt:nt.get(!0)}),O.interrupted=!0,(K=(U=e.callbacks).onNewMessage)==null||K.call(U,[...o.messages],"answer"),f?ju(o.streamingManager):(Fu(o.streamingManager,(Q=o.streamingManager)==null?void 0:Q.streamType,i),Bu(o.streamingManager,i))},_=Date.now();na(()=>{d.track("agent-sdk",{event:"loaded",...yu(h)},_)});async function I(k){var X,he,Re,de,me,De,Ze;(he=(X=e.callbacks).onConnectionStateChange)==null||he.call(X,se.Connecting),nt.reset(),k&&!t&&(delete o.chat,(de=(Re=e.callbacks).onNewMessage)==null||de.call(Re,[...o.messages],"answer"));const O=a===ke.DirectPlayback||f?Promise.resolve(void 0):Ku(e.auth,s,{onMessage:y,onError:e.callbacks.onError},e.externalId),U=tr(()=>ul(h,{...e,mode:a,callbacks:{...e.callbacks,onVideoIdChange:C,onMessage:y,onInterruptDetected:T}},l,d,o.chat),{limit:3,timeout:cu,timeoutErrorMessage:"Timeout initializing the stream",shouldRetryFn:B=>(B==null?void 0:B.message)!=="Could not connect"&&B.status!==429&&(B==null?void 0:B.message)!=="InsufficientCreditsError",delayMs:1e3}).catch(B=>{var F,te;throw b(ke.Maintenance),(te=(F=e.callbacks).onConnectionStateChange)==null||te.call(F,se.Fail),B}),[K,{streamingManager:Q,chat:ee}]=await Promise.all([O,U]);ee&&ee.id!==((me=o.chat)==null?void 0:me.id)&&((Ze=(De=e.callbacks).onNewChat)==null||Ze.call(De,ee.id)),o.streamingManager=Q,o.socketManager=K,o.chat=ee,t=!1,d.enrich({chatId:ee==null?void 0:ee.id,streamId:Q==null?void 0:Q.streamId,mode:o.chatMode}),b((ee==null?void 0:ee.chat_mode)??a)}async function v(){var k,O,U,K;(k=o.socketManager)==null||k.disconnect(),await((O=o.streamingManager)==null?void 0:O.disconnect()),delete o.streamingManager,delete o.socketManager,(K=(U=e.callbacks).onConnectionStateChange)==null||K.call(U,se.Disconnected)}async function b(k){var O,U;k!==o.chatMode&&(d.track("agent-mode-change",{mode:k}),o.chatMode=k,o.chatMode!==ke.Functional&&await v(),(U=(O=e.callbacks).onModeChange)==null||U.call(O,k))}return{agent:h,getStreamType:()=>{var k;return(k=o.streamingManager)==null?void 0:k.streamType},getIsInterruptAvailable:()=>{var k;return((k=o.streamingManager)==null?void 0:k.interruptAvailable)??!1},getIsTriggersAvailable:()=>{var k;return((k=o.streamingManager)==null?void 0:k.triggersAvailable)??!1},starterMessages:((x=h.knowledge)==null?void 0:x.starter_message)||[],getSTTToken:()=>l.getSTTToken(h.id),changeMode:b,enrichAnalytics:d.enrich,async connect(){await I(!0),d.track("agent-chat",{event:"connect",mode:o.chatMode})},async reconnect(){const k=o.streamingManager;if(f&&(k!=null&&k.reconnect)){try{await k.reconnect(),d.track("agent-chat",{event:"reconnect",mode:o.chatMode})}catch{await v(),await I(!1)}return}await v(),await I(!1),d.track("agent-chat",{event:"reconnect",mode:o.chatMode})},async disconnect(){await v(),d.track("agent-chat",{event:"disconnect",mode:o.chatMode})},async publishMicrophoneStream(k){var O;if(!((O=o.streamingManager)!=null&&O.publishMicrophoneStream))throw new Error("publishMicrophoneStream is not available for this streaming manager");return o.streamingManager.publishMicrophoneStream(k)},async unpublishMicrophoneStream(){var k;if(!((k=o.streamingManager)!=null&&k.unpublishMicrophoneStream))throw new Error("unpublishMicrophoneStream is not available for this streaming manager");return o.streamingManager.unpublishMicrophoneStream()},async publishCameraStream(k){var O;if(!((O=o.streamingManager)!=null&&O.publishCameraStream))throw new Error("publishCameraStream is not available for this streaming manager");return o.streamingManager.publishCameraStream(k)},async unpublishCameraStream(){var k;if(!((k=o.streamingManager)!=null&&k.unpublishCameraStream))throw new Error("unpublishCameraStream is not available for this streaming manager");return o.streamingManager.unpublishCameraStream()},async chat(k){var Q,ee,X,he,Re;const O=()=>{if(Zs(a))throw new Wt(`${a} is enabled, chat is disabled`);if(k.length>=800)throw new Wt("Message cannot be more than 800 characters");if(k.length===0)throw new Wt("Message cannot be empty");if(o.chatMode===ke.Maintenance)throw new Wt("Chat is in maintenance mode");if(![ke.TextOnly,ke.Playground].includes(o.chatMode)){if(!o.streamingManager)throw new Wt("Streaming manager is not initialized");if(!o.chat)throw new Wt("Chat is not initialized")}},U=async()=>{var de,me;if(!o.chat){const De=await sa(h,l,d,o.chatMode,e.persistentChat);if(!De.chat)throw new Kt(o.chatMode,!!e.persistentChat);o.chat=De.chat,(me=(de=e.callbacks).onNewChat)==null||me.call(de,o.chat.id)}return o.chat.id},K=async(de,me)=>{const De=o.chatMode===ke.Playground;return tr(f&&!De?async()=>{var F,te;return await((te=(F=o.streamingManager)==null?void 0:F.sendTextMessage)==null?void 0:te.call(F,k)),Promise.resolve({})}:async()=>{var F,te;return l.chat(h.id,me,{chatMode:o.chatMode,streamId:(F=o.streamingManager)==null?void 0:F.streamId,sessionId:(te=o.streamingManager)==null?void 0:te.sessionId,messages:de.map(({matches:Pe,...En})=>En)},{...ra(o.chatMode),skipErrorHandler:!0})},{limit:2,shouldRetryFn:F=>{var En,wn,Yi,_n;const te=(En=F==null?void 0:F.message)==null?void 0:En.includes("missing or invalid session_id");return!((wn=F==null?void 0:F.message)==null?void 0:wn.includes("Stream Error"))&&!te?((_n=(Yi=e.callbacks).onError)==null||_n.call(Yi,F),!1):!0},onRetry:async()=>{await v(),await I(!1)}})};try{g(),O(),o.messages.push({id:an(),role:"user",content:k,created_at:new Date(nt.update()).toISOString()}),(ee=(Q=e.callbacks).onNewMessage)==null||ee.call(Q,[...o.messages],"user");const de=await U(),me=await K([...o.messages],de);return o.messages.push({id:an(),role:"assistant",content:me.result||"",created_at:new Date().toISOString(),context:me.context,matches:me.matches}),d.track("agent-message-send",{event:"success",messages:o.messages.length+1}),me.result&&((he=(X=e.callbacks).onNewMessage)==null||he.call(X,[...o.messages],"answer"),d.track("agent-message-received",{latency:nt.get(!0),messages:o.messages.length})),me}catch(de){throw((Re=o.messages[o.messages.length-1])==null?void 0:Re.role)==="assistant"&&o.messages.pop(),d.track("agent-message-send",{event:"error",messages:o.messages.length}),de}},rate(k,O,U){var ee,X,he,Re;const K=o.messages.find(de=>de.id===k);if(o.chat){if(!K)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const Q=((ee=K.matches)==null?void 0:ee.map(de=>[de.document_id,de.id]))??[];return d.track("agent-rate",{event:U?"update":"create",thumb:O===1?"up":"down",knowledge_id:((X=h.knowledge)==null?void 0:X.id)??"",matches:Q,score:O}),U?l.updateRating(h.id,o.chat.id,U,{knowledge_id:((he=h.knowledge)==null?void 0:he.id)??"",message_id:k,matches:Q,score:O}):l.createRating(h.id,o.chat.id,{knowledge_id:((Re=h.knowledge)==null?void 0:Re.id)??"",message_id:k,matches:Q,score:O})},deleteRate(k){if(!o.chat)throw new Error("Chat is not initialized");return d.track("agent-rate-delete",{type:"text"}),l.deleteRating(h.id,o.chat.id,k)},async speak(k){var Q,ee,X;function O(){if(typeof k=="string"){if(!h.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:k,ssml:!1}}if(k.type==="text"&&!k.provider){if(!h.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:k.input,ssml:k.ssml}}return k}const U=O();if(d.track("agent-speak",U),nt.update(),o.messages&&U.type==="text"&&(o.messages.push({id:an(),role:"assistant",content:U.input,created_at:new Date().toISOString()}),(ee=(Q=e.callbacks).onNewMessage)==null||ee.call(Q,[...o.messages],"answer")),mu(o.chatMode))return{duration:0,video_id:"",status:"success"};if(!o.streamingManager)throw new Error("Please connect to the agent first");return o.streamingManager.speak({script:U,metadata:{chat_id:(X=o.chat)==null?void 0:X.id,agent_id:h.id}})},interrupt:T}}function hl(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var ml=Object.defineProperty,fl=(n,e,t)=>e in n?ml(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ma=(n,e,t)=>fl(n,typeof e!="symbol"?e+"":e,t);class we{constructor(){ma(this,"_locking"),ma(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function fe(n,e){if(!n)throw new Error(e)}const pl=34028234663852886e22,gl=-34028234663852886e22,vl=4294967295,yl=2147483647,bl=-2147483648;function oi(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>yl||n<bl)throw new Error("invalid int 32: "+n)}function dr(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>vl||n<0)throw new Error("invalid uint 32: "+n)}function fa(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>pl||n<gl))throw new Error("invalid float 32: "+n)}const pa=Symbol("@bufbuild/protobuf/enum-type");function kl(n){const e=n[pa];return fe(e,"missing enum type on enum object"),e}function ga(n,e,t,i){n[pa]=va(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function va(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const c of e){const a=ya(c);s.push(a),i[c.name]=a,r[c.no]=a}return{typeName:n,values:s,findName(c){return i[c]},findNumber(c){return r[c]}}}function Tl(n,e,t){const i={};for(const r of e){const s=ya(r);i[s.localName]=s.no,i[s.no]=s.localName}return ga(i,n,e),i}function ya(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class ur{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Sl(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),c={[s]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(c.prototype,new ur),Object.assign(c,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(a,o){return new c().fromBinary(a,o)},fromJson(a,o){return new c().fromJson(a,o)},fromJsonString(a,o){return new c().fromJsonString(a,o)},equals(a,o){return n.util.equals(c,a,o)}}),c}function Cl(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,!(r&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function lr(n,e,t){for(let s=0;s<28;s=s+7){const c=n>>>s,a=!(!(c>>>7)&&e==0),o=(a?c|128:c)&255;if(t.push(o),!a)return}const i=n>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const c=e>>>s,a=!!(c>>>7),o=(a?c|128:c)&255;if(t.push(o),!a)return}t.push(e>>>31&1)}}const ci=4294967296;function ba(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(c,a){const o=Number(n.slice(c,a));r*=t,i=i*t+o,i>=ci&&(r=r+(i/ci|0),i=i%ci)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Ta(i,r):hr(i,r)}function El(n,e){let t=hr(n,e);const i=t.hi&2147483648;i&&(t=Ta(t.lo,t.hi));const r=ka(t.lo,t.hi);return i?"-"+r:r}function ka(n,e){if({lo:n,hi:e}=wl(n,e),e<=2097151)return String(ci*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,c=i+r*8147497,a=r*2;const o=1e7;return s>=o&&(c+=Math.floor(s/o),s%=o),c>=o&&(a+=Math.floor(c/o),c%=o),a.toString()+Sa(c)+Sa(s)}function wl(n,e){return{lo:n>>>0,hi:e>>>0}}function hr(n,e){return{lo:n|0,hi:e|0}}function Ta(n,e){return e=~e,n?n=~n+1:e+=1,hr(n,e)}const Sa=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Ca(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function _l(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Rl(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),c=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(o){const d=typeof o=="bigint"?o:BigInt(o);if(d>s||d<r)throw new Error("int64 invalid: ".concat(o));return d},uParse(o){const d=typeof o=="bigint"?o:BigInt(o);if(d>a||d<c)throw new Error("uint64 invalid: ".concat(o));return d},enc(o){return n.setBigInt64(0,this.parse(o),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(o){return n.setBigInt64(0,this.uParse(o),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(o,d){return n.setInt32(0,o,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(o,d){return n.setInt32(0,o,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=r=>fe(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>fe(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),ba(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),ba(r)},dec(r,s){return El(r,s)},uDec(r,s){return ka(r,s)}}}const ce=Rl();var w;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(w||(w={}));var Mt;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Mt||(Mt={}));function Dt(n,e,t){if(e===t)return!0;if(n==w.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==t}return!1}function on(n,e){switch(n){case w.BOOL:return!1;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==0?ce.zero:"0";case w.DOUBLE:case w.FLOAT:return 0;case w.BYTES:return new Uint8Array(0);case w.STRING:return"";default:return 0}}function Ea(n,e){switch(n){case w.BOOL:return e===!1;case w.STRING:return e==="";case w.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ve;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ve||(ve={}));class Pl{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(dr(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return oi(e),Ca(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){fa(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){dr(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){oi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return oi(e),e=(e<<1^e>>31)>>>0,Ca(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=ce.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=ce.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ce.enc(e);return lr(t.lo,t.hi,this.buf),this}sint64(e){let t=ce.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return lr(r,s,this.buf),this}uint64(e){let t=ce.uEnc(e);return lr(t.lo,t.hi,this.buf),this}}class Il{constructor(e,t){this.varint64=Cl,this.uint32=_l,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ve.Varint:for(;this.buf[this.pos++]&128;);break;case ve.Bit64:this.pos+=4;case ve.Bit32:this.pos+=4;break;case ve.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ve.StartGroup:for(;;){const[s,c]=this.tag();if(c===ve.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(c,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ce.dec(...this.varint64())}uint64(){return ce.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,ce.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ce.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ce.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Ol(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function wa(n){const e=n.field.localName,t=Object.create(null);return t[e]=Ml(n),[t,()=>t[e]]}function Ml(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return on(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function Dl(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),di=[];for(let n=0;n<Tt.length;n++)di[Tt[n].charCodeAt(0)]=n;di[45]=Tt.indexOf("+"),di[95]=Tt.indexOf("/");const _a={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,c=0;for(let a=0;a<n.length;a++){if(s=di[n.charCodeAt(a)],s===void 0)switch(n[a]){case"=":r=0;case`
|
|
2
2
|
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:c=s,r=1;break;case 1:t[i++]=c<<2|(s&48)>>4,c=s,r=2;break;case 2:t[i++]=(c&15)<<4|(s&60)>>2,c=s,r=3;break;case 3:t[i++]=(c&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s<n.length;s++)switch(i=n[s],t){case 0:e+=Tt[i>>2],r=(i&3)<<4,t=1;break;case 1:e+=Tt[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=Tt[r|i>>6],e+=Tt[i&63],t=0;break}return t&&(e+=Tt[r],e+="=",t==1&&(e+="=")),e}};function Al(n,e,t){Pa(e,n);const i=e.runtime.bin.makeReadOptions(t),r=Dl(n.getType().runtime.bin.listUnknownFields(n),e.field),[s,c]=wa(e);for(const a of r)e.runtime.bin.readField(s,i.readerFactory(a.data),e.field,a.wireType,i);return c()}function xl(n,e,t,i){Pa(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(Ra(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(u=>u.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const u of d)n.getType().runtime.bin.onUnknownField(n,u.no,u.wireType,u.data)}const c=s.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,c,s);const o=r.readerFactory(c.finish());for(;o.pos<o.len;){const[d,u]=o.tag(),l=o.skip(u,d);n.getType().runtime.bin.onUnknownField(n,d,u,l)}}function Ra(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function Pa(n,e){fe(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Ia(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Ea(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Oa(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?on(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function St(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(ur.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Ma(n,e){return St(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}w.DOUBLE,w.FLOAT,w.INT64,w.UINT64,w.INT32,w.UINT32,w.BOOL,w.STRING,w.BYTES;const Da={ignoreUnknownFields:!1},Aa={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ll(n){return n?Object.assign(Object.assign({},Da),n):Da}function Nl(n){return n?Object.assign(Object.assign({},Aa),n):Aa}const ui=Symbol(),li=Symbol();function Ul(){return{makeReadOptions:Ll,makeWriteOptions:Nl,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(lt(e)));i=i??new n;const r=new Map,s=t.typeRegistry;for(const[c,a]of Object.entries(e)){const o=n.fields.findJsonName(c);if(o){if(o.oneof){if(a===null&&o.kind=="scalar")continue;const d=r.get(o.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(o.oneof.name,'" present: "').concat(d,'", "').concat(c,'"'));r.set(o.oneof,c)}xa(i,a,o,t,n)}else{let d=!1;if(s!=null&&s.findExtension&&c.startsWith("[")&&c.endsWith("]")){const u=s.findExtension(c.substring(1,c.length-1));if(u&&u.extendee.typeName==n.typeName){d=!0;const[l,h]=wa(u);xa(l,a,u.field,t,u),xl(i,u,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(c,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!Ia(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Bl(r))continue}const c=r.oneof?n[r.oneof.localName].value:n[r.localName],a=La(r,c,e);a!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=a)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const c of t.runtime.bin.listUnknownFields(n)){const a=s.findExtensionFor(t.typeName,c.no);if(a&&Ra(n,a)){const o=Al(n,a,e),d=La(a.field,o,e);d!==void 0&&(i[a.field.jsonName]=d)}}}catch(s){const c=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(c+(a.length>0?": ".concat(a):""))}return i},readScalar(n,e,t){return On(n,e,t??Mt.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Ea(n,e)))return hi(n,e)},debug:lt}}function lt(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function xa(n,e,t,i,r){let s=t.localName;if(t.repeated){if(fe(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(e)));const c=n[s];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(a)));switch(t.kind){case"message":c.push(t.T.fromJson(a,i));break;case"enum":const o=mr(t.T,a,i.ignoreUnknownFields,!0);o!==li&&c.push(o);break;case"scalar":try{c.push(On(t.T,a,t.L,!0))}catch(d){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(a));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(e)));const c=n[s];for(const[a,o]of Object.entries(e)){if(o===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=Fl(t.K,a)}catch(u){let l="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(e));throw u instanceof Error&&u.message.length>0&&(l+=": ".concat(u.message)),new Error(l)}switch(t.V.kind){case"message":c[d]=t.V.T.fromJson(o,i);break;case"enum":const u=mr(t.V.T,o,i.ignoreUnknownFields,!0);u!==li&&(c[d]=u);break;case"scalar":try{c[d]=On(t.V.T,o,Mt.BIGINT,!0)}catch(l){let h="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(e));throw l instanceof Error&&l.message.length>0&&(h+=": ".concat(l.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const c=t.T;if(e===null&&c.typeName!="google.protobuf.Value")return;let a=n[s];St(a)?a.fromJson(e,i):(n[s]=a=c.fromJson(e,i),c.fieldWrapper&&!t.oneof&&(n[s]=c.fieldWrapper.unwrapField(a)));break;case"enum":const o=mr(t.T,e,i.ignoreUnknownFields,!1);switch(o){case ui:Oa(t,n);break;case li:break;default:n[s]=o;break}break;case"scalar":try{const d=On(t.T,e,t.L,!1);switch(d){case ui:Oa(t,n);break;default:n[s]=d;break}}catch(d){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(lt(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}break}}function Fl(n,e){if(n===w.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return On(n,e,Mt.BIGINT,!0).toString()}function On(n,e,t,i){if(e===null)return i?on(n,t):ui;switch(n){case w.DOUBLE:case w.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==w.FLOAT&&fa(r),r;case w.INT32:case w.FIXED32:case w.SFIXED32:case w.SINT32:case w.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==w.UINT32||n==w.FIXED32?dr(s):oi(s),s;case w.INT64:case w.SFIXED64:case w.SINT64:if(typeof e!="number"&&typeof e!="string")break;const c=ce.parse(e);return t?c.toString():c;case w.FIXED64:case w.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ce.uParse(e);return t?a.toString():a;case w.BOOL:if(typeof e!="boolean")break;return e;case w.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case w.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return _a.dec(e)}throw new Error}function mr(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:ui;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);if(r!==void 0)return r.no;if(t)return li;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(lt(e)))}function Bl(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function La(n,e,t){if(n.kind=="map"){fe(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(n.V.kind){case"scalar":for(const[c,a]of r)i[c.toString()]=hi(n.V.T,a);break;case"message":for(const[c,a]of r)i[c.toString()]=a.toJson(t);break;case"enum":const s=n.V.T;for(const[c,a]of r)i[c.toString()]=fr(s,a,t.enumAsInteger);break}return t.emitDefaultValues||r.length>0?i:void 0}if(n.repeated){fe(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let r=0;r<e.length;r++)i.push(hi(n.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)i.push(fr(n.T,e[r],t.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)i.push(e[r].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return hi(n.T,e);case"enum":return fr(n.T,e,t.enumAsInteger);case"message":return Ma(n.T,e).toJson(t)}}function fr(n,e,t){var i;if(fe(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function hi(n,e){switch(n){case w.INT32:case w.SFIXED32:case w.SINT32:case w.FIXED32:case w.UINT32:return fe(typeof e=="number"),e;case w.FLOAT:case w.DOUBLE:return fe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case w.STRING:return fe(typeof e=="string"),e;case w.BOOL:return fe(typeof e=="boolean"),e;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return fe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case w.BYTES:return fe(e instanceof Uint8Array),_a.enc(e)}}const cn=Symbol("@bufbuild/protobuf/unknown-fields"),Na={readUnknownFields:!0,readerFactory:n=>new Il(n)},Ua={writeUnknownFields:!0,writerFactory:()=>new Pl};function jl(n){return n?Object.assign(Object.assign({},Na),n):Na}function Vl(n){return n?Object.assign(Object.assign({},Ua),n):Ua}function ql(){return{makeReadOptions:jl,makeWriteOptions:Vl,listUnknownFields(n){var e;return(e=n[cn])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[cn]},writeUnknownFields(n,e){const i=n[cn];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[cn])||(r[cn]=[]),r[cn].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),c=r?e.len:e.pos+t;let a,o;for(;e.pos<c&&([a,o]=e.tag(),!(r===!0&&o==ve.EndGroup));){const d=s.fields.find(a);if(!d){const u=e.skip(o,a);i.readUnknownFields&&this.onUnknownField(n,a,o,u);continue}Fa(n,e,d,o,i)}if(r&&(o!=ve.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:Fa,writeMessage(n,e,t){const i=n.getType();for(const r of i.fields.byNumber()){if(!Ia(r,n)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?n[r.oneof.localName].value:n[r.localName];Ba(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Ba(n,e,t,i)}}}function Fa(n,e,t,i,r){let{repeated:s,localName:c}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=c&&delete n.value,n.case=c,c="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?w.INT32:t.T;let o=fi;if(t.kind=="scalar"&&t.L>0&&(o=Wl),s){let h=n[c];if(i==ve.LengthDelimited&&a!=w.STRING&&a!=w.BYTES){let y=e.uint32()+e.pos;for(;e.pos<y;)h.push(o(e,a))}else h.push(o(e,a))}else n[c]=o(e,a);break;case"message":const d=t.T;s?n[c].push(mi(e,new d,r,t)):St(n[c])?mi(e,n[c],r,t):(n[c]=mi(e,new d,r,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[c]=d.fieldWrapper.unwrapField(n[c])));break;case"map":let[u,l]=Kl(t,e,r);n[c][u]=l;break}}function mi(n,e,t,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,n,s?i.no:n.uint32(),t,s),e}function Kl(n,e,t){const i=e.uint32(),r=e.pos+i;let s,c;for(;e.pos<r;){const[a]=e.tag();switch(a){case 1:s=fi(e,n.K);break;case 2:switch(n.V.kind){case"scalar":c=fi(e,n.V.T);break;case"enum":c=e.int32();break;case"message":c=mi(e,new n.V.T,t,void 0);break}break}}if(s===void 0&&(s=on(n.K,Mt.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),c===void 0)switch(n.V.kind){case"scalar":c=on(n.V.T,Mt.BIGINT);break;case"enum":c=n.V.T.values[0].no;break;case"message":c=new n.V.T;break}return[s,c]}function Wl(n,e){const t=fi(n,e);return typeof t=="bigint"?t.toString():t}function fi(n,e){switch(e){case w.STRING:return n.string();case w.BOOL:return n.bool();case w.DOUBLE:return n.double();case w.FLOAT:return n.float();case w.INT32:return n.int32();case w.INT64:return n.int64();case w.UINT64:return n.uint64();case w.FIXED64:return n.fixed64();case w.BYTES:return n.bytes();case w.FIXED32:return n.fixed32();case w.SFIXED32:return n.sfixed32();case w.SFIXED64:return n.sfixed64();case w.SINT64:return n.sint64();case w.UINT32:return n.uint32();case w.SINT32:return n.sint32()}}function Ba(n,e,t,i){fe(e!==void 0);const r=n.repeated;switch(n.kind){case"scalar":case"enum":let s=n.kind=="enum"?w.INT32:n.T;if(r)if(fe(Array.isArray(e)),n.packed)Jl(t,s,n.no,e);else for(const c of e)Mn(t,s,n.no,c);else Mn(t,s,n.no,e);break;case"message":if(r){fe(Array.isArray(e));for(const c of e)ja(t,i,n,c)}else ja(t,i,n,e);break;case"map":fe(typeof e=="object"&&e!=null);for(const[c,a]of Object.entries(e))Hl(t,i,n,c,a);break}}function Hl(n,e,t,i,r){n.tag(t.no,ve.LengthDelimited),n.fork();let s=i;switch(t.K){case w.INT32:case w.FIXED32:case w.UINT32:case w.SFIXED32:case w.SINT32:s=Number.parseInt(i);break;case w.BOOL:fe(i=="true"||i=="false"),s=i=="true";break}switch(Mn(n,t.K,1,s),t.V.kind){case"scalar":Mn(n,t.V.T,2,r);break;case"enum":Mn(n,w.INT32,2,r);break;case"message":fe(r!==void 0),n.tag(2,ve.LengthDelimited).bytes(r.toBinary(e));break}n.join()}function ja(n,e,t,i){const r=Ma(t.T,i);t.delimited?n.tag(t.no,ve.StartGroup).raw(r.toBinary(e)).tag(t.no,ve.EndGroup):n.tag(t.no,ve.LengthDelimited).bytes(r.toBinary(e))}function Mn(n,e,t,i){fe(i!==void 0);let[r,s]=Va(e);n.tag(t,r)[s](i)}function Jl(n,e,t,i){if(!i.length)return;n.tag(t,ve.LengthDelimited).fork();let[,r]=Va(e);for(let s=0;s<i.length;s++)n[r](i[s]);n.join()}function Va(n){let e=ve.Varint;switch(n){case w.BYTES:case w.STRING:e=ve.LengthDelimited;break;case w.DOUBLE:case w.FIXED64:case w.SFIXED64:e=ve.Bit64;break;case w.FIXED32:case w.SFIXED32:case w.FLOAT:e=ve.Bit32;break}const t=w[n].toLowerCase();return[e,t]}function Gl(){return{setEnumType:ga,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const r=i.localName,s=e,c=n;if(c[r]!=null)switch(i.kind){case"oneof":const a=c[r].case;if(a===void 0)continue;const o=i.findField(a);let d=c[r].value;o&&o.kind=="message"&&!St(d,o.T)?d=new o.T(d):o&&o.kind==="scalar"&&o.T===w.BYTES&&(d=Dn(d)),s[r]={case:a,value:d};break;case"scalar":case"enum":let u=c[r];i.T===w.BYTES&&(u=i.repeated?u.map(Dn):Dn(u)),s[r]=u;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===w.BYTES)for(const[f,y]of Object.entries(c[r]))s[r][f]=Dn(y);else Object.assign(s[r],c[r]);break;case"message":const h=i.V.T;for(const f of Object.keys(c[r])){let y=c[r][f];h.fieldWrapper||(y=new h(y)),s[r][f]=y}break}break;case"message":const l=i.T;if(i.repeated)s[r]=c[r].map(h=>St(h,l)?h:new l(h));else{const h=c[r];l.fieldWrapper?l.typeName==="google.protobuf.BytesValue"?s[r]=Dn(h):s[r]=h:s[r]=St(h,l)?h:new l(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((c,a)=>i.T.equals(c,s[a]));case"scalar":return r.every((c,a)=>Dt(i.T,c,s[a]));case"enum":return r.every((c,a)=>Dt(w.INT32,c,s[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let c=r,a=s;return i.T.fieldWrapper&&(c!==void 0&&!St(c)&&(c=i.T.fieldWrapper.wrapField(c)),a!==void 0&&!St(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(c,a);case"enum":return Dt(w.INT32,r,s);case"scalar":return Dt(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const o=i.findField(r.case);if(o===void 0)return!0;switch(o.kind){case"message":return o.T.equals(r.value,s.value);case"enum":return Dt(w.INT32,r.value,s.value);case"scalar":return Dt(o.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(o.kind));case"map":const d=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const u=i.V.T;return d.every(h=>u.equals(r[h],s[h]));case"enum":return d.every(h=>Dt(w.INT32,r[h],s[h]));case"scalar":const l=i.V.T;return d.every(h=>Dt(l,r[h],s[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const r of e.fields.byMember()){const s=n[r.localName];let c;if(r.repeated)c=s.map(pi);else if(r.kind=="map"){c=i[r.localName];for(const[a,o]of Object.entries(s))c[a]=pi(o)}else r.kind=="oneof"?c=r.findField(s.case)?{case:s.case,value:pi(s.value)}:{case:void 0}:c=pi(s);i[r.localName]=c}for(const r of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return t}}}function pi(n){if(n===void 0)return n;if(St(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Dn(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function zl(n,e,t){return{syntax:n,json:Ul(),bin:ql(),util:Object.assign(Object.assign({},Gl()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return Sl(this,i,r,s)},makeEnum:Tl,makeEnumType:va,getEnumType:kl,makeExtension(i,r,s){return Ol(this,i,r,s)}}}class $l{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function qa(n,e){const t=Ka(n);return e?t:th(eh(t))}function Ql(n){return qa(n,!1)}const Yl=Ka;function Ka(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let r=n.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const Xl=new Set(["constructor","toString","toJSON","valueOf"]),Zl=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Wa=n=>"".concat(n,"$"),eh=n=>Zl.has(n)?Wa(n):n,th=n=>Xl.has(n)?Wa(n):n;class nh{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Ql(e)}addField(e){fe(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function ih(n,e){var t,i,r,s,c,a;const o=[];let d;for(const u of typeof n=="function"?n():n){const l=u;if(l.localName=qa(u.name,u.oneof!==void 0),l.jsonName=(t=u.jsonName)!==null&&t!==void 0?t:Yl(u.name),l.repeated=(i=u.repeated)!==null&&i!==void 0?i:!1,u.kind=="scalar"&&(l.L=(r=u.L)!==null&&r!==void 0?r:Mt.BIGINT),l.delimited=(s=u.delimited)!==null&&s!==void 0?s:!1,l.req=(c=u.req)!==null&&c!==void 0?c:!1,l.opt=(a=u.opt)!==null&&a!==void 0?a:!1,u.packed===void 0&&(l.packed=u.kind=="enum"||u.kind=="scalar"&&u.T!=w.BYTES&&u.T!=w.STRING),u.oneof!==void 0){const h=typeof u.oneof=="string"?u.oneof:u.oneof.name;(!d||d.name!=h)&&(d=new nh(h)),l.oneof=d,d.addField(l)}o.push(l)}return o}const p=zl("proto3",n=>new $l(n,e=>ih(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=on(e.T,e.L);break}}});class je extends ur{constructor(e){super(),this.seconds=ce.zero,this.nanos=0,p.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(p.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=ce.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return je.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new je({seconds:ce.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new je().fromBinary(e,t)}static fromJson(e,t){return new je().fromJson(e,t)}static fromJsonString(e,t){return new je().fromJsonString(e,t)}static equals(e,t){return p.util.equals(je,e,t)}}je.runtime=p,je.typeName="google.protobuf.Timestamp",je.fields=p.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const rh=p.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:je},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:sh,repeated:!0},{no:5,name:"events",kind:"message",T:oh,repeated:!0}]),sh=p.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:ah,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ah=p.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:je},{no:3,name:"value",kind:"scalar",T:2}]),oh=p.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:je},{no:7,name:"normalized_end_timestamp",kind:"message",T:je,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ch=p.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),dh=p.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),uh=p.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Ha=p.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ge=p.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),be=p.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),pr=p.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),An=p.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),xn=p.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ze=p.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),Ht=p.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Ja=p.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Te=p.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),gi=p.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:vi,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:ao}]),vi=p.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),lh=p.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:p.getEnumType(be),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Jt=p.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:p.getEnumType(dn)},{no:4,name:"tracks",kind:"message",T:ln,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:lh},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:p.getEnumType(un)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:p.getEnumType(ze)},{no:18,name:"kind_details",kind:"enum",T:p.getEnumType(hh),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:gr,repeated:!0}]),dn=p.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),un=p.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),hh=p.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),pe=p.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),mh=p.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:At,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:p.getEnumType(Ga)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),ln=p.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:p.getEnumType(Ge)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:p.getEnumType(be)},{no:10,name:"layers",kind:"message",T:At,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:mh,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:p.getEnumType(pe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:ao},{no:19,name:"audio_features",kind:"enum",T:p.getEnumType(Te),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:p.getEnumType(Ha)}]),gr=p.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:p.getEnumType(pe)}]),fh=p.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),At=p.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:p.getEnumType(pr)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),Ga=p.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),Le=p.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:p.getEnumType(W)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:vr,oneof:"value"},{no:3,name:"speaker",kind:"message",T:ph,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Ya,oneof:"value"},{no:7,name:"transcription",kind:"message",T:gh,oneof:"value"},{no:8,name:"metrics",kind:"message",T:rh,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:yi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:yr,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:br,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:kr,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:bi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ki,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ti,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:za,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),W=p.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),za=p.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:p.getEnumType(pe)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),$a=p.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:vr,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:yi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:yr,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:br,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:kr,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:bi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ki,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Ti,oneof:"value"}]),ph=p.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Qa,repeated:!0}]),Qa=p.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),vr=p.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Ya=p.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),gh=p.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:vh,repeated:!0}]),vh=p.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),yi=p.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),yr=p.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),br=p.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),kr=p.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Xa,oneof:"value"}]),Xa=p.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),Za=p.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),eo=p.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:p.getEnumType(to)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),to=p.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),no=p.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:p.getEnumType(io)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),io=p.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),ro=p.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:so},{no:2,name:"screen",kind:"message",T:so},{no:3,name:"resume_connection",kind:"enum",T:p.getEnumType(xn)},{no:4,name:"disabled_codecs",kind:"message",T:yh},{no:5,name:"force_relay",kind:"enum",T:p.getEnumType(xn)}]),so=p.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:p.getEnumType(xn)}]),yh=p.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:vi,repeated:!0},{no:2,name:"publish",kind:"message",T:vi,repeated:!0}]),ao=p.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Tr=p.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),oo=p.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:p.getEnumType(Tr)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),co=p.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),bi=p.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:p.getEnumType(pe)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:oo,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:co,oneof:"content_header"}],{localName:"DataStream_Header"}),ki=p.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),Ti=p.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),bh=p.makeMessageType("livekit.FilterParams",()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}]),kh=p.makeMessageType("livekit.WebhookConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:bh}]),Th=p.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Sr=p.makeMessageType("livekit.RoomAgentDispatch",()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]),it=p.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Cr=p.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Sh=p.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Ch=p.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:xt,oneof:"message"},{no:2,name:"answer",kind:"message",T:xt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Si,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ln,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ci,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ei,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:fo,oneof:"message"},{no:8,name:"leave",kind:"message",T:wi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:go,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:bo,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ir,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ht,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Rr,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:So,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:_r,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:po,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:lo,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:mo,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Mh,oneof:"message"}]),uo=p.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Rh,oneof:"message"},{no:2,name:"answer",kind:"message",T:xt,oneof:"message"},{no:3,name:"offer",kind:"message",T:xt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Si,oneof:"message"},{no:5,name:"update",kind:"message",T:Oh,oneof:"message"},{no:6,name:"track_published",kind:"message",T:wr,oneof:"message"},{no:8,name:"leave",kind:"message",T:wi,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ci,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ah,oneof:"message"},{no:11,name:"room_update",kind:"message",T:xh,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Nh,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Fh,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:jh,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:qh,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Ih,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Ph,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Wh,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Gh,oneof:"message"},{no:22,name:"request_response",kind:"message",T:zh,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:$h,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Kh,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Zh,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Vh,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:ho,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Eh,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:wh,oneof:"message"}]),Er=p.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:At,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:p.getEnumType(Ga)}]),Ln=p.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:p.getEnumType(Ge)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:p.getEnumType(be)},{no:9,name:"layers",kind:"message",T:At,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Er,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:p.getEnumType(pe)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:p.getEnumType(Ha)},{no:17,name:"audio_features",kind:"enum",T:p.getEnumType(Te),repeated:!0}]),lo=p.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:p.getEnumType(pe)}]),ho=p.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:gr}]),mo=p.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Eh=p.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:gr}]),wh=p.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:_h}}]),_h=p.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),Si=p.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:p.getEnumType(it)},{no:3,name:"final",kind:"scalar",T:8}]),Ci=p.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Rh=p.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:gi},{no:2,name:"participant",kind:"message",T:Jt},{no:3,name:"other_participants",kind:"message",T:Jt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:vo,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:ro},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:eo},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:vi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Ph=p.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:vo,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ro},{no:3,name:"server_info",kind:"message",T:eo},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),wr=p.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ln}]),Ih=p.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),xt=p.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Oh=p.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Jt,repeated:!0}]),Ei=p.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Za,repeated:!0}]),Mh=p.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:Dh,repeated:!0}]),Dh=p.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:fh}],{localName:"UpdateDataSubscription_Update"}),fo=p.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:p.getEnumType(pr)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),_r=p.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:p.getEnumType(Te),repeated:!0}]),po=p.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),wi=p.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:p.getEnumType(ze)},{no:3,name:"action",kind:"enum",T:p.getEnumType(hn)},{no:4,name:"regions",kind:"message",T:Hh}]),hn=p.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),go=p.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:At,repeated:!0}]),Rr=p.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),vo=p.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Ah=p.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Qa,repeated:!0}]),xh=p.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:gi}]),Lh=p.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:p.getEnumType(An)},{no:3,name:"score",kind:"scalar",T:2}]),Nh=p.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Lh,repeated:!0}]),Uh=p.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:p.getEnumType(Cr)}]),Fh=p.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Uh,repeated:!0}]),Pr=p.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:p.getEnumType(pr)},{no:2,name:"enabled",kind:"scalar",T:8}]),Bh=p.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Pr,repeated:!0}]),jh=p.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Pr,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Bh,repeated:!0}]),Vh=p.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Th,repeated:!0}]),yo=p.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),bo=p.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:yo,repeated:!0}]),qh=p.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),Kh=p.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:gi},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Jt},{no:4,name:"other_participants",kind:"message",T:Jt,repeated:!0}]),Ir=p.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:xt},{no:2,name:"subscription",kind:"message",T:Ei},{no:3,name:"publish_tracks",kind:"message",T:wr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:To,repeated:!0},{no:5,name:"offer",kind:"message",T:xt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ko,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:ho,repeated:!0}]),ko=p.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),To=p.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:p.getEnumType(it)}]),ht=p.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:p.getEnumType(Sh),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),So=p.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Wh=p.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Hh=p.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Jh,repeated:!0}]),Jh=p.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),Gh=p.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:p.getEnumType(Ja)}]),zh=p.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:p.getEnumType(Or)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Si,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Ln,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ci,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Rr,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:_r,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:po,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:lo,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:mo,oneof:"request"}]),Or=p.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),$h=p.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Co=p.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),Qh=p.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:no},{no:2,name:"connection_settings",kind:"message",T:Co},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Ln,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:xt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:p.getEnumType(Ht)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ir}]),Yh=p.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:p.getEnumType(Xh)},{no:2,name:"join_request",kind:"scalar",T:12}]),Xh=p.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Zh=p.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]),em=p.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),tm=p.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),nm=p.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),im=p.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),rm=p.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"}]),sm=p.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),Eo=p.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),am=p.makeMessageType("livekit.RoomCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:p.getEnumType(sm)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:Mr,oneof:"output"},{no:7,name:"stream",kind:"message",T:_o,oneof:"output"},{no:10,name:"segments",kind:"message",T:Dr,oneof:"output"},{no:8,name:"preset",kind:"enum",T:p.getEnumType(Eo),oneof:"options"},{no:9,name:"advanced",kind:"message",T:Ro,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Mr,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:_o,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:Dr,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:om,repeated:!0},{no:16,name:"webhooks",kind:"message",T:kh,repeated:!0}]),Mr=p.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:p.getEnumType(em)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:_i,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Ri,oneof:"output"},{no:5,name:"azure",kind:"message",T:Pi,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:Ii,oneof:"output"}]),Dr=p.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:p.getEnumType(tm)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:p.getEnumType(nm)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:_i,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Ri,oneof:"output"},{no:7,name:"azure",kind:"message",T:Pi,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:Ii,oneof:"output"}]),om=p.makeMessageType("livekit.ImageOutput",()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:p.getEnumType(im)},{no:6,name:"image_codec",kind:"enum",T:p.getEnumType(uh)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:_i,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Ri,oneof:"output"},{no:10,name:"azure",kind:"message",T:Pi,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:Ii,oneof:"output"}]),_i=p.makeMessageType("livekit.S3Upload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:wo}]),Ri=p.makeMessageType("livekit.GCPUpload",()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:wo}]),Pi=p.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),Ii=p.makeMessageType("livekit.AliOSSUpload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}]),wo=p.makeMessageType("livekit.ProxyConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}]),_o=p.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:p.getEnumType(rm)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),Ro=p.makeMessageType("livekit.EncodingOptions",()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:p.getEnumType(ch)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:p.getEnumType(dh)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]),cm=p.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:p.getEnumType(Eo),oneof:"options"},{no:2,name:"advanced",kind:"message",T:Ro,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Mr,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:Dr,repeated:!0}]),dm=p.makeMessageType("livekit.AutoTrackEgress",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:_i,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Ri,oneof:"output"},{no:4,name:"azure",kind:"message",T:Pi,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:Ii,oneof:"output"}]),um=p.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:am},{no:3,name:"participant",kind:"message",T:cm},{no:2,name:"tracks",kind:"message",T:dm}]),Oi=p.makeMessageType("livekit.RoomConfiguration",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:um},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:Sr,repeated:!0}]),lm=p.makeMessageType("livekit.TokenSourceRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9,opt:!0},{no:2,name:"participant_name",kind:"scalar",T:9,opt:!0},{no:3,name:"participant_identity",kind:"scalar",T:9,opt:!0},{no:4,name:"participant_metadata",kind:"scalar",T:9,opt:!0},{no:5,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:6,name:"room_config",kind:"message",T:Oi,opt:!0}]),Po=p.makeMessageType("livekit.TokenSourceResponse",()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]);function hm(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Mi={exports:{}},mm=Mi.exports,Io;function fm(){return Io||(Io=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(mm,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},c=null;function a(g,C){var T=g[C];if(typeof T.bind=="function")return T.bind(g);try{return Function.prototype.bind.call(T,g)}catch{return function(){return Function.prototype.apply.apply(T,[g,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&i?o:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function u(){for(var g=this.getLevel(),C=0;C<r.length;C++){var T=r[C];this[T]=C<g?e:this.methodFactory(T,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function l(g){return function(){typeof console!==t&&(u.call(this),this[g].apply(this,arguments))}}function h(g,C,T){return d(g)||l.apply(this,arguments)}function f(g,C){var T=this,_,I,v,b="loglevel";typeof g=="string"?b+=":"+g:typeof g=="symbol"&&(b=void 0);function S(O){var U=(r[O]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=U;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+U+";"}catch{}}}function L(){var O;if(!(typeof window===t||!b)){try{O=window.localStorage[b]}catch{}if(typeof O===t)try{var U=window.document.cookie,K=encodeURIComponent(b),Q=U.indexOf(K+"=");Q!==-1&&(O=/^([^;]+)/.exec(U.slice(Q+K.length+1))[1])}catch{}return T.levels[O]===void 0&&(O=void 0),O}}function N(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b)}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function x(O){var U=O;if(typeof U=="string"&&T.levels[U.toUpperCase()]!==void 0&&(U=T.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=T.levels.SILENT)return U;throw new TypeError("log.setLevel() called with invalid level: "+O)}T.name=g,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=C||h,T.getLevel=function(){return v??I??_},T.setLevel=function(O,U){return v=x(O),U!==!1&&S(v),u.call(T)},T.setDefaultLevel=function(O){I=x(O),L()||T.setLevel(O,!1)},T.resetLevel=function(){v=null,N(),u.call(T)},T.enableAll=function(O){T.setLevel(T.levels.TRACE,O)},T.disableAll=function(O){T.setLevel(T.levels.SILENT,O)},T.rebuild=function(){if(c!==T&&(_=x(c.getLevel())),u.call(T),c===T)for(var O in s)s[O].rebuild()},_=x(c?c.getLevel():"WARN");var k=L();k!=null&&(v=x(k)),u.call(T)}c=new f,c.getLogger=function(C){if(typeof C!="symbol"&&typeof C!="string"||C==="")throw new TypeError("You must supply a name when creating a logger.");var T=s[C];return T||(T=s[C]=new f(C,c.methodFactory)),T};var y=typeof window!==t?window.log:void 0;return c.noConflict=function(){return typeof window!==t&&window.log===c&&(window.log=y),c},c.getLoggers=function(){return s},c.default=c,c})}(Mi)),Mi.exports}var Nn=fm(),mn;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(mn||(mn={}));var Ke;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee",n.DataTracks="livekit-data-tracks"})(Ke||(Ke={}));let q=Nn.getLogger("livekit");const Oo=Object.values(Ke).map(n=>Nn.getLogger(n));q.setDefaultLevel(mn.info);function rt(n){const e=Nn.getLogger(n);return e.setDefaultLevel(q.getLevel()),e}function pm(n,e){if(e)Nn.getLogger(e).setLevel(n);else for(const t of Oo)t.setLevel(n)}function gm(n,e){(e?[e]:Oo).forEach(i=>{const r=i.methodFactory;i.methodFactory=(s,c,a)=>{const o=r(s,c,a),d=mn[s],u=d>=c&&d<mn.silent;return(l,h)=>{h?o(l,h):o(l),u&&n(d,l,h)}},i.setLevel(i.getLevel())})}const vm=Nn.getLogger("lk-e2ee"),Un=7e3,ym=[0,300,2*2*300,3*3*300,4*4*300,Un,Un,Un,Un,Un];class Mo{constructor(e){this._retryDelays=e!==void 0?[...e]:ym}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Ar(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function m(n,e,t,i){function r(s){return s instanceof t?s:new t(function(c){c(s)})}return new(t||(t=Promise))(function(s,c){function a(u){try{d(i.next(u))}catch(l){c(l)}}function o(u){try{d(i.throw(u))}catch(l){c(l)}}function d(u){u.done?s(u.value):r(u.value).then(a,o)}d((i=i.apply(n,e||[])).next())})}function Do(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ct(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Do=="function"?Do(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(c){return new Promise(function(a,o){c=n[s](c),r(a,o,c.done,c.value)})}}function r(s,c,a,o){Promise.resolve(o).then(function(d){s({value:d,done:a})},c)}}typeof SuppressedError=="function"&&SuppressedError;var Di={exports:{}},Ao;function bm(){if(Ao)return Di.exports;Ao=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(b,S,L){return Function.prototype.apply.call(b,S,L)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(b){return Object.getOwnPropertyNames(b).concat(Object.getOwnPropertySymbols(b))}:t=function(b){return Object.getOwnPropertyNames(b)};function i(v){console&&console.warn&&console.warn(v)}var r=Number.isNaN||function(b){return b!==b};function s(){s.init.call(this)}Di.exports=s,Di.exports.once=T,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function a(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(v){if(typeof v!="number"||v<0||r(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");c=v}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+b+".");return this._maxListeners=b,this};function o(v){return v._maxListeners===void 0?s.defaultMaxListeners:v._maxListeners}s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(b){for(var S=[],L=1;L<arguments.length;L++)S.push(arguments[L]);var N=b==="error",x=this._events;if(x!==void 0)N=N&&x.error===void 0;else if(!N)return!1;if(N){var k;if(S.length>0&&(k=S[0]),k instanceof Error)throw k;var O=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw O.context=k,O}var U=x[b];if(U===void 0)return!1;if(typeof U=="function")e(U,this,S);else for(var K=U.length,Q=y(U,K),L=0;L<K;++L)e(Q[L],this,S);return!0};function d(v,b,S,L){var N,x,k;if(a(S),x=v._events,x===void 0?(x=v._events=Object.create(null),v._eventsCount=0):(x.newListener!==void 0&&(v.emit("newListener",b,S.listener?S.listener:S),x=v._events),k=x[b]),k===void 0)k=x[b]=S,++v._eventsCount;else if(typeof k=="function"?k=x[b]=L?[S,k]:[k,S]:L?k.unshift(S):k.push(S),N=o(v),N>0&&k.length>N&&!k.warned){k.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+k.length+" "+String(b)+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=v,O.type=b,O.count=k.length,i(O)}return v}s.prototype.addListener=function(b,S){return d(this,b,S,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(b,S){return d(this,b,S,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(v,b,S){var L={fired:!1,wrapFn:void 0,target:v,type:b,listener:S},N=u.bind(L);return N.listener=S,L.wrapFn=N,N}s.prototype.once=function(b,S){return a(S),this.on(b,l(this,b,S)),this},s.prototype.prependOnceListener=function(b,S){return a(S),this.prependListener(b,l(this,b,S)),this},s.prototype.removeListener=function(b,S){var L,N,x,k,O;if(a(S),N=this._events,N===void 0)return this;if(L=N[b],L===void 0)return this;if(L===S||L.listener===S)--this._eventsCount===0?this._events=Object.create(null):(delete N[b],N.removeListener&&this.emit("removeListener",b,L.listener||S));else if(typeof L!="function"){for(x=-1,k=L.length-1;k>=0;k--)if(L[k]===S||L[k].listener===S){O=L[k].listener,x=k;break}if(x<0)return this;x===0?L.shift():g(L,x),L.length===1&&(N[b]=L[0]),N.removeListener!==void 0&&this.emit("removeListener",b,O||S)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(b){var S,L,N;if(L=this._events,L===void 0)return this;if(L.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):L[b]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete L[b]),this;if(arguments.length===0){var x=Object.keys(L),k;for(N=0;N<x.length;++N)k=x[N],k!=="removeListener"&&this.removeAllListeners(k);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(S=L[b],typeof S=="function")this.removeListener(b,S);else if(S!==void 0)for(N=S.length-1;N>=0;N--)this.removeListener(b,S[N]);return this};function h(v,b,S){var L=v._events;if(L===void 0)return[];var N=L[b];return N===void 0?[]:typeof N=="function"?S?[N.listener||N]:[N]:S?C(N):y(N,N.length)}s.prototype.listeners=function(b){return h(this,b,!0)},s.prototype.rawListeners=function(b){return h(this,b,!1)},s.listenerCount=function(v,b){return typeof v.listenerCount=="function"?v.listenerCount(b):f.call(v,b)},s.prototype.listenerCount=f;function f(v){var b=this._events;if(b!==void 0){var S=b[v];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function y(v,b){for(var S=new Array(b),L=0;L<b;++L)S[L]=v[L];return S}function g(v,b){for(;b+1<v.length;b++)v[b]=v[b+1];v.pop()}function C(v){for(var b=new Array(v.length),S=0;S<b.length;++S)b[S]=v[S].listener||v[S];return b}function T(v,b){return new Promise(function(S,L){function N(k){v.removeListener(b,x),L(k)}function x(){typeof v.removeListener=="function"&&v.removeListener("error",N),S([].slice.call(arguments))}I(v,b,x,{once:!0}),b!=="error"&&_(v,N,{once:!0})})}function _(v,b,S){typeof v.on=="function"&&I(v,"error",b,S)}function I(v,b,S,L){if(typeof v.on=="function")L.once?v.once(b,S):v.on(b,S);else if(typeof v.addEventListener=="function")v.addEventListener(b,function N(x){L.once&&v.removeEventListener(b,N),S(x)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return Di.exports}var mt=bm();let xo=!0,Lo=!0;function Fn(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function Gt(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(c,a){if(c!==e)return r.apply(this,arguments);const o=d=>{const u=t(d);u&&(a.handleEvent?a.handleEvent(u):a(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,o),r.apply(this,[c,o])};const s=i.removeEventListener;i.removeEventListener=function(c,a){if(c!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const o=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[c,o])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(c){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),c&&this.addEventListener(e,this["_on"+e]=c)},enumerable:!0,configurable:!0})}function km(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(xo=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Tm(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Lo=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function No(){if(typeof window=="object"){if(xo)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function xr(n,e){Lo&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Sm(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Fn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Fn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Fn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=Fn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Uo(n){return Object.prototype.toString.call(n)==="[object Object]"}function Fo(n){return Uo(n)?Object.keys(n).reduce(function(e,t){const i=Uo(n[t]),r=i?Fo(n[t]):n[t],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):n}function Lr(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Lr(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(r=>{Lr(n,n.get(r),t)})}))}function Bo(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return n.forEach(c=>{c.type==="track"&&c.trackIdentifier===e.id&&s.push(c)}),s.forEach(c=>{n.forEach(a=>{a.type===i&&a.trackId===c.id&&Lr(n,a,r)})}),r}const jo=No;function Vo(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const o={};return Object.keys(a).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const u=typeof a[d]=="object"?a[d]:{ideal:a[d]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const l=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){o.optional=o.optional||[];let h={};typeof u.ideal=="number"?(h[l("min",d)]=u.ideal,o.optional.push(h),h={},h[l("max",d)]=u.ideal,o.optional.push(h)):(h[l("",d)]=u.ideal,o.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(o.mandatory=o.mandatory||{},o.mandatory[l("",d)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(o.mandatory=o.mandatory||{},o.mandatory[l(h,d)]=u[h])})}),a.advanced&&(o.optional=(o.optional||[]).concat(a.advanced)),o},r=function(a,o){if(e.version>=61)return o(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const d=function(u,l,h){l in u&&!(h in u)&&(u[h]=u[l],delete u[l])};a=JSON.parse(JSON.stringify(a)),d(a.audio,"autoGainControl","googAutoGainControl"),d(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let d=a.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const u=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete a.video.facingMode;let l;if(d.exact==="environment"||d.ideal==="environment"?l=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(l=["front"]),l)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(y=>y.kind==="videoinput");let f=h.find(y=>l.some(g=>y.label.toLowerCase().includes(g)));return!f&&h.length&&l.includes("back")&&(f=h[h.length-1]),f&&(a.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),a.video=i(a.video),jo("chrome: "+JSON.stringify(a)),o(a)})}a.video=i(a.video)}return jo("chrome: "+JSON.stringify(a)),o(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},c=function(a,o,d){r(a,u=>{t.webkitGetUserMedia(u,o,l=>{d&&d(s(l))})})};if(t.getUserMedia=c.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(o){return r(o,d=>a(d).then(u=>{if(d.audio&&!u.getAudioTracks().length||d.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(l=>{l.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function qo(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Ko(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):s={track:r.track};const c=new Event("track");c.track=r.track,c.receiver=s,c.transceiver={receiver:s},c.streams=[i.stream],this.dispatchEvent(c)}),i.stream.getTracks().forEach(r=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.id):s={track:r};const c=new Event("track");c.track=r,c.receiver=s,c.transceiver={receiver:s},c.streams=[i.stream],this.dispatchEvent(c)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Gt(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Wo(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){let d=r.apply(this,arguments);return d||(d=e(this,a),this._senders.push(d)),d};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const o=this._senders.indexOf(a);o!==-1&&this._senders.splice(o,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(c=>{this._senders.push(e(this,c))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(c=>{const a=this._senders.find(o=>o.track===c);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ho(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(c=>c._pc=this),s});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(c=>Bo(c,s.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r}),Gt(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>Bo(s,r.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let r,s,c;return this.getSenders().forEach(a=>{a.track===i&&(r?c=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(s?c=!0:s=a),a.track===i)),c||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Jo(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(c=>this._shimmedLocalStreams[c][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(c,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const o=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(o)===-1&&this._shimmedLocalStreams[a.id].push(o):this._shimmedLocalStreams[a.id]=[a,o],o};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(c){this._shimmedLocalStreams=this._shimmedLocalStreams||{},c.getTracks().forEach(d=>{if(this.getSenders().find(l=>l.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const o=this.getSenders().filter(d=>a.indexOf(d)===-1);this._shimmedLocalStreams[c.id]=[c].concat(o)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(c){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[c.id],i.apply(this,arguments)};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(c){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},c&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const o=this._shimmedLocalStreams[a].indexOf(c);o!==-1&&this._shimmedLocalStreams[a].splice(o,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function Go(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Jo(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(l=>this._reverseStreams[l.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(l=>{if(this.getSenders().find(f=>f.track===l))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const l=new n.MediaStream(u.getTracks());this._streams[u.id]=l,this._reverseStreams[l.id]=u,u=l}i.apply(this,[u])};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},n.RTCPeerConnection.prototype.addTrack=function(u,l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[l.id];if(y)y.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new n.MediaStream([u]);this._streams[l.id]=g,this._reverseStreams[g.id]=l,this.addStream(g)}return this.getSenders().find(g=>g.track===u)};function s(d,u){let l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],y=d._streams[f.id];l=l.replace(new RegExp(y.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:l})}function c(d,u){let l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],y=d._streams[f.id];l=l.replace(new RegExp(f.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:l})}["createOffer","createAnswer"].forEach(function(d){const u=n.RTCPeerConnection.prototype[d],l={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[y=>{const g=s(this,y);h[0].apply(null,[g])},y=>{h[1]&&h[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(y=>s(this,y))}};n.RTCPeerConnection.prototype[d]=l[d]});const a=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=c(this,arguments[0]),a.apply(this,arguments))};const o=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=o.get.apply(this);return d.type===""?d:s(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(g=>u.track===g)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Nr(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]})}function zo(n,e){Gt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var $o=Object.freeze({__proto__:null,fixNegotiationNeeded:zo,shimAddTrackRemoveTrack:Go,shimAddTrackRemoveTrackWithNative:Jo,shimGetSendersWithDtmf:Wo,shimGetUserMedia:Vo,shimMediaStream:qo,shimOnTrack:Ko,shimPeerConnection:Nr,shimSenderReceiverGetStats:Ho});function Qo(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(r,s,c){xr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,c)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(c,a,o){a in c&&!(o in c)&&(c[o]=c[a],delete c[a])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(c){return typeof c=="object"&&typeof c.audio=="object"&&(c=JSON.parse(JSON.stringify(c)),r(c.audio,"autoGainControl","mozAutoGainControl"),r(c.audio,"noiseSuppression","mozNoiseSuppression")),s(c)},i&&i.prototype.getSettings){const c=i.prototype.getSettings;i.prototype.getSettings=function(){const a=c.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const c=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),c.apply(this,[a])}}}}function Cm(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Yo(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ur(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=n.RTCPeerConnection.prototype[r],c={[r](){return arguments[0]=new(r==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};n.RTCPeerConnection.prototype[r]=c[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[s,c,a]=arguments;return i.apply(this,[s||null]).then(o=>{if(e.version<53&&!c)try{o.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;o.forEach((u,l)=>{o.set(l,Object.assign({},u,{type:t[u.type]||u.type}))})}return o}).then(c,a)}}function Xo(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Zo(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),Gt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ec(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){xr("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function tc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function nc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(c=>{if("rid"in c&&!/^[a-z0-9]{0,16}$/i.test(c.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in c&&!(parseFloat(c.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in c&&!(parseFloat(c.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:c}=s,a=c.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,c.sendEncodings=i,this.setParametersPromises.push(c.setParameters(a).then(()=>{delete c.sendEncodings}).catch(()=>{delete c.sendEncodings})))}return s})}function ic(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function rc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function sc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var ac=Object.freeze({__proto__:null,shimAddTransceiver:nc,shimCreateAnswer:sc,shimCreateOffer:rc,shimGetDisplayMedia:Cm,shimGetParameters:ic,shimGetUserMedia:Qo,shimOnTrack:Yo,shimPeerConnection:Ur,shimRTCDataChannel:tc,shimReceiverGetStats:Zo,shimRemoveStream:ec,shimSenderGetStats:Xo});function oc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),c=1;c<r;c++)s[c-1]=arguments[c];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function cc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const c=new Event("addstream");c.stream=s,i.dispatchEvent(c)})}),e.apply(i,arguments)}}}function dc(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,c=e.addIceCandidate;e.createOffer=function(d,u){const l=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[l]);return u?(h.then(d,u),Promise.resolve()):h},e.createAnswer=function(d,u){const l=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[l]);return u?(h.then(d,u),Promise.resolve()):h};let a=function(o,d,u){const l=r.apply(this,[o]);return u?(l.then(d,u),Promise.resolve()):l};e.setLocalDescription=a,a=function(o,d,u){const l=s.apply(this,[o]);return u?(l.then(d,u),Promise.resolve()):l},e.setRemoteDescription=a,a=function(o,d,u){const l=c.apply(this,[o]);return u?(l.then(d,u),Promise.resolve()):l},e.addIceCandidate=a}function uc(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>i(lc(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function lc(n){return n&&n.video!==void 0?Object.assign({},n,{video:Fo(n.video)}):n}function hc(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let c=0;c<i.iceServers.length;c++){let a=i.iceServers[c];a.urls===void 0&&a.url?(xr("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(i.iceServers[c])}i.iceServers=s}return new e(i,r)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function mc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function fc(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(c=>c.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(c=>c.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function pc(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var gc=Object.freeze({__proto__:null,shimAudioContext:pc,shimCallbacksAPI:dc,shimConstraints:lc,shimCreateOfferLegacy:fc,shimGetUserMedia:uc,shimLocalStreamsAPI:oc,shimRTCIceServerUrls:hc,shimRemoteStreamsAPI:cc,shimTrackEventTransceiver:mc}),Fr={exports:{}},vc;function Em(){return vc||(vc=1,function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
3
3
|
`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
|
|
4
4
|
m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
|
package/dist/src/types/auth.d.ts
CHANGED
|
@@ -2,11 +2,14 @@ export interface BearerToken {
|
|
|
2
2
|
type: 'bearer';
|
|
3
3
|
token: string;
|
|
4
4
|
}
|
|
5
|
-
export
|
|
5
|
+
export type BasicAuth = {
|
|
6
|
+
type: 'basic';
|
|
7
|
+
token: string;
|
|
8
|
+
} | {
|
|
6
9
|
type: 'basic';
|
|
7
10
|
username: string;
|
|
8
11
|
password: string;
|
|
9
|
-
}
|
|
12
|
+
};
|
|
10
13
|
export interface ClientKeyAuth {
|
|
11
14
|
type: 'key';
|
|
12
15
|
clientKey: string;
|