From 01e89c9358f80feeb3ed774787695f505ac375c5 Mon Sep 17 00:00:00 2001 From: "Rodrigo Rodriguez (Pragmatismo)" Date: Sat, 15 Nov 2025 19:08:26 -0300 Subject: [PATCH] feat: add actix-files dependency for file serving support Added actix-files and its dependencies (http-range, mime_guess, unicase, v_htmlescape) to enable static file functionality in the botserver. This will allow serving static assets and files through the web server. The change includes all required transitive dependencies for proper file handling and MIME type detection. --- Cargo.lock | 52 ++ Cargo.toml | 1 + src/drive_monitor/mod.rs | 4 +- src/llm/local.rs | 38 +- src/main.rs | 29 +- src/package_manager/cli.rs | 5 +- src/package_manager/facade.rs | 1 + src/web_server/mod.rs | 82 +-- .../tablesv2}/components/Footer.html | 0 .../tablesv2}/components/FormulaBar.html | 0 .../tablesv2}/components/Header.html | 0 .../tablesv2}/components/Layout.html | 0 .../tablesv2}/components/Spreadsheet.html | 0 .../tablesv2}/components/StatusBar.html | 0 .../tablesv2}/components/Toolbar.html | 0 web/app/tablesv2/index.html | 55 ++ web/app/tablesv2/tables.css | 85 +++ web/app/tablesv2/tables.js | 293 ++++++++ web/desktop/auth/app.js | 74 -- web/desktop/auth/index.html | 82 --- web/desktop/auth/styles.css | 249 ------- web/desktop/css/app.css | 352 ++++++++-- web/desktop/css/chat.css | 195 ------ web/desktop/css/theme.css | 114 --- web/desktop/drive/drive.js | 29 + web/desktop/drive/index.html | 648 ++---------------- web/desktop/index.html | 50 +- web/desktop/js/{cdn.min.js => alpine.js} | 0 web/desktop/js/auth.js | 61 -- web/desktop/js/layout.js | 85 +-- web/desktop/js/lib/gsap.min.js | 11 - web/desktop/js/lib/livekit-client.min.js | 8 - web/desktop/js/lib/marked.min.js | 69 -- web/desktop/js/mock-data.js | 46 -- web/desktop/mail/data.js | 29 - web/desktop/mail/index.html | 154 ++--- web/desktop/mail/mail.js | 78 +++ web/desktop/mail/store.js | 10 - web/desktop/shared/footer.html | 27 - web/desktop/shared/navbar.html | 30 - web/desktop/shared/resizable.html | 79 --- web/desktop/shared/styles.css | 112 --- web/desktop/tables/tables.html | 427 ------------ web/desktop/tasks/index.html | 37 + web/desktop/tasks/store.js | 32 - web/desktop/tasks/tasks.html | 101 --- web/desktop/tasks/tasks.js | 77 +++ web/html/static/about/index.html | 344 ---------- web/html/static/auth/login.html | 445 ------------ web/html/static/style.css | 0 50 files changed, 1286 insertions(+), 3414 deletions(-) rename web/{desktop/tables => app/tablesv2}/components/Footer.html (100%) rename web/{desktop/tables => app/tablesv2}/components/FormulaBar.html (100%) rename web/{desktop/tables => app/tablesv2}/components/Header.html (100%) rename web/{desktop/tables => app/tablesv2}/components/Layout.html (100%) rename web/{desktop/tables => app/tablesv2}/components/Spreadsheet.html (100%) rename web/{desktop/tables => app/tablesv2}/components/StatusBar.html (100%) rename web/{desktop/tables => app/tablesv2}/components/Toolbar.html (100%) create mode 100644 web/app/tablesv2/index.html create mode 100644 web/app/tablesv2/tables.css create mode 100644 web/app/tablesv2/tables.js delete mode 100644 web/desktop/auth/app.js delete mode 100644 web/desktop/auth/index.html delete mode 100644 web/desktop/auth/styles.css delete mode 100644 web/desktop/css/chat.css delete mode 100644 web/desktop/css/theme.css create mode 100644 web/desktop/drive/drive.js rename web/desktop/js/{cdn.min.js => alpine.js} (100%) delete mode 100644 web/desktop/js/auth.js delete mode 100644 web/desktop/js/lib/gsap.min.js delete mode 100644 web/desktop/js/lib/livekit-client.min.js delete mode 100644 web/desktop/js/lib/marked.min.js delete mode 100644 web/desktop/js/mock-data.js delete mode 100644 web/desktop/mail/data.js create mode 100644 web/desktop/mail/mail.js delete mode 100644 web/desktop/mail/store.js delete mode 100644 web/desktop/shared/footer.html delete mode 100644 web/desktop/shared/navbar.html delete mode 100644 web/desktop/shared/resizable.html delete mode 100644 web/desktop/shared/styles.css delete mode 100644 web/desktop/tables/tables.html create mode 100644 web/desktop/tasks/index.html delete mode 100644 web/desktop/tasks/store.js delete mode 100644 web/desktop/tasks/tasks.html create mode 100644 web/desktop/tasks/tasks.js delete mode 100644 web/html/static/about/index.html delete mode 100644 web/html/static/auth/login.html delete mode 100644 web/html/static/style.css diff --git a/Cargo.lock b/Cargo.lock index adb2b62aa..be8bc8e76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -34,6 +34,29 @@ dependencies = [ "smallvec", ] +[[package]] +name = "actix-files" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c0d87f10d70e2948ad40e8edea79c8e77c6c66e0250a4c1f09b690465199576" +dependencies = [ + "actix-http", + "actix-service", + "actix-utils", + "actix-web", + "bitflags 2.10.0", + "bytes", + "derive_more 2.0.1", + "futures-core", + "http-range", + "log", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "v_htmlescape", +] + [[package]] name = "actix-http" version = "3.11.2" @@ -1330,6 +1353,7 @@ name = "botserver" version = "6.0.8" dependencies = [ "actix-cors", + "actix-files", "actix-multipart", "actix-web", "actix-ws", @@ -3665,6 +3689,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21dec9db110f5f872ed9699c3ecf50cf16f423502706ba5c72462e28d3157573" + [[package]] name = "httparse" version = "1.10.1" @@ -4775,6 +4805,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -8592,6 +8632,12 @@ dependencies = [ "unic-common", ] +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -8766,6 +8812,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "v_htmlescape" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e8257fbc510f0a46eb602c10215901938b5c2a7d5e70fc11483b1d3c9b5b18c" + [[package]] name = "valuable" version = "0.1.1" diff --git a/Cargo.toml b/Cargo.toml index 1641b3f62..76adce2fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ desktop = ["dep:tauri", "dep:tauri-plugin-dialog", "dep:tauri-plugin-opener"] [dependencies] actix-cors = "0.7" +actix-files = "0.6.8" actix-multipart = "0.7" actix-web = "4.9" actix-ws = "0.3" diff --git a/src/drive_monitor/mod.rs b/src/drive_monitor/mod.rs index 64f942e4e..07296e634 100644 --- a/src/drive_monitor/mod.rs +++ b/src/drive_monitor/mod.rs @@ -29,7 +29,7 @@ impl DriveMonitor { pub fn spawn(self: Arc) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { info!("Drive Monitor service started for bucket: {}", self.bucket_name); - let mut tick = interval(Duration::from_secs(30)); + let mut tick = interval(Duration::from_secs(90)); loop { tick.tick().await; if let Err(e) = self.check_for_changes().await { @@ -44,7 +44,7 @@ impl DriveMonitor { None => return Ok(()), }; self.check_gbdialog_changes(client).await?; - // TODO: Remove self.check_gbot(client).await?; + self.check_gbot(client).await?; Ok(()) } async fn check_gbdialog_changes(&self, client: &Client) -> Result<(), Box> { diff --git a/src/llm/local.rs b/src/llm/local.rs index 28729ba40..74a4c022a 100644 --- a/src/llm/local.rs +++ b/src/llm/local.rs @@ -247,25 +247,25 @@ pub async fn start_llm_server( - // if n_moe != "0" { - // args.push_str(&format!(" --n-cpu-moe {}", n_moe)); - // } - // if parallel != "1" { - // args.push_str(&format!(" --parallel {}", parallel)); - // } - // if cont_batching == "true" { - // args.push_str(" --cont-batching"); - // } - // if mlock == "true" { - // args.push_str(" --mlock"); - // } - // if no_mmap == "true" { - // args.push_str(" --no-mmap"); - // } - // if n_predict != "0" { - // args.push_str(&format!(" --n-predict {}", n_predict)); - // } - // args.push_str(&format!(" --ctx-size {}", n_ctx_size)); + if n_moe != "0" { + args.push_str(&format!(" --n-cpu-moe {}", n_moe)); + } + if parallel != "1" { + args.push_str(&format!(" --parallel {}", parallel)); + } + if cont_batching == "true" { + args.push_str(" --cont-batching"); + } + if mlock == "true" { + args.push_str(" --mlock"); + } + if no_mmap == "true" { + args.push_str(" --no-mmap"); + } + if n_predict != "0" { + args.push_str(&format!(" --n-predict {}", n_predict)); + } + args.push_str(&format!(" --ctx-size {}", n_ctx_size)); if cfg!(windows) { let mut cmd = tokio::process::Command::new("cmd"); diff --git a/src/main.rs b/src/main.rs index 5c91cf322..9b06bda99 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,7 +46,7 @@ use crate::session::{create_session, get_session_history, get_sessions, start_se use crate::shared::state::AppState; use crate::shared::utils::create_conn; use crate::shared::utils::create_s3_operator; -use crate::web_server::{bot_index, index, static_files}; +use crate::web_server::{bot_index, index}; #[derive(Debug, Clone)] pub enum BootstrapProgress { StartingBootstrap, @@ -77,7 +77,29 @@ async fn main() -> std::io::Result<()> { let (state_tx, state_rx) = tokio::sync::mpsc::channel::>(1); let (http_tx, http_rx) = tokio::sync::oneshot::channel(); - let ui_handle = if !no_ui { + + let args: Vec = std::env::args().collect(); + if args.len() > 1 { + let command = &args[1]; + match command.as_str() { + "install" | "remove" | "list" | "status" | "start" | "stop" | "restart" | "--help" + | "-h" => match package_manager::cli::run().await { + Ok(_) => return Ok(()), + Err(e) => { + eprintln!("CLI error: {}", e); + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + format!("CLI command failed: {}", e), + )); + } + }, + _ => { + } + } + } + + + if !no_ui { let progress_rx = Arc::new(tokio::sync::Mutex::new(progress_rx)); let state_rx = Arc::new(tokio::sync::Mutex::new(state_rx)); let handle = std::thread::Builder::new() @@ -284,11 +306,11 @@ async fn main() -> std::io::Result<()> { .wrap(Logger::default()) .wrap(Logger::new("HTTP REQUEST: %a %{User-Agent}i")) .app_data(web::Data::from(app_state_clone)) + .configure(web_server::configure_app) .service(auth_handler) .service(create_session) .service(get_session_history) .service(get_sessions) - .service(index) .service(start_session) .service(upload_file) .service(voice_start) @@ -310,7 +332,6 @@ async fn main() -> std::io::Result<()> { .service(save_draft) .service(save_click); } - app = app.service(static_files); app = app.service(bot_index); app }) diff --git a/src/package_manager/cli.rs b/src/package_manager/cli.rs index c257894db..ddf77caa2 100644 --- a/src/package_manager/cli.rs +++ b/src/package_manager/cli.rs @@ -9,6 +9,8 @@ pub async fn run() -> Result<()> { print_usage(); return Ok(()); } +use tracing::info; +fn print_usage(){info!("usage: botserver [options]")} let command = &args[1]; match command.as_str() { "start" => { @@ -164,6 +166,3 @@ pub async fn run() -> Result<()> { } Ok(()) } -fn print_usage() { - println!("BotServer Package Manager\n\nUSAGE:\n botserver [options]\n\nCOMMANDS:\n start Start all installed components\n stop Stop all running components\n restart Restart all components\n install Install component\n remove Remove component\n list List all components\n status Check component status\n\nOPTIONS:\n --container Use container mode (LXC)\n --tenant Specify tenant (default: 'default')\n\nCOMPONENTS:\n Required: drive cache tables llm\n Optional: email proxy directory alm alm-ci dns webmail meeting table-editor doc-editor desktop devtools bot system vector-db host\n\nEXAMPLES:\n botserver start\n botserver stop\n botserver restart\n botserver install email\n botserver install email --container --tenant myorg\n botserver remove email\n botserver list"); -} diff --git a/src/package_manager/facade.rs b/src/package_manager/facade.rs index aec708e66..5c66bab55 100644 --- a/src/package_manager/facade.rs +++ b/src/package_manager/facade.rs @@ -156,6 +156,7 @@ impl PackageManager { ); Ok(()) } + pub fn remove(&self, component_name: &str) -> Result<()> { let component = self .components diff --git a/src/web_server/mod.rs b/src/web_server/mod.rs index dcadd8a59..896e28acd 100644 --- a/src/web_server/mod.rs +++ b/src/web_server/mod.rs @@ -1,20 +1,11 @@ +use actix_files::Files; use actix_web::{HttpRequest, HttpResponse, Result}; -use log::{debug, error, warn}; -use std::fs; +use log::{debug, error}; +use std::{fs, path::Path}; -#[actix_web::get("/auth")] -async fn auth() -> Result { - match fs::read_to_string("web/desktop/auth/index.html") { - Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)), - Err(e) => { - error!("Failed to load auth page: {}", e); - Ok(HttpResponse::InternalServerError().body("Failed to load auth page")) - } - } -} #[actix_web::get("/")] async fn index() -> Result { - match fs::read_to_string("web/desktop/auth/index.html") { + match fs::read_to_string("web/desktop/index.html") { Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)), Err(e) => { error!("Failed to load index page: {}", e); @@ -22,11 +13,12 @@ async fn index() -> Result { } } } + #[actix_web::get("/{botname}")] async fn bot_index(req: HttpRequest) -> Result { let botname = req.match_info().query("botname"); debug!("Serving bot interface for: {}", botname); - match fs::read_to_string("web/html/index.html") { + match fs::read_to_string("web/desktop/index.html") { Ok(html) => Ok(HttpResponse::Ok().content_type("text/html").body(html)), Err(e) => { error!("Failed to load index page for bot {}: {}", botname, e); @@ -34,31 +26,39 @@ async fn bot_index(req: HttpRequest) -> Result { } } } -#[actix_web::get("/static/{filename:.*}")] -async fn static_files(req: HttpRequest) -> Result { - let filename = req.match_info().query("filename"); - let path = format!("web/html/{}", filename); - match fs::read(&path) { - Ok(content) => { - debug!( - "Static file {} loaded successfully, size: {} bytes", - filename, - content.len() - ); - let content_type = match filename { - f if f.ends_with(".js") => "application/javascript", - f if f.ends_with(".riot") => "application/javascript", - f if f.ends_with(".html") => "application/javascript", - f if f.ends_with(".css") => "text/css", - f if f.ends_with(".png") => "image/png", - f if f.ends_with(".jpg") | f.ends_with(".jpeg") => "image/jpeg", - _ => "text/plain", - }; - Ok(HttpResponse::Ok().content_type(content_type).body(content)) - } - Err(e) => { - warn!("Static file not found: {} - {}", filename, e); - Ok(HttpResponse::NotFound().body("File not found")) - } - } + +pub fn configure_app(cfg: &mut actix_web::web::ServiceConfig) { + let static_path = Path::new("/home/rodriguez/src/botserver/web/desktop"); + + // Serve all static files from desktop directory + cfg.service( + Files::new("/", static_path) + .index_file("index.html") + .prefer_utf8(true) + .use_last_modified(true) + .use_etag(true) + .show_files_listing() + ); + + // Serve all JS files + cfg.service( + Files::new("/js", static_path.join("js")) + .prefer_utf8(true) + .use_last_modified(true) + .use_etag(true) + ); + + // Serve all component directories + ["drive", "tasks", "mail"].iter().for_each(|dir| { + cfg.service( + Files::new(&format!("/{}", dir), static_path.join(dir)) + .prefer_utf8(true) + .use_last_modified(true) + .use_etag(true) + ); + }); + + // Serve index routes + cfg.service(index); + cfg.service(bot_index); } diff --git a/web/desktop/tables/components/Footer.html b/web/app/tablesv2/components/Footer.html similarity index 100% rename from web/desktop/tables/components/Footer.html rename to web/app/tablesv2/components/Footer.html diff --git a/web/desktop/tables/components/FormulaBar.html b/web/app/tablesv2/components/FormulaBar.html similarity index 100% rename from web/desktop/tables/components/FormulaBar.html rename to web/app/tablesv2/components/FormulaBar.html diff --git a/web/desktop/tables/components/Header.html b/web/app/tablesv2/components/Header.html similarity index 100% rename from web/desktop/tables/components/Header.html rename to web/app/tablesv2/components/Header.html diff --git a/web/desktop/tables/components/Layout.html b/web/app/tablesv2/components/Layout.html similarity index 100% rename from web/desktop/tables/components/Layout.html rename to web/app/tablesv2/components/Layout.html diff --git a/web/desktop/tables/components/Spreadsheet.html b/web/app/tablesv2/components/Spreadsheet.html similarity index 100% rename from web/desktop/tables/components/Spreadsheet.html rename to web/app/tablesv2/components/Spreadsheet.html diff --git a/web/desktop/tables/components/StatusBar.html b/web/app/tablesv2/components/StatusBar.html similarity index 100% rename from web/desktop/tables/components/StatusBar.html rename to web/app/tablesv2/components/StatusBar.html diff --git a/web/desktop/tables/components/Toolbar.html b/web/app/tablesv2/components/Toolbar.html similarity index 100% rename from web/desktop/tables/components/Toolbar.html rename to web/app/tablesv2/components/Toolbar.html diff --git a/web/app/tablesv2/index.html b/web/app/tablesv2/index.html new file mode 100644 index 000000000..83a46f64c --- /dev/null +++ b/web/app/tablesv2/index.html @@ -0,0 +1,55 @@ +
+ + +
+
+

📊 Tables

+
Excel Clone - Celebrating Lotus 1-2-3 Legacy 🎉
+
+ +
+
+ +
+
+
+
+ + + +
+
+
+
+
+ + +
+ A1 + +
+ + +
+ Rows: + Columns: +
+ + +
+ + + + + + + + +
+
diff --git a/web/app/tablesv2/tables.css b/web/app/tablesv2/tables.css new file mode 100644 index 000000000..a6deaffac --- /dev/null +++ b/web/app/tablesv2/tables.css @@ -0,0 +1,85 @@ +/* Tables Component Styles */ +.app-container { + display: flex; + flex-direction: column; + height: 100vh; + background: var(--background); +} + +.content-container { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; +} + +.header { + background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%); + color: white; + padding: 15px 20px; + box-shadow: 0 2px 10px rgba(0,0,0,0.1); +} + +.header h1 { + font-size: 24px; + margin-bottom: 5px; +} + +.header .subtitle { + font-size: 12px; + opacity: 0.9; +} + +.spreadsheet-content { + display: flex; + flex-direction: column; + height: 100%; +} + +/* Spreadsheet specific styles */ +table { + border-collapse: collapse; + width: 100%; +} + +th, td { + border: 1px solid #ddd; + padding: 8px; + text-align: left; +} + +th { + background-color: #f2f2f2; + position: sticky; + top: 0; +} + +.selected { + background-color: #e6f2ff; + outline: 2px solid #4d90fe; +} + +.editing input { + width: 100%; + height: 100%; + border: none; + padding: 0; + margin: 0; + font: inherit; +} + +.resizable-container { + display: flex; + flex: 1; + overflow: hidden; +} + +.resizable-panel { + overflow: auto; +} + +.resizable-handle { + width: 10px; + background: #f0f0f0; + cursor: col-resize; +} diff --git a/web/app/tablesv2/tables.js b/web/app/tablesv2/tables.js new file mode 100644 index 000000000..be4725b86 --- /dev/null +++ b/web/app/tablesv2/tables.js @@ -0,0 +1,293 @@ +function tablesApp() { + return { + data: [], + selectedCell: null, + cols: 26, + rows: 100, + visibleRows: 30, + rowOffset: 0, + + init() { + this.data = this.generateMockData(this.rows, this.cols); + this.setupEventListeners(); + this.updateStats(); + }, + + generateMockData(rows, cols) { + const data = []; + const products = ['Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Headphones', 'Webcam', 'Desk', 'Chair']; + const regions = ['North', 'South', 'East', 'West']; + + for (let i = 0; i < rows; i++) { + const row = {}; + for (let j = 0; j < cols; j++) { + const col = this.getColumnName(j); + if (i === 0) { + if (j === 0) row[col] = 'Product'; + else if (j === 1) row[col] = 'Region'; + else if (j === 2) row[col] = 'Q1'; + else if (j === 3) row[col] = 'Q2'; + else if (j === 4) row[col] = 'Q3'; + else if (j === 5) row[col] = 'Q4'; + else if (j === 6) row[col] = 'Total'; + else row[col] = `Col ${col}`; + } else { + if (j === 0) row[col] = products[i % products.length]; + else if (j === 1) row[col] = regions[i % regions.length]; + else if (j >= 2 && j <= 5) row[col] = Math.floor(Math.random() * 10000) + 1000; + else if (j === 6) { + row[col] = `=C${i+1}+D${i+1}+E${i+1}+F${i+1}`; + } + else row[col] = Math.random() > 0.5 ? Math.floor(Math.random() * 1000) : ''; + } + } + data.push(row); + } + return data; + }, + + getColumnName(index) { + let name = ''; + while (index >= 0) { + name = String.fromCharCode(65 + (index % 26)) + name; + index = Math.floor(index / 26) - 1; + } + return name; + }, + + setupEventListeners() { + // Will be replaced with Alpine.js directives + }, + + selectCell(cell) { + if (this.selectedCell) { + this.selectedCell.classList.remove('selected'); + } + this.selectedCell = cell; + cell.classList.add('selected'); + + const cellRef = cell.dataset.cell; + document.getElementById('cellRef').textContent = cellRef; + document.getElementById('selectedCell').textContent = cellRef; + + const row = parseInt(cell.dataset.row); + const col = this.getColumnName(parseInt(cell.dataset.col)); + const value = this.data[row][col] || ''; + document.getElementById('formulaInput').value = value; + }, + + calculateCell(value, row, col) { + if (typeof value === 'string' && value.startsWith('=')) { + try { + const formula = value.substring(1).toUpperCase(); + + if (formula.includes('SUM')) { + const match = formula.match(/SUM\(([A-Z]+\d+):([A-Z]+\d+)\)/); + if (match) { + const sum = this.calculateRange(match[1], match[2], 'sum'); + return sum.toFixed(2); + } + } + + if (formula.includes('AVERAGE')) { + const match = formula.match(/AVERAGE\(([A-Z]+\d+):([A-Z]+\d+)\)/); + if (match) { + const avg = this.calculateRange(match[1], match[2], 'avg'); + return avg.toFixed(2); + } + } + + let expression = formula; + const cellRefs = expression.match(/[A-Z]+\d+/g); + if (cellRefs) { + cellRefs.forEach(ref => { + const val = this.getCellValue(ref); + expression = expression.replace(ref, val); + }); + return eval(expression).toFixed(2); + } + } catch (e) { + return '#ERROR'; + } + } + return value; + }, + + getCellValue(cellRef) { + const col = cellRef.match(/[A-Z]+/)[0]; + const row = parseInt(cellRef.match(/\d+/)[0]) - 1; + const value = this.data[row][col]; + + if (typeof value === 'string' && value.startsWith('=')) { + return this.calculateCell(value, row, this.getColIndex(col)); + } + return parseFloat(value) || 0; + }, + + getColIndex(colName) { + let index = 0; + for (let i = 0; i < colName.length; i++) { + index = index * 26 + (colName.charCodeAt(i) - 64); + } + return index - 1; + }, + + calculateRange(start, end, operation) { + const startCol = start.match(/[A-Z]+/)[0]; + const startRow = parseInt(start.match(/\d+/)[0]) - 1; + const endCol = end.match(/[A-Z]+/)[0]; + const endRow = parseInt(end.match(/\d+/)[0]) - 1; + + let values = []; + for (let r = startRow; r <= endRow; r++) { + for (let c = this.getColIndex(startCol); c <= this.getColIndex(endCol); c++) { + const col = this.getColumnName(c); + const val = parseFloat(this.data[r][col]) || 0; + values.push(val); + } + } + + if (operation === 'sum') { + return values.reduce((a, b) => a + b, 0); + } else if (operation === 'avg') { + return values.reduce((a, b) => a + b, 0) / values.length; + } + return 0; + }, + + updateCellValue(value) { + if (!this.selectedCell) return; + + const row = parseInt(this.selectedCell.dataset.row); + const col = this.getColumnName(parseInt(this.selectedCell.dataset.col)); + + this.data[row][col] = value; + this.renderTable(); + + const newCell = document.querySelector(`td[data-row="${row}"][data-col="${this.selectedCell.dataset.col}"]`); + if (newCell) this.selectCell(newCell); + }, + + renderTable() { + const thead = document.getElementById('tableHead'); + const tbody = document.getElementById('tableBody'); + + let headerHTML = ''; + for (let i = 0; i < this.cols; i++) { + headerHTML += `${this.getColumnName(i)}`; + } + headerHTML += ''; + thead.innerHTML = headerHTML; + + let bodyHTML = ''; + const endRow = Math.min(this.rowOffset + this.visibleRows, this.rows); + + for (let i = this.rowOffset; i < endRow; i++) { + bodyHTML += `${i + 1}`; + for (let j = 0; j < this.cols; j++) { + const col = this.getColumnName(j); + const value = this.data[i][col] || ''; + const displayValue = this.calculateCell(value, i, j); + bodyHTML += ` + ${displayValue} + `; + } + bodyHTML += ''; + } + tbody.innerHTML = bodyHTML; + }, + + updateStats() { + document.getElementById('rowCount').textContent = this.rows; + document.getElementById('colCount').textContent = this.cols; + }, + + // Toolbar actions + addRow() { + const newRow = {}; + for (let i = 0; i < this.cols; i++) { + newRow[this.getColumnName(i)] = ''; + } + this.data.push(newRow); + this.rows++; + this.renderTable(); + this.updateStats(); + }, + + addColumn() { + const newCol = this.getColumnName(this.cols); + this.data.forEach(row => row[newCol] = ''); + this.cols++; + this.renderTable(); + this.updateStats(); + }, + + deleteRow() { + if (this.selectedCell && this.rows > 1) { + const row = parseInt(this.selectedCell.dataset.row); + this.data.splice(row, 1); + this.rows--; + this.renderTable(); + this.updateStats(); + } + }, + + deleteColumn() { + if (this.selectedCell && this.cols > 1) { + const col = this.getColumnName(parseInt(this.selectedCell.dataset.col)); + this.data.forEach(row => delete row[col]); + this.cols--; + this.renderTable(); + this.updateStats(); + } + }, + + sort() { + if (this.selectedCell) { + const col = this.getColumnName(parseInt(this.selectedCell.dataset.col)); + const header = this.data[0]; + const dataRows = this.data.slice(1); + + dataRows.sort((a, b) => { + const aVal = a[col] || ''; + const bVal = b[col] || ''; + return aVal.toString().localeCompare(bVal.toString()); + }); + + this.data = [header, ...dataRows]; + this.renderTable(); + } + }, + + sum() { + if (this.selectedCell) { + const col = this.getColumnName(parseInt(this.selectedCell.dataset.col)); + this.formulaInputValue = `=SUM(${col}2:${col}${this.rows})`; + } + }, + + average() { + if (this.selectedCell) { + const col = this.getColumnName(parseInt(this.selectedCell.dataset.col)); + this.formulaInputValue = `=AVERAGE(${col}2:${col}${this.rows})`; + } + }, + + exportData() { + const csv = this.data.map(row => { + return Object.values(row).join(','); + }).join('\n'); + + const blob = new Blob([csv], { type: 'text/csv' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = 'tables_export.csv'; + a.click(); + } + }; +} diff --git a/web/desktop/auth/app.js b/web/desktop/auth/app.js deleted file mode 100644 index 2a33ef889..000000000 --- a/web/desktop/auth/app.js +++ /dev/null @@ -1,74 +0,0 @@ -document.addEventListener('alpine:init', () => { - Alpine.data('auth', () => ({ - email: '', - password: '', - rememberMe: false, - isLoading: false, - error: '', - - async socialLogin(provider) { - this.isLoading = true; - this.error = ''; - - try { - // In a real implementation, this would redirect to the auth endpoint - const authUrl = `${this.getAuthEndpoint()}/oauth/v2/authorize?` + - `client_id=${this.getClientId()}&` + - `redirect_uri=${encodeURIComponent(window.location.origin)}&` + - `response_type=code&` + - `scope=openid profile email&` + - `provider=${provider}`; - - window.location.href = authUrl; - } catch (err) { - this.error = 'Failed to initiate login'; - console.error('Login error:', err); - } finally { - this.isLoading = false; - } - }, - - async emailLogin() { - this.isLoading = true; - this.error = ''; - - try { - const response = await fetch('/api/auth/login', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - email: this.email, - password: this.password, - rememberMe: this.rememberMe - }) - }); - - if (!response.ok) { - const errorData = await response.json(); - throw new Error(errorData.message || 'Login failed'); - } - - const data = await response.json(); - localStorage.setItem('authToken', data.token); - window.location.href = '/tables.html'; - } catch (err) { - this.error = err.message || 'Login failed. Please check your credentials.'; - console.error('Login error:', err); - } finally { - this.isLoading = false; - } - }, - - getAuthEndpoint() { - // In a real app, this would come from config - return 'https://auth.example.com'; - }, - - getClientId() { - // In a real app, this would come from config - return 'general-bots-client'; - } - })); -}); diff --git a/web/desktop/auth/index.html b/web/desktop/auth/index.html deleted file mode 100644 index 236bcc545..000000000 --- a/web/desktop/auth/index.html +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - General Bots - Authentication - - - - - -
-
- -
-

"Errar é Humano."

-

General Bots

-
-
- -
-
-

Sign in to your account

-

Choose your preferred login method

-
- -
- -
- - - - - -
- -
- OR -
- -
-
- - -
- -
- - -
- -
-
- - -
- Forgot password? -
- - -
- - -
-
- - diff --git a/web/desktop/auth/styles.css b/web/desktop/auth/styles.css deleted file mode 100644 index bb13a748d..000000000 --- a/web/desktop/auth/styles.css +++ /dev/null @@ -1,249 +0,0 @@ -:root { - --background: #1a1a2e; - --foreground: #ffffff; - --primary: #4f46e5; - --primary-foreground: #ffffff; - --secondary: #374151; - --secondary-foreground: #ffffff; - --muted: #4b5563; - --muted-foreground: #9ca3af; - --accent: #7c3aed; - --destructive: #ef4444; - --border: #374151; - --input: #1f2937; - --radius: 0.5rem; -} - -* { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -body { - font-family: 'Segoe UI', sans-serif; - background-color: var(--background); - color: var(--foreground); - min-height: 100vh; - display: flex; - align-items: center; - justify-content: center; -} - -.auth-container { - display: flex; - width: 100%; - max-width: 1200px; - background-color: var(--secondary); - border-radius: var(--radius); - overflow: hidden; - box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); -} - -.auth-left-panel { - flex: 1; - padding: 4rem; - background: linear-gradient(135deg, var(--primary), var(--accent)); - color: var(--primary-foreground); - display: flex; - flex-direction: column; - justify-content: space-between; -} - -.auth-logo h1 { - font-size: 2rem; - margin-bottom: 1rem; -} - -.auth-quote { - font-style: italic; - margin-top: auto; -} - -.auth-quote p:last-child { - text-align: right; - margin-top: 0.5rem; -} - -.auth-form-container { - flex: 1; - padding: 4rem; - max-width: 500px; -} - -.auth-form-header { - margin-bottom: 2rem; - text-align: center; -} - -.auth-form-header h2 { - font-size: 1.5rem; - margin-bottom: 0.5rem; -} - -.auth-form-header p { - color: var(--muted-foreground); -} - -.auth-error { - background-color: var(--destructive); - color: var(--primary-foreground); - padding: 0.75rem; - border-radius: var(--radius); - margin-bottom: 1rem; - text-align: center; -} - -.auth-social-buttons { - display: grid; - grid-template-columns: 1fr; - gap: 0.75rem; - margin-bottom: 1.5rem; -} - -.auth-social-button { - display: flex; - align-items: center; - justify-content: center; - padding: 0.75rem; - border-radius: var(--radius); - font-weight: 500; - cursor: pointer; - transition: all 0.2s; - border: 1px solid var(--border); - background-color: var(--input); - color: var(--foreground); -} - -.auth-social-button:hover { - background-color: var(--muted); -} - -.auth-social-icon { - width: 1.25rem; - height: 1.25rem; - margin-right: 0.5rem; - font-weight: bold; -} - -.auth-divider { - display: flex; - align-items: center; - margin: 1.5rem 0; - color: var(--muted-foreground); -} - -.auth-divider::before, -.auth-divider::after { - content: ""; - flex: 1; - border-bottom: 1px solid var(--border); -} - -.auth-divider span { - padding: 0 1rem; -} - -.auth-form { - margin-top: 1.5rem; -} - -.auth-form-group { - margin-bottom: 1rem; -} - -.auth-form-group label { - display: block; - margin-bottom: 0.5rem; - font-weight: 500; -} - -.auth-form-group input { - width: 100%; - padding: 0.75rem; - border-radius: var(--radius); - border: 1px solid var(--border); - background-color: var(--input); - color: var(--foreground); -} - -.auth-form-group input:focus { - outline: none; - border-color: var(--primary); -} - -.auth-form-options { - display: flex; - justify-content: space-between; - align-items: center; - margin: 1rem 0; -} - -.auth-remember-me { - display: flex; - align-items: center; -} - -.auth-remember-me input { - margin-right: 0.5rem; -} - -.auth-forgot-password { - color: var(--primary); - text-decoration: none; -} - -.auth-forgot-password:hover { - text-decoration: underline; -} - -.auth-submit-button { - width: 100%; - padding: 0.75rem; - border-radius: var(--radius); - background-color: var(--primary); - color: var(--primary-foreground); - font-weight: 500; - border: none; - cursor: pointer; - transition: all 0.2s; -} - -.auth-submit-button:hover { - background-color: var(--accent); -} - -.auth-submit-button:disabled { - opacity: 0.7; - cursor: not-allowed; -} - -.auth-signup-link { - text-align: center; - margin: 1.5rem 0; - color: var(--muted-foreground); -} - -.auth-signup-link a { - color: var(--primary); - text-decoration: none; -} - -.auth-signup-link a:hover { - text-decoration: underline; -} - -@media (max-width: 768px) { - .auth-container { - flex-direction: column; - } - - .auth-left-panel { - padding: 2rem; - } - - .auth-form-container { - padding: 2rem; - max-width: 100%; - } -} diff --git a/web/desktop/css/app.css b/web/desktop/css/app.css index bc2914d11..fb0000ab7 100644 --- a/web/desktop/css/app.css +++ b/web/desktop/css/app.css @@ -1,64 +1,324 @@ -/* Main app styles */ -@import url('../shared/styles.css'); -@import url('chat.css'); +* { margin: 0; padding: 0; box-sizing: border-box; } -/* Navbar styles */ -.navbar { - background: white; - color: #333; - padding: 0.5rem 1rem; - box-shadow: 0 2px 4px rgba(0,0,0,0.1); - position: fixed; - top: 0; - left: 0; - right: 0; - z-index: 1000; +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif; + background: #0f172a; + color: #e2e8f0; + height: 100vh; + overflow: hidden; } -.nav-container { +/* Navbar */ +nav { + background: #1e293b; + border-bottom: 2px solid #334155; + padding: 0 1rem; display: flex; align-items: center; - max-width: 1200px; - margin: 0 auto; + height: 60px; + gap: 0.5rem; } -.nav-brand { +nav .logo { + font-size: 1.5rem; font-weight: bold; - font-size: 1.2rem; - margin-right: 2rem; - color: #333; + background: linear-gradient(135deg, #3b82f6, #8b5cf6); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + margin-right: auto; } -.nav-links { - display: flex; - list-style: none; - margin: 0; - padding: 0; -} - -.nav-link { - color: #555; +nav a { + color: #94a3b8; text-decoration: none; - padding: 0.5rem 1rem; - display: flex; - align-items: center; + padding: 0.75rem 1.25rem; + border-radius: 0.5rem; transition: all 0.2s; -} - -.nav-link:hover { - color: #000; -} - -.nav-link.active { - color: #0066ff; font-weight: 500; } -.nav-link i { - margin-right: 0.5rem; - color: #666; +nav a:hover { + background: #334155; + color: #e2e8f0; } -.nav-link.active i { - color: #0066ff; +nav a.active { + background: #3b82f6; + color: white; +} + +/* Main Content */ +#main-content { + height: calc(100vh - 60px); + overflow: hidden; +} + +.content-section { + display: none; + height: 100%; + overflow: auto; +} + +.content-section.active { + display: block; +} + +/* Panel Styles */ +.panel { + background: #1e293b; + border: 1px solid #334155; + border-radius: 0.5rem; +} + +/* Drive Styles */ +.drive-layout { + display: grid; + grid-template-columns: 250px 1fr 300px; + gap: 1rem; + padding: 1rem; + height: 100%; +} + +.drive-sidebar, .drive-details { + overflow-y: auto; +} + +.drive-main { + display: flex; + flex-direction: column; + overflow: hidden; +} + +.nav-item { + padding: 0.75rem 1rem; + display: flex; + align-items: center; + gap: 0.75rem; + cursor: pointer; + border-radius: 0.375rem; + margin: 0.25rem 0.5rem; + transition: background 0.2s; +} + +.nav-item:hover { + background: #334155; +} + +.nav-item.active { + background: #3b82f6; +} + +.file-list { + flex: 1; + overflow-y: auto; + padding: 1rem; +} + +.file-item { + padding: 1rem; + display: flex; + align-items: center; + gap: 1rem; + cursor: pointer; + border-radius: 0.375rem; + border-bottom: 1px solid #334155; + transition: background 0.2s; +} + +.file-item:hover { + background: #334155; +} + +.file-item.selected { + background: #1e40af; +} + +.file-icon { + font-size: 2rem; +} + +/* Tasks Styles */ +.tasks-container { + max-width: 800px; + margin: 0 auto; + padding: 2rem; +} + +.task-input { + display: flex; + gap: 0.5rem; + margin-bottom: 2rem; +} + +.task-input input { + flex: 1; + padding: 0.75rem; + background: #1e293b; + border: 1px solid #334155; + border-radius: 0.5rem; + color: #e2e8f0; + font-size: 1rem; +} + +.task-input input:focus { + outline: none; + border-color: #3b82f6; +} + +.task-input button { + padding: 0.75rem 1.5rem; + background: #3b82f6; + color: white; + border: none; + border-radius: 0.5rem; + cursor: pointer; + font-weight: 600; + transition: background 0.2s; +} + +.task-input button:hover { + background: #2563eb; +} + +.task-list { + list-style: none; +} + +.task-item { + padding: 1rem; + display: flex; + align-items: center; + gap: 1rem; + background: #1e293b; + border: 1px solid #334155; + border-radius: 0.5rem; + margin-bottom: 0.5rem; +} + +.task-item.completed span { + text-decoration: line-through; + opacity: 0.5; +} + +.task-item input[type="checkbox"] { + width: 1.25rem; + height: 1.25rem; + cursor: pointer; +} + +.task-item span { + flex: 1; +} + +.task-item button { + background: #ef4444; + color: white; + border: none; + padding: 0.5rem 0.75rem; + border-radius: 0.375rem; + cursor: pointer; + transition: background 0.2s; +} + +.task-item button:hover { + background: #dc2626; +} + +.task-filters { + display: flex; + gap: 0.5rem; + margin-top: 2rem; + padding-top: 2rem; + border-top: 1px solid #334155; +} + +.task-filters button { + padding: 0.5rem 1rem; + background: #334155; + color: #e2e8f0; + border: none; + border-radius: 0.375rem; + cursor: pointer; + transition: all 0.2s; +} + +.task-filters button.active { + background: #3b82f6; +} + +/* Mail Styles */ +.mail-layout { + display: grid; + grid-template-columns: 250px 350px 1fr; + gap: 1rem; + padding: 1rem; + height: 100%; +} + +.mail-sidebar, .mail-list, .mail-content { + overflow-y: auto; +} + +.mail-item { + padding: 1rem; + cursor: pointer; + border-bottom: 1px solid #334155; + transition: background 0.2s; +} + +.mail-item:hover { + background: #334155; +} + +.mail-item.unread { + font-weight: 600; +} + +.mail-item.selected { + background: #1e40af; +} + +.mail-content-view { + padding: 2rem; +} + +.mail-header { + margin-bottom: 2rem; + padding-bottom: 1rem; + border-bottom: 1px solid #334155; +} + +.mail-body { + line-height: 1.6; +} + +/* Buttons */ +button { + font-family: inherit; +} + +button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +/* Utility */ +h1, h2, h3 { + margin-bottom: 1rem; +} + +.text-sm { + font-size: 0.875rem; +} + +.text-xs { + font-size: 0.75rem; +} + +.text-gray { + color: #94a3b8; +} + +[x-cloak] { + display: none !important; } diff --git a/web/desktop/css/chat.css b/web/desktop/css/chat.css deleted file mode 100644 index f9bebbaee..000000000 --- a/web/desktop/css/chat.css +++ /dev/null @@ -1,195 +0,0 @@ -.chat-container { - margin-top: 60px; /* Account for navbar height */ - height: calc(100vh - 60px); - display: flex; - flex-direction: column; -} - -#messages { - flex: 1; - overflow-y: auto; - padding: 20px 20px 140px; - max-width: 680px; - margin: 0 auto; - width: 100%; - position: relative; - z-index: 1; -} - -.chat-footer { - position: fixed; - bottom: 0; - left: 0; - right: 0; - background: var(--bg); - border-top: 1px solid var(--border); - padding: 12px; - z-index: 100; - transition: all 0.3s; - backdrop-filter: blur(20px); -} - -/* Message styles */ -.message-container { - margin-bottom: 24px; - opacity: 0; - transform: translateY(10px); -} - -.user-message { - display: flex; - justify-content: flex-end; - margin-bottom: 8px; -} - -.user-message-content { - background: var(--fg); - color: var(--bg); - border-radius: 18px; - padding: 12px 18px; - max-width: 80%; - font-size: 14px; - line-height: 1.5; - box-shadow: 0 2px 8px var(--shadow); - position: relative; - overflow: hidden; -} - -.user-message-content::before { - content: ''; - position: absolute; - inset: 0; - background: var(--gradient-2); - opacity: 0.3; - pointer-events: none; -} - -.assistant-message { - display: flex; - gap: 8px; - align-items: flex-start; -} - -.assistant-avatar { - width: 24px; - height: 24px; - border-radius: 50%; - background: var(--logo-url) center/contain no-repeat; - flex-shrink: 0; - margin-top: 2px; - filter: var(--logo-filter, none); -} - -.assistant-message-content { - flex: 1; - font-size: 14px; - line-height: 1.7; - background: var(--glass); - border-radius: 18px; - padding: 12px 18px; - border: 1px solid var(--border); - box-shadow: 0 2px 8px var(--shadow); - position: relative; - overflow: hidden; -} - -.assistant-message-content::before { - content: ''; - position: absolute; - inset: 0; - background: var(--gradient-1); - opacity: 0.5; - pointer-events: none; -} - -/* Input and suggestions */ -.suggestions-container { - display: flex; - flex-wrap: wrap; - gap: 4px; - margin-bottom: 8px; - justify-content: center; - max-width: 680px; - margin: 0 auto 8px; -} - -.suggestion-button { - padding: 6px 12px; - border-radius: 12px; - cursor: pointer; - font-size: 11px; - font-weight: 400; - transition: all 0.2s; - background: var(--glass); - border: 1px solid var(--border); - color: var(--fg); -} - -.suggestion-button:hover { - background: var(--fg); - color: var(--bg); - transform: scale(1.05); -} - -.input-container { - display: flex; - gap: 6px; - max-width: 680px; - margin: 0 auto; - align-items: center; -} - -#messageInput { - flex: 1; - border-radius: 20px; - padding: 10px 16px; - font-size: 14px; - font-family: "Inter", sans-serif; - outline: none; - transition: all 0.3s; - background: var(--glass); - border: 1px solid var(--border); - color: var(--fg); - backdrop-filter: blur(10px); -} - -#messageInput:focus { - border-color: var(--accent); - box-shadow: 0 0 0 3px rgba(0,102,255,0.1); -} - -#messageInput::placeholder { - opacity: 0.3; -} - -#sendBtn, #voiceBtn { - width: 36px; - height: 36px; - border-radius: 18px; - display: flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: all 0.2s; - border: none; - background: var(--fg); - color: var(--bg); - font-size: 16px; - flex-shrink: 0; -} - -#voiceBtn.recording { - animation: pulse 1.5s infinite; -} - -@keyframes pulse { - 0%, 100% { opacity: 1; transform: scale(1) } - 50% { opacity: 0.6; transform: scale(1.1) } -} - -/* Responsive adjustments */ -@media (max-width: 768px) { - #messages { - padding: 20px 16px 140px; - } -} diff --git a/web/desktop/css/theme.css b/web/desktop/css/theme.css deleted file mode 100644 index 69761b844..000000000 --- a/web/desktop/css/theme.css +++ /dev/null @@ -1,114 +0,0 @@ -:root { - /* Main theme */ - --background: #ffffff; - --foreground: #000000; - --card: #f8f9fa; - --popover: #ffffff; - --primary: #2563eb; - --secondary: #f1f5f9; - --muted: #64748b; - --accent: #f59e0b; - --destructive: #ef4444; - --border: #e2e8f0; - --input: #e2e8f0; - --ring: #93c5fd; - --radius: 0.5rem; - --chart-1: #3b82f6; - --chart-2: #10b981; - --chart-3: #f59e0b; - --chart-4: #ef4444; - --chart-5: #8b5cf6; - - /* File manager theme */ - --bg-primary: #1a1a2e; - --bg-secondary: #16213e; - --bg-tertiary: #0f3460; - --text-primary: #e94560; - --text-secondary: #00d9ff; - --filemanager-border: #533483; -} - -.navbar { - background: var(--background); - padding: 1rem; - border-bottom: 1px solid var(--border); -} - -.mobile-menu-btn { - display: none; -} - -.nav-links { - display: flex; - gap: 1rem; -} - -.nav-links a { - color: var(--foreground); - text-decoration: none; - padding: 0.5rem 1rem; - border-radius: var(--radius); -} - -.nav-links a:hover { - background: var(--secondary); -} - -.footer { - background: var(--background); - padding: 1rem; - border-top: 1px solid var(--border); - display: flex; - gap: 2rem; - justify-content: center; -} - -.shortcut-group { - display: flex; - gap: 1rem; -} - -.shortcut-btn { - display: flex; - flex-direction: column; - align-items: center; - padding: 0.5rem; - background: var(--card); - border: 1px solid var(--border); - border-radius: var(--radius); - cursor: pointer; -} - -.shortcut-btn .key { - font-weight: bold; - color: var(--primary); -} - -@media (max-width: 768px) { - .mobile-menu-btn { - display: block; - } - - .nav-links { - display: none; - flex-direction: column; - position: absolute; - background: var(--background); - width: 100%; - left: 0; - padding: 1rem; - box-shadow: 0 2px 4px rgba(0,0,0,0.1); - } - - .nav-links.hidden { - display: none; - } - - .nav-links:not(.hidden) { - display: flex; - } - - .shortcut-group { - flex-wrap: wrap; - } -} diff --git a/web/desktop/drive/drive.js b/web/desktop/drive/drive.js new file mode 100644 index 000000000..ee877239a --- /dev/null +++ b/web/desktop/drive/drive.js @@ -0,0 +1,29 @@ +function driveApp() { + return { + current: 'All Files', + search: '', + selectedFile: null, + navItems: [ + { name: 'All Files', icon: '📁' }, + { name: 'Recent', icon: '🕐' }, + { name: 'Starred', icon: '⭐' }, + { name: 'Shared', icon: '👥' }, + { name: 'Trash', icon: '🗑' } + ], + files: [ + { id: 1, name: 'Project Proposal.pdf', type: 'PDF', icon: '📄', size: '2.4 MB', date: 'Nov 10, 2025' }, + { id: 2, name: 'Design Assets', type: 'Folder', icon: '📁', size: '—', date: 'Nov 12, 2025' }, + { id: 3, name: 'Meeting Notes.docx', type: 'Document', icon: '📝', size: '156 KB', date: 'Nov 14, 2025' }, + { id: 4, name: 'Budget 2025.xlsx', type: 'Spreadsheet', icon: '📊', size: '892 KB', date: 'Nov 13, 2025' }, + { id: 5, name: 'Presentation.pptx', type: 'Presentation', icon: '📽', size: '5.2 MB', date: 'Nov 11, 2025' }, + { id: 6, name: 'team-photo.jpg', type: 'Image', icon: '🖼', size: '3.1 MB', date: 'Nov 9, 2025' }, + { id: 7, name: 'source-code.zip', type: 'Archive', icon: '📦', size: '12.8 MB', date: 'Nov 8, 2025' }, + { id: 8, name: 'video-demo.mp4', type: 'Video', icon: '🎬', size: '45.2 MB', date: 'Nov 7, 2025' } + ], + get filteredFiles() { + return this.files.filter(file => + file.name.toLowerCase().includes(this.search.toLowerCase()) + ); + } + }; +} diff --git a/web/desktop/drive/index.html b/web/desktop/drive/index.html index 0f9155a3c..820148c0b 100644 --- a/web/desktop/drive/index.html +++ b/web/desktop/drive/index.html @@ -1,585 +1,67 @@ - - - - - - XTree Gold File Manager - - - - - - -
- -
- -
- -
- -
- - -
- -
- - - -
- - -
- -
-

- - -
- - -
-
- - -
- - -
- No files found -
-
-
- - -
-
- - - -
- -
- - - -
-
-
- - -
-
- -
- -
- - -
- -
-
-
- - -
- +
+
+
+

General Bots Drive

+ +
- - - +
+
+

+ +
+
+ +
+
+ +
+ + +
+
diff --git a/web/desktop/index.html b/web/desktop/index.html index 852202356..bf1b1a6e6 100644 --- a/web/desktop/index.html +++ b/web/desktop/index.html @@ -1,35 +1,31 @@ - + - -General Bots - - - - - - + + General Bots Desktop + + + - + - -
-
-
- -
- -
-
-
- - - -
-
-
+
+ +
- + + + + + diff --git a/web/desktop/js/cdn.min.js b/web/desktop/js/alpine.js similarity index 100% rename from web/desktop/js/cdn.min.js rename to web/desktop/js/alpine.js diff --git a/web/desktop/js/auth.js b/web/desktop/js/auth.js deleted file mode 100644 index 003abdfa3..000000000 --- a/web/desktop/js/auth.js +++ /dev/null @@ -1,61 +0,0 @@ -// Handle authentication state -let currentUser = null; -let currentSession = null; - -// Initialize auth with mock data -function initializeAuth() { - if (window.location.pathname.includes('auth')) { - return; // Don't initialize on auth pages - } - - // Check for existing session - const sessionId = localStorage.getItem('sessionId'); - if (sessionId) { - currentSession = mockSessions.find(s => s.id === sessionId) || mockSessions[0]; - } else { - currentSession = mockSessions[0]; - localStorage.setItem('sessionId', currentSession.id); - } - - // Set current user - currentUser = mockUsers[0]; - updateUserUI(); -} - -// Update UI based on auth state -function updateUserUI() { - const userAvatar = document.getElementById('userAvatar'); - if (userAvatar && currentUser) { - userAvatar.textContent = currentUser.avatar; - } -} - -// Handle login -function handleLogin(email, password) { - // In a real app, this would call an API - currentUser = mockUsers.find(u => u.email === email) || mockUsers[0]; - currentSession = mockSessions[0]; - localStorage.setItem('sessionId', currentSession.id); - updateUserUI(); - window.location.href = '/desktop/index.html'; -} - -// Handle logout -function handleLogout() { - localStorage.removeItem('sessionId'); - window.location.href = '/desktop/auth/login.html'; -} - -// Check auth state for protected routes -function checkAuth() { - if (!currentUser && !window.location.pathname.includes('auth')) { - window.location.href = '/desktop/auth/login.html'; - } -} - -// Initialize on page load -if (document.readyState === 'complete') { - initializeAuth(); -} else { - window.addEventListener('load', initializeAuth); -} diff --git a/web/desktop/js/layout.js b/web/desktop/js/layout.js index 0233c6f30..ccf61d75b 100644 --- a/web/desktop/js/layout.js +++ b/web/desktop/js/layout.js @@ -1,56 +1,37 @@ -class Layout { - static currentPage = 'chat'; +const sections = { + drive: 'drive/index.html', + tasks: 'tasks/index.html', + mail: 'mail/index.html' +}; + +async function loadSectionHTML(path) { + const response = await fetch(path); + if (!response.ok) throw new Error('Failed to load section'); + return await response.text(); +} + +async function switchSection(section) { + const mainContent = document.getElementById('main-content'); - static init() { - this.setCurrentPage(); - this.loadNavbar(); - this.setupNavigation(); - } - - static setCurrentPage() { - const hash = window.location.hash.substring(1) || 'chat'; - this.currentPage = hash; - this.updateContent(); - } - - static async loadNavbar() { - try { - const response = await fetch('shared/navbar.html'); - const html = await response.text(); - - if (!document.querySelector('.navbar')) { - document.body.insertAdjacentHTML('afterbegin', html); - } - - document.querySelectorAll('.nav-link').forEach(link => { - link.classList.toggle('active', link.dataset.target === this.currentPage); - }); - } catch (error) { - console.error('Failed to load navbar:', error); - } - } - - static updateContent() { - // Add your content loading logic here - // For example: fetch(`pages/${this.currentPage}.html`) - // and update the main content area - } - - static setupNavigation() { - document.addEventListener('click', (e) => { - const navLink = e.target.closest('.nav-link'); - if (navLink) { - e.preventDefault(); - const target = navLink.dataset.target; - window.location.hash = target; - this.currentPage = target; - this.loadNavbar(); - this.updateContent(); - } - }); + try { + const html = await loadSectionHTML(sections[section]); + mainContent.innerHTML = html; + window.history.pushState({}, '', `#${section}`); + Alpine.initTree(mainContent); + } catch (err) { + console.error('Error loading section:', err); + mainContent.innerHTML = `
Failed to load ${section} section
`; } } -// Initialize on load and also on navigation -Layout.init(); -window.addEventListener('popstate', () => Layout.init()); +// Handle initial load based on URL hash +window.addEventListener('DOMContentLoaded', () => { + const initialSection = window.location.hash.substring(1) || 'drive'; + switchSection(initialSection); +}); + +// Handle browser back/forward navigation +window.addEventListener('popstate', () => { + const section = window.location.hash.substring(1) || 'drive'; + switchSection(section); +}); diff --git a/web/desktop/js/lib/gsap.min.js b/web/desktop/js/lib/gsap.min.js deleted file mode 100644 index 0c38bc45c..000000000 --- a/web/desktop/js/lib/gsap.min.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * GSAP 3.12.2 - * https://greensock.com - * - * @license Copyright 2023, GreenSock. All rights reserved. - * Subject to the terms at https://greensock.com/standard-license or for Club GreenSock members, the agreement issued with that membership. - * @author: Jack Doyle, jack@greensock.com - */ - -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).window=t.window||{})}(this,function(e){"use strict";function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),(t.prototype.constructor=t).__proto__=e}function _assertThisInitialized(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function r(t){return"string"==typeof t}function s(t){return"function"==typeof t}function t(t){return"number"==typeof t}function u(t){return void 0===t}function v(t){return"object"==typeof t}function w(t){return!1!==t}function x(){return"undefined"!=typeof window}function y(t){return s(t)||r(t)}function P(t){return(i=yt(t,ot))&&Ee}function Q(t,e){return console.warn("Invalid property",t,"set to",e,"Missing plugin? gsap.registerPlugin()")}function R(t,e){return!e&&console.warn(t)}function S(t,e){return t&&(ot[t]=e)&&i&&(i[t]=e)||ot}function T(){return 0}function ea(t){var e,r,i=t[0];if(v(i)||s(i)||(t=[t]),!(e=(i._gsap||{}).harness)){for(r=gt.length;r--&&!gt[r].targetTest(i););e=gt[r]}for(r=t.length;r--;)t[r]&&(t[r]._gsap||(t[r]._gsap=new Vt(t[r],e)))||t.splice(r,1);return t}function fa(t){return t._gsap||ea(Ot(t))[0]._gsap}function ga(t,e,r){return(r=t[e])&&s(r)?t[e]():u(r)&&t.getAttribute&&t.getAttribute(e)||r}function ha(t,e){return(t=t.split(",")).forEach(e)||t}function ia(t){return Math.round(1e5*t)/1e5||0}function ja(t){return Math.round(1e7*t)/1e7||0}function ka(t,e){var r=e.charAt(0),i=parseFloat(e.substr(2));return t=parseFloat(t),"+"===r?t+i:"-"===r?t-i:"*"===r?t*i:t/i}function la(t,e){for(var r=e.length,i=0;t.indexOf(e[i])<0&&++ia;)s=s._prev;return s?(e._next=s._next,s._next=e):(e._next=t[r],t[r]=e),e._next?e._next._prev=e:t[i]=e,e._prev=s,e.parent=e._dp=t,e}function ya(t,e,r,i){void 0===r&&(r="_first"),void 0===i&&(i="_last");var n=e._prev,a=e._next;n?n._next=a:t[r]===e&&(t[r]=a),a?a._prev=n:t[i]===e&&(t[i]=n),e._next=e._prev=e.parent=null}function za(t,e){t.parent&&(!e||t.parent.autoRemoveChildren)&&t.parent.remove&&t.parent.remove(t),t._act=0}function Aa(t,e){if(t&&(!e||e._end>t._dur||e._start<0))for(var r=t;r;)r._dirty=1,r=r.parent;return t}function Ca(t,e,r,i){return t._startAt&&(L?t._startAt.revert(ht):t.vars.immediateRender&&!t.vars.autoRevert||t._startAt.render(e,!0,i))}function Ea(t){return t._repeat?Tt(t._tTime,t=t.duration()+t._rDelay)*t:0}function Ga(t,e){return(t-e._start)*e._ts+(0<=e._ts?0:e._dirty?e.totalDuration():e._tDur)}function Ha(t){return t._end=ja(t._start+(t._tDur/Math.abs(t._ts||t._rts||X)||0))}function Ia(t,e){var r=t._dp;return r&&r.smoothChildTiming&&t._ts&&(t._start=ja(r._time-(0X)&&e.render(r,!0)),Aa(t,e)._dp&&t._initted&&t._time>=t._dur&&t._ts){if(t._dur(n=Math.abs(n))&&(a=i,o=n);return a}function tb(t){return za(t),t.scrollTrigger&&t.scrollTrigger.kill(!!L),t.progress()<1&&At(t,"onInterrupt"),t}function wb(t){if(x()&&t){var e=(t=!t.name&&t.default||t).name,r=s(t),i=e&&!r&&t.init?function(){this._props=[]}:t,n={init:T,render:he,add:Qt,kill:ce,modifier:fe,rawVars:0},a={targetTest:0,get:0,getSetter:ne,aliases:{},register:0};if(Ft(),t!==i){if(pt[e])return;qa(i,qa(ua(t,n),a)),yt(i.prototype,yt(n,ua(t,a))),pt[i.prop=e]=i,t.targetTest&&(gt.push(i),ft[e]=1),e=("css"===e?"CSS":e.charAt(0).toUpperCase()+e.substr(1))+"Plugin"}S(e,i),t.register&&t.register(Ee,i,_e)}else t&&Ct.push(t)}function zb(t,e,r){return(6*(t+=t<0?1:1>16,e>>8&St,e&St]:0:Et.black;if(!p){if(","===e.substr(-1)&&(e=e.substr(0,e.length-1)),Et[e])p=Et[e];else if("#"===e.charAt(0)){if(e.length<6&&(e="#"+(n=e.charAt(1))+n+(a=e.charAt(2))+a+(s=e.charAt(3))+s+(5===e.length?e.charAt(4)+e.charAt(4):"")),9===e.length)return[(p=parseInt(e.substr(1,6),16))>>16,p>>8&St,p&St,parseInt(e.substr(7),16)/255];p=[(e=parseInt(e.substr(1),16))>>16,e>>8&St,e&St]}else if("hsl"===e.substr(0,3))if(p=d=e.match(tt),r){if(~e.indexOf("="))return p=e.match(et),i&&p.length<4&&(p[3]=1),p}else o=+p[0]%360/360,u=p[1]/100,n=2*(h=p[2]/100)-(a=h<=.5?h*(u+1):h+u-h*u),3=U?u.endTime(!1):t._dur;return r(e)&&(isNaN(e)||e in o)?(a=e.charAt(0),s="%"===e.substr(-1),n=e.indexOf("="),"<"===a||">"===a?(0<=n&&(e=e.replace(/=/,"")),("<"===a?u._start:u.endTime(0<=u._repeat))+(parseFloat(e.substr(1))||0)*(s?(n<0?u:i).totalDuration()/100:1)):n<0?(e in o||(o[e]=h),o[e]):(a=parseFloat(e.charAt(n-1)+e.substr(n+1)),s&&i&&(a=a/100*($(i)?i[0]:i).totalDuration()),1=r&&te)return i;i=i._next}else for(i=t._last;i&&i._start>=r;){if("isPause"===i.data&&i._start=n._start)&&n._ts&&h!==n){if(n.parent!==this)return this.render(t,e,r);if(n.render(0=this.totalDuration()||!v&&_)&&(f!==this._start&&Math.abs(l)===Math.abs(this._ts)||this._lock||(!t&&g||!(v===m&&0=i&&(a instanceof Zt?e&&n.push(a):(r&&n.push(a),t&&n.push.apply(n,a.getChildren(!0,e,r)))),a=a._next;return n},e.getById=function getById(t){for(var e=this.getChildren(1,1,1),r=e.length;r--;)if(e[r].vars.id===t)return e[r]},e.remove=function remove(t){return r(t)?this.removeLabel(t):s(t)?this.killTweensOf(t):(ya(this,t),t===this._recent&&(this._recent=this._last),Aa(this))},e.totalTime=function totalTime(t,e){return arguments.length?(this._forcing=1,!this._dp&&this._ts&&(this._start=ja(Rt.time-(0r:!r||s.isActive())&&n.push(s):(i=s.getTweensOf(a,r)).length&&n.push.apply(n,i),s=s._next;return n},e.tweenTo=function tweenTo(t,e){e=e||{};var r,i=this,n=xt(i,t),a=e.startAt,s=e.onStart,o=e.onStartParams,u=e.immediateRender,h=Zt.to(i,qa({ease:e.ease||"none",lazy:!1,immediateRender:!1,time:n,overwrite:"auto",duration:e.duration||Math.abs((n-(a&&"time"in a?a.time:i._time))/i.timeScale())||X,onStart:function onStart(){if(i.pause(),!r){var t=e.duration||Math.abs((n-(a&&"time"in a?a.time:i._time))/i.timeScale());h._dur!==t&&Ra(h,t,0,1).render(h._time,!0,!0),r=1}s&&s.apply(h,o||[])}},e));return u?h.render(0):h},e.tweenFromTo=function tweenFromTo(t,e,r){return this.tweenTo(e,qa({startAt:{time:xt(this,t)}},r))},e.recent=function recent(){return this._recent},e.nextLabel=function nextLabel(t){return void 0===t&&(t=this._time),rb(this,xt(this,t))},e.previousLabel=function previousLabel(t){return void 0===t&&(t=this._time),rb(this,xt(this,t),1)},e.currentLabel=function currentLabel(t){return arguments.length?this.seek(t,!0):this.previousLabel(this._time+X)},e.shiftChildren=function shiftChildren(t,e,r){void 0===r&&(r=0);for(var i,n=this._first,a=this.labels;n;)n._start>=r&&(n._start+=t,n._end+=t),n=n._next;if(e)for(i in a)a[i]>=r&&(a[i]+=t);return Aa(this)},e.invalidate=function invalidate(t){var e=this._first;for(this._lock=0;e;)e.invalidate(t),e=e._next;return i.prototype.invalidate.call(this,t)},e.clear=function clear(t){void 0===t&&(t=!0);for(var e,r=this._first;r;)e=r._next,this.remove(r),r=e;return this._dp&&(this._time=this._tTime=this._pTime=0),t&&(this.labels={}),Aa(this)},e.totalDuration=function totalDuration(t){var e,r,i,n=0,a=this,s=a._last,o=U;if(arguments.length)return a.timeScale((a._repeat<0?a.duration():a.totalDuration())/(a.reversed()?-t:t));if(a._dirty){for(i=a.parent;s;)e=s._prev,s._dirty&&s.totalDuration(),o<(r=s._start)&&a._sort&&s._ts&&!a._lock?(a._lock=1,Ka(a,s,r-s._delay,1)._lock=0):o=r,r<0&&s._ts&&(n-=r,(!i&&!a._dp||i&&i.smoothChildTiming)&&(a._start+=r/a._ts,a._time-=r,a._tTime-=r),a.shiftChildren(-r,!1,-Infinity),o=0),s._end>n&&s._ts&&(n=s._end),s=e;Ra(a,a===I&&a._time>n?a._time:n,1,1),a._dirty=0}return a._tDur},Timeline.updateRoot=function updateRoot(t){if(I._ts&&(na(I,Ga(t,I)),f=Rt.frame),Rt.frame>=mt){mt+=q.autoSleep||120;var e=I._first;if((!e||!e._ts)&&q.autoSleep&&Rt._listeners.length<2){for(;e&&!e._ts;)e=e._next;e||Rt.sleep()}}},Timeline}(Ut);qa(Xt.prototype,{_lock:0,_hasPause:0,_forcing:0});function ac(t,e,i,n,a,o){var u,h,l,f;if(pt[t]&&!1!==(u=new pt[t]).init(a,u.rawVars?e[t]:function _processVars(t,e,i,n,a){if(s(t)&&(t=Kt(t,a,e,i,n)),!v(t)||t.style&&t.nodeType||$(t)||Z(t))return r(t)?Kt(t,a,e,i,n):t;var o,u={};for(o in t)u[o]=Kt(t[o],a,e,i,n);return u}(e[t],n,a,o,i),i,n,o)&&(i._pt=h=new _e(i._pt,a,t,0,1,u.render,u,0,u.priority),i!==c))for(l=i._ptLookup[i._targets.indexOf(a)],f=u._props.length;f--;)l[u._props[f]]=h;return u}function gc(t,r,e,i){var n,a,s=r.ease||i||"power1.inOut";if($(r))a=e[t]||(e[t]=[]),r.forEach(function(t,e){return a.push({t:e/(r.length-1)*100,v:t,e:s})});else for(n in r)a=e[n]||(e[n]=[]),"ease"===n||a.push({t:parseFloat(t),v:r[n],e:s})}var Nt,Wt,Qt=function _addPropTween(t,e,i,n,a,o,u,h,l,f){s(n)&&(n=n(a||0,t,o));var c,d=t[e],p="get"!==i?i:s(d)?l?t[e.indexOf("set")||!s(t["get"+e.substr(3)])?e:"get"+e.substr(3)](l):t[e]():d,_=s(d)?l?re:te:$t;if(r(n)&&(~n.indexOf("random(")&&(n=ob(n)),"="===n.charAt(1)&&(!(c=ka(p,n)+(Ya(p)||0))&&0!==c||(n=c))),!f||p!==n||Wt)return isNaN(p*n)||""===n?(d||e in t||Q(e,n),function _addComplexStringPropTween(t,e,r,i,n,a,s){var o,u,h,l,f,c,d,p,_=new _e(this._pt,t,e,0,1,ue,null,n),m=0,g=0;for(_.b=r,_.e=i,r+="",(d=~(i+="").indexOf("random("))&&(i=ob(i)),a&&(a(p=[r,i],t,e),r=p[0],i=p[1]),u=r.match(it)||[];o=it.exec(i);)l=o[0],f=i.substring(m,o.index),h?h=(h+1)%5:"rgba("===f.substr(-5)&&(h=1),l!==u[g++]&&(c=parseFloat(u[g-1])||0,_._pt={_next:_._pt,p:f||1===g?f:",",s:c,c:"="===l.charAt(1)?ka(c,l)-c:parseFloat(l)-c,m:h&&h<4?Math.round:0},m=it.lastIndex);return _.c=m")}),s.duration();else{for(l in u={},x)"ease"===l||"easeEach"===l||gc(l,x[l],u,x.easeEach);for(l in u)for(C=u[l].sort(function(t,e){return t.t-e.t}),o=D=0;o=t._tDur||e<0)&&t.ratio===u&&(u&&za(t,1),r||L||(At(t,u?"onComplete":"onReverseComplete",!0),t._prom&&t._prom()))}else t._zTime||(t._zTime=e)}(this,t,e,r);return this},e.targets=function targets(){return this._targets},e.invalidate=function invalidate(t){return t&&this.vars.runBackwards||(this._startAt=0),this._pt=this._op=this._onUpdate=this._lazy=this.ratio=0,this._ptLookup=[],this.timeline&&this.timeline.invalidate(t),z.prototype.invalidate.call(this,t)},e.resetTo=function resetTo(t,e,r,i){d||Rt.wake(),this._ts||this.play();var n,a=Math.min(this._dur,(this._dp._time-this._start)*this._ts);return this._initted||Gt(this,a),n=this._ease(a/this._dur),function _updatePropTweens(t,e,r,i,n,a,s){var o,u,h,l,f=(t._pt&&t._ptCache||(t._ptCache={}))[e];if(!f)for(f=t._ptCache[e]=[],h=t._ptLookup,l=t._targets.length;l--;){if((o=h[l][e])&&o.d&&o.d._pt)for(o=o.d._pt;o&&o.p!==e&&o.fp!==e;)o=o._next;if(!o)return Wt=1,t.vars[e]="+=0",Gt(t,s),Wt=0,1;f.push(o)}for(l=f.length;l--;)(o=(u=f[l])._pt||u).s=!i&&0!==i||n?o.s+(i||0)+a*o.c:i,o.c=r-o.s,u.e&&(u.e=ia(r)+Ya(u.e)),u.b&&(u.b=o.s+Ya(u.b))}(this,t,e,r,i,n,a)?this.resetTo(t,e,r,i):(Ia(this,0),this.parent||xa(this._dp,this,"_first","_last",this._dp._sort?"_start":0),this.render(0))},e.kill=function kill(t,e){if(void 0===e&&(e="all"),!(t||e&&"all"!==e))return this._lazy=this._pt=0,this.parent?tb(this):this;if(this.timeline){var i=this.timeline.totalDuration();return this.timeline.killTweensOf(t,e,Nt&&!0!==Nt.vars.overwrite)._first||tb(this),this.parent&&i!==this.timeline.totalDuration()&&Ra(this,this._dur*this.timeline._tDur/i,0,1),this}var n,a,s,o,u,h,l,f=this._targets,c=t?Ot(t):f,d=this._ptLookup,p=this._pt;if((!e||"all"===e)&&function _arraysMatch(t,e){for(var r=t.length,i=r===e.length;i&&r--&&t[r]===e[r];);return r<0}(f,c))return"all"===e&&(this._pt=0),tb(this);for(n=this._op=this._op||[],"all"!==e&&(r(e)&&(u={},ha(e,function(t){return u[t]=1}),e=u),e=function _addAliasesToVars(t,e){var r,i,n,a,s=t[0]?fa(t[0]).harness:0,o=s&&s.aliases;if(!o)return e;for(i in r=yt({},e),o)if(i in r)for(n=(a=o[i].split(",")).length;n--;)r[a[n]]=r[i];return r}(f,e)),l=f.length;l--;)if(~c.indexOf(f[l]))for(u in a=d[l],"all"===e?(n[l]=e,o=a,s={}):(s=n[l]=n[l]||{},o=e),o)(h=a&&a[u])&&("kill"in h.d&&!0!==h.d.kill(u)||ya(this,h,"_pt"),delete a[u]),"all"!==s&&(s[u]=1);return this._initted&&!this._pt&&p&&tb(this),this},Tween.to=function to(t,e,r){return new Tween(t,e,r)},Tween.from=function from(t,e){return Va(1,arguments)},Tween.delayedCall=function delayedCall(t,e,r,i){return new Tween(e,0,{immediateRender:!1,lazy:!1,overwrite:!1,delay:t,onComplete:e,onReverseComplete:e,onCompleteParams:r,onReverseCompleteParams:r,callbackScope:i})},Tween.fromTo=function fromTo(t,e,r){return Va(2,arguments)},Tween.set=function set(t,e){return e.duration=0,e.repeatDelay||(e.repeat=0),new Tween(t,e)},Tween.killTweensOf=function killTweensOf(t,e,r){return I.killTweensOf(t,e,r)},Tween}(Ut);qa(Zt.prototype,{_targets:[],_lazy:0,_startAt:0,_op:0,_onInit:0}),ha("staggerTo,staggerFrom,staggerFromTo",function(r){Zt[r]=function(){var t=new Xt,e=Mt.call(arguments,0);return e.splice("staggerFromTo"===r?5:4,0,0),t[r].apply(t,e)}});function oc(t,e,r){return t.setAttribute(e,r)}function wc(t,e,r,i){i.mSet(t,e,i.m.call(i.tween,r,i.mt),i)}var $t=function _setterPlain(t,e,r){return t[e]=r},te=function _setterFunc(t,e,r){return t[e](r)},re=function _setterFuncWithParam(t,e,r,i){return t[e](i.fp,r)},ne=function _getSetter(t,e){return s(t[e])?te:u(t[e])&&t.setAttribute?oc:$t},ae=function _renderPlain(t,e){return e.set(e.t,e.p,Math.round(1e6*(e.s+e.c*t))/1e6,e)},se=function _renderBoolean(t,e){return e.set(e.t,e.p,!!(e.s+e.c*t),e)},ue=function _renderComplexString(t,e){var r=e._pt,i="";if(!t&&e.b)i=e.b;else if(1===t&&e.e)i=e.e;else{for(;r;)i=r.p+(r.m?r.m(r.s+r.c*t):Math.round(1e4*(r.s+r.c*t))/1e4)+i,r=r._next;i+=e.c}e.set(e.t,e.p,i,e)},he=function _renderPropTweens(t,e){for(var r=e._pt;r;)r.r(t,r.d),r=r._next},fe=function _addPluginModifier(t,e,r,i){for(var n,a=this._pt;a;)n=a._next,a.p===i&&a.modifier(t,e,r),a=n},ce=function _killPropTweensOf(t){for(var e,r,i=this._pt;i;)r=i._next,i.p===t&&!i.op||i.op===t?ya(this,i,"_pt"):i.dep||(e=1),i=r;return!e},pe=function _sortPropTweensByPriority(t){for(var e,r,i,n,a=t._pt;a;){for(e=a._next,r=i;r&&r.pr>a.pr;)r=r._next;(a._prev=r?r._prev:n)?a._prev._next=a:i=a,(a._next=r)?r._prev=a:n=a,a=e}t._pt=i},_e=(PropTween.prototype.modifier=function modifier(t,e,r){this.mSet=this.mSet||this.set,this.set=wc,this.m=t,this.mt=r,this.tween=e},PropTween);function PropTween(t,e,r,i,n,a,s,o,u){this.t=e,this.s=i,this.c=n,this.p=r,this.r=a||ae,this.d=s||this,this.set=o||$t,this.pr=u||0,(this._next=t)&&(t._prev=this)}ha(vt+"parent,duration,ease,delay,overwrite,runBackwards,startAt,yoyo,immediateRender,repeat,repeatDelay,data,paused,reversed,lazy,callbackScope,stringFilter,id,yoyoEase,stagger,inherit,repeatRefresh,keyframes,autoRevert,scrollTrigger",function(t){return ft[t]=1}),ot.TweenMax=ot.TweenLite=Zt,ot.TimelineLite=ot.TimelineMax=Xt,I=new Xt({sortChildren:!1,defaults:V,autoRemoveChildren:!0,id:"root",smoothChildTiming:!0}),q.stringFilter=Fb;function Ec(t){return(ye[t]||Te).map(function(t){return t()})}function Fc(){var t=Date.now(),o=[];2((e,t,i)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class o{constructor(){i(this,"_locking"),i(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}function s(e,t){if(!e)throw new Error(t)}const r=34028234663852886e22,a=-34028234663852886e22,c=4294967295,d=2147483647,l=-2147483648;function u(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>d||ec||e<0)throw new Error("invalid uint 32: "+e)}function p(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>r||e({no:t.no,name:t.name,localName:e[t.no]}))))}function f(e,t,n){const i=Object.create(null),o=Object.create(null),s=[];for(const e of t){const t=y(e);s.push(t),i[e.name]=t,o[e.no]=t}return{typeName:e,values:s,findName:e=>i[e],findNumber:e=>o[e]}}function k(e,t,n){const i={};for(const e of t){const t=y(e);i[t.localName]=t.no,i[t.no]=t.localName}return v(i,e,t),i}function y(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class b{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType().runtime.bin,i=n.makeReadOptions(t);return n.readMessage(this,i.readerFactory(e),e.byteLength,i),this}fromJson(e,t){const n=this.getType(),i=n.runtime.json,o=i.makeReadOptions(t);return i.readMessage(n,e,o,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType().runtime.bin,n=t.makeWriteOptions(e),i=n.writerFactory();return t.writeMessage(this,i,n),i.finish()}toJson(e){const t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){var t;const n=this.toJson(e);return JSON.stringify(n,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function T(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<>>i,s=!(o>>>7==0&&0==t),r=255&(s?128|o:o);if(n.push(r),!s)return}const i=e>>>28&15|(7&t)<<4,o=!(t>>3==0);if(n.push(255&(o?128|i:i)),o){for(let e=3;e<31;e+=7){const i=t>>>e,o=!(i>>>7==0),s=255&(o?128|i:i);if(n.push(s),!o)return}n.push(t>>>31&1)}}const S=4294967296;function E(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,o=0;function s(t,s){const r=Number(e.slice(t,s));o*=n,i=i*n+r,i>=S&&(o+=i/S|0,i%=S)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),t?P(i,o):R(i,o)}function w(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(S*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let o=(16777215&e)+6777216*n+6710656*i,s=n+8147497*i,r=2*i;const a=1e7;return o>=a&&(s+=Math.floor(o/a),o%=a),s>=a&&(r+=Math.floor(s/a),s%=a),r.toString()+I(s)+I(o)}function R(e,t){return{lo:0|e,hi:0|t}}function P(e,t){return t=~t,e?e=1+~e:t+=1,R(e,t)}const I=e=>{const t=String(e);return"0000000".slice(t.length)+t};function O(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function _(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const D=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||io||t(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}const t=e=>s(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),n=e=>s(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),n(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),E(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),n(e),E(e)),dec:(e,t)=>function(e,t){let n=R(e,t);const i=2147483648&n.hi;i&&(n=P(n.lo,n.hi));const o=w(n.lo,n.hi);return i?"-"+o:o}(e,t),uDec:(e,t)=>w(e,t)}}();var M,x,A;function N(e,t,n){if(t===n)return!0;if(e==M.BYTES){if(!(t instanceof Uint8Array&&n instanceof Uint8Array))return!1;if(t.length!==n.length)return!1;for(let e=0;e>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(h(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return u(e),O(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){p(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){h(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){u(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return u(e),O(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=D.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=D.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=D.enc(e);return C(t.lo,t.hi,this.buf),this}sint64(e){let t=D.enc(e),n=t.hi>>31;return C(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=D.uEnc(e);return C(t.lo,t.hi,this.buf),this}}class F{constructor(e,t){this.varint64=T,this.uint32=_,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case A.Varint:for(;128&this.buf[this.pos++];);break;case A.Bit64:this.pos+=4;case A.Bit32:this.pos+=4;break;case A.LengthDelimited:let n=this.uint32();this.pos+=n;break;case A.StartGroup:for(;;){const[e,n]=this.tag();if(n===A.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return D.dec(...this.varint64())}uint64(){return D.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,D.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return D.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return D.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 B(e){const t=e.field.localName,n=Object.create(null);return n[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return L(t.T,t.L);case"message":const e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[n,()=>n[t]]}let V="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),q=[];for(let e=0;e>4,r=n,s=2;break;case 2:i[o++]=(15&r)<<4|(60&n)>>2,r=n,s=3;break;case 3:i[o++]=(3&r)<<6|n,s=0}}if(1==s)throw Error("invalid base64 string.");return i.subarray(0,o)},enc(e){let t,n="",i=0,o=0;for(let s=0;s>2],o=(3&t)<<4,i=1;break;case 1:n+=V[o|t>>4],o=(15&t)<<2,i=2;break;case 2:n+=V[o|t>>6],n+=V[63&t],i=0}return i&&(n+=V[o],n+="=",1==i&&(n+="=")),n}};function K(e,t,n){J(t,e);const i=t.runtime.bin.makeReadOptions(n),o=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[s,r]=B(t);for(const e of o)t.runtime.bin.readField(s,i.readerFactory(e.data),t.field,e.wireType,i);return r()}function H(e,t,n,i){J(t,e);const o=t.runtime.bin.makeReadOptions(i),s=t.runtime.bin.makeWriteOptions(i);if(G(e,t)){const n=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const r=s.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,n,r,s);const c=o.readerFactory(r.finish());for(;c.pose.no==t.field.no))}function J(e,t){s(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function z(e,t){const n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[n]:"enum"==e.kind?t[n]!==e.T.values[0].no:!U(e.T,t[n]);case"message":return void 0!==t[n];case"map":return Object.keys(t[n]).length>0}}function Q(e,t){const n=e.localName,i=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[n]={};break;case"enum":t[n]=i?e.T.values[0].no:void 0;break;case"scalar":t[n]=i?L(e.T,e.L):void 0;break;case"message":t[n]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(b.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const n=e.getType();return null!==n&&"function"==typeof n&&"typeName"in n&&"string"==typeof n.typeName&&(void 0===t||n.typeName==t.typeName)}function X(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}M.DOUBLE,M.FLOAT,M.INT64,M.UINT64,M.INT32,M.UINT32,M.BOOL,M.STRING,M.BYTES;const Z={ignoreUnknownFields:!1},$={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ee(e){return e?Object.assign(Object.assign({},Z),e):Z}function te(e){return e?Object.assign(Object.assign({},$),e):$}const ne=Symbol(),ie=Symbol();function oe(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function se(e,t,n,i,o){let r=n.localName;if(n.repeated){if(s("map"!=n.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(e)));switch(n.kind){case"message":a.push(n.T.fromJson(e,i));break;case"enum":const t=ce(n.T,e,i.ignoreUnknownFields,!0);t!==ie&&a.push(t);break;case"scalar":try{a.push(ae(n.T,e,n.L,!0))}catch(t){let i="cannot decode field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(e));throw t instanceof Error&&t.message.length>0&&(i+=": ".concat(t.message)),new Error(i)}}}}else if("map"==n.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(t)));const s=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(o.typeName,".").concat(n.name," from JSON: map value null"));let a;try{a=re(n.K,e)}catch(e){let i="cannot decode map key for field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}switch(n.V.kind){case"message":s[a]=n.V.T.fromJson(r,i);break;case"enum":const e=ce(n.V.T,r,i.ignoreUnknownFields,!0);e!==ie&&(s[a]=e);break;case"scalar":try{s[a]=ae(n.V.T,r,x.BIGINT,!0)}catch(e){let i="cannot decode map value for field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:r},r="value"),n.kind){case"message":const s=n.T;if(null===t&&"google.protobuf.Value"!=s.typeName)return;let a=e[r];Y(a)?a.fromJson(t,i):(e[r]=a=s.fromJson(t,i),s.fieldWrapper&&!n.oneof&&(e[r]=s.fieldWrapper.unwrapField(a)));break;case"enum":const c=ce(n.T,t,i.ignoreUnknownFields,!1);switch(c){case ne:Q(n,e);break;case ie:break;default:e[r]=c}break;case"scalar":try{const i=ae(n.T,t,n.L,!1);if(i===ne)Q(n,e);else e[r]=i}catch(e){let i="cannot decode field ".concat(o.typeName,".").concat(n.name," from JSON: ").concat(oe(t));throw e instanceof Error&&e.message.length>0&&(i+=": ".concat(e.message)),new Error(i)}}}function re(e,t){if(e===M.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return ae(e,t,x.BIGINT,!0).toString()}function ae(e,t,n,i){if(null===t)return i?L(e,n):ne;switch(e){case M.DOUBLE:case M.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const i=Number(t);if(Number.isNaN(i))break;if(!Number.isFinite(i))break;return e==M.FLOAT&&p(i),i;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:let o;if("number"==typeof t?o=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(o=Number(t)),void 0===o)break;return e==M.UINT32||e==M.FIXED32?h(o):u(o),o;case M.INT64:case M.SFIXED64:case M.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const s=D.parse(t);return n?s.toString():s;case M.FIXED64:case M.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const r=D.uParse(t);return n?r.toString():r;case M.BOOL:if("boolean"!=typeof t)break;return t;case M.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw new Error("invalid UTF8")}return t;case M.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return W.dec(t)}throw new Error}function ce(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?e.values[0].no:ne;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=e.findName(t);if(void 0!==i)return i.no;if(n)return ie}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(oe(t)))}function de(e){return!(!e.repeated&&"map"!=e.kind)||!e.oneof&&("message"!=e.kind&&(!e.opt&&!e.req))}function le(e,t,n){if("map"==e.kind){s("object"==typeof t&&null!=t);const i={},o=Object.entries(t);switch(e.V.kind){case"scalar":for(const[t,n]of o)i[t.toString()]=he(e.V.T,n);break;case"message":for(const[e,t]of o)i[e.toString()]=t.toJson(n);break;case"enum":const t=e.V.T;for(const[e,s]of o)i[e.toString()]=ue(t,s,n.enumAsInteger)}return n.emitDefaultValues||o.length>0?i:void 0}if(e.repeated){s(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n0?i:void 0}switch(e.kind){case"scalar":return he(e.T,t);case"enum":return ue(e.T,t,n.enumAsInteger);case"message":return X(e.T,t).toJson(n)}}function ue(e,t,n){var i;if(s("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const o=e.findNumber(t);return null!==(i=null==o?void 0:o.name)&&void 0!==i?i:t}function he(e,t){switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:case M.FIXED32:case M.UINT32:return s("number"==typeof t),t;case M.FLOAT:case M.DOUBLE:return s("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case M.STRING:return s("string"==typeof t),t;case M.BOOL:return s("boolean"==typeof t),t;case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:return s("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case M.BYTES:return s(t instanceof Uint8Array),W.enc(t)}}const pe=Symbol("@bufbuild/protobuf/unknown-fields"),me={readUnknownFields:!0,readerFactory:e=>new F(e)},ge={writeUnknownFields:!0,writerFactory:()=>new j};function ve(e){return e?Object.assign(Object.assign({},me),e):me}function fe(e){return e?Object.assign(Object.assign({},ge),e):ge}function ke(e,t,n,i,o){let{repeated:s,localName:r}=n;switch(n.oneof&&((e=e[n.oneof.localName]).case!=r&&delete e.value,e.case=r,r="value"),n.kind){case"scalar":case"enum":const a="enum"==n.kind?M.INT32:n.T;let c=Te;if("scalar"==n.kind&&n.L>0&&(c=be),s){let n=e[r];if(i==A.LengthDelimited&&a!=M.STRING&&a!=M.BYTES){let e=t.uint32()+t.pos;for(;t.pose.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function _e(e,t){const n=Me(e);return t?n:Ue(Le(n))}const De=Me;function Me(e){let t=!1;const n=[];for(let i=0;i"".concat(e,"$"),Le=e=>Ae.has(e)?Ne(e):e,Ue=e=>xe.has(e)?Ne(e):e;class je{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=_e(e,!1)}addField(e){s(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 e=0;enew Oe(e,(e=>function(e,t){var n,i,o,s,r,a;const c=[];let d;for(const t of"function"==typeof e?e():e){const e=t;if(e.localName=_e(t.name,void 0!==t.oneof),e.jsonName=null!==(n=t.jsonName)&&void 0!==n?n:De(t.name),e.repeated=null!==(i=t.repeated)&&void 0!==i&&i,"scalar"==t.kind&&(e.L=null!==(o=t.L)&&void 0!==o?o:x.BIGINT),e.delimited=null!==(s=t.delimited)&&void 0!==s&&s,e.req=null!==(r=t.req)&&void 0!==r&&r,e.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(e.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=M.BYTES&&t.T!=M.STRING),void 0!==t.oneof){const n="string"==typeof t.oneof?t.oneof:t.oneof.name;d&&d.name==n||(d=new je(n)),e.oneof=d,d.addField(e)}c.push(e)}return c}(e))),Ve=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const n=t.localName,i=e;if(t.repeated)i[n]=[];else switch(t.kind){case"oneof":i[n]={case:void 0};break;case"enum":i[n]=0;break;case"map":i[n]={};break;case"scalar":i[n]=L(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:ee,makeWriteOptions:te,readMessage(e,t,n,i){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(oe(t)));i=null!=i?i:new e;const o=new Map,s=n.typeRegistry;for(const[r,a]of Object.entries(t)){const t=e.fields.findJsonName(r);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const n=o.get(t.oneof);if(void 0!==n)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(n,'", "').concat(r,'"'));o.set(t.oneof,r)}se(i,a,t,n,e)}else{let t=!1;if((null==s?void 0:s.findExtension)&&r.startsWith("[")&&r.endsWith("]")){const o=s.findExtension(r.substring(1,r.length-1));if(o&&o.extendee.typeName==e.typeName){t=!0;const[e,s]=B(o);se(e,a,o.field,n,o),H(i,o,s(),n)}}if(!t&&!n.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(r,'" is unknown'))}}return i},writeMessage(e,t){const n=e.getType(),i={};let o;try{for(o of n.fields.byNumber()){if(!z(o,e)){if(o.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!de(o))continue}const n=le(o,o.oneof?e[o.oneof.localName].value:e[o.localName],t);void 0!==n&&(i[t.useProtoFieldName?o.name:o.jsonName]=n)}const s=t.typeRegistry;if(null==s?void 0:s.findExtensionFor)for(const o of n.runtime.bin.listUnknownFields(e)){const r=s.findExtensionFor(n.typeName,o.no);if(r&&G(e,r)){const n=K(e,r,t),o=le(r.field,n,t);void 0!==o&&(i[r.field.jsonName]=o)}}}catch(e){const t=o?"cannot encode field ".concat(n.typeName,".").concat(o.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),i=e instanceof Error?e.message:String(e);throw new Error(t+(i.length>0?": ".concat(i):""))}return i},readScalar:(e,t,n)=>ae(e,t,null!=n?n:x.BIGINT,!0),writeScalar(e,t,n){if(void 0!==t)return n||U(e,t)?he(e,t):void 0},debug:oe},bin:{makeReadOptions:ve,makeWriteOptions:fe,listUnknownFields(e){var t;return null!==(t=e[pe])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[pe]},writeUnknownFields(e,t){const n=e[pe];if(n)for(const e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,i){const o=e;Array.isArray(o[pe])||(o[pe]=[]),o[pe].push({no:t,wireType:n,data:i})},readMessage(e,t,n,i,o){const s=e.getType(),r=o?t.len:t.pos+n;let a,c;for(;t.posY(e,c)?e:new c(e)));else{const e=s[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?o[n]=Ie(e):o[n]=e:o[n]=Y(e,c)?e:new c(e)}}}},equals:(e,t,n)=>t===n||!(!t||!n)&&e.fields.byMember().every((e=>{const i=t[e.localName],o=n[e.localName];if(e.repeated){if(i.length!==o.length)return!1;switch(e.kind){case"message":return i.every(((t,n)=>e.T.equals(t,o[n])));case"scalar":return i.every(((t,n)=>N(e.T,t,o[n])));case"enum":return i.every(((e,t)=>N(M.INT32,e,o[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let t=i,n=o;return e.T.fieldWrapper&&(void 0===t||Y(t)||(t=e.T.fieldWrapper.wrapField(t)),void 0===n||Y(n)||(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case"enum":return N(M.INT32,i,o);case"scalar":return N(e.T,i,o);case"oneof":if(i.case!==o.case)return!1;const s=e.findField(i.case);if(void 0===s)return!0;switch(s.kind){case"message":return s.T.equals(i.value,o.value);case"enum":return N(M.INT32,i.value,o.value);case"scalar":return N(s.T,i.value,o.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const r=Object.keys(i).concat(Object.keys(o));switch(e.V.kind){case"message":const t=e.V.T;return r.every((e=>t.equals(i[e],o[e])));case"enum":return r.every((e=>N(M.INT32,i[e],o[e])));case"scalar":const n=e.V.T;return r.every((e=>N(n,i[e],o[e])))}}})),clone(e){const t=e.getType(),n=new t,i=n;for(const n of t.fields.byMember()){const t=e[n.localName];let o;if(n.repeated)o=t.map(Pe);else if("map"==n.kind){o=i[n.localName];for(const[e,n]of Object.entries(t))o[e]=Pe(n)}else o="oneof"==n.kind?n.findField(t.case)?{case:t.case,value:Pe(t.value)}:{case:void 0}:Pe(t);i[n.localName]=o}for(const n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return n}}),{newFieldList:Be,initFields:Ve}),makeMessageType(e,t,n){return function(e,t,n,i){var o;const s=null!==(o=null==i?void 0:i.localName)&&void 0!==o?o:t.substring(t.lastIndexOf(".")+1),r={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(r.prototype,new b),Object.assign(r,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary:(e,t)=>(new r).fromBinary(e,t),fromJson:(e,t)=>(new r).fromJson(e,t),fromJsonString:(e,t)=>(new r).fromJsonString(e,t),equals:(t,n)=>e.util.equals(r,t,n)}),r}(this,e,t,n)},makeEnum:k,makeEnumType:f,getEnumType:g,makeExtension(e,t,n){return function(e,t,n,i){let o;return{typeName:t,extendee:n,get field(){if(!o){const n="function"==typeof i?i():i;n.name=t.split(".").pop(),n.jsonName="[".concat(t,"]"),o=e.util.newFieldList([n]).list()[0]}return o},runtime:e}}(this,e,t,n)}});var Be,Ve;class qe extends b{constructor(e){super(),this.seconds=D.zero,this.nanos=0,Fe.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(Fe.json.debug(e)));const n=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(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(iDate.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=D.parse(i/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(tDate.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 n="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);n="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return qe.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new qe({seconds:D.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new qe).fromBinary(e,t)}static fromJson(e,t){return(new qe).fromJson(e,t)}static fromJsonString(e,t){return(new qe).fromJsonString(e,t)}static equals(e,t){return Fe.util.equals(qe,e,t)}}qe.runtime=Fe,qe.typeName="google.protobuf.Timestamp",qe.fields=Fe.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const We=Fe.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:qe},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ke,repeated:!0},{no:5,name:"events",kind:"message",T:Ge,repeated:!0}])),Ke=Fe.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:He,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),He=Fe.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:qe},{no:3,name:"value",kind:"scalar",T:2}])),Ge=Fe.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:qe},{no:7,name:"normalized_end_timestamp",kind:"message",T:qe,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),Je=Fe.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),ze=Fe.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"}]),Qe=Fe.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),Ye=Fe.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Xe=Fe.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Ze=Fe.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"}]),$e=Fe.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),et=Fe.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),tt=Fe.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),nt=Fe.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"}]),it=Fe.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"}]),ot=Fe.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),st=Fe.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"}]),rt=Fe.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:at,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:Vt}])),at=Fe.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),ct=Fe.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:Fe.getEnumType(Ze),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}])),dt=Fe.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:Fe.getEnumType(lt)},{no:4,name:"tracks",kind:"message",T:gt,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:ct},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:Fe.getEnumType(ut)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:Fe.getEnumType(nt)},{no:18,name:"kind_details",kind:"enum",T:Fe.getEnumType(ht),repeated:!0}])),lt=Fe.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ut=Fe.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"}]),ht=Fe.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),pt=Fe.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),mt=Fe.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:vt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Fe.getEnumType(ft)},{no:6,name:"sdp_cid",kind:"scalar",T:9}])),gt=Fe.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:Fe.getEnumType(Xe)},{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:Fe.getEnumType(Ze)},{no:10,name:"layers",kind:"message",T:vt,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:mt,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:Fe.getEnumType(pt)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Vt},{no:19,name:"audio_features",kind:"enum",T:Fe.getEnumType(st),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:Fe.getEnumType(Ye)}])),vt=Fe.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:Fe.getEnumType($e)},{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}])),ft=Fe.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"}]),kt=Fe.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:Fe.getEnumType(yt)},{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:Et,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Ct,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:wt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Rt,oneof:"value"},{no:8,name:"metrics",kind:"message",T:We,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:It,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ot,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:_t,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Dt,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ht,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Gt,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Jt,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:bt,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}])),yt=Fe.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),bt=Fe.makeMessageType("livekit.EncryptedPacket",(()=>[{no:1,name:"encryption_type",kind:"enum",T:Fe.getEnumType(pt)},{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}])),Tt=Fe.makeMessageType("livekit.EncryptedPacketPayload",(()=>[{no:1,name:"user",kind:"message",T:Et,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:It,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Ot,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:_t,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Dt,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Ht,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:Gt,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Jt,oneof:"value"}])),Ct=Fe.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:St,repeated:!0}])),St=Fe.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}])),Et=Fe.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}])),wt=Fe.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Rt=Fe.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:Pt,repeated:!0}])),Pt=Fe.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}])),It=Fe.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}])),Ot=Fe.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}])),_t=Fe.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Dt=Fe.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:Mt,oneof:"value"}])),Mt=Fe.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}])),xt=Fe.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),At=Fe.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:Fe.getEnumType(Nt)},{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}])),Nt=Fe.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Lt=Fe.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:Fe.getEnumType(Ut)},{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}])),Ut=Fe.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"}]),jt=Fe.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:Ft},{no:2,name:"screen",kind:"message",T:Ft},{no:3,name:"resume_connection",kind:"enum",T:Fe.getEnumType(tt)},{no:4,name:"disabled_codecs",kind:"message",T:Bt},{no:5,name:"force_relay",kind:"enum",T:Fe.getEnumType(tt)}])),Ft=Fe.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:Fe.getEnumType(tt)}])),Bt=Fe.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:at,repeated:!0},{no:2,name:"publish",kind:"message",T:at,repeated:!0}])),Vt=Fe.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),qt=Fe.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Wt=Fe.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:Fe.getEnumType(qt)},{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"}),Kt=Fe.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),Ht=Fe.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:Fe.getEnumType(pt)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Wt,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Kt,oneof:"content_header"}]),{localName:"DataStream_Header"}),Gt=Fe.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"}),Jt=Fe.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"}),zt=Fe.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}])),Qt=Fe.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:zt}])),Yt=Fe.makeMessageType("livekit.SubscribedAudioCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}])),Xt=Fe.makeMessageType("livekit.RoomAgentDispatch",(()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}])),Zt=Fe.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),$t=Fe.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),en=Fe.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),tn=Fe.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),nn=Fe.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"}]),on=Fe.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),sn=Fe.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"}]),rn=Fe.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:Fe.getEnumType(on)},{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:an,oneof:"output"},{no:7,name:"stream",kind:"message",T:gn,oneof:"output"},{no:10,name:"segments",kind:"message",T:cn,oneof:"output"},{no:8,name:"preset",kind:"enum",T:Fe.getEnumType(sn),oneof:"options"},{no:9,name:"advanced",kind:"message",T:vn,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:an,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:gn,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:cn,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:dn,repeated:!0},{no:16,name:"webhooks",kind:"message",T:Qt,repeated:!0}])),an=Fe.makeMessageType("livekit.EncodedFileOutput",(()=>[{no:1,name:"file_type",kind:"enum",T:Fe.getEnumType(Zt)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:ln,oneof:"output"},{no:4,name:"gcp",kind:"message",T:un,oneof:"output"},{no:5,name:"azure",kind:"message",T:hn,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:pn,oneof:"output"}])),cn=Fe.makeMessageType("livekit.SegmentedFileOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Fe.getEnumType($t)},{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:Fe.getEnumType(en)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:ln,oneof:"output"},{no:6,name:"gcp",kind:"message",T:un,oneof:"output"},{no:7,name:"azure",kind:"message",T:hn,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:pn,oneof:"output"}])),dn=Fe.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:Fe.getEnumType(tn)},{no:6,name:"image_codec",kind:"enum",T:Fe.getEnumType(Qe)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:ln,oneof:"output"},{no:9,name:"gcp",kind:"message",T:un,oneof:"output"},{no:10,name:"azure",kind:"message",T:hn,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:pn,oneof:"output"}])),ln=Fe.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:mn}])),un=Fe.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:mn}])),hn=Fe.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}])),pn=Fe.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}])),mn=Fe.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}])),gn=Fe.makeMessageType("livekit.StreamOutput",(()=>[{no:1,name:"protocol",kind:"enum",T:Fe.getEnumType(nn)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}])),vn=Fe.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:Fe.getEnumType(Je)},{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:Fe.getEnumType(ze)},{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}])),fn=Fe.makeMessageType("livekit.AutoParticipantEgress",(()=>[{no:1,name:"preset",kind:"enum",T:Fe.getEnumType(sn),oneof:"options"},{no:2,name:"advanced",kind:"message",T:vn,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:an,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:cn,repeated:!0}])),kn=Fe.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:ln,oneof:"output"},{no:3,name:"gcp",kind:"message",T:un,oneof:"output"},{no:4,name:"azure",kind:"message",T:hn,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:pn,oneof:"output"}])),yn=Fe.makeMessageType("livekit.RoomEgress",(()=>[{no:1,name:"room",kind:"message",T:rn},{no:3,name:"participant",kind:"message",T:fn},{no:2,name:"tracks",kind:"message",T:kn}])),bn=Fe.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:yn},{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:Xt,repeated:!0}])),Tn=Fe.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Cn=Fe.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Sn=Fe.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),En=Fe.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:An,oneof:"message"},{no:2,name:"answer",kind:"message",T:An,oneof:"message"},{no:3,name:"trickle",kind:"message",T:In,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Pn,oneof:"message"},{no:5,name:"mute",kind:"message",T:On,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ln,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Un,oneof:"message"},{no:8,name:"leave",kind:"message",T:Bn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:qn,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ni,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:si,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ci,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Wn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:di,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:jn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Fn,oneof:"message"}])),wn=Fe.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:_n,oneof:"message"},{no:2,name:"answer",kind:"message",T:An,oneof:"message"},{no:3,name:"offer",kind:"message",T:An,oneof:"message"},{no:4,name:"trickle",kind:"message",T:In,oneof:"message"},{no:5,name:"update",kind:"message",T:Nn,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Mn,oneof:"message"},{no:8,name:"leave",kind:"message",T:Bn,oneof:"message"},{no:9,name:"mute",kind:"message",T:On,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Hn,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Gn,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:zn,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Yn,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:$n,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ii,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:xn,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Dn,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:li,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:pi,oneof:"message"},{no:22,name:"request_response",kind:"message",T:mi,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:vi,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:oi,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Ti,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:ei,oneof:"message"}])),Rn=Fe.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:vt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:Fe.getEnumType(ft)}])),Pn=Fe.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:Fe.getEnumType(Xe)},{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:Fe.getEnumType(Ze)},{no:9,name:"layers",kind:"message",T:vt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Rn,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:Fe.getEnumType(pt)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:Fe.getEnumType(Ye)},{no:17,name:"audio_features",kind:"enum",T:Fe.getEnumType(st),repeated:!0}])),In=Fe.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:Fe.getEnumType(Tn)},{no:3,name:"final",kind:"scalar",T:8}])),On=Fe.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),_n=Fe.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:rt},{no:2,name:"participant",kind:"message",T:dt},{no:3,name:"other_participants",kind:"message",T:dt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Kn,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:jt},{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:At},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:at,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Dn=Fe.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Kn,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:jt},{no:3,name:"server_info",kind:"message",T:At},{no:4,name:"last_message_seq",kind:"scalar",T:13}])),Mn=Fe.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:gt}])),xn=Fe.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),An=Fe.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}}])),Nn=Fe.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:dt,repeated:!0}])),Ln=Fe.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:xt,repeated:!0}])),Un=Fe.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:Fe.getEnumType($e)},{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}])),jn=Fe.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:Fe.getEnumType(st),repeated:!0}])),Fn=Fe.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}])),Bn=Fe.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:Fe.getEnumType(nt)},{no:3,name:"action",kind:"enum",T:Fe.getEnumType(Vn)},{no:4,name:"regions",kind:"message",T:ui}])),Vn=Fe.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),qn=Fe.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:vt,repeated:!0}])),Wn=Fe.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}])),Kn=Fe.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}])),Hn=Fe.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:St,repeated:!0}])),Gn=Fe.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:rt}])),Jn=Fe.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:Fe.getEnumType(et)},{no:3,name:"score",kind:"scalar",T:2}])),zn=Fe.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Jn,repeated:!0}])),Qn=Fe.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:Fe.getEnumType(Cn)}])),Yn=Fe.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Qn,repeated:!0}])),Xn=Fe.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:Fe.getEnumType($e)},{no:2,name:"enabled",kind:"scalar",T:8}])),Zn=Fe.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Xn,repeated:!0}])),$n=Fe.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Xn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Zn,repeated:!0}])),ei=Fe.makeMessageType("livekit.SubscribedAudioCodecUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Yt,repeated:!0}])),ti=Fe.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}])),ni=Fe.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:ti,repeated:!0}])),ii=Fe.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}])),oi=Fe.makeMessageType("livekit.RoomMovedResponse",(()=>[{no:1,name:"room",kind:"message",T:rt},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:dt},{no:4,name:"other_participants",kind:"message",T:dt,repeated:!0}])),si=Fe.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:An},{no:2,name:"subscription",kind:"message",T:Ln},{no:3,name:"publish_tracks",kind:"message",T:Mn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ai,repeated:!0},{no:5,name:"offer",kind:"message",T:An},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:ri,repeated:!0}])),ri=Fe.makeMessageType("livekit.DataChannelReceiveState",(()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}])),ai=Fe.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:Fe.getEnumType(Tn)}])),ci=Fe.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:Fe.getEnumType(Sn),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"}])),di=Fe.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),li=Fe.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),ui=Fe.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:hi,repeated:!0}])),hi=Fe.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}])),pi=Fe.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:Fe.getEnumType(ot)}])),mi=Fe.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:Fe.getEnumType(gi)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:In,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Pn,oneof:"request"},{no:6,name:"mute",kind:"message",T:On,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Wn,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:jn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Fn,oneof:"request"}])),gi=Fe.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"}]),vi=Fe.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),fi=Fe.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}])),ki=Fe.makeMessageType("livekit.JoinRequest",(()=>[{no:1,name:"client_info",kind:"message",T:Lt},{no:2,name:"connection_settings",kind:"message",T:fi},{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:Pn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:An},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:Fe.getEnumType(it)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:si}])),yi=Fe.makeMessageType("livekit.WrappedJoinRequest",(()=>[{no:1,name:"compression",kind:"enum",T:Fe.getEnumType(bi)},{no:2,name:"join_request",kind:"scalar",T:12}])),bi=Fe.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Ti=Fe.makeMessageType("livekit.MediaSectionsRequirement",(()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}])),Ci=Fe.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:bn,opt:!0}])),Si=Fe.makeMessageType("livekit.TokenSourceResponse",(()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]));function Ei(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var wi,Ri={exports:{}},Pi=Ri.exports;var Ii,Oi,_i=(wi||(wi=1,function(e){var t,n;t=Pi,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],o={},s=null;function r(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),o=0;o=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=n||l,u.getLevel=function(){return null!=d?d:null!=a?a:r},u.setLevel=function(e,n){return d=m(e),!1!==n&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+n+";"}catch(e){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(r=m(s.getLevel())),c.call(u),s===u)for(var e in o)o[e].rebuild()},r=m(s?s.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(s=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=o[e];return t||(t=o[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return o},s.default=s,s},e.exports?e.exports=n():t.log=n()}(Ri)),Ri.exports);e.LogLevel=void 0,(Ii=e.LogLevel||(e.LogLevel={}))[Ii.trace=0]="trace",Ii[Ii.debug=1]="debug",Ii[Ii.info=2]="info",Ii[Ii.warn=3]="warn",Ii[Ii.error=4]="error",Ii[Ii.silent=5]="silent",e.LoggerNames=void 0,(Oi=e.LoggerNames||(e.LoggerNames={})).Default="livekit",Oi.Room="livekit-room",Oi.TokenSource="livekit-token-source",Oi.Participant="livekit-participant",Oi.Track="livekit-track",Oi.Publication="livekit-track-publication",Oi.Engine="livekit-engine",Oi.Signal="livekit-signal",Oi.PCManager="livekit-pc-manager",Oi.PCTransport="livekit-pc-transport",Oi.E2EE="lk-e2ee";let Di=_i.getLogger("livekit");const Mi=Object.values(e.LoggerNames).map((e=>_i.getLogger(e)));function xi(e){const t=_i.getLogger(e);return t.setDefaultLevel(Di.getLevel()),t}Di.setDefaultLevel(e.LogLevel.info);const Ai=_i.getLogger("lk-e2ee"),Ni=7e3,Li=[0,300,1200,2700,4800,Ni,Ni,Ni,Ni,Ni];class Ui{constructor(e){this._retryDelays=void 0!==e?[...e]:Li}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function ji(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vi(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Bi(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,o){(function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)})(i,o,(t=e[n](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var qi,Wi={exports:{}};var Ki=function(){if(qi)return Wi.exports;qi=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}Wi.exports=o,Wi.exports.once=function(e,t){return new Promise((function(n,i){function o(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",o),n([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,n)}(e,o,{once:!0})}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function c(e,t,n,i){var o,s,c,d;if(r(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),c=s[t]),void 0===c)c=s[t]=n,++e._eventsCount;else if("function"==typeof c?c=s[t]=i?[n,c]:[c,n]:i?c.unshift(n):c.push(n),(o=a(e))>0&&c.length>o&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=d.bind(i);return o.listener=n,i.wrapFn=o,o}function u(e,t,n){var i=e._events;if(void 0===i)return[];var o=i[t];return void 0===o?[]:"function"==typeof o?n?[o.listener||o]:[o]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(r=t[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,l=p(c,d);for(i=0;i=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;0===o?n.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},o.prototype.listeners=function(e){return u(this,e,!0)},o.prototype.rawListeners=function(e){return u(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},o.prototype.listenerCount=h,o.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Wi.exports}();let Hi=!0,Gi=!0;function Ji(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseFloat(i[n],10)}function zi(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return o.apply(this,arguments);const s=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),o.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(n))return s.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Qi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Hi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Yi(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Gi=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Xi(){if("object"==typeof window){if(Hi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Zi(e,t){Gi&&console.warn(e+" is deprecated, please use "+t+" instead.")}function $i(e){return"[object Object]"===Object.prototype.toString.call(e)}function eo(e){return $i(e)?Object.keys(e).reduce((function(t,n){const i=$i(e[n]),o=i?eo(e[n]):e[n],s=i&&!Object.keys(o).length;return void 0===o||s?t:Object.assign(t,{[n]:o})}),{}):e}function to(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?to(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{to(e,e.get(t),n)}))})))}function no(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",o=new Map;if(null===t)return o;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((n=>{n.type===i&&n.trackId===t.id&&to(e,n,o)}))})),o}const io=Xi;function oo(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const o=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[o("min",n)]=i.ideal,t.optional.push(e),e={},e[o("max",n)]=i.ideal,t.optional.push(e)):(e[o("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[o("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[o(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(t.version>=61)return o(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const r=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||r)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{let r=(n=n.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!r&&n.length&&t.includes("back")&&(r=n[n.length-1]),r&&(e.video.deviceId=s.exact?{exact:r.deviceId}:{ideal:r.deviceId}),e.video=i(e.video),io("chrome: "+JSON.stringify(e)),o(e)}))}e.video=i(e.video)}return io("chrome: "+JSON.stringify(e)),o(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){o(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return o(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function so(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function ro(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const o=new Event("track");o.track=n.track,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],this.dispatchEvent(o)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const o=new Event("track");o.track=n,o.receiver=i,o.transceiver={receiver:i},o.streams=[t.stream],this.dispatchEvent(o)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else zi(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function ao(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let o=n.apply(this,arguments);return o||(o=t(this,e),this._senders.push(o)),o};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function co(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>no(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),zi(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>no(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function lo(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),o.apply(this,arguments)}}function uo(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return lo(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const o=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],o=e._streams[i.id];n=n.replace(new RegExp(o.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},o.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))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((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[n.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=s(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const r=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],o=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),o.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),r.apply(this,arguments)):r.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ho(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function po(e,t){zi(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var mo=Object.freeze({__proto__:null,fixNegotiationNeeded:po,shimAddTrackRemoveTrack:uo,shimAddTrackRemoveTrackWithNative:lo,shimGetSendersWithDtmf:ao,shimGetUserMedia:oo,shimMediaStream:so,shimOnTrack:ro,shimPeerConnection:ho,shimSenderReceiverGetStats:co});function go(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Zi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function vo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function fo(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,o,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(o,s)}}function ko(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function yo(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),zi(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function bo(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Zi("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function To(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Co(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(n){const{sender:t}=i,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function So(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Eo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function wo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var Ro=Object.freeze({__proto__:null,shimAddTransceiver:Co,shimCreateAnswer:wo,shimCreateOffer:Eo,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:So,shimGetUserMedia:go,shimOnTrack:vo,shimPeerConnection:fo,shimRTCDataChannel:To,shimReceiverGetStats:yo,shimRemoveStream:bo,shimSenderGetStats:ko});function Po(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach((e=>{n.includes(e.track)&&this.removeTrack(e)}))})}}function Io(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function Oo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,o=t.setLocalDescription,s=t.setRemoteDescription,r=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],o=n.apply(this,[i]);return t?(o.then(e,t),Promise.resolve()):o},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],o=i.apply(this,[n]);return t?(o.then(e,t),Promise.resolve()):o};let a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i},t.addIceCandidate=a}function _o(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Do(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function Do(e){return e&&void 0!==e.video?Object.assign({},e,{video:eo(e.video)}):e}function Mo(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;nt.generateCertificate})}function xo(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ao(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function No(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Lo,Uo=Object.freeze({__proto__:null,shimAudioContext:No,shimCallbacksAPI:Oo,shimConstraints:Do,shimCreateOfferLegacy:Ao,shimGetUserMedia:_o,shimLocalStreamsAPI:Po,shimRTCIceServerUrls:Mo,shimRemoteStreamsAPI:Io,shimTrackEventTransceiver:xo}),jo={exports:{}};var Fo=(Lo||(Lo=1,function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],o=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&o?{usernameFragment:i.substring(12),password:o.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let o=3;o{n.headerExtensions.push(t.parseExtmap(e))}));const o=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{o.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let o=0;return n.codecs.forEach((e=>{e.maxptime>o&&(o=e.maxptime)})),o>0&&(i+="a=maxptime:"+o+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),o=-1!==i.fecMechanisms.indexOf("RED"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=r.length>0&&r[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),n.push(t),o&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const o=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=o.length>0,n.compound=0===o.length;const s=t.matchPrefix(e,"a=rtcp-mux");return n.mux=s.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const o=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return o.length>0?(n=o[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let o;i.length>0&&(o=parseInt(i[0].substring(19),10)),isNaN(o)&&(o=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:o};const r=t.matchPrefix(e,"a=sctpmap:");if(r.length>0){const e=r[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:o}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let o;const s=void 0!==n?n:2;return o=e||t.generateSessionId(),"v=0\r\no="+(i||"thisisadapterortc")+" "+o+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Wo(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||zi(e,"icecandidate",(e=>{if(e.candidate){const t=Bo.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Ko(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Bo.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=Bo.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),n=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(e),i=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const o=Bo.matchPrefix(e.sdp,"a=max-message-size:");return o.length>0?i=parseInt(o[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i}(arguments[0],e);let o;o=0===n&&0===i?Number.POSITIVE_INFINITY:0===n||0===i?Math.max(n,i):Math.min(n,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>o}),this._sctp=s}return n.apply(this,arguments)}}function Ho(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],o=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&o>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},zi(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Go(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function Jo(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function zo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Qo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var Yo=Object.freeze({__proto__:null,removeExtmapAllowMixed:Jo,shimAddIceCandidateNullOrEmpty:zo,shimConnectionState:Go,shimMaxMessageSize:Ko,shimParameterlessSetLocalDescription:Qo,shimRTCIceCandidate:qo,shimRTCIceCandidateRelayProtocol:Wo,shimSendThrowTypeError:Ho});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Xi,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){const e=n.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser="firefox",t.version=parseInt(Ji(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(Ji(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(Ji(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=Ji(n.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),o={browserDetails:i,commonShim:Yo,extractVersion:Ji,disableLog:Qi,disableWarnings:Yi,sdp:Vo};switch(i.browser){case"chrome":if(!mo||!ho||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),o;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),o;n("adapter.js shimming chrome."),o.browserShim=mo,zo(e,i),Qo(e),oo(e,i),so(e),ho(e,i),ro(e),uo(e,i),ao(e),co(e),po(e,i),qo(e),Wo(e),Go(e),Ko(e,i),Ho(e),Jo(e,i);break;case"firefox":if(!Ro||!fo||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),o;n("adapter.js shimming firefox."),o.browserShim=Ro,zo(e,i),Qo(e),go(e,i),fo(e,i),vo(e),bo(e),ko(e),yo(e),To(e),Co(e),So(e),Eo(e),wo(e),qo(e),Go(e),Ko(e,i),Ho(e);break;case"safari":if(!Uo||!t.shimSafari)return n("Safari shim is not included in this adapter release."),o;n("adapter.js shimming safari."),o.browserShim=Uo,zo(e,i),Qo(e),Mo(e),Ao(e),Oo(e),Po(e),Io(e),xo(e),_o(e),No(e),qo(e),Wo(e),Ko(e,i),Ho(e),Jo(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Xo="AES-GCM",Zo="lk_e2ee",$o={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};var es,ts;function ns(){return os()||is()}function is(){return void 0!==window.RTCRtpScriptTransform}function os(){return void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams}function ss(e){return Fi(this,void 0,void 0,(function*(){let t=new TextEncoder;return yield crypto.subtle.importKey("raw",t.encode(e),{name:"PBKDF2"},!1,["deriveBits","deriveKey"])}))}function rs(e){return Fi(this,void 0,void 0,(function*(){return yield crypto.subtle.importKey("raw",e,"HKDF",!1,["deriveBits","deriveKey"])}))}function as(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}e.KeyProviderEvent=void 0,(es=e.KeyProviderEvent||(e.KeyProviderEvent={})).SetKey="setKey",es.RatchetRequest="ratchetRequest",es.KeyRatcheted="keyRatcheted",e.KeyHandlerEvent=void 0,(e.KeyHandlerEvent||(e.KeyHandlerEvent={})).KeyRatcheted="keyRatcheted",e.EncryptionEvent=void 0,(ts=e.EncryptionEvent||(e.EncryptionEvent={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",ts.EncryptionError="encryptionError",e.CryptorEvent=void 0,(e.CryptorEvent||(e.CryptorEvent={})).Error="cryptorError";function cs(e){var t,n,i,o,s;if("sipDtmf"!==(null===(t=e.value)||void 0===t?void 0:t.case)&&"metrics"!==(null===(n=e.value)||void 0===n?void 0:n.case)&&"speaker"!==(null===(i=e.value)||void 0===i?void 0:i.case)&&"transcription"!==(null===(o=e.value)||void 0===o?void 0:o.case)&&"encryptedPacket"!==(null===(s=e.value)||void 0===s?void 0:s.case))return new Tt({value:e.value})}class ds extends Ki.EventEmitter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.onKeyRatcheted=(e,t,n)=>{Di.debug("key ratcheted event received",{ratchetResult:e,participantId:t,keyIndex:n})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},$o),t),this.on(e.KeyProviderEvent.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(t,n,i){const o={key:t,participantIdentity:n,keyIndex:i};if(!this.options.sharedKey&&!n)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(null!=n?n:"shared","-").concat(null!=i?i:0),o),this.emit(e.KeyProviderEvent.SetKey,o)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(t,n){this.emit(e.KeyProviderEvent.RatchetRequest,t,n)}}class ls extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var us,hs,ps,ms,gs,vs,fs,ks;e.ConnectionErrorReason=void 0,(us=e.ConnectionErrorReason||(e.ConnectionErrorReason={}))[us.NotAllowed=0]="NotAllowed",us[us.ServerUnreachable=1]="ServerUnreachable",us[us.InternalError=2]="InternalError",us[us.Cancelled=3]="Cancelled",us[us.LeaveRequest=4]="LeaveRequest",us[us.Timeout=5]="Timeout";class ys extends ls{constructor(t,n,i,o){super(1,t),this.name="ConnectionError",this.status=i,this.reason=n,this.context=o,this.reasonName=e.ConnectionErrorReason[n]}}class bs extends ls{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class Ts extends ls{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class Cs extends ls{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class Ss extends ls{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Es extends ls{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class ws extends ls{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Rs extends ls{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:gi[t]}}e.DataStreamErrorReason=void 0,(hs=e.DataStreamErrorReason||(e.DataStreamErrorReason={}))[hs.AlreadyOpened=0]="AlreadyOpened",hs[hs.AbnormalEnd=1]="AbnormalEnd",hs[hs.DecodeFailed=2]="DecodeFailed",hs[hs.LengthExceeded=3]="LengthExceeded",hs[hs.Incomplete=4]="Incomplete",hs[hs.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",hs[hs.EncryptionTypeMismatch=8]="EncryptionTypeMismatch";class Ps extends ls{constructor(t,n){super(16,t),this.name="DataStreamError",this.reason=n,this.reasonName=e.DataStreamErrorReason[n]}}e.MediaDeviceFailure=void 0,(ps=e.MediaDeviceFailure||(e.MediaDeviceFailure={})).PermissionDenied="PermissionDenied",ps.NotFound="NotFound",ps.DeviceInUse="DeviceInUse",ps.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(e.MediaDeviceFailure||(e.MediaDeviceFailure={})),e.CryptorErrorReason=void 0,(ms=e.CryptorErrorReason||(e.CryptorErrorReason={}))[ms.InvalidKey=0]="InvalidKey",ms[ms.MissingKey=1]="MissingKey",ms[ms.InternalError=2]="InternalError";e.RoomEvent=void 0,(gs=e.RoomEvent||(e.RoomEvent={})).Connected="connected",gs.Reconnecting="reconnecting",gs.SignalReconnecting="signalReconnecting",gs.Reconnected="reconnected",gs.Disconnected="disconnected",gs.ConnectionStateChanged="connectionStateChanged",gs.Moved="moved",gs.MediaDevicesChanged="mediaDevicesChanged",gs.ParticipantConnected="participantConnected",gs.ParticipantDisconnected="participantDisconnected",gs.TrackPublished="trackPublished",gs.TrackSubscribed="trackSubscribed",gs.TrackSubscriptionFailed="trackSubscriptionFailed",gs.TrackUnpublished="trackUnpublished",gs.TrackUnsubscribed="trackUnsubscribed",gs.TrackMuted="trackMuted",gs.TrackUnmuted="trackUnmuted",gs.LocalTrackPublished="localTrackPublished",gs.LocalTrackUnpublished="localTrackUnpublished",gs.LocalAudioSilenceDetected="localAudioSilenceDetected",gs.ActiveSpeakersChanged="activeSpeakersChanged",gs.ParticipantMetadataChanged="participantMetadataChanged",gs.ParticipantNameChanged="participantNameChanged",gs.ParticipantAttributesChanged="participantAttributesChanged",gs.ParticipantActive="participantActive",gs.RoomMetadataChanged="roomMetadataChanged",gs.DataReceived="dataReceived",gs.SipDTMFReceived="sipDTMFReceived",gs.TranscriptionReceived="transcriptionReceived",gs.ConnectionQualityChanged="connectionQualityChanged",gs.TrackStreamStateChanged="trackStreamStateChanged",gs.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",gs.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",gs.AudioPlaybackStatusChanged="audioPlaybackChanged",gs.VideoPlaybackStatusChanged="videoPlaybackChanged",gs.MediaDevicesError="mediaDevicesError",gs.ParticipantPermissionsChanged="participantPermissionsChanged",gs.SignalConnected="signalConnected",gs.RecordingStatusChanged="recordingStatusChanged",gs.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",gs.EncryptionError="encryptionError",gs.DCBufferStatusChanged="dcBufferStatusChanged",gs.ActiveDeviceChanged="activeDeviceChanged",gs.ChatMessage="chatMessage",gs.LocalTrackSubscribed="localTrackSubscribed",gs.MetricsReceived="metricsReceived",e.ParticipantEvent=void 0,(vs=e.ParticipantEvent||(e.ParticipantEvent={})).TrackPublished="trackPublished",vs.TrackSubscribed="trackSubscribed",vs.TrackSubscriptionFailed="trackSubscriptionFailed",vs.TrackUnpublished="trackUnpublished",vs.TrackUnsubscribed="trackUnsubscribed",vs.TrackMuted="trackMuted",vs.TrackUnmuted="trackUnmuted",vs.LocalTrackPublished="localTrackPublished",vs.LocalTrackUnpublished="localTrackUnpublished",vs.LocalTrackCpuConstrained="localTrackCpuConstrained",vs.LocalSenderCreated="localSenderCreated",vs.ParticipantMetadataChanged="participantMetadataChanged",vs.ParticipantNameChanged="participantNameChanged",vs.DataReceived="dataReceived",vs.SipDTMFReceived="sipDTMFReceived",vs.TranscriptionReceived="transcriptionReceived",vs.IsSpeakingChanged="isSpeakingChanged",vs.ConnectionQualityChanged="connectionQualityChanged",vs.TrackStreamStateChanged="trackStreamStateChanged",vs.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",vs.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",vs.TrackCpuConstrained="trackCpuConstrained",vs.MediaDevicesError="mediaDevicesError",vs.AudioStreamAcquired="audioStreamAcquired",vs.ParticipantPermissionsChanged="participantPermissionsChanged",vs.PCTrackAdded="pcTrackAdded",vs.AttributesChanged="attributesChanged",vs.LocalTrackSubscribed="localTrackSubscribed",vs.ChatMessage="chatMessage",vs.Active="active",e.EngineEvent=void 0,(fs=e.EngineEvent||(e.EngineEvent={})).TransportsCreated="transportsCreated",fs.Connected="connected",fs.Disconnected="disconnected",fs.Resuming="resuming",fs.Resumed="resumed",fs.Restarting="restarting",fs.Restarted="restarted",fs.SignalResumed="signalResumed",fs.SignalRestarted="signalRestarted",fs.Closing="closing",fs.MediaTrackAdded="mediaTrackAdded",fs.ActiveSpeakersUpdate="activeSpeakersUpdate",fs.DataPacketReceived="dataPacketReceived",fs.RTPVideoMapUpdate="rtpVideoMapUpdate",fs.DCBufferStatusChanged="dcBufferStatusChanged",fs.ParticipantUpdate="participantUpdate",fs.RoomUpdate="roomUpdate",fs.SpeakersChanged="speakersChanged",fs.StreamStateChanged="streamStateChanged",fs.ConnectionQualityUpdate="connectionQualityUpdate",fs.SubscriptionError="subscriptionError",fs.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",fs.RemoteMute="remoteMute",fs.SubscribedQualityUpdate="subscribedQualityUpdate",fs.LocalTrackUnpublished="localTrackUnpublished",fs.LocalTrackSubscribed="localTrackSubscribed",fs.Offline="offline",fs.SignalRequestResponse="signalRequestResponse",fs.SignalConnected="signalConnected",fs.RoomMoved="roomMoved",e.TrackEvent=void 0,(ks=e.TrackEvent||(e.TrackEvent={})).Message="message",ks.Muted="muted",ks.Unmuted="unmuted",ks.Restarted="restarted",ks.Ended="ended",ks.Subscribed="subscribed",ks.Unsubscribed="unsubscribed",ks.CpuConstrained="cpuConstrained",ks.UpdateSettings="updateSettings",ks.UpdateSubscription="updateSubscription",ks.AudioPlaybackStarted="audioPlaybackStarted",ks.AudioPlaybackFailed="audioPlaybackFailed",ks.AudioSilenceDetected="audioSilenceDetected",ks.VisibilityChanged="visibilityChanged",ks.VideoDimensionsChanged="videoDimensionsChanged",ks.VideoPlaybackStarted="videoPlaybackStarted",ks.VideoPlaybackFailed="videoPlaybackFailed",ks.ElementAttached="elementAttached",ks.ElementDetached="elementDetached",ks.UpstreamPaused="upstreamPaused",ks.UpstreamResumed="upstreamResumed",ks.SubscriptionPermissionChanged="subscriptionPermissionChanged",ks.SubscriptionStatusChanged="subscriptionStatusChanged",ks.SubscriptionFailed="subscriptionFailed",ks.TrackProcessorUpdate="trackProcessorUpdate",ks.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",ks.TranscriptionReceived="transcriptionReceived",ks.TimeSyncUpdate="timeSyncUpdate",ks.PreConnectBufferFlushed="preConnectBufferFlushed";const Is=/version\/(\d+(\.?_?\d+)+)/i;let Os;function _s(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const n=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===Os||t){const e=Ds.find((e=>{let{test:t}=e;return t.test(n)}));Os=null==e?void 0:e.describe(n)}return Os}const Ds=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:Ms(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:xs(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:Ms(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:xs(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:Ms(Is,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:xs(e)})}];function Ms(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const i=t.match(e);return i&&i.length>=n&&i[n]||""}function xs(e){return e.includes("mac os")?Ms(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}const As="2.15.16";class Ns{}Ns.setTimeout=function(){return setTimeout(...arguments)},Ns.setInterval=function(){return setInterval(...arguments)},Ns.clearTimeout=function(){return clearTimeout(...arguments)},Ns.clearInterval=function(){return clearInterval(...arguments)};const Ls=[];var Us;e.VideoQuality=void 0,(Us=e.VideoQuality||(e.VideoQuality={}))[Us.LOW=0]="LOW",Us[Us.MEDIUM=1]="MEDIUM",Us[Us.HIGH=2]="HIGH";class js extends Ki.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var o;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=js.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Di,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=xi(null!==(o=i.loggerName)&&void 0!==o?o:e.LoggerNames.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=js.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ia(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n="audio";this.kind===js.Kind.Video&&(n="video"),0===this.attachedElements.length&&this.kind===js.Kind.Video&&this.addAppVisibilityListener(),t||("audio"===n&&(Ls.forEach((e=>{null!==e.parentElement||t||(t=e)})),t&&Ls.splice(Ls.indexOf(t),1)),t||(t=document.createElement(n))),this.attachedElements.includes(t)||this.attachedElements.push(t),Fs(this.mediaStreamTrack,t);const i=t.srcObject.getTracks(),o=i.some((e=>"audio"===e.kind));return t.play().then((()=>{this.emit(o?e.TrackEvent.AudioPlaybackStarted:e.TrackEvent.VideoPlaybackStarted)})).catch((n=>{"NotAllowedError"===n.name?this.emit(o?e.TrackEvent.AudioPlaybackFailed:e.TrackEvent.VideoPlaybackFailed,n):"AbortError"===n.name?Di.debug("".concat(o?"audio":"video"," playback aborted, likely due to new play request")):Di.warn("could not playback ".concat(o?"audio":"video"),n),o&&t&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===n.name&&(t.muted=!0,t.play().catch((()=>{})))})),this.emit(e.TrackEvent.ElementAttached,t),t}detach(t){try{if(t){Bs(this.mediaStreamTrack,t);const n=this.attachedElements.indexOf(t);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)),t}const n=[];return this.attachedElements.forEach((t=>{Bs(this.mediaStreamTrack,t),n.push(t),this.recycleElement(t),this.emit(e.TrackEvent.ElementDetached,t)})),this.attachedElements=[],n}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=xi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Ls.forEach((e=>{e.parentElement||(t=!1)})),t&&Ls.push(e)}}handleAppVisibilityChanged(){return Fi(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==js.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){pr()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){pr()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fs(e,t){let n,i;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,i="audio"===e.kind?n.getAudioTracks():n.getVideoTracks(),i.includes(e)||(i.forEach((e=>{n.removeTrack(e)})),n.addTrack(e)),dr()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===n.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(dr()||ar())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=n,t.play().catch((()=>{}))}),0))}function Bs(e,t){if(t.srcObject instanceof MediaStream){const n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}!function(e){let t,n,i;!function(e){e.Audio="audio",e.Video="video",e.Unknown="unknown"}(t=e.Kind||(e.Kind={})),function(e){e.Camera="camera",e.Microphone="microphone",e.ScreenShare="screen_share",e.ScreenShareAudio="screen_share_audio",e.Unknown="unknown"}(n=e.Source||(e.Source={})),function(e){e.Active="active",e.Paused="paused",e.Unknown="unknown"}(i=e.StreamState||(e.StreamState={})),e.kindToProto=function(e){switch(e){case t.Audio:return Xe.AUDIO;case t.Video:return Xe.VIDEO;default:return Xe.DATA}},e.kindFromProto=function(e){switch(e){case Xe.AUDIO:return t.Audio;case Xe.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return Ze.CAMERA;case n.Microphone:return Ze.MICROPHONE;case n.ScreenShare:return Ze.SCREEN_SHARE;case n.ScreenShareAudio:return Ze.SCREEN_SHARE_AUDIO;default:return Ze.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case Ze.CAMERA:return n.Camera;case Ze.MICROPHONE:return n.Microphone;case Ze.SCREEN_SHARE:return n.ScreenShare;case Ze.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case Cn.ACTIVE:return i.Active;case Cn.PAUSED:return i.Paused;default:return i.Unknown}}}(js||(js={}));class Vs{constructor(e,t,n,i,o){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===n)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,priority:o}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const qs=["opus","red"],Ws=["vp8","h264"],Ks=["vp8","h264","vp9","av1","h265"];function Hs(e){return!!Ws.find((t=>t===e))}const Gs=Hs;var Js,zs;e.BackupCodecPolicy=void 0,(Js=e.BackupCodecPolicy||(e.BackupCodecPolicy={}))[Js.PREFER_REGRESSION=0]="PREFER_REGRESSION",Js[Js.SIMULCAST=1]="SIMULCAST",Js[Js.REGRESSION=2]="REGRESSION",e.AudioPresets=void 0,(zs=e.AudioPresets||(e.AudioPresets={})).telephone={maxBitrate:12e3},zs.speech={maxBitrate:24e3},zs.music={maxBitrate:48e3},zs.musicStereo={maxBitrate:64e3},zs.musicHighQuality={maxBitrate:96e3},zs.musicHighQualityStereo={maxBitrate:128e3};const Qs={h90:new Vs(160,90,9e4,20),h180:new Vs(320,180,16e4,20),h216:new Vs(384,216,18e4,20),h360:new Vs(640,360,45e4,20),h540:new Vs(960,540,8e5,25),h720:new Vs(1280,720,17e5,30),h1080:new Vs(1920,1080,3e6,30),h1440:new Vs(2560,1440,5e6,30),h2160:new Vs(3840,2160,8e6,30)},Ys={h120:new Vs(160,120,7e4,20),h180:new Vs(240,180,125e3,20),h240:new Vs(320,240,14e4,20),h360:new Vs(480,360,33e4,20),h480:new Vs(640,480,5e5,20),h540:new Vs(720,540,6e5,25),h720:new Vs(960,720,13e5,30),h1080:new Vs(1440,1080,23e5,30),h1440:new Vs(1920,1440,38e5,30)},Xs={h360fps3:new Vs(640,360,2e5,3,"medium"),h360fps15:new Vs(640,360,4e5,15,"medium"),h720fps5:new Vs(1280,720,8e5,5,"medium"),h720fps15:new Vs(1280,720,15e5,15,"medium"),h720fps30:new Vs(1280,720,2e6,30,"medium"),h1080fps15:new Vs(1920,1080,25e5,15,"medium"),h1080fps30:new Vs(1920,1080,5e6,30,"medium"),original:new Vs(0,0,7e6,30,"medium")},Zs="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function $s(e){return Fi(this,void 0,void 0,(function*(){return new Promise((t=>Ns.setTimeout(t,e)))}))}function er(){return"addTransceiver"in RTCPeerConnection.prototype}function tr(){return"addTrack"in RTCPeerConnection.prototype}function nr(){if(!("getCapabilities"in RTCRtpSender))return!1;if(dr()||ar())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/av1"===n.mimeType.toLowerCase()){t=!0;break}return t}function ir(){if(!("getCapabilities"in RTCRtpSender))return!1;if(ar())return!1;if(dr()){const e=_s();if((null==e?void 0:e.version)&&br(e.version,"16")<0)return!1;if("iOS"===(null==e?void 0:e.os)&&(null==e?void 0:e.osVersion)&&br(e.osVersion,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const n of e.codecs)if("video/vp9"===n.mimeType.toLowerCase()){t=!0;break}return t}function or(e){return"av1"===e||"vp9"===e}function sr(e){return!(!document||lr())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function rr(){return"undefined"!=typeof RTCPeerConnection&&(er()||tr())}function ar(){var e;return"Firefox"===(null===(e=_s())||void 0===e?void 0:e.name)}function cr(){const e=_s();return!!e&&"Chrome"===e.name&&"iOS"!==e.os}function dr(){var e;return"Safari"===(null===(e=_s())||void 0===e?void 0:e.name)}function lr(){const e=_s();return"Safari"===(null==e?void 0:e.name)||"iOS"===(null==e?void 0:e.os)}function ur(){const e=_s();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&br(e.osVersion,"17")>=0}function hr(){var e,t;return!!pr()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function pr(){return"undefined"!=typeof document}function mr(){return"ReactNative"==navigator.product}function gr(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function vr(e){return gr(e)?e.hostname.split(".")[0]:null}function fr(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function kr(){if(!mr())return;let e=fr();return e?e.platform:void 0}function yr(){if(pr())return window.devicePixelRatio;if(mr()){let e=fr();if(e)return e.devicePixelRatio}return 1}function br(e,t){const n=e.split("."),i=t.split("."),o=Math.min(n.length,i.length);for(let e=0;es)return 1;if(t(Sr||(Sr=new ResizeObserver(Tr)),Sr);let wr=null;const Rr=()=>(wr||(wr=new IntersectionObserver(Cr,{root:null,rootMargin:"0px"})),wr);let Pr,Ir;function Or(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=document.createElement("canvas");o.width=e,o.height=t;const s=o.getContext("2d");null==s||s.fillRect(0,0,o.width,o.height),i&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());const r=o.captureStream(),[a]=r.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=n,a}function _r(){if(!Ir){const e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);const i=e.createMediaStreamDestination();if(t.connect(n),n.connect(i),t.start(),[Ir]=i.stream.getAudioTracks(),!Ir)throw Error("Could not get empty media stream audio track");Ir.enabled=!1}return Ir.clone()}class Dr{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise(((t,n)=>Fi(this,void 0,void 0,(function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})))).finally((()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)}))}}function Mr(e){return Ks.includes(e)}function xr(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(void 0!==e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(void 0!==e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function Ar(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function Nr(t){switch(t.reason){case e.ConnectionErrorReason.LeaveRequest:return t.context;case e.ConnectionErrorReason.Cancelled:return nt.CLIENT_INITIATED;case e.ConnectionErrorReason.NotAllowed:return nt.USER_REJECTED;case e.ConnectionErrorReason.ServerUnreachable:return nt.JOIN_FAILURE;default:return nt.UNKNOWN_REASON}}function Lr(e){return void 0!==e?Number(e):void 0}function Ur(e){return void 0!==e?BigInt(e):void 0}function jr(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Fr(e){return!!e&&e.kind==js.Kind.Audio}function Br(e){return!!e&&e.kind==js.Kind.Video}function Vr(e){return jr(e)&&Br(e)}function qr(e){return jr(e)&&Fr(e)}function Wr(e){return!!e&&!e.isLocal}function Kr(e){return!!e&&!e.isLocal}function Hr(e){return Wr(e)&&Br(e)}function Gr(e){return e.isLocal}function Jr(e,t,n){var i,o,s,r;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=oa(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==n?void 0:n.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(zr(h.audio,t),null!==(i=(s=h.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(zr(h.video,n),null!==(o=(r=h.video).deviceId)&&void 0!==o||(r.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function zr(e,t){return Object.keys(t).forEach((n=>{void 0===e[n]&&(e[n]=t[n])})),e}function Qr(e){var t,n,i,o;const s={};if(e.video)if("object"==typeof e.video){const n={},o=n,r=e.video;Object.keys(r).forEach((e=>{if("resolution"===e)zr(o,r.resolution);else o[e]=r[e]})),s.video=n,null!==(t=(i=s.video).deviceId)&&void 0!==t||(i.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}};else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(n=(o=s.audio).deviceId)&&void 0!==n||(o.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Yr(e){return Fi(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const n=Xr();if(n){const i=n.createAnalyser();i.fftSize=2048;const o=i.frequencyBinCount,s=new Uint8Array(o);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield $s(t),i.getByteTimeDomainData(s);const r=s.some((e=>128!==e&&0!==e));return n.close(),!r}return!1}()}))}function Xr(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const n=new t({latencyHint:"interactive"});if("suspended"===n.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Fi(this,void 0,void 0,(function*(){var t;try{"suspended"===n.state&&(yield n.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}finally{null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}}));n.addEventListener("statechange",(()=>{var t;"closed"===n.state&&(null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e))})),window.document.body.addEventListener("click",e)}return n}}function Zr(e){return"audioinput"===e?js.Source.Microphone:"videoinput"===e?js.Source.Camera:js.Source.Unknown}function $r(e){return e===js.Source.Microphone?"audioinput":e===js.Source.Camera?"videoinput":void 0}function ea(e){var t,n;let i=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(i="boolean"==typeof i?{}:i,i=dr()?Object.assign(Object.assign({},i),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},i),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(n=e.audio)&&void 0!==n&&n,video:i,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function ta(e){return e.split("/")[1].toLowerCase()}function na(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Mn({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function ia(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?ia(e.track):{})}}function oa(e){const t=Object.assign({},e);let n,i;return"object"==typeof t.audio&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(i=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:(o=t,void 0===o?o:"function"==typeof structuredClone?"object"==typeof o&&null!==o?structuredClone(Object.assign({},o)):structuredClone(o):JSON.parse(JSON.stringify(o)))};var o}function sa(e,t){return e.width*e.height{var n,i;const{kind:o,data:s}=t.data;switch(o){case"error":if(Di.error(s.error.message),s.uuid){const e=this.decryptDataRequests.get(s.uuid);if(null==e?void 0:e.reject){e.reject(s.error);break}const t=this.encryptDataRequests.get(s.uuid);if(null==t?void 0:t.reject){t.reject(s.error);break}}this.emit(e.EncryptionEvent.EncryptionError,s.error,s.participantIdentity);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity))this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const t=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!t)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(e.EncryptionEvent.ParticipantEncryptionStatusChanged,s.enabled,t)}break;case"ratchetKey":this.keyProvider.emit(e.KeyProviderEvent.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break;case"decryptDataResponse":const t=this.decryptDataRequests.get(s.uuid);(null==t?void 0:t.resolve)&&t.resolve(s);break;case"encryptDataResponse":const o=this.encryptDataRequests.get(s.uuid);(null==o?void 0:o.resolve)&&o.resolve(s)}},this.onWorkerError=t=>{Di.error("e2ee worker encountered an error:",{error:t.error}),this.emit(e.EncryptionEvent.EncryptionError,t.error,void 0)},this.keyProvider=t.keyProvider,this.worker=t.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=n}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!ns())throw new bs("tried to setup end-to-end encryption on an unsupported browser");if(Di.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Ai.getLevel()}};this.worker&&(Di.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Di.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):Di.warn("ignoring server sent trailer as it's empty")}setupEngine(t){t.on(e.EngineEvent.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(t,n){t.on(e.RoomEvent.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==pt.NONE,t.identity))),t.on(e.RoomEvent.ConnectionStateChanged,(n=>{n===e.ConnectionState.Connected&&t.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==pt.NONE,e.identity)}))}))})).on(e.RoomEvent.TrackUnsubscribed,((e,t,n)=>{var i;const o={kind:"removeTransform",data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};null===(i=this.worker)||void 0===i||i.postMessage(o)})).on(e.RoomEvent.TrackSubscribed,((e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)})).on(e.RoomEvent.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");n.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),t.localParticipant.on(e.ParticipantEvent.LocalSenderCreated,((e,t)=>Fi(this,void 0,void 0,(function*(){this.setupE2EESender(t,e)})))),t.localParticipant.on(e.ParticipantEvent.LocalTrackPublished,(e=>{if(!Br(e.track)||!lr())return;const t={kind:"updateCodec",data:{trackId:e.track.mediaStreamID,codec:ta(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)})),n.on(e.KeyProviderEvent.SetKey,(e=>this.postKey(e))).on(e.KeyProviderEvent.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}encryptData(e){return Fi(this,void 0,void 0,(function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},i=new Dr;return i.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,i),this.worker.postMessage(n),i.promise}))}handleEncryptedData(e,t,n,i){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const o=crypto.randomUUID(),s={kind:"decryptDataRequest",data:{uuid:o,payload:e,iv:t,participantIdentity:n,keyIndex:i}},r=new Dr;return r.onFinally=()=>{this.decryptDataRequests.delete(o)},this.decryptDataRequests.set(o,r),this.worker.postMessage(s),r.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var o;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(o=this.room)||void 0===o?void 0:o.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!(null==n?void 0:n.mimeType)||""===n.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?ta(n.mimeType):void 0)}}setupE2EESender(e,t){jr(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||Di.warn("early return because sender is not ready")}handleReceiver(e,t,n,i){return Fi(this,void 0,void 0,(function*(){if(this.worker){if(is()&&!cr()){const o={kind:"decode",participantIdentity:n,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,o)}else{if(Zo in e&&i){const e={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}};return void this.worker.postMessage(e)}let o=e.writableStream,s=e.readableStream;if(!o||!s){const t=e.createEncodedStreams();e.writableStream=t.writable,o=t.writable,e.readableStream=t.readable,s=t.readable}const r={kind:"decode",data:{readableStream:s,writableStream:o,trackId:t,codec:i,participantIdentity:n,isReuse:Zo in e}};this.worker.postMessage(r,[s,o])}e[Zo]=!0}}))}handleSender(e,t,n){var i;if(!(Zo in e)&&this.worker){if(!(null===(i=this.room)||void 0===i?void 0:i.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(is()&&!cr()){Di.info("initialize script transform");const i={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{Di.info("initialize encoded streams");const i=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(o,[i.readable,i.writable])}e[Zo]=!0}}}class aa{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new aa),this._instance}addFailedConnectionAttempt(e){var t;const n=vr(new URL(e));if(!n)return;let i=null!==(t=this.failedConnectionAttempts.get(n))&&void 0!==t?t:0;this.failedConnectionAttempts.set(n,i+1),this.backOffPromises.set(n,$s(Math.min(500*Math.pow(2,i),15e3)))}getBackOffPromise(e){const t=new URL(e),n=t&&vr(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&vr(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}aa._instance=null;const ca="default";class da{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new da),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Fi(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var i;if((null===(i=da.userMediaPromiseMap)||void 0===i?void 0:i.size)>0){Di.debug("awaiting getUserMedia promise");try{e?yield da.userMediaPromiseMap.get(e):yield Promise.all(da.userMediaPromiseMap.values())}catch(e){Di.warn("error waiting for media permissons")}}let o=yield navigator.mediaDevices.enumerateDevices();if(n&&(!dr()||!t.hasDeviceInUse(e))){if(0===o.filter((t=>t.kind===e)).length||o.some((t=>{const n=""===t.label,i=!e||t.kind===e;return n&&i}))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},n=yield navigator.mediaDevices.getUserMedia(t);o=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach((e=>{e.stop()}))}}return t._previousDevices=o,e&&(o=o.filter((t=>t.kind===e))),o}()}))}normalizeDeviceId(e,t,n){return Fi(this,void 0,void 0,(function*(){if(t!==ca)return t;const i=yield this.getDevices(e),o=i.find((e=>e.deviceId===ca));if(!o)return void Di.warn("could not reliably determine default device");const s=i.find((e=>e.deviceId!==ca&&e.groupId===(null!=n?n:o.groupId)));if(s)return null==s?void 0:s.deviceId;Di.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?da.userMediaPromiseMap.has(e):da.userMediaPromiseMap.size>0}}var la;da.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],da.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(la||(la={}));class ua{constructor(){this.pendingTasks=new Map,this.taskMutex=new o,this.nextTaskIndex=0}run(e){return Fi(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:la.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=la.RUNNING,yield e()}finally{t.status=la.COMPLETED,this.pendingTasks.delete(t.id),n()}}))}flush(){return Fi(this,void 0,void 0,(function*(){return this.run((()=>Fi(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}class ha{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n,i;if(null===(n=t.signal)||void 0===n?void 0:n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const o=new WebSocket(e,null!==(i=t.protocols)&&void 0!==i?i:[]);o.binaryType="arraybuffer",this.ws=o;const s=function(){let{closeCode:e,reason:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return o.close(e,t)};this.opened=new Promise(((e,t)=>{o.onopen=()=>{e({readable:new ReadableStream({start(e){o.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},o.onerror=t=>e.error(t)},cancel:s}),writable:new WritableStream({write(e){o.send(e)},abort(){o.close()},close:s}),protocol:o.protocol,extensions:o.extensions}),o.removeEventListener("error",t)},o.addEventListener("error",t)})),this.closed=new Promise(((e,t)=>{const n=()=>Fi(this,void 0,void 0,(function*(){const n=new Promise((e=>{o.readyState!==WebSocket.CLOSED&&o.addEventListener("close",(t=>{e(t)}),{once:!0})})),i=yield Promise.race([$s(250),n]);i?e(i):t(new Error("Encountered unspecified websocket error without a timely close event"))}));o.onclose=t=>{let{code:i,reason:s}=t;e({closeCode:i,reason:s}),o.removeEventListener("error",n)},o.addEventListener("error",n)})),t.signal&&(t.signal.onabort=()=>o.close()),this.close=s}}function pa(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}function ma(e){if("string"==typeof e)return wn.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return wn.fromBinary(new Uint8Array(e));throw new Error("could not decode websocket message: ".concat(typeof e))}const ga=["syncState","trickle","offer","answer","simulate","leave"];var va;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(va||(va={}));class fa{get currentState(){return this.state}get isDisconnected(){return this.state===va.DISCONNECTING||this.state===va.DISCONNECTED}get isEstablishingConnection(){return this.state===va.CONNECTING||this.state===va.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=va.DISCONNECTED,this.log=Di,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=xi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.Signal),this.loggerContextCb=n.loggerContextCb,this.useJSON=t,this.requestQueue=new ua,this.queuedRequests=[],this.closingLock=new o,this.connectionLock=new o,this.state=va.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,n,i){return Fi(this,void 0,void 0,(function*(){this.state=va.CONNECTING,this.options=n;return yield this.connect(e,t,n,i)}))}reconnect(e,t,n,i){return Fi(this,void 0,void 0,(function*(){if(!this.options)return void this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);this.state=va.RECONNECTING,this.clearPingInterval();return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))}))}connect(t,n,i,o){return Fi(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();this.connectOptions=i;const r=function(){var e;const t=new Lt({sdk:Ut.JS,protocol:16,version:As});return mr()&&(t.os=null!==(e=kr())&&void 0!==e?e:""),t}(),a=i.singlePeerConnection?function(e,t,n){const i=new URLSearchParams;i.set("access_token",e);const o=new ki({clientInfo:t,connectionSettings:new fi({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0});n.reconnectReason&&(o.reconnectReason=n.reconnectReason);const s=new yi({joinRequest:o.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(s.toBinary()))),i}(n,r,i):function(e,t,n){var i;const o=new URLSearchParams;o.set("access_token",e),n.reconnect&&(o.set("reconnect","1"),n.sid&&o.set("sid",n.sid));o.set("auto_subscribe",n.autoSubscribe?"1":"0"),o.set("sdk",mr()?"reactnative":"js"),o.set("version",t.version),o.set("protocol",t.protocol.toString()),t.deviceModel&&o.set("device_model",t.deviceModel);t.os&&o.set("os",t.os);t.osVersion&&o.set("os_version",t.osVersion);t.browser&&o.set("browser",t.browser);t.browserVersion&&o.set("browser_version",t.browserVersion);n.adaptiveStream&&o.set("adaptive_stream","1");n.reconnectReason&&o.set("reconnect_reason",n.reconnectReason.toString());(null===(i=navigator.connection)||void 0===i?void 0:i.type)&&o.set("network",navigator.connection.type);return o}(n,r,i),c=function(e,t){const n=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{n.searchParams.set(t,e)})),pa(n,"rtc")}(t,a),d=pa(new URL(Ar(c)),"validate");return new Promise(((t,n)=>Fi(this,void 0,void 0,(function*(){var r,a;try{let s=!1;const l=e=>Fi(this,void 0,void 0,(function*(){if(s)return;s=!0;const t=e instanceof Event?e.currentTarget:e,i=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unknown reason";if(!(e instanceof AbortSignal))return t;const n=e.reason;switch(typeof n){case"string":return n;case"object":return n instanceof Error?n.message:t;default:return"toString"in n?n.toString():t}}(t,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then((()=>this.close(i))).catch((e=>{this.log.error(e),this.close()})):this.close(),u(),n(t instanceof AbortSignal?t.reason:t)}));null==o||o.addEventListener("abort",l);const u=()=>{clearTimeout(h),null==o||o.removeEventListener("abort",l)},h=setTimeout((()=>{l(new ys("room connection has timed out (signal)",e.ConnectionErrorReason.ServerUnreachable))}),i.websocketTimeout),p=(e,t)=>{this.handleSignalConnected(e,h,t)},m=new URL(c);m.searchParams.has("access_token")&&m.searchParams.set("access_token",""),this.log.debug("connecting to ".concat(m),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new ha(c);try{this.ws.closed.then((t=>{var i;this.isEstablishingConnection&&n(new ys("Websocket got closed during a (re)connection attempt: ".concat(t.reason),e.ConnectionErrorReason.InternalError)),1e3!==t.closeCode&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:t.reason,code:t.closeCode,wasClean:1e3===t.closeCode,state:this.state})),this.state===va.CONNECTED&&this.handleOnClose(null!==(i=t.reason)&&void 0!==i?i:"Unexpected WS error"))})).catch((t=>{this.isEstablishingConnection&&n(new ys("Websocket error during a (re)connection attempt: ".concat(t),e.ConnectionErrorReason.InternalError))}));const o=yield this.ws.opened.catch((e=>Fi(this,void 0,void 0,(function*(){if(this.state===va.CONNECTED)this.handleWSError(e),n(e);else{this.state=va.DISCONNECTED,clearTimeout(h);const t=yield this.handleConnectionError(e,d);n(t)}}))));if(clearTimeout(h),!o)return;const s=o.readable.getReader();this.streamWriter=o.writable.getWriter();const c=yield s.read();if(s.releaseLock(),!c.value)throw new ys("no message received as first message",e.ConnectionErrorReason.InternalError);const l=ma(c.value),u=this.validateFirstMessage(l,null!==(r=i.reconnect)&&void 0!==r&&r);if(!u.isValid)return void n(u.error);"join"===(null===(a=l.message)||void 0===a?void 0:a.case)&&(this.pingTimeoutDuration=l.message.value.pingTimeout,this.pingIntervalDuration=l.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));p(o,u.shouldProcessFirstMessage?l:void 0),t(u.response)}catch(e){n(e)}finally{u()}}finally{s()}}))))}))}startReadingLoop(e,t){return Fi(this,void 0,void 0,(function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield $s(this.signalLatency));const{done:t,value:n}=yield e.read();if(t)break;const i=ma(n);this.handleSignalResponse(i)}}))}close(){return Fi(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Close method called on signal client";return function*(){if([va.DISCONNECTING||va.DISCONNECTED].includes(e.state))return void e.log.debug("ignoring signal close as it's already in disconnecting state");const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=va.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,$s(250)])}}catch(t){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=va.DISCONNECTED),i()}}()}))}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:ya(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:ya(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new In({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new On({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Fi(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const o=n.getNextRequestId();return yield n.sendRequest({case:"updateMetadata",value:new Wn({requestId:o,metadata:e,name:t,attributes:i})}),o}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new qn({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ni({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:D.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new di({timestamp:D.parse(Date.now()),rtt:D.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new jn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Bn({reason:nt.CLIENT_INITIATED,action:Vn.DISCONNECT})})}sendRequest(e){return Fi(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const i=!n&&!function(e){const t=ga.indexOf(e.case)>=0;return Di.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(i&&t.state===va.RECONNECTING)return void t.queuedRequests.push((()=>Fi(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield $s(t.signalLatency)),t.isDisconnected)return void t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));if(!t.streamWriter)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const o=new En({message:e});try{t.useJSON?yield t.streamWriter.write(o.toJsonString()):yield t.streamWriter.write(o.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()}))}handleSignalResponse(e){var t,n;const i=e.message;if(null==i)return void this.log.debug("received unsupported message",this.logContext);let o=!1;if("answer"===i.case){const e=ka(i.value);this.onAnswer&&this.onAnswer(e,i.value.id,i.value.midToTrackId)}else if("offer"===i.case){const e=ka(i.value);this.onOffer&&this.onOffer(e,i.value.id,i.value.midToTrackId)}else if("trickle"===i.case){const e=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(e,i.value.target)}else"update"===i.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=i.value.participants)&&void 0!==t?t:[]):"trackPublished"===i.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):"speakersChanged"===i.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(n=i.value.speakers)&&void 0!==n?n:[]):"leave"===i.case?this.onLeave&&this.onLeave(i.value):"mute"===i.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):"roomUpdate"===i.case?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):"connectionQuality"===i.case?this.onConnectionQuality&&this.onConnectionQuality(i.value):"streamStateUpdate"===i.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):"subscribedQualityUpdate"===i.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):"subscriptionPermissionUpdate"===i.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):"refreshToken"===i.case?this.onTokenRefresh&&this.onTokenRefresh(i.value):"trackUnpublished"===i.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):"subscriptionResponse"===i.case?this.onSubscriptionError&&this.onSubscriptionError(i.value):"pong"===i.case||("pongResp"===i.case?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),o=!0):"requestResponse"===i.case?this.onRequestResponse&&this.onRequestResponse(i.value):"trackSubscribed"===i.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):"roomMoved"===i.case?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):"mediaSectionsRequirement"===i.case?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(i.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));o||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Fi(this,void 0,void 0,(function*(){if(this.state===va.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=Ns.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&Ns.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=Ns.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Ns.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=va.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(t,n){var i,o,s,r,a;return"join"===(null===(i=t.message)||void 0===i?void 0:i.case)?{isValid:!0,response:t.message.value}:this.state===va.RECONNECTING&&"leave"!==(null===(o=t.message)||void 0===o?void 0:o.case)?"reconnect"===(null===(s=t.message)||void 0===s?void 0:s.case)?{isValid:!0,response:t.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&"leave"===(null===(r=t.message)||void 0===r?void 0:r.case)?{isValid:!1,error:new ys("Received leave request while trying to (re)connect",e.ConnectionErrorReason.LeaveRequest,void 0,t.message.value.reason)}:n?{isValid:!1,error:new ys("Unexpected first message",e.ConnectionErrorReason.InternalError)}:{isValid:!1,error:new ys("did not receive join response, got ".concat(null===(a=t.message)||void 0===a?void 0:a.case," instead"),e.ConnectionErrorReason.InternalError)}}handleConnectionError(t,n){return Fi(this,void 0,void 0,(function*(){try{const i=yield fetch(n);if(i.status.toFixed(0).startsWith("4")){const t=yield i.text();return new ys(t,e.ConnectionErrorReason.NotAllowed,i.status)}return t instanceof ys?t:new ys("Encountered unknown websocket error during connection: ".concat(t),e.ConnectionErrorReason.InternalError,i.status)}catch(t){return t instanceof ys?t:new ys(t instanceof Error?t.message:"server was not reachable",e.ConnectionErrorReason.ServerUnreachable)}}))}}function ka(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function ya(e,t){return new An({sdp:e.sdp,type:e.type,id:t})}class ba{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;){if(!(this.buffer[0].sequence<=e))break;this.pop()}}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Ta{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const i=n+this.ttl;return this._map.set(e,{value:t,expiresAt:i}),this}get(e){const t=this._map.get(e);if(t){if(!(t.expiresAt=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[i,o]of n.entries())t.push(e(o,i,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Ca,Sa,Ea,wa,Ra,Pa={},Ia={},Oa={exports:{}};function _a(){if(Ca)return Oa.exports;Ca=1;var e=Oa.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),Oa.exports}function Da(){return Sa||(Sa=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,i){var o=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:o&&!n[e.name]&&(n[e.name]={});var s=e.push?{}:o?n[e.name]:n;!function(e,n,i,o){if(o&&!i)n[o]=t(e[1]);else for(var s=0;s1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],i=e.split(" ").map(t),o=0;o=o)return e;var t=i[n];switch(n+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},i=function(e,t,i){var o=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var s=0;s=c)return c-e}return t}var h=function(){var t=[].slice.call(arguments),n=this;return new Promise((function(i,o){var c=r&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout((function(){if(s=void 0,d=Date.now(),!r){var i=e.apply(n,t);a&&a(i),l.forEach((function(e){return(0,e.resolve)(i)})),l=[]}}),u()),c){var h=e.apply(n,t);return a&&a(h),i(h)}l.push({resolve:i,reject:o})}))};return h.cancel=function(e){void 0!==s&&clearTimeout(s),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},h}const Na="negotiationStarted",La="negotiationComplete",Ua="rtpVideoPayloadTypes";class ja extends Ki.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=Di,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Aa((e=>Fi(this,void 0,void 0,(function*(){this.emit(Na);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=xi(null!==(i=n.loggerName)&&void 0!==i?i:e.LoggerNames.PCTransport),this.loggerOptions=n,this.config=t,this._pc=this.createPC(),this.offerLock=new o}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Fi(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e,t){return Fi(this,void 0,void 0,(function*(){var n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let i;if("offer"===e.type){let{stereoMids:t,nackMids:n}=function(e){var t;const n=[],i=[],o=xa.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let s=0;return o.media.forEach((e=>{var t;const o=Va(e.mid);"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(s=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===s&&"nack"===e.type)))&&i.push(o),e.fmtp.some((e=>e.payload===s&&(e.config.includes("sprop-stereo=1")&&n.push(o),!0))))})),{stereoMids:n,nackMids:i}}(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if("answer"===e.type){const t=xa.parse(null!==(n=e.sdp)&&void 0!==n?n:"");t.media.forEach((e=>{const t=Va(e.mid);"audio"===e.type&&this.trackBitrates.some((n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let o=!1;for(const t of e.fmtp)if(t.payload===i){t.config=t.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),n.maxbr>0&&(t.config+=";maxaveragebitrate=".concat(1e3*n.maxbr)),o=!0;break}return o||n.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*n.maxbr)}),!0}))})),i=xa.write(t)}if(yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate)this.renegotiate=!1,yield this.createAndSendOffer();else if("answer"===e.type&&(this.emit(La),e.sdp)){xa.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(Ua,e.rtp)}))}return!0}))}createAndSendOffer(e){return Fi(this,void 0,void 0,(function*(){var t;const n=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const n=this.latestOfferId+1;this.latestOfferId=n;const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const o=xa.parse(null!==(t=i.sdp)&&void 0!==t?t:"");if(o.media.forEach((e=>{Ba(e),"audio"===e.type?Fa(e,["all"],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(n=e.payload,!0))),0===n)return!0;if(or(t.codec)&&!dr()&&this.ensureVideoDDExtensionForSVC(e,o),!or(t.codec))return!0;const i=Math.round(.7*t.maxbr);for(const t of e.fmtp)if(t.payload===n){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(i));break}return!0}))})),this.latestOfferId>n)return void this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:n}));yield this.setMungedSDP(i,xa.write(o)),this.onOffer(i,this.latestOfferId)}finally{n()}}))}createAndSetAnswer(){return Fi(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),n=xa.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return n.media.forEach((e=>{Ba(e),"audio"===e.type&&Fa(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,xa.write(n)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Ss("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new Ss("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Fi(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),n.set(e.id,e);break;case"remote-candidate":i.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const o=null===(e=n.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==o?i.get(o):void 0}))}setMungedSDP(e,t,n){return Fi(this,void 0,void 0,(function*(){if(t){const i=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),void(n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let i="unknown error";t instanceof Error?i=t.message:"string"==typeof t&&(i=t);const o={error:i,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Es(i)}}))}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!(null===(n=e.ext)||void 0===n?void 0:n.some((e=>e.uri===Zs)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var n;"video"===t.type&&(null===(n=t.ext)||void 0===n||n.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(i=e.ext)||void 0===i||i.push({value:this.ddExtID,uri:Zs})}}}function Fa(e,t,n){const i=Va(e.mid);let o=0;e.rtp.some((e=>"opus"===e.codec&&(o=e.payload,!0))),o>0&&(e.rtcpFb||(e.rtcpFb=[]),n.includes(i)&&!e.rtcpFb.some((e=>e.payload===o&&"nack"===e.type))&&e.rtcpFb.push({payload:o,type:"nack"}),(t.includes(i)||1===t.length&&"all"===t[0])&&e.fmtp.some((e=>e.payload===o&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function Ba(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}function Va(e){return"number"==typeof e?e.toFixed(0):e}const qa="vp8",Wa={audioPreset:e.AudioPresets.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:qa,backupCodec:!0,preConnectBuffer:!1},Ka={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Ha={deviceId:{ideal:"default"},resolution:Qs.h720.resolution},Ga={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ui,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},Ja={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var za;!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(za||(za={}));class Qa{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(t,n,i){var s;this.peerConnectionTimeout=Ja.peerConnectionTimeout,this.log=Di,this.updateState=()=>{var e,t;const n=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=za.CONNECTED:i.some((e=>"failed"===e))?this.state=za.FAILED:i.some((e=>"connecting"===e))?this.state=za.CONNECTING:i.every((e=>"closed"===e))?this.state=za.CLOSED:i.some((e=>"closed"===e))?this.state=za.CLOSING:i.every((e=>"new"===e))&&(this.state=za.NEW),n!==this.state&&(this.log.debug("pc state change: from ".concat(za[n]," to ").concat(za[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),null===(t=this.subscriber)||void 0===t?void 0:t.getConnectionState()))},this.log=xi(null!==(s=i.loggerName)&&void 0!==s?s:e.LoggerNames.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired="subscriber-primary"!==n,this.isSubscriberConnectionRequired="subscriber-primary"===n,this.publisher=new ja(t,i),"publisher-only"!==n&&(this.subscriber=new ja(t,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Tn.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,Tn.PUBLISHER)},this.publisher.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;null===(n=this.onPublisherOffer)||void 0===n||n.call(this,e,t)},this.state=za.NEW,this.connectionLock=new o,this.remoteOfferLock=new o}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return Fi(this,void 0,void 0,(function*(){var e;if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),null===(e=this.subscriber)||void 0===e?void 0:e.close()]),this.updateState()}))}triggerIceRestart(){return Fi(this,void 0,void 0,(function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Fi(this,void 0,void 0,(function*(){var n;t===Tn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield null===(n=this.subscriber)||void 0===n?void 0:n.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e,t){return Fi(this,void 0,void 0,(function*(){var n,i,o;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:null===(n=this.subscriber)||void 0===n?void 0:n.getSignallingState().toString()}));const s=yield this.remoteOfferLock.lock();try{if(!(yield null===(i=this.subscriber)||void 0===i?void 0:i.setRemoteDescription(e,t)))return;return yield null===(o=this.subscriber)||void 0===o?void 0:o.createAndSetAnswer()}finally{s()}}))}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),null===(n=this.subscriber)||void 0===n||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Fi(this,void 0,void 0,(function*(){var n;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(n=this.requiredTransports)||void 0===n?void 0:n.map((n=>this.ensureTransportConnected(n,e,t))))}finally{i()}}))}negotiate(e){return Fi(this,void 0,void 0,(function*(){return new Promise(((t,n)=>Fi(this,void 0,void 0,(function*(){const i=setTimeout((()=>{n("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(i),n("negotiation aborted")})),this.publisher.once(Na,(()=>{e.signal.aborted||this.publisher.once(La,(()=>{clearTimeout(i),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(i),n(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const t=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find((t=>t.receiver===e));return null==t?void 0:t.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Tn.PUBLISHER||e===Tn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(t,n){return Fi(this,arguments,void 0,(function(t,n){var i=this;let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==t.getConnectionState())return new Promise(((t,s)=>Fi(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),Ns.clearTimeout(r),s(new ys("room connection has been cancelled",e.ConnectionErrorReason.Cancelled))};(null==n?void 0:n.signal.aborted)&&i(),null==n||n.signal.addEventListener("abort",i);const r=Ns.setTimeout((()=>{null==n||n.signal.removeEventListener("abort",i),s(new ys("could not establish pc connection",e.ConnectionErrorReason.InternalError))}),o);for(;this.state!==za.CONNECTED;)if(yield $s(50),null==n?void 0:n.signal.aborted)return void s(new ys("room connection has been cancelled",e.ConnectionErrorReason.Cancelled));Ns.clearTimeout(r),null==n||n.signal.removeEventListener("abort",i),t()}))))}()}))}}class Ya{static fetchRegionSettings(t,n,i){return Fi(this,void 0,void 0,(function*(){const o=yield Ya.fetchLock.lock();try{const o=yield fetch("".concat(function(e){return"".concat(e.protocol.replace("ws","http"),"//").concat(e.host,"/settings")}(t),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(o.ok){const e=function(e){var t;const n=e.get("Cache-Control");if(n){const e=null===(t=n.match(/(?:^|[,\s])max-age=(\d+)/))||void 0===t?void 0:t[1];if(e)return parseInt(e,10)}}(o.headers),t=e?1e3*e:5e3;return{regionSettings:yield o.json(),updatedAtInMs:Date.now(),maxAgeInMs:t}}throw new ys("Could not fetch region settings: ".concat(o.statusText),401===o.status?e.ConnectionErrorReason.NotAllowed:e.ConnectionErrorReason.InternalError,o.status)}catch(t){throw t instanceof ys?t:(null==i?void 0:i.aborted)?new ys("Region fetching was aborted",e.ConnectionErrorReason.Cancelled):new ys("Could not fetch region settings, ".concat(t instanceof Error?"".concat(t.name,": ").concat(t.message):t),e.ConnectionErrorReason.ServerUnreachable,500)}finally{o()}}))}static scheduleRefetch(e,t,n){return Fi(this,void 0,void 0,(function*(){const i=Ya.settingsTimeouts.get(e.hostname);clearTimeout(i),Ya.settingsTimeouts.set(e.hostname,setTimeout((()=>Fi(this,void 0,void 0,(function*(){try{const n=yield Ya.fetchRegionSettings(e,t);Ya.updateCachedRegionSettings(e,t,n)}catch(i){Di.debug("auto refetching of region settings failed",{error:i}),Ya.scheduleRefetch(e,t,n)}}))),n))}))}static updateCachedRegionSettings(e,t,n){Ya.cache.set(e.hostname,n),Ya.scheduleRefetch(e,t,n.maxAgeInMs)}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return gr(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return Fi(this,void 0,void 0,(function*(){return Ya.fetchRegionSettings(this.serverUrl,this.token,e)}))}getNextBestRegionUrl(e){return Fi(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=Ya.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),Ya.updateCachedRegionSettings(this.serverUrl,this.token,t));const n=t.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(n.length>0){const e=n[0];return this.attemptedRegions.push(e),Di.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ya.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ya.cache=new Map,Ya.settingsTimeouts=new Map,Ya.fetchLock=new o;class Xa extends Error{constructor(e,t,n){super(t),this.code=e,this.message=$a(t,Xa.MAX_MESSAGE_BYTES),this.data=n?$a(n,Xa.MAX_DATA_BYTES):void 0}static fromProto(e){return new Xa(e.code,e.message,e.data)}toProto(){return new Mt({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Xa(Xa.ErrorCode[e],Xa.ErrorMessage[e],t)}}Xa.MAX_MESSAGE_BYTES=256,Xa.MAX_DATA_BYTES=15360,Xa.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Xa.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};function Za(e){return(new TextEncoder).encode(e).length}function $a(e,t){if(Za(e)<=t)return e;let n=0,i=e.length;const o=new TextEncoder;for(;n{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",s),null==i||i.close(),i=void 0},s=e=>{null==i||i.error(e),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",o),this.removeEventListener("error",s),i=void 0};this.byteStream=new ReadableStream({start:e=>{i=e,n=t=>Fi(this,void 0,void 0,(function*(){let n;if(t.data.arrayBuffer){const e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else{if(!t.data.byteArray)throw new Error("no data available!");n=t.data.byteArray}void 0!==i&&e.enqueue(n)})),this.addEventListener("dataavailable",n)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",s)}}class sc extends js{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(t,n,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(t,n,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Aa((()=>Fi(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Fi(this,void 0,void 0,(function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()})),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(e.TrackEvent.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new o,this.pauseUpstreamLock=new o,this.trackChangeLock=new o,this.trackChangeLock.lock().then((e=>Fi(this,void 0,void 0,(function*(){try{yield this.setMediaStreamTrack(t,!0)}finally{e()}})))),this._constraints=t.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==js.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Fi(this,void 0,void 0,(function*(){var n;if(e===this._mediaStreamTrack&&!t)return;let i;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Bs(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fs(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}this.sender&&"closed"!==(null===(n=this.sender.transport)||void 0===n?void 0:n.state)&&(yield this.sender.replaceTrack(null!=i?i:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Fs(null!=i?i:e,t)})))}))}waitForDimensions(){return Fi(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var n;if(e.kind===js.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(n=_s())||void 0===n?void 0:n.os)&&(yield $s(10));const i=Date.now();for(;Date.now()-i0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===js.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),o=e.kind===js.Kind.Audio?"audioinput":"videoinput";return t?da.getInstance().normalizeDeviceId(o,n,i):n}()}))}mute(){return Fi(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Fi(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Fi(this,void 0,void 0,(function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Ts("unable to replace an unpublished track");let n,i;return"boolean"==typeof t?n=t:void 0!==t&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=null==n||n,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}}))}restart(t){return Fi(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{t||(t=this._constraints);const{deviceId:n,facingMode:i}=t,o=ji(t,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:t}));const s={audio:!1,video:!1};this.kind===js.Kind.Video?s.video=!n&&!i||{deviceId:n,facingMode:i}:s.audio=!n||Object.assign({deviceId:n},o),this.attachedElements.forEach((e=>{Bs(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return this.kind===js.Kind.Video&&(yield r.applyConstraints(o)),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=t,this.emit(e.TrackEvent.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}}))}setTrackMuted(t){this.log.debug("setting ".concat(this.kind," track ").concat(t?"muted":"unmuted"),this.logContext),this.isMuted===t&&this._mediaStreamTrack.enabled!==t||(this.isMuted=t,this._mediaStreamTrack.enabled=!t,this.emit(t?e.TrackEvent.Muted:e.TrackEvent.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Fi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),hr()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Fi(this,void 0,void 0,(function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(e.TrackEvent.UpstreamPaused,this);const n=_s();if("Safari"===(null==n?void 0:n.name)&&br(n.version,"12.0")<0)throw new bs("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(null))}finally{n()}}))}resumeUpstream(){return Fi(this,void 0,void 0,(function*(){var t;const n=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(e.TrackEvent.UpstreamResumed,this),"closed"!==(null===(t=this.sender.transport)||void 0===t?void 0:t.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}}))}getRTCStatsReport(){return Fi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;return yield this.sender.getStats()}))}setProcessor(t){return Fi(this,arguments,void 0,(function(t){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var o;const s=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const s=document.createElement(n.kind),r={kind:n.kind,track:n._mediaStreamTrack,element:s,audioContext:n.audioContext};if(yield t.init(r),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),"unknown"===n.kind)throw TypeError("cannot set processor on track of unknown kind");if(Fs(n._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>{e instanceof DOMException&&"AbortError"===e.name?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:e})),setTimeout((()=>{s.play().catch((e=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:e}))}))}),100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:e}))})),n.processor=t,n.processorElement=s,n.processor.processedTrack){for(const e of n.attachedElements)e!==n.processorElement&&i&&(Bs(n._mediaStreamTrack,e),Fs(n.processor.processedTrack,e));yield null===(o=n.sender)||void 0===o?void 0:o.replaceTrack(n.processor.processedTrack)}n.emit(e.TrackEvent.TrackProcessorUpdate,n.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Fi(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()}))}internalStopProcessor(){return Fi(this,arguments,void 0,(function(){var t=this;let n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,o;t.processor&&(t.log.debug("stopping processor",t.logContext),null===(i=t.processor.processedTrack)||void 0===i||i.stop(),yield t.processor.destroy(),t.processor=void 0,n||(null===(o=t.processorElement)||void 0===o||o.remove(),t.processorElement=void 0),yield t._mediaStreamTrack.applyConstraints(t._constraints),yield t.setMediaStreamTrack(t._mediaStreamTrack,!0),t.emit(e.TrackEvent.TrackProcessorUpdate))}()}))}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(nc)if(this.localTrackRecorder)this.log.warn("preconnect buffer already started");else{{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new oc(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout((()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()}),1e4)}else this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class rc extends sc{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(t,js.Kind.Audio,n,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Fi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(e){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}e&&this.prevStats&&(this._currentBitrate=tc(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(e.TrackEvent.AudioTrackFeatureUpdate,this,st.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=o,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Fi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===js.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Fi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==xr(this._constraints.deviceId);return this.source!==js.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Fi(this,void 0,void 0,(function*(){let t;if(e){const n=Qr({audio:e});"boolean"!=typeof n.audio&&(t=n.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Fi(this,void 0,void 0,(function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n}))}startMonitor(){pr()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ec)))}setProcessor(t){return Fi(this,void 0,void 0,(function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!mr()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(t.name),this.logContext),yield t.init(i),this.processor=t,this.processor.processedTrack&&(yield null===(n=this.sender)||void 0===n?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(e.TrackEvent.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Fi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Fi(this,void 0,void 0,(function*(){const t=yield Yr(this);return t&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(e.TrackEvent.AudioSilenceDetected)),t}))}}const ac=Object.values(Qs),cc=Object.values(Ys),dc=Object.values(Xs),lc=[Qs.h180,Qs.h360],uc=[Ys.h180,Ys.h360],hc=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map((t=>{var n,i;return new Vs(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(n=e.encoding.maxFramerate)&&void 0!==n?n:30)/(null!==(i=t.fps)&&void 0!==i?i:30))))),t.fps,e.encoding.priority)})),pc=["q","h","f"];function mc(e,t,n,i){var o,s;let r=null==i?void 0:i.videoEncoding;e&&(r=null==i?void 0:i.screenShareEncoding);const a=null==i?void 0:i.simulcast,c=null==i?void 0:i.scalabilityMode,d=null==i?void 0:i.videoCodec;if(!r&&!a&&!c||!t||!n)return[{}];r||(r=function(e,t,n,i){const o=function(e,t,n){if(e)return dc;const i=t>n?t/n:n/t;if(Math.abs(i-16/9)=r)break}if(i)switch(i){case"av1":case"h265":s=Object.assign({},s),s.maxBitrate=.7*s.maxBitrate;break;case"vp9":s=Object.assign({},s),s.maxBitrate=.85*s.maxBitrate}return s}(e,t,n,d),Di.debug("using video encoding",r));const l=r.maxFramerate,u=new Vs(t,n,r.maxBitrate,r.maxFramerate,r.priority);if(c&&or(d)){const e=new kc(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const n=_s();if(lr()||mr()||"Chrome"===(null==n?void 0:n.name)&&br(null==n?void 0:n.version,"113")<0){const i="h"==e.suffix?2:3,o=function(e){return e||(e=_s()),"Safari"===(null==e?void 0:e.name)&&br(e.version,"18.3")>0||"iOS"===(null==e?void 0:e.os)&&!!(null==e?void 0:e.osVersion)&&br(e.osVersion,"18.3")>0}(n);for(let n=0;n0){const e=p[0];p.length>1&&([,h]=p);const i=Math.max(t,n);if(i>=960&&h)return vc(t,n,[e,h,u],l);if(i>=480)return vc(t,n,[e,u],l)}return vc(t,n,[u])}function gc(e,t){if(e)return hc(t);const{width:n,height:i}=t,o=n>i?n/i:i/n;return Math.abs(o-16/9){if(s>=pc.length)return;const r=Math.min(e,t),a={rid:pc[s],scaleResolutionDownBy:Math.max(1,r/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=i&&n.encoding.maxFramerate?Math.min(i,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=ar()||0===s;n.encoding.priority&&d&&(a.priority=n.encoding.priority,a.networkPriority=n.encoding.priority),o.push(a)})),mr()&&"ios"===kr()){let e;o.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;o.forEach((n=>{var i;n.maxFramerate!=e&&(t&&(t=!1,Di.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Di.info('Setting framerate of encoding "'.concat(null!==(i=n.rid)&&void 0!==i?i:"",'" to ').concat(e)),n.maxFramerate=e)}))}return o}function fc(e){if(e)return e.sort(((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitratei.maxFramerate?1:-1:0}))}class kc{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class yc extends sc{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(t,n){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s=arguments.length>3?arguments[3]:void 0;super(t,js.Kind.Video,n,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>Fi(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let t;try{t=yield this.getSenderStats()}catch(e){return void this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}))}const n=new Map(t.map((e=>[e.rid,e]))),i=t.some((e=>"cpu"===e.qualityLimitationReason));if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(e.TrackEvent.CpuConstrained)),this.prevStats){let e=0;n.forEach(((t,n)=>{var i;const o=null===(i=this.prevStats)||void 0===i?void 0:i.get(n);e+=tc(t,o)})),this._currentBitrate=e}this.prevStats=n})),this.senderLock=new o}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!pr())return;const n=null===(t=this.sender)||void 0===t?void 0:t.getParameters();n&&(this.encodings=n.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),ec))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Fi(this,void 0,void 0,(function*(){var t,n,i,o,s;yield e.pauseUpstream.call(this);try{for(var r,a=!0,c=Vi(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){o=r.value,a=!1;const e=o;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(null)}}catch(e){n={error:e}}finally{try{a||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Fi(this,void 0,void 0,(function*(){var t,n,i,o,s;yield e.resumeUpstream.call(this);try{for(var r,a=!0,c=Vi(this.simulcastCodecs.values());!(t=(r=yield c.next()).done);a=!0){o=r.value,a=!1;const e=o;yield null===(s=e.sender)||void 0===s?void 0:s.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{a||t||!(i=c.return)||(yield i.call(c))}finally{if(n)throw n.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Fi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==js.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Fi(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==js.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Fi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach((e=>{var i;if("outbound-rtp"===e.type){const o={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(i=e.rid)&&void 0!==i?i:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},s=n.get(e.remoteId);s&&(o.jitter=s.jitter,o.packetsLost=s.packetsLost,o.roundTripTime=s.roundTripTime),t.push(o)}})),t.sort(((e,t)=>{var n,i;return(null!==(n=t.frameWidth)&&void 0!==n?n:0)-(null!==(i=e.frameWidth)&&void 0!==i?i:0)})),t}))}setPublishingQuality(t){const n=[];for(let i=e.VideoQuality.LOW;i<=e.VideoQuality.HIGH;i+=1)n.push(new Xn({quality:i,enabled:i<=t}));this.log.debug("setting publishing quality. max quality ".concat(t),this.logContext),this.setPublishingLayers(or(this.codec),n)}restartTrack(e){return Fi(this,void 0,void 0,(function*(){var t,n,i,o,s;let r;if(e){const t=Qr({video:e});"boolean"!=typeof t.video&&(r=t.video)}yield this.restart(r),this.isCpuConstrained=!1;try{for(var a,c=!0,d=Vi(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){o=a.value,c=!1;const e=o;e.sender&&"closed"!==(null===(s=e.sender.transport)||void 0===s?void 0:s.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{c||t||!(i=d.return)||(yield i.call(d))}finally{if(n)throw n.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Fi(this,arguments,void 0,(function(e){var n=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var o,s,r,a,c,d;if(yield t.setProcessor.call(n,e,i),null===(c=n.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Vi(n.simulcastCodecs.values());!(o=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(n.processor.processedTrack)}}catch(e){s={error:e}}finally{try{u||o||!(r=h.return)||(yield r.call(h))}finally{if(s)throw s.error}}}()}))}setDegradationPreference(e){return Fi(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Fi(this,void 0,void 0,(function*(){var t,n,i,o,s,r,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(or(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=Vi(e);!(o=(i=yield n.next()).done);t=!0){a=i.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield bc(t.sender,t.encodings,e.qualities,this.senderLock,or(e.codec),this.log,this.logContext));else for(const t of e.qualities)if(t.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(or(e.codec),e.qualities)}}catch(e){s={error:e}}finally{try{t||o||!(r=n.return)||(yield r.call(n))}finally{if(s)throw s.error}}return c}))}setPublishingLayers(e,t){return Fi(this,void 0,void 0,(function*(){this.optimizeForPerformance?this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t})):(this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield bc(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext)))}))}prioritizePerformance(){return Fi(this,void 0,void 0,(function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const e=this.sender.getParameters();e.encodings=e.encodings.map(((e,t)=>{var n;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(n=this.mediaStreamTrack.getSettings().height)&&void 0!==n?n:360)/360)),scalabilityMode:0===t&&or(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})})),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Fi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),hr()&&this.isInBackground&&this.source===js.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function bc(e,t,n,i,o,s,r){return Fi(this,void 0,void 0,(function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:n,senderEncodings:t}));try{const i=e.getParameters(),{encodings:a}=i;if(!a)return;if(a.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:t}));let c=!1;if(!1&&a[0].scalabilityMode);else{if(o){n.some((e=>e.enabled))&&n.forEach((e=>e.enabled=!0))}a.forEach(((e,i)=>{var o;let a=null!==(o=e.rid)&&void 0!==o?o:"";""===a&&(a="q");const d=Tc(a),l=n.find((e=>e.quality===d));l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),ar()&&(l.enabled?(e.scaleResolutionDownBy=t[i].scaleResolutionDownBy,e.maxBitrate=t[i].maxBitrate,e.maxFrameRate=t[i].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}))}c&&(i.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:i.encodings})),yield e.setParameters(i))}finally{a()}}))}function Tc(t){switch(t){case"f":default:return e.VideoQuality.HIGH;case"h":return e.VideoQuality.MEDIUM;case"q":return e.VideoQuality.LOW}}function Cc(t,n,i,o){if(!i)return[new vt({quality:e.VideoQuality.HIGH,width:t,height:n,bitrate:0,ssrc:0})];if(o){const o=i[0].scalabilityMode,s=new kc(o),r=[],a="h"==s.suffix?1.5:2,c="h"==s.suffix?2:3;for(let o=0;o{var i,o,s;const r=null!==(i=e.scaleResolutionDownBy)&&void 0!==i?i:1;let a=Tc(null!==(o=e.rid)&&void 0!==o?o:"");return new vt({quality:a,width:Math.ceil(t/r),height:Math.ceil(n/r),bitrate:null!==(s=e.maxBitrate)&&void 0!==s?s:0,ssrc:0})}))}const Sc="_lossy",Ec="_reliable",wc="leave-reconnect";var Rc;!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(Rc||(Rc={}));class Pc extends Ki.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(t){var n;super(),this.options=t,this.rtcConfig={},this.peerConnectionTimeout=Ja.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Rc.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Di,this.reliableDataSequence=1,this.reliableMessageBuffer=new ba,this.reliableReceivedState=new Ta(3e4),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>Fi(this,[e],void 0,(function(e){var t=this;let{channel:n}=e;return function*(){if(n){if(n.label===Ec)t.reliableDCSub=n;else{if(n.label!==Sc)return;t.lossyDCSub=n}t.log.debug("on data channel ".concat(n.id,", ").concat(n.label),t.logContext),n.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=t=>Fi(this,void 0,void 0,(function*(){var n,i,o,s,r;const a=yield this.dataProcessLock.lock();try{let a;if(t.data instanceof ArrayBuffer)a=t.data;else{if(!(t.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));a=yield t.data.arrayBuffer()}const c=kt.fromBinary(new Uint8Array(a));if(c.sequence>0&&""!==c.participantSid){const e=this.reliableReceivedState.get(c.participantSid);if(e&&c.sequence<=e)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}if("speaker"===(null===(n=c.value)||void 0===n?void 0:n.case))this.emit(e.EngineEvent.ActiveSpeakersUpdate,c.value.value.speakers);else if("encryptedPacket"===(null===(i=c.value)||void 0===i?void 0:i.case)){if(!this.e2eeManager)return void this.log.error("Received encrypted packet but E2EE not set up",this.logContext);const t=yield null===(o=this.e2eeManager)||void 0===o?void 0:o.handleEncryptedData(c.value.value.encryptedValue,c.value.value.iv,c.participantIdentity,c.value.value.keyIndex),n=Tt.fromBinary(t.payload),i=new kt({value:n.value,participantIdentity:c.participantIdentity,participantSid:c.participantSid});"user"===(null===(s=i.value)||void 0===s?void 0:s.case)&&Oc(i,i.value.value),this.emit(e.EngineEvent.DataPacketReceived,i,c.value.value.encryptionType)}else"user"===(null===(r=c.value)||void 0===r?void 0:r.case)&&Oc(c,c.value.value),this.emit(e.EngineEvent.DataPacketReceived,c,pt.NONE)}finally{a()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:n}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?yt.LOSSY:yt.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(t,n)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=t=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(t,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});null!==s?(t===wc&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ns.setTimeout((()=>this.attemptReconnect(n).finally((()=>this.reconnectTimeout=void 0))),s)):i(o)},this.waitForRestarted=()=>new Promise(((t,n)=>{this.pcState===Rc.Connected&&t();const i=()=>{this.off(e.EngineEvent.Disconnected,o),t()},o=()=>{this.off(e.EngineEvent.Restarted,i),n()};this.once(e.EngineEvent.Restarted,i),this.once(e.EngineEvent.Disconnected,o)})),this.updateAndEmitDCBufferStatus=t=>{const n=this.isBufferStatusLow(t);void 0!==n&&n!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,n),this.emit(e.EngineEvent.DCBufferStatusChanged,n,t))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return e===yt.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>Fi(this,void 0,void 0,(function*(){if(!this.url)return;(yield fetch(Ar(this.url),{method:"HEAD"}).then((e=>e.ok)).catch((()=>!1)))&&(this.log.info("detected network reconnected"),(this.client.currentState===va.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===va.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(it.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))})),this.handleBrowserOffline=()=>Fi(this,void 0,void 0,(function*(){if(this.url)try{yield Promise.race([fetch(Ar(this.url),{method:"HEAD"}),$s(4e3).then((()=>Promise.reject()))])}catch(e){!1===window.navigator.onLine&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}})),this.log=xi(null!==(n=t.loggerName)&&void 0!==n?n:e.LoggerNames.Engine),this.loggerOptions={loggerName:t.loggerName,loggerContextCb:()=>this.logContext},this.client=new fa(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new o,this.dataProcessLock=new o,this.dcBufferStatus=new Map([[yt.LOSSY,!0],[yt.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(e.EngineEvent.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(e.EngineEvent.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(e.EngineEvent.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(e.EngineEvent.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(e.EngineEvent.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(e.EngineEvent.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(e.EngineEvent.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(e.EngineEvent.SignalRequestResponse,t)}get logContext(){var e,t,n,i,o,s;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(i=null===(n=this.latestJoinResponse)||void 0===n?void 0:n.room)||void 0===i?void 0:i.sid,participant:null===(s=null===(o=this.latestJoinResponse)||void 0===o?void 0:o.participant)||void 0===s?void 0:s.identity,pID:this.participantSid}}join(t,n,i,o){return Fi(this,void 0,void 0,(function*(){this.url=t,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(t,n,i,o);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate().catch((e=>{Di.error(e,this.logContext)})),this.registerOnLineListener(),this.clientConfiguration=s.clientConfiguration,this.emit(e.EngineEvent.SignalConnected,s),s}catch(s){if(s instanceof ys&&s.reason===e.ConnectionErrorReason.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ba,this.reliableDataSequence=1,this.reliableReceivedState.clear()}))}cleanupClient(){return Fi(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(t){if(this.pendingTrackResolvers[t.cid])throw new Ts("a track with the same ID has already been published");return new Promise(((n,i)=>{const o=setTimeout((()=>{delete this.pendingTrackResolvers[t.cid],i(new ys("publication of local track timed out, no response from server",e.ConnectionErrorReason.Timeout))}),1e4);this.pendingTrackResolvers[t.cid]={resolve:e=>{clearTimeout(o),n(e)},reject:()=>{clearTimeout(o),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(t)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Fi(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(t){return Fi(this,void 0,void 0,(function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==za.NEW)return;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid;const o=this.makeRTCConfiguration(t);var s;this.pcManager=new Qa(o,this.options.singlePeerConnection?"publisher-only":t.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(e.EngineEvent.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(n,i,o)=>Fi(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(n),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),n===za.CONNECTED){const n=this.pcState===Rc.New;this.pcState=Rc.Connected,n&&this.emit(e.EngineEvent.Connected,t)}else n===za.FAILED&&(this.pcState!==Rc.Connected&&this.pcState!==Rc.Reconnecting||(this.pcState=Rc.Disconnected,this.handleDisconnect("peerconnection failed","failed"===o?it.RR_SUBSCRIBER_FAILED:it.RR_PUBLISHER_FAILED)));const s=this.client.isDisconnected||this.client.currentState===va.RECONNECTING,r=[za.FAILED,za.CLOSING,za.CLOSED].includes(n);s&&r&&!this._isClosed&&this.emit(e.EngineEvent.Offline)})),this.pcManager.onTrack=t=>{0!==t.streams.length&&this.emit(e.EngineEvent.MediaTrackAdded,t.track,t.streams[0],t.receiver)},void 0!==(s=null===(i=t.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>Fi(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>Fi(this,void 0,void 0,(function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=t=>{this.emit(e.EngineEvent.LocalTrackUnpublished,t)},this.client.onLocalTrackSubscribed=t=>{this.emit(e.EngineEvent.LocalTrackSubscribed,t)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(t,n)=>{this.emit(e.EngineEvent.RemoteMute,t,n)},this.client.onSubscribedQualityUpdate=t=>{this.emit(e.EngineEvent.SubscribedQualityUpdate,t)},this.client.onRoomMoved=t=>{var n;this.participantSid=null===(n=t.participant)||void 0===n?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=t.room),this.emit(e.EngineEvent.RoomMoved,t)},this.client.onMediaSectionsRequirement=e=>{var t,n;const i={direction:"recvonly"};for(let n=0;n{this.handleDisconnect("signal",it.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=t=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==t?void 0:t.reason})),t.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:5e3,regionSettings:t.regions})),t.action){case Vn.DISCONNECT:this.emit(e.EngineEvent.Disconnected,null==t?void 0:t.reason),this.close();break;case Vn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case Vn.RESUME:this.handleDisconnect(wc)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const t=[];e.iceServers.forEach((e=>{const n={urls:e.urls};e.username&&(n.username=e.username),e.credential&&(n.credential=e.credential),t.push(n)})),n.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===tt.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Sc,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ec,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return Fi(this,void 0,void 0,(function*(){if(er()){return yield this.createTransceiverRTCRtpSender(e,t,n)}if(tr()){this.log.warn("using add-track fallback",this.logContext);return yield this.createRTCRtpSender(e.mediaStreamTrack)}throw new Ss("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,n,i){return Fi(this,void 0,void 0,(function*(){if(er())return this.createSimulcastTransceiverSender(e,t,n,i);if(tr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ss("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,n){return Fi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ss("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Br(e)&&(e.codec=t.videoCodec);const o={direction:"sendonly",streams:i};n&&(o.sendEncodings=n);return(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,o)).sender}))}createSimulcastTransceiverSender(e,t,n,i){return Fi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ss("publisher is closed");const o={direction:"sendonly"};i&&(o.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,o);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender}))}createRTCRtpSender(e){return Fi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ss("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(t){return Fi(this,void 0,void 0,(function*(){var n,i,o;if(!this._isClosed)if(this.attemptingReconnect)Di.warn("already attempting reconnect, returning early",this.logContext);else{(null===(n=this.clientConfiguration)||void 0===n?void 0:n.resumeConnection)!==tt.DISABLED&&(null!==(o=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==o?o:za.NEW)!==za.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(t),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let n=!0;t instanceof Ss?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),n=!1):t instanceof Ic||(this.fullReconnectOnNext=!0),n?this.handleDisconnect("reconnect",it.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(e.EngineEvent.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(t){return Fi(this,void 0,void 0,(function*(){var n,i,o;try{if(!this.url||!this.token)throw new Ss("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ic;i=yield this.join(null!=t?t:this.url,this.token,this.signalOpts)}catch(t){if(t instanceof ys&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new Ss("could not reconnect, token might be expired");throw new Ic}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(e.EngineEvent.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==va.CONNECTED)throw new Ic("Signal connection got severed during reconnect");null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),this.emit(e.EngineEvent.Restarted)}catch(e){const t=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(t)return void(yield this.restartConnection(t));throw null===(o=this.regionUrlProvider)||void 0===o||o.resetAttempts(),e}}))}resumeConnection(t){return Fi(this,void 0,void 0,(function*(){var n;if(!this.url||!this.token)throw new Ss("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ss("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(e.EngineEvent.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,t)}catch(t){let n="";if(t instanceof Error&&(n=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof ys&&t.reason===e.ConnectionErrorReason.NotAllowed)throw new Ss("could not reconnect, token might be expired");if(t instanceof ys&&t.reason===e.ConnectionErrorReason.LeaveRequest)throw t;throw new Ic(n)}if(this.emit(e.EngineEvent.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==va.CONNECTED)throw new Ic("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(n=this.reliableDC)||void 0===n?void 0:n.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(e.EngineEvent.Resumed)}))}waitForPCInitialConnection(e,t){return Fi(this,void 0,void 0,(function*(){if(!this.pcManager)throw new Ss("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Fi(this,void 0,void 0,(function*(){this.pcState=Rc.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield $s(2e3),!this.pcManager)throw new Ss("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Rc.Connected}catch(t){throw this.pcState=Rc.Disconnected,new ys("could not establish PC connection, ".concat(t.message),e.ConnectionErrorReason.InternalError)}}))}publishRpcResponse(e,t,n,i){return Fi(this,void 0,void 0,(function*(){const o=new kt({destinationIdentities:[e],kind:yt.RELIABLE,value:{case:"rpcResponse",value:new Dt({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:null!=n?n:""}})}});yield this.sendDataPacket(o,yt.RELIABLE)}))}publishRpcAck(e,t){return Fi(this,void 0,void 0,(function*(){const n=new kt({destinationIdentities:[e],kind:yt.RELIABLE,value:{case:"rpcAck",value:new _t({requestId:t})}});yield this.sendDataPacket(n,yt.RELIABLE)}))}sendDataPacket(e,t){return Fi(this,void 0,void 0,(function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const t=cs(e);if(t){const n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:"encryptedPacket",value:new bt({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===yt.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),i=this.dataChannelForKind(t);if(i){if(t===yt.RELIABLE&&this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;i.send(n)}this.updateAndEmitDCBufferStatus(t)}))}resendReliableMessagesForResume(e){return Fi(this,void 0,void 0,(function*(){yield this.ensurePublisherConnected(yt.RELIABLE);const t=this.dataChannelForKind(yt.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach((e=>{t.send(e.data)}))),this.updateAndEmitDCBufferStatus(yt.RELIABLE)}))}waitForBufferStatusLow(t){return new Promise(((n,i)=>Fi(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(t))n();else{const o=()=>i("Engine closed");for(this.once(e.EngineEvent.Closing,o);!this.dcBufferStatus.get(t);)yield $s(10);this.off(e.EngineEvent.Closing,o),n()}}))))}ensureDataTransportConnected(t){return Fi(this,arguments,void 0,(function(t){var n=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var o;if(!n.pcManager)throw new Ss("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new ys("".concat(r," connection not set"),e.ConnectionErrorReason.InternalError);let a=!1;i||n.dataChannelForKind(t,i)||(n.createDataChannels(),a=!0),a||i||n.pcManager.publisher.isICEConnected||"checking"===n.pcManager.publisher.getICEConnectionState()||(a=!0),a&&n.negotiate().catch((e=>{Di.error(e,n.logContext)}));const c=n.dataChannelForKind(t,i);if("open"===(null==c?void 0:c.readyState))return;const d=(new Date).getTime()+n.peerConnectionTimeout;for(;(new Date).getTime()Fi(this,void 0,void 0,(function*(){if(!this.pcManager)return void n(new Es("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,o=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),t()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(e.EngineEvent.Closing,o),this.pcManager.publisher.once(Ua,(t=>{const n=new Map;t.forEach((e=>{const t=e.codec.toLowerCase();Mr(t)&&n.set(e.payload,t)})),this.emit(e.EngineEvent.RTPVideoMapUpdate,n)}));try{yield this.pcManager.negotiate(i),t()}catch(e){e instanceof Es&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",it.RR_UNKNOWN),n(e)}finally{this.off(e.EngineEvent.Closing,o)}}))))}))}dataChannelForKind(e,t){if(t){if(e===yt.LOSSY)return this.lossyDCSub;if(e===yt.RELIABLE)return this.reliableDCSub}else{if(e===yt.LOSSY)return this.lossyDC;if(e===yt.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i,o,s;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const r=this.pcManager.publisher.getLocalDescription(),a=this.pcManager.publisher.getRemoteDescription(),c=null===(n=this.pcManager.subscriber)||void 0===n?void 0:n.getRemoteDescription(),d=null===(i=this.pcManager.subscriber)||void 0===i?void 0:i.getLocalDescription(),l=null===(s=null===(o=this.signalOpts)||void 0===o?void 0:o.autoSubscribe)||void 0===s||s,u=new Array,h=new Array;e.forEach((e=>{e.isDesired!==l&&u.push(e.trackSid),e.isEnabled||h.push(e.trackSid)})),this.client.sendSyncState(new si({answer:this.options.singlePeerConnection?a?ya({sdp:a.sdp,type:a.type}):void 0:d?ya({sdp:d.sdp,type:d.type}):void 0,offer:this.options.singlePeerConnection?r?ya({sdp:r.sdp,type:r.type}):void 0:c?ya({sdp:c.sdp,type:c.type}):void 0,subscription:new Ln({trackSids:u,subscribe:!l,participantTracks:[]}),publishTracks:na(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:h,datachannelReceiveStates:this.reliableReceivedState.map(((e,t)=>new ri({publisherSid:t,lastSeq:e})))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,n)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new ai({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(yt.LOSSY),Tn.PUBLISHER),t(this.dataChannelForKind(yt.RELIABLE),Tn.PUBLISHER),t(this.dataChannelForKind(yt.LOSSY,!0),Tn.SUBSCRIBER),t(this.dataChannelForKind(yt.RELIABLE,!0),Tn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ns.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){pr()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){pr()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=null===(t=this.pcManager)||void 0===t?void 0:t.getMidForReceiver(e);if(n){const e=Object.entries(this.midToTrackId).find((e=>{let[t]=e;return t===n}));if(e)return e[1]}}}class Ic extends Error{}function Oc(e,t){const n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;const i=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=i,t.destinationIdentities=i}class _c{get info(){return this._info}validateBytesReceived(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if("number"==typeof this.totalByteSize&&0!==this.totalByteSize){if(t&&this.bytesReceivedthis.totalByteSize)throw new Ps("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),e.DataStreamErrorReason.LengthExceeded)}}constructor(e,t,n,i){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=i}}class Dc extends _c{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Dr,n=null,i=null;if(this.signal){const e=this.signal;i=()=>{var n;null===(n=t.reject)||void 0===n||n.call(t,e.reason)},e.addEventListener("abort",i),n=e}const o=()=>{e.releaseLock(),n&&i&&n.removeEventListener("abort",i),this.signal=void 0};return{next:()=>Fi(this,void 0,void 0,(function*(){var n,i;try{const{done:o,value:s}=yield Promise.race([e.read(),t.promise,null!==(i=null===(n=this.outOfBandFailureRejectingFuture)||void 0===n?void 0:n.promise)&&void 0!==i?i:new Promise((()=>{}))]);return o?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(s),{done:!1,value:s.content})}catch(e){throw o(),e}})),return(){return Fi(this,void 0,void 0,(function*(){return o(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Fi(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,o,s;let r=new Set;const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Vi(a);!(n=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;r.add(e)}}catch(e){i={error:e}}finally{try{d||n||!(o=l.return)||(yield o.call(l))}finally{if(i)throw i.error}}return Array.from(r)}()}))}}class Mc extends _c{constructor(e,t,n,i){super(e,t,n,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Lr(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const o=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,o)}[Symbol.asyncIterator](){const t=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new Dr,o=null,s=null;if(this.signal){const e=this.signal;s=()=>{var t;null===(t=i.reject)||void 0===t||t.call(i,e.reason)},e.addEventListener("abort",s),o=e}const r=()=>{t.releaseLock(),o&&s&&o.removeEventListener("abort",s),this.signal=void 0};return{next:()=>Fi(this,void 0,void 0,(function*(){var o,s;try{const{done:r,value:a}=yield Promise.race([t.read(),i.promise,null!==(s=null===(o=this.outOfBandFailureRejectingFuture)||void 0===o?void 0:o.promise)&&void 0!==s?s:new Promise((()=>{}))]);if(r)return this.validateBytesReceived(!0),{done:!0,value:void 0};{let t;this.handleChunkReceived(a);try{t=n.decode(a.content)}catch(t){throw new Ps("Cannot decode datastream chunk ".concat(a.chunkIndex," as text: ").concat(t),e.DataStreamErrorReason.DecodeFailed)}return{done:!1,value:t}}}catch(e){throw r(),e}})),return(){return Fi(this,void 0,void 0,(function*(){return r(),{done:!0,value:void 0}}))}}}withAbortSignal(e){return this.signal=e,this}readAll(){return Fi(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i,o,s;let r="";const a=t.signal?e.withAbortSignal(t.signal):e;try{for(var c,d=!0,l=Vi(a);!(n=(c=yield l.next()).done);d=!0){s=c.value,d=!1;r+=s}}catch(e){i={error:e}}finally{try{d||n||!(o=l.return)||(yield o.call(l))}finally{if(i)throw i.error}}return r}()}))}}class xc{constructor(){this.log=Di,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(t,n){if(this.textStreamHandlers.has(t))throw new Ps('A text stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.textStreamHandlers.set(t,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(t,n){if(this.byteStreamHandlers.has(t))throw new Ps('A byte stream handler for topic "'.concat(t,'" has already been set.'),e.DataStreamErrorReason.HandlerAlreadyRegistered);this.byteStreamHandlers.set(t,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(t){var n,i,o,s;const r=Array.from(this.textStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t)),a=Array.from(this.byteStreamControllers.entries()).filter((e=>e[1].sendingParticipantIdentity===t));if(r.length>0||a.length>0){const c=new Ps("Participant ".concat(t," unexpectedly disconnected in the middle of sending data"),e.DataStreamErrorReason.AbnormalEnd);for(const[e,t]of a)null===(i=(n=t.outOfBandFailureRejectingFuture).reject)||void 0===i||i.call(n,c),this.byteStreamControllers.delete(e);for(const[e,t]of r)null===(s=(o=t.outOfBandFailureRejectingFuture).reject)||void 0===s||s.call(o,c),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return Fi(this,void 0,void 0,(function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}}))}handleStreamHeader(t,n,i){return Fi(this,void 0,void 0,(function*(){var o;if("byteHeader"===t.contentHeader.case){const s=this.byteStreamHandlers.get(t.topic);if(!s)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",t.topic);let r;const a=new Dr;a.promise.catch((e=>{this.log.error(e)}));const c={id:t.streamId,name:null!==(o=t.contentHeader.value.name)&&void 0!==o?o:"unknown",mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Lr(t.timestamp),attributes:t.attributes,encryptionType:i},d=new ReadableStream({start:i=>{if(r=i,this.textStreamControllers.has(t.streamId))throw new Ps("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.byteStreamControllers.set(t.streamId,{info:c,controller:r,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:a})}});s(new Dc(c,d,Lr(t.totalLength),a),{identity:n})}else if("textHeader"===t.contentHeader.case){const o=this.textStreamHandlers.get(t.topic);if(!o)return void this.log.debug("ignoring incoming text stream due to no handler for topic",t.topic);let s;const r=new Dr;r.promise.catch((e=>{this.log.error(e)}));const a={id:t.streamId,mimeType:t.mimeType,size:t.totalLength?Number(t.totalLength):void 0,topic:t.topic,timestamp:Number(t.timestamp),attributes:t.attributes,encryptionType:i},c=new ReadableStream({start:i=>{if(s=i,this.textStreamControllers.has(t.streamId))throw new Ps("A data stream read is already in progress for a stream with id ".concat(t.streamId,"."),e.DataStreamErrorReason.AlreadyOpened);this.textStreamControllers.set(t.streamId,{info:a,controller:s,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:r})}});o(new Mc(a,c,Lr(t.totalLength),r),{identity:n})}}))}handleStreamChunk(t,n){const i=this.byteStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new Ps("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.byteStreamControllers.delete(t.streamId)):t.content.length>0&&i.controller.enqueue(t));const o=this.textStreamControllers.get(t.streamId);o&&(o.info.encryptionType!==n?(o.controller.error(new Ps("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(o.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)),this.textStreamControllers.delete(t.streamId)):t.content.length>0&&o.controller.enqueue(t))}handleStreamTrailer(t,n){const i=this.textStreamControllers.get(t.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new Ps("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),t.attributes),i.controller.close(),this.textStreamControllers.delete(t.streamId)));const o=this.byteStreamControllers.get(t.streamId);o&&(o.info.encryptionType!==n?o.controller.error(new Ps("Encryption type mismatch for stream ".concat(t.streamId,". Expected ").concat(n,", got ").concat(o.info.encryptionType),e.DataStreamErrorReason.EncryptionTypeMismatch)):(o.info.attributes=Object.assign(Object.assign({},o.info.attributes),t.attributes),o.controller.close()),this.byteStreamControllers.delete(t.streamId))}}class Ac{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Fi(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class Nc extends Ac{}class Lc extends Ac{}class Uc{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return Fi(this,void 0,void 0,(function*(){var n;const i=crypto.randomUUID(),o=(new TextEncoder).encode(e).byteLength,s=null===(n=null==t?void 0:t.attachments)||void 0===n?void 0:n.map((()=>crypto.randomUUID())),r=new Array(s?s.length+1:1).fill(0),a=(e,n)=>{var i;r[n]=e;const o=r.reduce(((e,t)=>e+t),0);null===(i=null==t?void 0:t.onProgress)||void 0===i||i.call(t,o)},c=yield this.streamText({streamId:i,totalSize:o,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map(((e,n)=>Fi(this,void 0,void 0,(function*(){return this._sendFile(s[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,n+1)}})})))))),c.info}))}streamText(t){return Fi(this,void 0,void 0,(function*(){var n,i,o;const s=null!==(n=null==t?void 0:t.streamId)&&void 0!==n?n:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==t?void 0:t.topic)&&void 0!==i?i:"",size:null==t?void 0:t.totalSize,attributes:null==t?void 0:t.attributes,encryptionType:(null===(o=this.engine.e2eeManager)||void 0===o?void 0:o.isDataChannelEncryptionEnabled)?pt.GCM:pt.NONE},a=new Ht({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:Ur(r.timestamp),totalLength:Ur(null==t?void 0:t.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Wt({version:null==t?void 0:t.version,attachedStreamIds:null==t?void 0:t.attachedStreamIds,replyToStreamId:null==t?void 0:t.replyToStreamId,operationType:"update"===(null==t?void 0:t.type)?qt.UPDATE:qt.CREATE})}}),c=null==t?void 0:t.destinationIdentities,d=new kt({destinationIdentities:c,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(d,yt.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(e){return Fi(this,void 0,void 0,(function*(){for(const t of function(e,t){const n=[];let i=(new TextEncoder).encode(e);for(;i.length>t;){let e=t;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}n.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&n.push(i),n}(e,15e3)){yield u.waitForBufferStatusLow(yt.RELIABLE);const e=new Gt({content:t,streamId:s,chunkIndex:Ur(l)}),n=new kt({destinationIdentities:c,value:{case:"streamChunk",value:e}});yield u.sendDataPacket(n,yt.RELIABLE),l+=1}}))},close(){return Fi(this,void 0,void 0,(function*(){const e=new Jt({streamId:s}),t=new kt({destinationIdentities:c,value:{case:"streamTrailer",value:e}});yield u.sendDataPacket(t,yt.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let p=()=>Fi(this,void 0,void 0,(function*(){yield m.close()}));u.once(e.EngineEvent.Closing,p);const m=new Nc(h,r,(()=>this.engine.off(e.EngineEvent.Closing,p)));return m}))}sendFile(e,t){return Fi(this,void 0,void 0,(function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}}))}_sendFile(e,t,n){return Fi(this,void 0,void 0,(function*(){var i;const o=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(i=null==n?void 0:n.mimeType)&&void 0!==i?i:t.type,topic:null==n?void 0:n.topic,destinationIdentities:null==n?void 0:n.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:e,value:t}=yield s.read();if(e)break;yield o.write(t)}return yield o.close(),o.info}))}streamBytes(e){return Fi(this,void 0,void 0,(function*(){var t,n,i,s,r,a;const c=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),d=null==e?void 0:e.destinationIdentities,l={id:c,mimeType:null!==(n=null==e?void 0:e.mimeType)&&void 0!==n?n:"application/octet-stream",topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown",encryptionType:(null===(r=this.engine.e2eeManager)||void 0===r?void 0:r.isDataChannelEncryptionEnabled)?pt.GCM:pt.NONE},u=new Ht({totalLength:Ur(null!==(a=l.size)&&void 0!==a?a:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:Ur(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Kt({name:l.name})}}),h=new kt({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,yt.RELIABLE);let p=0;const m=new o,g=this.engine,v=this.log,f=new WritableStream({write(e){return Fi(this,void 0,void 0,(function*(){const t=yield m.lock();let n=0;try{for(;n{i.track===this._mediaStreamTrack&&(t.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(e.TrackEvent.Ended,this))};t.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Fi(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.receiver)||void 0===e?void 0:e.getStats))return;return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),ec)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const t=()=>{var n;this.timeSyncHandle=requestAnimationFrame((()=>t()));const i=null===(n=this.receiver)||void 0===n?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:t,rtpTimestamp:n}=i;n&&this.rtpTimestamp!==n&&(this.emit(e.TrackEvent.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}};t()}}class Fc extends jc{constructor(e,t,n,i,o,s){super(e,t,js.Kind.Audio,n,s),this.monitorReceiver=()=>Fi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=tc(e,this.prevStats)),this.prevStats=e})),this.audioContext=i,this.webAudioPluginNodes=[],o&&(this.sinkId=o.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):n.volume=e;mr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(mr())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Fi(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(sr(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&sr(e)&&e.setSinkId(this.sinkId).catch((e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)})),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(t,n){this.disconnectWebAudio(),this.sourceNode=t.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=t.createGain(),i.connect(this.gainNode),this.gainNode.connect(t.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==t.state&&t.resume().then((()=>{"running"!==t.state&&this.emit(e.TrackEvent.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((t=>{this.emit(e.TrackEvent.AudioPlaybackFailed,t)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Fi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class Bc extends jc{constructor(e,t,n,i,o){super(e,t,js.Kind.Video,n,o),this.elementInfos=[],this.monitorReceiver=()=>Fi(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=tc(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Aa((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===js.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Bs(this._mediaStreamTrack,t):Fs(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new Vc(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Fi(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(n=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&i.set(e.id,e)})),t&&""!==n&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Fi(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(t){var n,i;const o=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),s=!(null!==(i=null===(n=this.adaptiveStreamSettings)||void 0===n?void 0:n.pauseVideoInBackground)&&void 0!==i&&!i)&&this.isInBackground,r=this.elementInfos.some((e=>e.pictureInPicture)),a=this.elementInfos.some((e=>e.visible))&&!s||r;(this.lastVisible!==a||t)&&(!a&&Date.now()-o<100?Ns.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=a,this.emit(e.TrackEvent.VisibilityChanged,a,this)))}updateDimensions(){var t,n;let i=0,o=0;const s=this.getPixelDensity();for(const e of this.elementInfos){const t=e.width()*s,n=e.height()*s;t+n>i+o&&(i=t,o=n)}(null===(t=this.lastDimensions)||void 0===t?void 0:t.width)===i&&(null===(n=this.lastDimensions)||void 0===n?void 0:n.height)===o||(this.lastDimensions={width:i,height:o},this.emit(e.TrackEvent.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;if("screen"===t)return yr();if(!t){return yr()>2?2:1}return t}}class Vc{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:n,isIntersecting:i}=e;n===this.element&&(this.isIntersecting=i,this.isPiP=qc(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,n;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=qc(this.element),null===(n=this.handleVisibilityChanged)||void 0===n||n.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=qc(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:Wc(e),this.isPiP=pr()&&qc(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Wc(this.element),this.isPiP=qc(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Rr().observe(this.element),Er().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(n=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===n||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,o;null===(e=Rr())||void 0===e||e.unobserve(this.element),null===(t=Er())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(n=window.documentPictureInPicture)||void 0===n||n.removeEventListener("enter",this.onEnterPiP),null===(o=null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)||void 0===o||o.removeEventListener("pagehide",this.onLeavePiP)}}function qc(e){var t,n;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&Wc(e,null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)}function Wc(e,t){const n=t||window;let i=e.offsetTop,o=e.offsetLeft;const s=e.offsetWidth,r=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)i+=(e=e.offsetParent).offsetTop,o+=e.offsetLeft;return in.pageYOffset&&o+s>n.pageXOffset&&!a&&"none"!==c}class Kc extends Ki.EventEmitter{constructor(t,n,i,o){var s;super(),this.metadataMuted=!1,this.encryption=pt.NONE,this.log=Di,this.handleMuted=()=>{this.emit(e.TrackEvent.Muted)},this.handleUnmuted=()=>{this.emit(e.TrackEvent.Unmuted)},this.log=xi(null!==(s=null==o?void 0:o.loggerName)&&void 0!==s?s:e.LoggerNames.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=t,this.trackSid=n,this.trackName=i,this.source=js.Source.Unknown}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Muted,this.handleMuted),this.track.off(e.TrackEvent.Unmuted,this.handleUnmuted)),this.track=t,t&&(t.on(e.TrackEvent.Muted,this.handleMuted),t.on(e.TrackEvent.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),ia(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==pt.NONE}get audioTrack(){if(Fr(this.track))return this.track}get videoTrack(){if(Br(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=js.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===js.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}!function(e){var t,n;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(n=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",n.NotAllowed="not_allowed"}(Kc||(Kc={}));class Hc extends Kc{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(t,n,i,o){super(t,n.sid,n.name,o),this.track=void 0,this.handleTrackEnded=()=>{this.emit(e.TrackEvent.Ended)},this.handleCpuConstrained=()=>{this.track&&Br(this.track)&&this.emit(e.TrackEvent.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(t){this.track&&(this.track.off(e.TrackEvent.Ended,this.handleTrackEnded),this.track.off(e.TrackEvent.CpuConstrained,this.handleCpuConstrained)),super.setTrack(t),t&&(t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return Fi(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Fi(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Fi(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Fi(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(Fr(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(st.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(st.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(st.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(st.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||n.add(st.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(st.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}return[]}}function Gc(e,t){return Fi(this,void 0,void 0,(function*(){null!=e||(e={});let n=!1;const{audioProcessor:i,videoProcessor:o,optionsWithoutProcessor:s}=oa(e);let r=s.audio,a=s.video;if(i&&"object"==typeof s.audio&&(s.audio.processor=i),o&&"object"==typeof s.video&&(s.video.processor=o),e.audio&&"object"==typeof s.audio&&"string"==typeof s.audio.deviceId){const e=s.audio.deviceId;s.audio.deviceId={exact:e},n=!0,r=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:e}})}if(s.video&&"object"==typeof s.video&&"string"==typeof s.video.deviceId){const e=s.video.deviceId;s.video.deviceId={exact:e},n=!0,a=Object.assign(Object.assign({},s.video),{deviceId:{ideal:e}})}(!0===s.audio||"object"==typeof s.audio&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),!0===s.video?s.video={deviceId:"default"}:"object"!=typeof s.video||s.video.deviceId||(s.video.deviceId="default");const c=Jr(s,Ka,Ha),d=Qr(c),l=navigator.mediaDevices.getUserMedia(d);s.audio&&(da.userMediaPromiseMap.set("audioinput",l),l.catch((()=>da.userMediaPromiseMap.delete("audioinput")))),s.video&&(da.userMediaPromiseMap.set("videoinput",l),l.catch((()=>da.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((n=>Fi(this,void 0,void 0,(function*(){const s="audio"===n.kind;let r,a=s?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=s?d.audio:d.video;"boolean"!=typeof l&&(r=l);const u=n.getSettings().deviceId;(null==r?void 0:r.deviceId)&&xr(r.deviceId)!==u?r.deviceId=u:r||(r={deviceId:u});const h=function(e,t,n){switch(e.kind){case"audio":return new rc(e,t,!1,void 0,n);case"video":return new yc(e,t,!1,n);default:throw new Ts("unsupported track type: ".concat(e.kind))}}(n,r,t);return h.kind===js.Kind.Video?h.source=js.Source.Camera:h.kind===js.Kind.Audio&&(h.source=js.Source.Microphone),h.mediaStream=e,Fr(h)&&i?yield h.setProcessor(i):Br(h)&&o&&(yield h.setProcessor(o)),h})))))}catch(i){if(!n)throw i;return Gc(Object.assign(Object.assign({},e),{audio:r,video:a}),t)}}))}function Jc(e){return Fi(this,void 0,void 0,(function*(){return(yield Gc({audio:!1,video:null==e||e}))[0]}))}function zc(e){return Fi(this,void 0,void 0,(function*(){return(yield Gc({audio:null==e||e,video:!1}))[0]}))}var Qc,Yc;e.ConnectionQuality=void 0,(Qc=e.ConnectionQuality||(e.ConnectionQuality={})).Excellent="excellent",Qc.Good="good",Qc.Poor="poor",Qc.Lost="lost",Qc.Unknown="unknown";class Xc extends Ki.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===ut.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===lt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(t,n,i,o,s,r){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:ut.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=e.ConnectionQuality.Unknown,this.log=Di,this.log=xi(null!==(c=null==r?void 0:r.loggerName)&&void 0!==c?c:e.LoggerNames.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=t,this.identity=n,this.name=i,this.metadata=o,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new Dr,this.once(e.ParticipantEvent.Active,(()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0}))),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(js.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(js.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(js.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(t){var n;return!(this.participantInfo&&this.participantInfo.sid===t.sid&&this.participantInfo.version>t.version)&&(this.identity=t.identity,this.sid=t.sid,this._setName(t.name),this._setMetadata(t.metadata),this._setAttributes(t.attributes),t.state===lt.ACTIVE&&(null===(n=this.participantInfo)||void 0===n?void 0:n.state)!==lt.ACTIVE&&this.emit(e.ParticipantEvent.Active),t.permission&&this.setPermissions(t.permission),this.participantInfo=t,!0)}_setMetadata(t){const n=this.metadata!==t,i=this.metadata;this.metadata=t,n&&this.emit(e.ParticipantEvent.ParticipantMetadataChanged,i)}_setName(t){const n=this.name!==t;this.name=t,n&&this.emit(e.ParticipantEvent.ParticipantNameChanged,t)}_setAttributes(t){const n=function(e,t){var n;void 0===e&&(e={}),void 0===t&&(t={});const i=[...Object.keys(t),...Object.keys(e)],o={};for(const s of i)e[s]!==t[s]&&(o[s]=null!==(n=t[s])&&void 0!==n?n:"");return o}(this.attributes,t);this._attributes=t,Object.keys(n).length>0&&this.emit(e.ParticipantEvent.AttributesChanged,n)}setPermissions(t){var n,i,o,s,r,a;const c=this.permissions,d=t.canPublish!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublish)||t.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||t.canPublishData!==(null===(o=this.permissions)||void 0===o?void 0:o.canPublishData)||t.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||t.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||t.canPublishSources.length!==this.permissions.canPublishSources.length||t.canPublishSources.some(((e,t)=>{var n;return e!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishSources[t])}))||t.canSubscribeMetrics!==(null===(a=this.permissions)||void 0===a?void 0:a.canSubscribeMetrics);return this.permissions=t,d&&this.emit(e.ParticipantEvent.ParticipantPermissionsChanged,c),d}setIsSpeaking(t){t!==this.isSpeaking&&(this.isSpeaking=t,t&&(this.lastSpokeAt=new Date),this.emit(e.ParticipantEvent.IsSpeakingChanged,t))}setConnectionQuality(t){const n=this._connectionQuality;this._connectionQuality=function(t){switch(t){case et.EXCELLENT:return e.ConnectionQuality.Excellent;case et.GOOD:return e.ConnectionQuality.Good;case et.POOR:return e.ConnectionQuality.Poor;case et.LOST:return e.ConnectionQuality.Lost;default:return e.ConnectionQuality.Unknown}}(t),n!==this._connectionQuality&&this.emit(e.ParticipantEvent.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>Fr(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(t){t.on(e.TrackEvent.Muted,(()=>{this.emit(e.ParticipantEvent.TrackMuted,t)})),t.on(e.TrackEvent.Unmuted,(()=>{this.emit(e.ParticipantEvent.TrackUnmuted,t)}));const n=t;switch(n.track&&(n.track.sid=t.trackSid),this.trackPublications.set(t.trackSid,t),t.kind){case js.Kind.Audio:this.audioTrackPublications.set(t.trackSid,t);break;case js.Kind.Video:this.videoTrackPublications.set(t.trackSid,t)}}}class Zc extends Xc{constructor(t,n,i,o,s,r){super(t,n,void 0,void 0,void 0,{loggerName:o.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=pt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Dr)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,i,o,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(i=(n=this.signalConnectedFuture).reject)||void 0===i||i.call(n,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(s=null===(o=this.activeAgentFuture)||void 0===o?void 0:o.reject)||void 0===s||s.call(o,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Dr),null===(n=(t=this.signalConnectedFuture).resolve)||void 0===n||n.call(t)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:n,message:i}=e,o=this.pendingSignalRequests.get(t);o&&(n!==gi.OK&&o.reject(new Rs(i,n)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,n=null,i=null;"payload"===t.value.case?n=t.value.value:"error"===t.value.case&&(i=Xa.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,i);break;case"rpcAck":let o=e.value.value;this.handleIncomingRpcAck(o.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,n,i;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new ti({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(n=e.participantSid)&&void 0!==n?n:"",allTracks:null!==(i=e.allowAll)&&void 0!==i&&i,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ia(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ia(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ia(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.onTrackCpuConstrained=(t,n)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),ia(n))),this.emit(e.ParticipantEvent.LocalTrackCpuConstrained,t,n)},this.handleSubscribedQualityUpdate=e=>Fi(this,void 0,void 0,(function*(){var t,n,i,o,s;if(!(null===(s=this.roomOptions)||void 0===s?void 0:s.dynacast))return;const r=this.videoTrackPublications.get(e.trackSid);if(!r)return void this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));if(!r.videoTrack)return;const a=yield r.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Vi(a);!(t=(c=yield l.next()).done);d=!0){o=c.value,d=!1;const e=o;Gs(e)&&(this.log.debug("publish ".concat(e," for ").concat(r.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ia(r))),yield this.publishAdditionalCodecForTrack(r.videoTrack,e,r.options))}}catch(e){n={error:e}}finally{try{d||t||!(i=l.return)||(yield i.call(l))}finally{if(n)throw n.error}}})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Fi(this,void 0,void 0,(function*(){if(e.source===js.Source.ScreenShare||e.source===js.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ia(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(qr(e)||Vr(e))try{if(pr())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===js.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),ia(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ia(e))),qr(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ia(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=o,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s,this.roomOutgoingDataStreamManager=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==pt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(t){var n;this.engine=t,this.engine.on(e.EngineEvent.RemoteMute,((e,t)=>{const n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())})),(null===(n=this.signalConnectedFuture)||void 0===n?void 0:n.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(e.EngineEvent.Connected,this.handleReconnected).on(e.EngineEvent.SignalConnected,this.handleSignalConnected).on(e.EngineEvent.SignalRestarted,this.handleReconnected).on(e.EngineEvent.SignalResumed,this.handleReconnected).on(e.EngineEvent.Restarting,this.handleReconnecting).on(e.EngineEvent.Resuming,this.handleReconnecting).on(e.EngineEvent.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(e.EngineEvent.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(e.EngineEvent.Closing,this.handleClosing).on(e.EngineEvent.SignalRequestResponse,this.handleSignalRequestResponse).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Fi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Fi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Fi(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Fi(this,arguments,void 0,(function(e){var t=this;let{metadata:n,name:i,attributes:o}=e;return function*(){return new Promise(((e,s)=>Fi(t,void 0,void 0,(function*(){var t,r;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=n?n:this.metadata)&&void 0!==t?t:"",null!==(r=null!=i?i:this.name)&&void 0!==r?r:"",o),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{s(e),a=!0},values:{name:i,metadata:n,attributes:o}});performance.now()-d<5e3&&!a;){if((!i||this.name===i)&&(!n||this.metadata===n)&&(!o||Object.entries(o).every((e=>{let[t,n]=e;return this.attributes[t]===n||""===n&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield $s(50)}s(new Rs("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&s(e)}}))))}()}))}setCameraEnabled(e,t,n){return this.setTrackEnabled(js.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(js.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(js.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return Fi(this,void 0,void 0,(function*(){this.encryptionType=e?pt.GCM:pt.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(t,n,i,o){return Fi(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:t,enabled:n})),this.republishPromise&&(yield this.republishPromise);let a=this.getTrackPublication(t);if(n)if(a)yield a.unmute();else{let n;if(this.pendingPublishing.has(t)){const e=yield this.waitForPendingPublicationOfSource(t);return e||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t})),yield null==e?void 0:e.unmute(),e}this.pendingPublishing.add(t);try{switch(t){case js.Source.Camera:n=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case js.Source.Microphone:n=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case js.Source.ScreenShare:n=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Ts(t)}}catch(i){throw null==n||n.forEach((e=>{e.stop()})),i instanceof Error&&this.emit(e.ParticipantEvent.MediaDevicesError,i,$r(t)),this.pendingPublishing.delete(t),i}for(const e of n){const n=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);t===js.Source.Microphone&&Fr(e)&&n.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),e.startPreConnectBuffer())}try{const e=[];for(const t of n)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ia(t))),e.push(this.publishTrack(t,o));const t=yield Promise.all(e);[a]=t}catch(e){throw null==n||n.forEach((e=>{e.stop()})),e}finally{this.pendingPublishing.delete(t)}}else if(!(null==a?void 0:a.track)&&this.pendingPublishing.has(t)&&(a=yield this.waitForPendingPublicationOfSource(t),a||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:t}))),a&&a.track)if(t===js.Source.ScreenShare){a=yield this.unpublishTrack(a.track);const e=this.getTrackPublication(js.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield a.mute();return a}))}enableCameraAndMicrophone(){return Fi(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(js.Source.Camera)&&!this.pendingPublishing.has(js.Source.Microphone)){this.pendingPublishing.add(js.Source.Camera),this.pendingPublishing.add(js.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(js.Source.Camera),this.pendingPublishing.delete(js.Source.Microphone)}}}))}createTracks(t){return Fi(this,void 0,void 0,(function*(){var n,i;null!=t||(t={});const o=Jr(t,null===(n=this.roomOptions)||void 0===n?void 0:n.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{const t=yield Gc(o,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return t.map((t=>(Fr(t)&&(this.microphoneError=void 0,t.setAudioContext(this.audioContext),t.source=js.Source.Microphone,this.emit(e.ParticipantEvent.AudioStreamAcquired)),Br(t)&&(this.cameraError=void 0,t.source=js.Source.Camera),t)))}catch(e){throw e instanceof Error&&(t.audio&&(this.microphoneError=e),t.video&&(this.cameraError=e)),e}}))}createScreenTracks(t){return Fi(this,void 0,void 0,(function*(){if(void 0===t&&(t={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new bs("getDisplayMedia not supported");void 0!==t.resolution||ur()||(t.resolution=Xs.h1080fps30.resolution);const n=ea(t),i=yield navigator.mediaDevices.getDisplayMedia(n),o=i.getVideoTracks();if(0===o.length)throw new Ts("no video track found");const s=new yc(o[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=js.Source.ScreenShare,t.contentHint&&(s.mediaStreamTrack.contentHint=t.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(e.ParticipantEvent.AudioStreamAcquired);const t=new rc(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});t.source=js.Source.ScreenShareAudio,r.push(t)}return r}))}publishTrack(e,t){return Fi(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return Fi(this,arguments,void 0,(function(e,t){var n=this;let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var o,s,r,a;let c,d;if(qr(e)&&e.setAudioContext(n.audioContext),yield null===(o=n.reconnectFuture)||void 0===o?void 0:o.promise,n.republishPromise&&!i&&(yield n.republishPromise),jr(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case js.Source.Microphone:t="audioinput";break;case js.Source.Camera:t="videoinput"}t&&n.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new rc(e,c,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case"video":e=new yc(e,c,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new Ts("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});if(n.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return n.log.warn("track has already been published, skipping",Object.assign(Object.assign({},n.logContext),ia(d))),d;const l=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),u="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,h=null!==(s=l.forceStereo)&&void 0!==s?s:u;h&&(void 0===l.dtx&&n.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},n.logContext),ia(e))),void 0===l.red&&n.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(r=l.dtx)&&void 0!==r||(l.dtx=!1),null!==(a=l.red)&&void 0!==a||(l.red=!1)),!function(){const e=_s(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&br(e.osVersion,t)>=0)||"Safari"===e.name&&br(e.version,t)>=0}()&&n.roomOptions.e2ee&&(n.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},n.logContext)),l.simulcast=!1),l.source&&(e.source=l.source);const p=new Promise(((t,i)=>Fi(n,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==va.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ia(e)}));let n=!1;const o=setTimeout((()=>{n=!0,e.stop(),i(new ws("publishing rejected as engine not connected within timeout",408))}),15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(o),n)return;const s=yield this.publish(e,l,h);t(s)}else try{const n=yield this.publish(e,l,h);t(n)}catch(e){i(e)}}catch(e){i(e)}}))));n.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()}))}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Dr),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ia(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return!(!t||0!==n.length&&!n.map((e=>function(e){switch(e){case Ze.CAMERA:return js.Source.Camera;case Ze.MICROPHONE:return js.Source.Microphone;case Ze.SCREEN_SHARE:return js.Source.ScreenShare;case Ze.SCREEN_SHARE_AUDIO:return js.Source.ScreenShareAudio;default:return js.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ia(e))),!1)}publish(t,n,i){return Fi(this,void 0,void 0,(function*(){var o,s,r,a,c,d,l,u,h,p;if(!this.hasPermissionsToPublish(t))throw new ws("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((e=>jr(t)&&e.source===t.source))&&t.source!==js.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(t.source),Object.assign(Object.assign({},this.logContext),ia(t))),n.stopMicTrackOnMute&&Fr(t)&&(t.stopOnMute=!0),t.source===js.Source.ScreenShare&&ar()&&(n.simulcast=!1),"av1"!==n.videoCodec||nr()||(n.videoCodec=void 0),"vp9"!==n.videoCodec||ir()||(n.videoCodec=void 0),void 0===n.videoCodec&&(n.videoCodec=qa),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>n.videoCodec===ta(e.mime)))||(n.videoCodec=ta(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;t.on(e.TrackEvent.Muted,this.onTrackMuted),t.on(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.on(e.TrackEvent.Ended,this.handleTrackEnded),t.on(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.on(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.on(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=[],v=!(null===(o=n.dtx)||void 0===o||o),f=t.getSourceTrackSettings();f.autoGainControl&&g.push(st.TF_AUTO_GAIN_CONTROL),f.echoCancellation&&g.push(st.TF_ECHO_CANCELLATION),f.noiseSuppression&&g.push(st.TF_NOISE_SUPPRESSION),f.channelCount&&f.channelCount>1&&g.push(st.TF_STEREO),v&&g.push(st.TF_NO_DTX),qr(t)&&t.hasPreConnectBuffer&&g.push(st.TF_PRECONNECT_BUFFER);const k=new Pn({cid:t.mediaStreamTrack.id,name:n.name,type:js.kindToProto(t.kind),muted:t.isMuted,source:js.sourceToProto(t.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=n.red)||void 0===s||s),stream:null==n?void 0:n.stream,backupCodecPolicy:null==n?void 0:n.backupCodecPolicy,audioFeatures:g});let y;if(t.kind===js.Kind.Video){let e={width:0,height:0};try{e=yield t.waitForDimensions()}catch(n){const i=null!==(a=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==a?a:Qs.h720.resolution;e={width:i.width,height:i.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ia(t)),{dims:e}))}k.width=e.width,k.height=e.height,Vr(t)&&(or(m)&&(t.source===js.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in t.mediaStreamTrack&&(t.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),ia(t))))),n.scalabilityMode=null!==(c=n.scalabilityMode)&&void 0!==c?c:"L3T3_KEY"),k.simulcastCodecs=[new Rn({codec:m,cid:t.mediaStreamTrack.id})],!0===n.backupCodec&&(n.backupCodec={codec:qa}),n.backupCodec&&m!==n.backupCodec.codec&&k.encryption===pt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),k.simulcastCodecs.push(new Rn({codec:n.backupCodec.codec,cid:""})))),y=mc(t.source===js.Source.ScreenShare,k.width,k.height,n),k.layers=Cc(k.width,k.height,y,or(n.videoCodec))}else t.kind===js.Kind.Audio&&(y=[{maxBitrate:null===(d=n.audioPreset)||void 0===d?void 0:d.maxBitrate,priority:null!==(u=null===(l=n.audioPreset)||void 0===l?void 0:l.priority)&&void 0!==u?u:"high",networkPriority:null!==(p=null===(h=n.audioPreset)||void 0===h?void 0:h.priority)&&void 0!==p?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ss("cannot publish track when not connected");const b=()=>Fi(this,void 0,void 0,(function*(){var i,o,s;if(!this.engine.pcManager)throw new Ss("pcManager is not ready");if(t.sender=yield this.engine.createSender(t,n,y),this.emit(e.ParticipantEvent.LocalSenderCreated,t.sender,t),Vr(t)&&(null!==(i=n.degradationPreference)&&void 0!==i||(n.degradationPreference=function(e){return e.source===js.Source.ScreenShare||e.constraints.height&&xr(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(t)),t.setDegradationPreference(n.degradationPreference)),y)if(ar()&&t.kind===js.Kind.Audio){let e;for(const n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===t.sender){e=n;break}e&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:e,codec:"opus",maxbr:(null===(o=y[0])||void 0===o?void 0:o.maxBitrate)?y[0].maxBitrate/1e3:0})}else t.codec&&or(t.codec)&&(null===(s=y[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:k.cid,codec:t.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()}));let T;const C=new Promise(((e,n)=>Fi(this,void 0,void 0,(function*(){var i;try{T=yield this.engine.addTrack(k),e(T)}catch(e){t.sender&&(null===(i=this.engine.pcManager)||void 0===i?void 0:i.publisher)&&(this.engine.pcManager.publisher.removeTrack(t.sender),yield this.engine.negotiate().catch((e=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),ia(t)),{error:e}))}))),n(e)}}))));if(this.enabledPublishVideoCodecs.length>0){const e=yield Promise.all([C,b()]);T=e[0]}else{let e;if(T=yield C,T.codecs.forEach((t=>{void 0===e&&(e=t.mimeType)})),e&&t.kind===js.Kind.Video){const i=ta(e);i!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ia(t)),{codec:i})),n.videoCodec=i,y=mc(t.source===js.Source.ScreenShare,k.width,k.height,n))}yield b()}const S=new Hc(t.kind,T,t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(e.TrackEvent.CpuConstrained,(e=>this.onTrackCpuConstrained(e,S))),S.options=n,t.sid=T.sid,this.log.debug("publishing ".concat(t.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:T})),Vr(t)?t.startMonitor(this.engine.client):qr(t)&&t.startMonitor(),this.addTrackPublication(S),this.emit(e.ParticipantEvent.LocalTrackPublished,S),qr(t)&&T.audioFeatures.includes(st.TF_PRECONNECT_BUFFER)){const n=t.getPreConnectBuffer(),i=t.getPreConnectBufferMimeType();if(this.on(e.ParticipantEvent.LocalTrackSubscribed,(e=>{if(e.trackSid===T.sid){if(!t.hasPreConnectBuffer)return void this.log.warn("subscribe event came to late, buffer already closed",this.logContext);this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),ia(t))),t.stopPreConnectBuffer()}})),n){const e=new Promise(((e,o)=>Fi(this,void 0,void 0,(function*(){var s,r,a,c,d,l;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),ia(t)));const m=setTimeout((()=>{o(new Error("agent not active within 10 seconds"))}),1e4),g=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),ia(t)));const v=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[g.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(d=f.sampleRate)&&void 0!==d?d:"48000"),channels:String(null!==(l=f.channelCount)&&void 0!==l?l:"1")}});try{for(var u,h=!0,p=Vi(n);!(s=(u=yield p.next()).done);h=!0){c=u.value,h=!1;const e=c;yield v.write(e)}}catch(e){r={error:e}}finally{try{h||s||!(a=p.return)||(yield a.call(p))}finally{if(r)throw r.error}}yield v.close(),e()}catch(e){o(e)}}))));e.then((()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),ia(t)))})).catch((e=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),ia(t)),{error:e}))}))}}return S}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return Fi(this,void 0,void 0,(function*(){var i;if(this.encryptionType!==pt.NONE)return;let o;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(o=t)})),!o)throw new Ts("track is not published");if(!Vr(e))throw new Ts("track is not a video track");const s=Object.assign(Object.assign({},null===(i=this.roomOptions)||void 0===i?void 0:i.publishDefaults),n),r=function(e,t,n){var i,o,s,r;if(!n.backupCodec||!0===n.backupCodec||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&Di.warn("requested a different codec than specified as backup",{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(i=a.width)&&void 0!==i?i:null===(o=e.dimensions)||void 0===o?void 0:o.width,d=null!==(s=a.height)&&void 0!==s?s:null===(r=e.dimensions)||void 0===r?void 0:r.height;return e.source===js.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),mc(e.source===js.Source.ScreenShare,c,d,n)}(e,t,s);if(!r)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ia(e)));const a=e.addSimulcastTrack(t,r);if(!a)return;const c=new Pn({cid:a.mediaStreamTrack.id,type:js.kindToProto(e.kind),muted:e.isMuted,source:js.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Cc(c.width,c.height,r),!this.engine||this.engine.isClosed)throw new Ss("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Fi(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,s,r),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:r,trackInfo:d}))}))}unpublishTrack(t,n){return Fi(this,void 0,void 0,(function*(){var i,o;if(jr(t)){const e=this.pendingPublishPromises.get(t);e&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ia(t))),yield e)}const s=this.getPublicationForTrack(t),r=s?ia(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(t=s.track).off(e.TrackEvent.Muted,this.onTrackMuted),t.off(e.TrackEvent.Unmuted,this.onTrackUnmuted),t.off(e.TrackEvent.Ended,this.handleTrackEnded),t.off(e.TrackEvent.UpstreamPaused,this.onTrackUpstreamPaused),t.off(e.TrackEvent.UpstreamResumed,this.onTrackUpstreamResumed),t.off(e.TrackEvent.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===n&&(n=null===(o=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===o||o),n?t.stop():t.stopMonitor();let a=!1;const c=t.sender;if(t.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentStatethis.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Fi(this,arguments,void 0,(function(e){var t=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((i,o)=>Fi(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))})),yield Promise.all(t.map((e=>Fi(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!n||t.isMuted||t.source===js.Source.ScreenShare||t.source===js.Source.ScreenShareAudio||!qr(t)&&!Vr(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),i()}catch(e){o(e)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Fi(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const i=n.reliable?yt.RELIABLE:yt.LOSSY,o=n.destinationIdentities,s=n.topic;let r=new Et({participantIdentity:t.identity,payload:e,destinationIdentities:o,topic:s});const a=new kt({kind:i,value:{case:"user",value:r}});yield t.engine.sendDataPacket(a,i)}()}))}publishDtmf(e,t){return Fi(this,void 0,void 0,(function*(){const n=new kt({kind:yt.RELIABLE,value:{case:"sipDtmf",value:new wt({code:e,digit:t})}});yield this.engine.sendDataPacket(n,yt.RELIABLE)}))}sendChatMessage(t,n){return Fi(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:t,timestamp:Date.now(),attachedFiles:null==n?void 0:n.attachments},o=new kt({value:{case:"chatMessage",value:new It(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(o,yt.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}editChatMessage(t,n){return Fi(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},n),{message:t,editTimestamp:Date.now()}),o=new kt({value:{case:"chatMessage",value:new It(Object.assign(Object.assign({},i),{timestamp:D.parse(i.timestamp),editTimestamp:D.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(o,yt.RELIABLE),this.emit(e.ParticipantEvent.ChatMessage,i),i}))}sendText(e,t){return Fi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)}))}streamText(e){return Fi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamText(e)}))}sendFile(e,t){return Fi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)}))}streamBytes(e){return Fi(this,void 0,void 0,(function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)}))}performRpc(e){return Fi(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:n,method:i,payload:o,responseTimeout:s=15e3}=e;return function*(){return new Promise(((e,r)=>Fi(t,void 0,void 0,(function*(){var t,a,c,d;if(Za(o)>15360)return void r(Xa.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&br(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void r(Xa.builtIn("UNSUPPORTED_SERVER"));const l=Math.max(s,8e3),u=crypto.randomUUID();yield this.publishRpcRequest(n,u,i,o,l);const h=setTimeout((()=>{this.pendingAcks.delete(u),r(Xa.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(u),clearTimeout(p)}),7e3);this.pendingAcks.set(u,{resolve:()=>{clearTimeout(h)},participantIdentity:n});const p=setTimeout((()=>{this.pendingResponses.delete(u),r(Xa.builtIn("RESPONSE_TIMEOUT"))}),s);this.pendingResponses.set(u,{resolve:(t,n)=>{clearTimeout(p),this.pendingAcks.has(u)&&(console.warn("RPC response received before ack",u),this.pendingAcks.delete(u),clearTimeout(h)),n?r(n):e(null!=t?t:"")},participantIdentity:n})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,o){return Fi(this,void 0,void 0,(function*(){const s=new kt({destinationIdentities:[e],kind:yt.RELIABLE,value:{case:"rpcRequest",value:new Ot({id:t,method:n,payload:i,responseTimeoutMs:o,version:1})}});yield this.engine.sendDataPacket(s,yt.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,Xa.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,n;const i=this.trackPublications.get(e.sid);if(i){const o=i.isMuted||null!==(n=null===(t=i.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==n&&n;o!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ia(i)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(e.sid,o))}})),!0)}setActiveAgent(e){var t,n,i,o;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(n=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===n||n.call(t,e):null===(o=null===(i=this.activeAgentFuture)||void 0===i?void 0:i.reject)||void 0===o||o.call(i,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Dr),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(qr(i)||Vr(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))})),t}waitForPendingPublicationOfSource(e){return Fi(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now(){let[n]=t;return n.source===e}));if(t)return t[1];yield $s(20)}}))}}class $c extends Kc{constructor(t,n,i,o){super(t,n.sid,n.name,o),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=t=>{this.setTrack(void 0),this.emit(e.TrackEvent.Ended,t)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(t){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=t,t&&(this.allowed=!0);const o=new Ln({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new xt({participantSid:"",trackSids:[this.trackSid]})]});this.emit(e.TrackEvent.UpdateSubscription,o),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?Kc.SubscriptionStatus.Unsubscribed:super.isSubscribed?Kc.SubscriptionStatus.Subscribed:Kc.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Kc.PermissionStatus.Allowed:Kc.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(n=this.requestedVideoDimensions)||void 0===n?void 0:n.height)===e.height||(Hr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Hr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var t;return null!==(t=this.requestedMaxQuality)&&void 0!==t?t:e.VideoQuality.HIGH}setTrack(t){const n=this.subscriptionStatus,i=this.permissionStatus,o=this.track;o!==t&&(o&&(o.off(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),o.off(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),o.off(e.TrackEvent.Ended,this.handleEnded),o.detach(),o.stopMonitor(),this.emit(e.TrackEvent.Unsubscribed,o)),super.setTrack(t),t&&(t.sid=this.trackSid,t.on(e.TrackEvent.VideoDimensionsChanged,this.handleVideoDimensionsChange),t.on(e.TrackEvent.VisibilityChanged,this.handleVisibilityChange),t.on(e.TrackEvent.Ended,this.handleEnded),this.emit(e.TrackEvent.Subscribed,t)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(t){this.emit(e.TrackEvent.SubscriptionFailed,t)}updateInfo(t){super.updateInfo(t);const n=this.metadataMuted;this.metadataMuted=t.muted,this.track?this.track.setMuted(t.muted):n!==t.muted&&this.emit(t.muted?e.TrackEvent.Muted:e.TrackEvent.Unmuted)}emitSubscriptionUpdateIfChanged(t){const n=this.subscriptionStatus;t!==n&&this.emit(e.TrackEvent.SubscriptionStatusChanged,n,t)}emitPermissionUpdateIfChanged(t){this.permissionStatus!==t&&this.emit(e.TrackEvent.SubscriptionPermissionChanged,this.permissionStatus,t)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Hr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const t=new Un({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===js.Kind.Video){let s=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream)if(s){sa(this.videoDimensionsAdaptiveStream,s)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else if(void 0!==this.requestedMaxQuality&&this.trackInfo){const e=(n=this.trackInfo,i=this.requestedMaxQuality,null===(o=n.layers)||void 0===o?void 0:o.find((e=>e.quality===i)));e&&sa(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),s=this.videoDimensionsAdaptiveStream;s?(t.width=Math.ceil(s.width),t.height=Math.ceil(s.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),t.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:e.VideoQuality.HIGH})),t.quality=e.VideoQuality.HIGH)}var n,i,o;this.emit(e.TrackEvent.UpdateSettings,t)}}class ed extends Xc{static fromParticipantInfo(e,t,n){return new ed(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,o,s,r){super(t,n||"",i,o,s,r,arguments.length>7&&void 0!==arguments[7]?arguments[7]:ut.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(t){super.addTrackPublication(t),t.on(e.TrackEvent.UpdateSettings,(e=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),ia(t)),{settings:e})),this.signalClient.sendUpdateTrackSettings(e)})),t.on(e.TrackEvent.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),t.on(e.TrackEvent.SubscriptionPermissionChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionPermissionChanged,t,n)})),t.on(e.TrackEvent.SubscriptionStatusChanged,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionStatusChanged,t,n)})),t.on(e.TrackEvent.Subscribed,(n=>{this.emit(e.ParticipantEvent.TrackSubscribed,n,t)})),t.on(e.TrackEvent.Unsubscribed,(n=>{this.emit(e.ParticipantEvent.TrackUnsubscribed,n,t)})),t.on(e.TrackEvent.SubscriptionFailed,(n=>{this.emit(e.ParticipantEvent.TrackSubscriptionFailed,t.trackSid,n)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:js.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:js.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(t,n,i,o,s,r){let a=this.getTrackPublicationBySid(n);if(a||n.startsWith("TR")||this.trackPublications.forEach((e=>{a||t.kind!==e.kind.toString()||(a=e)})),!a)return 0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(t,n,i,o,s,r-1)}),150));if("ended"===t.readyState)return this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ia(a))),void this.emit(e.ParticipantEvent.TrackSubscriptionFailed,n);let c;return c="video"===t.kind?new Bc(t,n,o,s):new Fc(t,n,o,this.audioContext,this.audioOutput),c.source=a.source,c.isMuted=a.isMuted,c.setMediaStream(i),c.start(),a.setTrack(c),this.volumeMap.has(a.source)&&Wr(c)&&Fr(c)&&c.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(t){if(!super.updateInfo(t))return!1;const n=new Map,i=new Map;return t.tracks.forEach((e=>{var t,o;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{const n=js.kindFromProto(e.type);if(!n)return;s=new $c(n,e,null===(t=this.signalClient.connectOptions)||void 0===t?void 0:t.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(o=this.loggerOptions)||void 0===o?void 0:o.loggerName}),s.updateInfo(e),i.set(e.sid,s);const r=Array.from(this.trackPublications.values()).find((e=>e.source===(null==s?void 0:s.source)));r&&s.source!==js.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:ia(r),newTrack:ia(s)})),this.addTrackPublication(s)}n.set(e.sid,s)})),this.trackPublications.forEach((e=>{n.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ia(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((t=>{this.emit(e.ParticipantEvent.TrackPublished,t)})),!0}unpublishTrack(t,n){const i=this.trackPublications.get(t);if(!i)return;const{track:o}=i;switch(o&&(o.stop(),i.setTrack(void 0)),this.trackPublications.delete(t),i.kind){case js.Kind.Audio:this.audioTrackPublications.delete(t);break;case js.Kind.Video:this.videoTrackPublications.delete(t)}n&&this.emit(e.ParticipantEvent.TrackUnpublished,i)}setAudioOutput(e){return Fi(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((n=>{var i;Fr(n.track)&&Wr(n.track)&&t.push(n.track.setSinkId(null!==(i=e.deviceId)&&void 0!==i?i:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;iFi(this,void 0,void 0,(function*(){var o;if(!rr())throw mr()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===e.ConnectionState.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(e.ConnectionState.Connecting),(null===(o=this.regionUrlProvider)||void 0===o?void 0:o.getServerUrl().toString())!==t&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),gr(new URL(t))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Ya(t,n):this.regionUrlProvider.updateToken(n),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(o,a,c)=>Fi(this,void 0,void 0,(function*(){var d,l;this.abortController&&this.abortController.abort();const u=new AbortController;this.abortController=u,null==s||s();try{if(yield aa.getInstance().getBackOffPromise(t),u.signal.aborted)throw new ys("Connection attempt aborted",e.ConnectionErrorReason.Cancelled);yield this.attemptConnection(null!=c?c:t,n,i,u),this.abortController=void 0,o()}catch(n){if(this.regionUrlProvider&&n instanceof ys&&n.reason!==e.ConnectionErrorReason.Cancelled&&n.reason!==e.ConnectionErrorReason.NotAllowed){let i=null;try{this.log.debug("Fetching next region"),i=yield this.regionUrlProvider.getNextBestRegionUrl(null===(d=this.abortController)||void 0===d?void 0:d.signal)}catch(t){if(t instanceof ys&&(401===t.status||t.reason===e.ConnectionErrorReason.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void a(t)}[e.ConnectionErrorReason.InternalError,e.ConnectionErrorReason.ServerUnreachable,e.ConnectionErrorReason.Timeout].includes(n.reason)&&(this.log.debug("Adding failed connection attempt to back off"),aa.getInstance().addFailedConnectionAttempt(t)),i&&!(null===(l=this.abortController)||void 0===l?void 0:l.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(n.message,". Retrying with another region: ").concat(i),this.logContext),this.recreateEngine(),yield r(o,a,i)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Nr(n)),a(n))}else{let e=nt.UNKNOWN_REASON;n instanceof ys&&(e=Nr(n)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),a(n)}}})),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Dr(((e,t)=>{r(e,t,a)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,n,i,o,s)=>Fi(this,void 0,void 0,(function*(){var r,a,c;const d=yield n.join(e,t,{autoSubscribe:i.autoSubscribe,adaptiveStream:"object"==typeof o.adaptiveStream||o.adaptiveStream,maxRetries:i.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:i.websocketTimeout,singlePeerConnection:o.singlePeerConnection},s.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,n]=e;return"".concat(t,": ").concat(n)})).join(", ")),{room:null===(r=d.room)||void 0===r?void 0:r.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new Cs("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),o.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(t,n,i,o)=>Fi(this,void 0,void 0,(function*(){var s,r;this.state===e.ConnectionState.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ja),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(t,n,this.engine,this.connOptions,this.options,o);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(e.RoomEvent.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();const n=new ys("could not establish signal connection",o.signal.aborted?e.ConnectionErrorReason.Cancelled:e.ConnectionErrorReason.ServerUnreachable);throw t instanceof Error&&(n.message="".concat(n.message,": ").concat(t.message)),t instanceof ys&&(n.reason=t.reason,n.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),n}if(o.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ys("Connection attempt aborted",e.ConnectionErrorReason.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,o)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}pr()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),pr()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Connected),aa.getInstance().resetFailedConnectionAttempts(t),this.registerConnectionReconcile()})),this.disconnect=function(){for(var t=arguments.length,i=new Array(t),o=0;o0&&void 0!==arguments[0])||arguments[0];return function*(){var i,o,s;const r=yield t.disconnectLock.lock();try{if(t.state===e.ConnectionState.Disconnected)return void t.log.debug("already disconnected",t.logContext);if(t.log.info("disconnect from room",Object.assign({},t.logContext)),t.state===e.ConnectionState.Connecting||t.state===e.ConnectionState.Reconnecting||t.isResuming){const n="Abort connection attempt due to user initiated disconnect";t.log.warn(n,t.logContext),null===(i=t.abortController)||void 0===i||i.abort(n),null===(s=null===(o=t.connectFuture)||void 0===o?void 0:o.reject)||void 0===s||s.call(o,new ys("Client initiated disconnect",e.ConnectionErrorReason.Cancelled)),t.connectFuture=void 0}t.engine&&(t.engine.client.isDisconnected||(yield t.engine.client.sendLeave()),yield t.engine.close()),t.handleDisconnect(n,nt.CLIENT_INITIATED),t.engine=void 0}finally{r()}}()}))},this.onPageLeave=()=>Fi(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Fi(this,void 0,void 0,(function*(){const t=[],n=_s();if(n&&"iOS"===n.os){const n="livekit-dummy-audio-el";let i=document.getElementById(n);if(!i){i=document.createElement("audio"),i.id=n,i.autoplay=!0,i.hidden=!0;const t=_r();t.enabled=!0;const o=new MediaStream([t]);i.srcObject=o,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:o,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(e.RoomEvent.Disconnected,(()=>{null==i||i.remove(),i=null}))}t.push(i)}this.remoteParticipants.forEach((e=>{e.audioTrackPublications.forEach((e=>{e.track&&e.track.attachedElements.forEach((e=>{t.push(e)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...t.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}})),this.startVideo=()=>Fi(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var n;null===(n=t.track)||void 0===n||n.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)},this.handleSignalRestarted=t=>Fi(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(t.serverRegion),Object.assign(Object.assign({},this.logContext),{region:t.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(t);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:t.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(e.ConnectionState.Connected),this.emit(e.RoomEvent.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let n=this.remoteParticipants.get(e.identity);e.state===lt.DISCONNECTED?this.handleParticipantDisconnected(e.identity,n):n=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=t=>{const n=[],i={};t.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),n.push(this.localParticipant);else{const t=this.getRemoteParticipantBySid(e.sid);t&&(t.audioLevel=e.level,t.setIsSpeaking(!0),n.push(t))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=n,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,n)},this.handleSpeakersChanged=t=>{const n=new Map;this.activeSpeakers.forEach((e=>{const t=this.remoteParticipants.get(e.identity);t&&t.sid!==e.sid||n.set(e.sid,e)})),t.forEach((e=>{let t=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(t=this.localParticipant),t&&(t.audioLevel=e.level,t.setIsSpeaking(e.active),e.active?n.set(e.sid,t):n.delete(e.sid))}));const i=Array.from(n.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(e.RoomEvent.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=t=>{t.streamStates.forEach((t=>{const n=this.getRemoteParticipantBySid(t.participantSid);if(!n)return;const i=n.getTrackPublicationBySid(t.trackSid);if(!i||!i.track)return;const o=js.streamStateFromProto(t.state);i.track.setStreamState(o),o!==i.track.streamState&&(n.emit(e.ParticipantEvent.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(e.RoomEvent.TrackStreamStateChanged,i,i.track.streamState,n))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{const n=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(n,e.value.value,e.kind,t);else if("transcription"===e.value.case)this.handleTranscription(n,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(n,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(n,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,n);else if("streamHeader"===e.value.case||"streamChunk"===e.value.case||"streamTrailer"===e.value.case)this.handleDataStream(e,t);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(t,n,i,o)=>{this.emit(e.RoomEvent.DataReceived,n.payload,t,i,n.topic,o),null==t||t.emit(e.ParticipantEvent.DataReceived,n.payload,i,o)},this.handleSipDtmf=(t,n)=>{this.emit(e.RoomEvent.SipDTMFReceived,n,t),null==t||t.emit(e.ParticipantEvent.SipDTMFReceived,n)},this.handleTranscription=(t,n)=>{const i=n.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(n.transcribedParticipantIdentity),o=null==i?void 0:i.trackPublications.get(n.trackId),s=function(e,t){return e.segments.map((e=>{let{id:n,text:i,language:o,startTime:s,endTime:r,final:a}=e;var c;const d=null!==(c=t.get(n))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(n):t.set(n,d),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(r.toString()),final:a,language:o,firstReceivedTime:d,lastReceivedTime:l}}))}(n,this.transcriptionReceivedTimes);null==o||o.emit(e.TrackEvent.TranscriptionReceived,s),null==i||i.emit(e.ParticipantEvent.TranscriptionReceived,s,o),this.emit(e.RoomEvent.TranscriptionReceived,s,i,o)},this.handleChatMessage=(t,n)=>{const i=function(e){const{id:t,timestamp:n,message:i,editTimestamp:o}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:o?Number.parseInt(o.toString()):void 0,message:i}}(n);this.emit(e.RoomEvent.ChatMessage,i,t)},this.handleMetrics=(t,n)=>{this.emit(e.RoomEvent.MetricsReceived,t,n)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=t=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:t})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(e.RoomEvent.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Fi(this,void 0,void 0,(function*(){var t;"iOS"!==(null===(t=_s())||void 0===t?void 0:t.os)&&(yield this.selectDefaultDevices()),this.emit(e.RoomEvent.MediaDevicesChanged)})),this.handleRoomUpdate=t=>{const n=this.roomInfo;this.roomInfo=t,n&&n.metadata!==t.metadata&&this.emitWhenConnected(e.RoomEvent.RoomMetadataChanged,t.metadata),(null==n?void 0:n.activeRecording)!==t.activeRecording&&this.emitWhenConnected(e.RoomEvent.RecordingStatusChanged,t.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=t=>{this.emit(e.RoomEvent.ParticipantMetadataChanged,t,this.localParticipant)},this.onLocalParticipantNameChanged=t=>{this.emit(e.RoomEvent.ParticipantNameChanged,t,this.localParticipant)},this.onLocalAttributesChanged=t=>{this.emit(e.RoomEvent.ParticipantAttributesChanged,t,this.localParticipant)},this.onLocalTrackMuted=t=>{this.emit(e.RoomEvent.TrackMuted,t,this.localParticipant)},this.onLocalTrackUnmuted=t=>{this.emit(e.RoomEvent.TrackUnmuted,t,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=t=>Fi(this,void 0,void 0,(function*(){var n,i,o,s,r,a;if(null===(n=t.track)||void 0===n||n.on(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.on(e.TrackEvent.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(o=t.track)||void 0===o?void 0:o.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(e.RoomEvent.LocalTrackPublished,t,this.localParticipant),qr(t.track)){(yield t.track.checkForSilence())&&this.emit(e.RoomEvent.LocalAudioSilenceDetected,t)}const c=yield null===(a=t.track)||void 0===a?void 0:a.getDeviceId(!1),d=$r(t.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.localParticipant.activeDeviceMap.set(d,c),this.emit(e.RoomEvent.ActiveDeviceChanged,d,c))})),this.onLocalTrackUnpublished=t=>{var n,i;null===(n=t.track)||void 0===n||n.off(e.TrackEvent.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=t.track)||void 0===i||i.off(e.TrackEvent.Restarted,this.onLocalTrackRestarted),this.emit(e.RoomEvent.LocalTrackUnpublished,t,this.localParticipant)},this.onLocalTrackRestarted=t=>Fi(this,void 0,void 0,(function*(){const n=yield t.getDeviceId(!1),i=$r(t.source);i&&n&&n!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(n," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,n),this.emit(e.RoomEvent.ActiveDeviceChanged,i,n))})),this.onLocalConnectionQualityChanged=t=>{this.emit(e.RoomEvent.ConnectionQualityChanged,t,this.localParticipant)},this.onMediaDevicesError=(t,n)=>{this.emit(e.RoomEvent.MediaDevicesError,t,n)},this.onLocalParticipantPermissionsChanged=t=>{this.emit(e.RoomEvent.ParticipantPermissionsChanged,t,this.localParticipant)},this.onLocalChatMessageSent=t=>{this.emit(e.RoomEvent.ChatMessage,t,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Ga),t),this.log=xi(null!==(i=this.options.loggerName)&&void 0!==i?i:e.LoggerNames.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ka),null==t?void 0:t.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Ha),null==t?void 0:t.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Wa),null==t?void 0:t.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new xc,this.outgoingDataStreamManager=new Uc(this.engine,this.log),this.disconnectLock=new o,this.localParticipant=new Zc("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",xr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",xr(this.options.audioCaptureDefaults.deviceId)),(null===(s=this.options.audioOutput)||void 0===s?void 0:s.deviceId)&&this.switchActiveDevice("audiooutput",xr(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),pr()){const e=new AbortController;null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),td.cleanupRegistry&&td.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return Fi(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var t;const n=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new ra(i,n),this.e2eeManager.on(e.EncryptionEvent.ParticipantEncryptionStatusChanged,((t,n)=>{Gr(n)&&(this.isE2EEEnabled=t),this.emit(e.RoomEvent.ParticipantEncryptionStatusChanged,t,n)})),this.e2eeManager.on(e.EncryptionEvent.EncryptionError,((t,n)=>{const i=n?this.getParticipantByIdentity(n):void 0;this.emit(e.RoomEvent.EncryptionError,t,i)})),null===(t=this.e2eeManager)||void 0===t||t.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Fi(this,void 0,void 0,(function*(){return this.state===e.ConnectionState.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((t,n)=>{const i=n=>{""!==n.sid&&(this.engine.off(e.EngineEvent.RoomUpdate,i),t(n.sid))};this.engine.on(e.EngineEvent.RoomUpdate,i),this.once(e.RoomEvent.Disconnected,(()=>{this.engine.off(e.EngineEvent.RoomUpdate,i),n("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Pc(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(e.EngineEvent.ParticipantUpdate,this.handleParticipantUpdates).on(e.EngineEvent.RoomUpdate,this.handleRoomUpdate).on(e.EngineEvent.SpeakersChanged,this.handleSpeakersChanged).on(e.EngineEvent.StreamStateChanged,this.handleStreamStateUpdate).on(e.EngineEvent.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(e.EngineEvent.SubscriptionError,this.handleSubscriptionError).on(e.EngineEvent.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(e.EngineEvent.MediaTrackAdded,((e,t,n)=>{this.onTrackAdded(e,t,n)})).on(e.EngineEvent.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(e.EngineEvent.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(e.EngineEvent.DataPacketReceived,this.handleDataPacket).on(e.EngineEvent.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(e.ConnectionState.SignalReconnecting)&&this.emit(e.RoomEvent.SignalReconnecting)})).on(e.EngineEvent.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(e.ConnectionState.Connected)&&this.emit(e.RoomEvent.Reconnected)})).on(e.EngineEvent.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===e.ConnectionState.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(e.EngineEvent.Restarting,this.handleRestarting).on(e.EngineEvent.SignalRestarted,this.handleSignalRestarted).on(e.EngineEvent.Offline,(()=>{this.setAndEmitConnectionState(e.ConnectionState.Reconnecting)&&this.emit(e.RoomEvent.Reconnecting)})).on(e.EngineEvent.DCBufferStatusChanged,((t,n)=>{this.emit(e.RoomEvent.DCBufferStatusChanged,t,n)})).on(e.EngineEvent.LocalTrackSubscribed,(t=>{const n=this.localParticipant.getTrackPublications().find((e=>{let{trackSid:n}=e;return n===t}));n?(this.localParticipant.emit(e.ParticipantEvent.LocalTrackSubscribed,n),this.emitWhenConnected(e.RoomEvent.LocalTrackSubscribed,n,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})).on(e.EngineEvent.RoomMoved,(t=>{this.log.debug("room moved",t),t.room&&this.handleRoomUpdate(t.room),this.remoteParticipants.forEach(((e,t)=>{this.handleParticipantDisconnected(t,e)})),this.emit(e.RoomEvent.Moved,t.room.name),t.participant?this.handleParticipantUpdates([t.participant,...t.otherParticipants]):this.handleParticipantUpdates(t.otherParticipants)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return da.getInstance().getDevices(e,t)}prepareConnection(t,n){return Fi(this,void 0,void 0,(function*(){if(this.state===e.ConnectionState.Disconnected){this.log.debug("prepareConnection to ".concat(t),this.logContext);try{if(gr(new URL(t))&&n){this.regionUrlProvider=new Ya(t,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===e.ConnectionState.Disconnected&&(this.regionUrl=i,yield fetch(Ar(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ar(t),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Fi(this,void 0,void 0,(function*(){let n,i=()=>Fi(this,void 0,void 0,(function*(){}));switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":n=new ci({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":n=new ci({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":n=new ci({scenario:{case:"serverLeave",value:!0}});break;case"migration":n=new ci({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>Fi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new ci({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>Fi(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),n=new ci({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":n=new ci({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),i=()=>Fi(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Bn({reason:nt.CLIENT_INITIATED,action:Vn.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");n=new ci({scenario:{case:"subscriberBandwidth",value:Ur(t)}});break;case"leave-full-reconnect":n=new ci({scenario:{case:"leaveRequestFullReconnect",value:!0}})}n&&(yield this.engine.client.sendSimulateScenario(n),yield i())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(t,n){return Fi(this,arguments,void 0,(function(t,n){var i=this;let o=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,a,c,d,l,u;let h=!0,p=!1;const m=o?{exact:n}:n;if("audioinput"===t){p=0===i.localParticipant.audioTrackPublications.size;const e=null!==(s=i.getActiveDevice(t))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===js.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.audioCaptureDefaults.deviceId=e,t}const o=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&o&&(p=!0)}else if("videoinput"===t){p=0===i.localParticipant.videoTrackPublications.size;const e=null!==(r=i.getActiveDevice(t))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===js.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(t){throw i.options.videoCaptureDefaults.deviceId=e,t}const o=n.some((e=>{var t,n;return null!==(n=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==n&&n}));h&&o&&(p=!0)}else if("audiooutput"===t){if(p=!0,!sr()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(n=null!==(a=yield da.getInstance().normalizeDeviceId("audiooutput",n))&&void 0!==a?a:""),null!==(c=(u=i.options).audioOutput)&&void 0!==c||(u.audioOutput={});const e=null!==(d=i.getActiveDevice(t))&&void 0!==d?d:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=n;try{i.options.webAudioMix&&(null===(l=i.audioContext)||void 0===l||l.setSinkId(n)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:n}))))}catch(t){throw i.options.audioOutput.deviceId=e,t}}return p&&(i.localParticipant.activeDeviceMap.set(t,n),i.emit(e.RoomEvent.ActiveDeviceChanged,t,n)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).on(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).on(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).on(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).on(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).on(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).on(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).on(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(t,n,i){if(this.state===e.ConnectionState.Connecting||this.state===e.ConnectionState.Reconnecting){const o=()=>{this.log.debug("deferring on track for later",{mediaTrackId:t.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map((e=>e.id))}),this.onTrackAdded(t,n,i),s()},s=()=>{this.off(e.RoomEvent.Reconnected,o),this.off(e.RoomEvent.Connected,o),this.off(e.RoomEvent.Disconnected,s)};return this.once(e.RoomEvent.Reconnected,o),this.once(e.RoomEvent.Connected,o),void this.once(e.RoomEvent.Disconnected,s)}if(this.state===e.ConnectionState.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===t.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const o=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(n.id),s=o[0];let r=o[1],a=t.id;if(r&&r.startsWith("TR")&&(a=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const c=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!c)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);if(!a.startsWith("TR")){const e=this.engine.getTrackIdForReceiver(i);if(!e)return void this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s),this.logContext);a=e}let d;a.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(s,", streamId: ").concat(r,", trackId: ").concat(a),Object.assign(Object.assign({},this.logContext),{rpID:s,streamId:r,trackId:a})),this.options.adaptiveStream&&(d="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{});const l=c.addSubscribedMediaTrack(t,a,n,i,d);(null==l?void 0:l.isEncrypted)&&!this.e2eeManager&&this.emit(e.RoomEvent.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==e.ConnectionState.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((e=>{var n,i,o;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(n=e.track)||void 0===n||n.detach(),null===(i=e.track)||void 0===i||i.stop()):null===(o=e.track)||void 0===o||o.stopMonitor()})),this.localParticipant.off(e.ParticipantEvent.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(e.ParticipantEvent.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(e.ParticipantEvent.AttributesChanged,this.onLocalAttributesChanged).off(e.ParticipantEvent.TrackMuted,this.onLocalTrackMuted).off(e.ParticipantEvent.TrackUnmuted,this.onLocalTrackUnmuted).off(e.ParticipantEvent.LocalTrackPublished,this.onLocalTrackPublished).off(e.ParticipantEvent.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(e.ParticipantEvent.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(e.ParticipantEvent.MediaDevicesError,this.onMediaDevicesError).off(e.ParticipantEvent.AudioStreamAcquired,this.startAudio).off(e.ParticipantEvent.ChatMessage,this.onLocalChatMessageSent).off(e.ParticipantEvent.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),pr()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(e.ConnectionState.Disconnected),this.emit(e.RoomEvent.Disconnected,n)}}}handleParticipantDisconnected(t,n){var i;this.remoteParticipants.delete(t),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(t),n.trackPublications.forEach((e=>{n.unpublishTrack(e.trackSid,!0)})),this.emit(e.RoomEvent.ParticipantDisconnected,n),n.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,t,n,i,o,s){return Fi(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==s)return void(yield this.engine.publishRpcResponse(e,t,null,Xa.builtIn("UNSUPPORTED_VERSION")));const r=this.rpcHandlers.get(n);if(!r)return void(yield this.engine.publishRpcResponse(e,t,null,Xa.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const s=yield r({requestId:t,callerIdentity:e,payload:i,responseTimeout:o});Za(s)>15360?(a=Xa.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=s}catch(e){e instanceof Xa?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),e),a=Xa.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}selectDefaultDevices(){return Fi(this,void 0,void 0,(function*(){var t,n,i;const o=da.getInstance().previousDevices,s=yield da.getInstance().getDevices(void 0,!1),r=_s();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let t of s){const n=o.find((e=>e.deviceId===t.deviceId));n&&""!==n.label&&n.kind===t.kind&&n.label!==t.label&&"default"===this.getActiveDevice(t.kind)&&this.emit(e.RoomEvent.ActiveDeviceChanged,t.kind,t.deviceId)}const a=["audiooutput","audioinput","videoinput"];for(let e of a){const r=Zr(e),a=this.localParticipant.getTrackPublication(r);if(a&&(null===(t=a.track)||void 0===t?void 0:t.isUserProvided))continue;const c=s.filter((t=>t.kind===e)),d=this.getActiveDevice(e);d===(null===(n=o.filter((t=>t.kind===e))[0])||void 0===n?void 0:n.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(e,c[0].deviceId):"audioinput"===e&&!lr()||"videoinput"===e||!(c.length>0)||c.find((t=>t.deviceId===this.getActiveDevice(e)))||"audiooutput"===e&&lr()||(yield this.switchActiveDevice(e,c[0].deviceId))}}))}acquireAudioContext(){return Fi(this,void 0,void 0,(function*(){var t,n;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(t=Xr())&&void 0!==t?t:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),$s(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}const i="running"===(null===(n=this.audioContext)||void 0===n?void 0:n.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(e.RoomEvent.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var n;let i;return i=t?ed.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new ed(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&i.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),i}getOrCreateParticipant(t,n){if(this.remoteParticipants.has(t)){const e=this.remoteParticipants.get(t);if(n){e.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity)}return e}const i=this.createParticipant(t,n);return this.remoteParticipants.set(t,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(e.RoomEvent.ParticipantConnected,i),i.on(e.ParticipantEvent.TrackPublished,(t=>{this.emitWhenConnected(e.RoomEvent.TrackPublished,t,i)})).on(e.ParticipantEvent.TrackSubscribed,((t,n)=>{t.kind===js.Kind.Audio?(t.on(e.TrackEvent.AudioPlaybackStarted,this.handleAudioPlaybackStarted),t.on(e.TrackEvent.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):t.kind===js.Kind.Video&&(t.on(e.TrackEvent.VideoPlaybackFailed,this.handleVideoPlaybackFailed),t.on(e.TrackEvent.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(e.RoomEvent.TrackSubscribed,t,n,i)})).on(e.ParticipantEvent.TrackUnpublished,(t=>{this.emit(e.RoomEvent.TrackUnpublished,t,i)})).on(e.ParticipantEvent.TrackUnsubscribed,((t,n)=>{this.emit(e.RoomEvent.TrackUnsubscribed,t,n,i)})).on(e.ParticipantEvent.TrackMuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackMuted,t,i)})).on(e.ParticipantEvent.TrackUnmuted,(t=>{this.emitWhenConnected(e.RoomEvent.TrackUnmuted,t,i)})).on(e.ParticipantEvent.ParticipantMetadataChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantMetadataChanged,t,i)})).on(e.ParticipantEvent.ParticipantNameChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantNameChanged,t,i)})).on(e.ParticipantEvent.AttributesChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantAttributesChanged,t,i)})).on(e.ParticipantEvent.ConnectionQualityChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ConnectionQualityChanged,t,i)})).on(e.ParticipantEvent.ParticipantPermissionsChanged,(t=>{this.emitWhenConnected(e.RoomEvent.ParticipantPermissionsChanged,t,i)})).on(e.ParticipantEvent.TrackSubscriptionStatusChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionStatusChanged,t,n,i)})).on(e.ParticipantEvent.TrackSubscriptionFailed,((t,n)=>{this.emit(e.RoomEvent.TrackSubscriptionFailed,t,i,n)})).on(e.ParticipantEvent.TrackSubscriptionPermissionChanged,((t,n)=>{this.emitWhenConnected(e.RoomEvent.TrackSubscriptionPermissionChanged,t,n,i)})).on(e.ParticipantEvent.Active,(()=>{this.emitWhenConnected(e.RoomEvent.ParticipantActive,i),i.kind===ut.AGENT&&this.localParticipant.setActiveAgent(i)})),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Kr(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ns.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,nt.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ns.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(t){return t!==this.state&&(this.state=t,this.emit(e.RoomEvent.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,n]=e;this.emit(t,...n)})),this.bufferedEvents=[]}emitWhenConnected(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;othis.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}if(o.audio){const t=new Hc(js.Kind.Audio,new gt({source:Ze.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:Xe.AUDIO}),new rc(o.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:_r(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(t),this.localParticipant.emit(e.ParticipantEvent.LocalTrackPublished,t)}for(let e=0;e1?n-1:0),o=1;ovoid 0!==e));t!==e.RoomEvent.TrackSubscribed&&t!==e.RoomEvent.TrackUnsubscribed||this.log.trace("subscribe trace: ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:n})),this.log.debug("room event ".concat(t),Object.assign(Object.assign({},this.logContext),{event:t,args:n}))}return super.emit(t,...i)}}function nd(e){return e.map((e=>{if(e)return Array.isArray(e)?nd(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}td.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()}));var id,od=Object.freeze({__proto__:null,Convert:class{static toAgentAttributes(e){return JSON.parse(e)}static agentAttributesToJson(e){return JSON.stringify(e)}static toTranscriptionAttributes(e){return JSON.parse(e)}static transcriptionAttributesToJson(e){return JSON.stringify(e)}}});e.CheckStatus=void 0,(id=e.CheckStatus||(e.CheckStatus={}))[id.IDLE=0]="IDLE",id[id.RUNNING=1]="RUNNING",id[id.SKIPPED=2]="SKIPPED",id[id.SUCCESS=3]="SUCCESS",id[id.FAILED=4]="FAILED";class sd extends Ki.EventEmitter{constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.status=e.CheckStatus.IDLE,this.logs=[],this.options={},this.url=t,this.token=n,this.name=this.constructor.name,this.room=new td(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(t){return Fi(this,void 0,void 0,(function*(){if(this.status!==e.CheckStatus.IDLE)throw Error("check is running already");this.setStatus(e.CheckStatus.RUNNING);try{yield this.perform()}catch(e){e instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(e.message):this.appendError(e.message))}return yield this.disconnect(),yield new Promise((e=>setTimeout(e,500))),this.status!==e.CheckStatus.SKIPPED&&this.setStatus(this.isSuccess()?e.CheckStatus.SUCCESS:e.CheckStatus.FAILED),t&&t(),this.getInfo()}))}isSuccess(){return!this.logs.some((e=>"error"===e.level))}connect(t){return Fi(this,void 0,void 0,(function*(){return this.room.state===e.ConnectionState.Connected||(t||(t=this.url),yield this.room.connect(t,this.token,this.connectOptions)),this.room}))}disconnect(){return Fi(this,void 0,void 0,(function*(){this.room&&this.room.state!==e.ConnectionState.Disconnected&&(yield this.room.disconnect(),yield new Promise((e=>setTimeout(e,500))))}))}skip(){this.setStatus(e.CheckStatus.SKIPPED)}switchProtocol(t){return Fi(this,void 0,void 0,(function*(){let n=!1,i=!1;if(this.room.on(e.RoomEvent.Reconnecting,(()=>{n=!0})),this.room.once(e.RoomEvent.Reconnected,(()=>{i=!0})),this.room.simulateScenario("force-".concat(t)),yield new Promise((e=>setTimeout(e,1e3))),!n)return;const o=Date.now()+1e4;for(;Date.now().5*(e.duration-t.duration)+.5*(e.rtt-t.rtt)));const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return Fi(this,void 0,void 0,(function*(){var t,n;yield this.connect(e),"tcp"===this.options.protocol&&(yield this.switchProtocol("tcp"));const i=null===(t=this.room.serverInfo)||void 0===t?void 0:t.region;if(!i)throw new Error("Region not found");const o=yield this.room.localParticipant.streamText({topic:"test"}),s="A".repeat(1e3),r=Date.now();for(let e=0;e<1e3;e++)yield o.write(s);yield o.close();const a=Date.now(),c=yield null===(n=this.room.engine.pcManager)||void 0===n?void 0:n.publisher.getStats(),d={region:i,rtt:1e4,duration:a-r};return null==c||c.forEach((e=>{"candidate-pair"===e.type&&e.nominated&&(d.rtt=1e3*e.currentRoundTripTime)})),yield this.disconnect(),d}))}}const ad=1e4;class cd extends sd{get description(){return"Connection via UDP vs TCP"}perform(){return Fi(this,void 0,void 0,(function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/10*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/10*100).toFixed(2),"%"))}))}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return Fi(this,void 0,void 0,(function*(){yield this.connect(),"tcp"===e?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const o=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(o)};o();const s=t.captureStream(30).getVideoTracks()[0],r=(yield this.room.localParticipant.publishTrack(s,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,a={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},c=setInterval((()=>Fi(this,void 0,void 0,(function*(){const e=yield r.getRTCStatsReport();null==e||e.forEach((e=>{"outbound-rtp"===e.type?(a.packetsSent=e.packetsSent,a.qualityLimitationDurations=e.qualityLimitationDurations,a.bitrateTotal+=e.targetBitrate,a.count++):"remote-inbound-rtp"===e.type&&(a.packetsLost=e.packetsLost,a.rttTotal+=e.roundTripTime,a.jitterTotal+=e.jitter)}))}))),1e3);return yield new Promise((e=>setTimeout(e,ad))),clearInterval(c),s.stop(),t.remove(),yield this.disconnect(),a}))}}class dd extends sd{get description(){return"Can publish audio"}perform(){return Fi(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield zc();if(yield Yr(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,3e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let o=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&(e.kind||"audio"!==e.mediaType)||(o=e.packetsSent)})),0===o)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))}))}}class ld extends sd{get description(){return"Can publish video"}perform(){return Fi(this,void 0,void 0,(function*(){var e;const t=yield this.connect(),n=yield Jc();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise((e=>setTimeout(e,5e3)));const i=yield null===(e=n.sender)||void 0===e?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let o=0;if(i.forEach((e=>{"outbound-rtp"!==e.type||"video"!==e.kind&&(e.kind||"video"!==e.mediaType)||(o+=e.packetsSent)})),0===o)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," video packets"))}))}checkForVideo(e){return Fi(this,void 0,void 0,(function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise((t=>{n.onplay=()=>{setTimeout((()=>{var i,o,s,r;const a=document.createElement("canvas"),c=e.getSettings(),d=null!==(o=null!==(i=c.width)&&void 0!==i?i:n.videoWidth)&&void 0!==o?o:1280,l=null!==(r=null!==(s=c.height)&&void 0!==s?s:n.videoHeight)&&void 0!==r?r:720;a.width=d,a.height=l;const u=a.getContext("2d");u.drawImage(n,0,0);const h=u.getImageData(0,0,a.width,a.height).data;let p=!0;for(let e=0;ee.stop())),n.remove()}))}}class ud extends sd{get description(){return"Resuming connection after interruption"}perform(){return Fi(this,void 0,void 0,(function*(){var t;const n=yield this.connect();let i,o=!1,s=!1;const r=new Promise((e=>{setTimeout(e,5e3),i=e})),a=()=>{o=!0};n.on(e.RoomEvent.SignalReconnecting,a).on(e.RoomEvent.Reconnecting,a).on(e.RoomEvent.Reconnected,(()=>{s=!0,i(!0)})),null===(t=n.engine.client.ws)||void 0===t||t.close();const c=n.engine.client.onClose;if(c&&c(""),yield r,!o)throw new Error("Did not attempt to reconnect");if(!s||n.state!==e.ConnectionState.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}))}}class hd extends sd{get description(){return"Can connect via TURN"}perform(){return Fi(this,void 0,void 0,(function*(){var e,t;const n=new fa,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1});let o=!1,s=!1,r=!1;for(let e of i.iceServers)for(let t of e.urls)t.startsWith("turn:")?(s=!0,r=!0):t.startsWith("turns:")&&(s=!0,r=!0,o=!0),t.startsWith("stun:")&&(r=!0);r?s&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),(null===(t=null===(e=this.connectOptions)||void 0===e?void 0:e.rtcConfig)||void 0===t?void 0:t.iceServers)||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise((e=>setTimeout(e,0))))}))}}class pd extends sd{get description(){return"Establishing WebRTC connection"}perform(){return Fi(this,void 0,void 0,(function*(){let t=!1,n=!1;this.room.on(e.RoomEvent.SignalConnected,(()=>{var e;const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(e,o)=>{if(e.candidate){const i=new RTCIceCandidate(e);let o="".concat(i.protocol," ").concat(i.address,":").concat(i.port," ").concat(i.type);i.address&&(!function(e){const t=e.split(".");if(4===t.length){if("10"===t[0])return!0;if("192"===t[0]&&"168"===t[1])return!0;if("172"===t[0]){const e=parseInt(t[1],10);if(e>=16&&e<=31)return!0}}return!1}(i.address)?"tcp"===i.protocol&&"passive"===i.tcpType?(t=!0,o+=" (passive)"):"udp"===i.protocol&&(n=!0):o+=" (private)"),this.appendMessage(o)}i&&i(e,o)},(null===(e=this.room.engine.pcManager)||void 0===e?void 0:e.subscriber)&&(this.room.engine.pcManager.subscriber.onIceCandidateError=e=>{e instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(e.errorCode," ").concat(e.errorText," ").concat(e.url))})}));try{yield this.connect(),Di.info("now the room is connected")}catch(e){throw this.appendWarning("ports need to be open on firewall in order to connect."),e}t||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")}))}}class md extends sd{get description(){return"Connecting to signal connection via WebSocket"}perform(){return Fi(this,void 0,void 0,(function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new fa;const o=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1});this.appendMessage("Connected to server, version ".concat(o.serverVersion,".")),(null===(e=o.serverInfo)||void 0===e?void 0:e.edition)===Nt.Cloud&&(null===(t=o.serverInfo)||void 0===t?void 0:t.region)&&this.appendMessage("LiveKit Cloud: ".concat(null===(n=o.serverInfo)||void 0===n?void 0:n.region)),yield i.close()}))}}class gd extends Ki.EventEmitter{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const t=this.checkResults.size;return this.checkResults.set(t,{logs:[],status:e.CheckStatus.IDLE,name:"",description:""}),t}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every((t=>t.status!==e.CheckStatus.FAILED))}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return Fi(this,void 0,void 0,(function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=e=>{this.updateCheck(t,e)};n.on("update",i);const o=yield n.run();return n.off("update",i),o}))}checkWebsocket(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(md)}))}checkWebRTC(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(pd)}))}checkTURN(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(hd)}))}checkReconnect(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(ud)}))}checkPublishAudio(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(dd)}))}checkPublishVideo(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(ld)}))}checkConnectionProtocol(){return Fi(this,void 0,void 0,(function*(){const e=yield this.createAndRunCheck(cd);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e}))}checkCloudRegion(){return Fi(this,void 0,void 0,(function*(){return this.createAndRunCheck(rd)}))}}class vd{}class fd{}function kd(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}new TextEncoder;const yd=new TextDecoder;function bd(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:yd.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=yd.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return function(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),kd(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),kd(this,"claim",void 0),kd(this,"reason",void 0),kd(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_CLAIM_VALIDATION_FAILED");kd(class extends Td{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"unspecified",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:i,payload:t}}),kd(this,"code","ERR_JWT_EXPIRED"),kd(this,"claim",void 0),kd(this,"reason",void 0),kd(this,"payload",void 0),this.claim=n,this.reason=i,this.payload=t}},"code","ERR_JWT_EXPIRED");kd(class extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}},"code","ERR_JOSE_ALG_NOT_ALLOWED");kd(class extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JOSE_NOT_SUPPORTED")}},"code","ERR_JOSE_NOT_SUPPORTED");kd(class extends Td{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"decryption operation failed",arguments.length>1?arguments[1]:void 0),kd(this,"code","ERR_JWE_DECRYPTION_FAILED")}},"code","ERR_JWE_DECRYPTION_FAILED");kd(class extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JWE_INVALID")}},"code","ERR_JWE_INVALID");kd(class extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JWS_INVALID")}},"code","ERR_JWS_INVALID");class Cd extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JWT_INVALID")}}kd(Cd,"code","ERR_JWT_INVALID");kd(class extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JWK_INVALID")}},"code","ERR_JWK_INVALID");kd(class extends Td{constructor(){super(...arguments),kd(this,"code","ERR_JWKS_INVALID")}},"code","ERR_JWKS_INVALID");kd(class extends Td{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no applicable key found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),kd(this,"code","ERR_JWKS_NO_MATCHING_KEY")}},"code","ERR_JWKS_NO_MATCHING_KEY");kd(class extends Td{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"multiple matching keys found in the JSON Web Key Set",arguments.length>1?arguments[1]:void 0),kd(this,Symbol.asyncIterator,void 0),kd(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}},"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");kd(class extends Td{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"request timed out",arguments.length>1?arguments[1]:void 0),kd(this,"code","ERR_JWKS_TIMEOUT")}},"code","ERR_JWKS_TIMEOUT");kd(class extends Td{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"signature verification failed",arguments.length>1?arguments[1]:void 0),kd(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}},"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Sd=e=>{if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let n=e;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n};const Ed=1e3;function wd(e){const t=function(e){if("string"!=typeof e)throw new Cd("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:n}=e.split(".");if(5===n)throw new Cd("Only JWTs using Compact JWS serialization can be decoded");if(3!==n)throw new Cd("Invalid JWT");if(!t)throw new Cd("JWTs must contain a payload");let i,o;try{i=bd(t)}catch(e){throw new Cd("Failed to base64url decode the payload")}try{o=JSON.parse(yd.decode(i))}catch(e){throw new Cd("Failed to parse the decoded payload as JSON")}if(!Sd(o))throw new Cd("Invalid JWT Claims Set");return o}(e),{roomConfig:n}=t,i=ji(t,["roomConfig"]);return Object.assign(Object.assign({},i),{roomConfig:t.roomConfig?bn.fromJson(t.roomConfig):void 0})}class Rd extends fd{constructor(){super(...arguments),this.cachedFetchOptions=null,this.cachedResponse=null,this.fetchMutex=new o}isSameAsCachedFetchOptions(e){if(!this.cachedFetchOptions)return!1;for(const t of Object.keys(this.cachedFetchOptions))switch(t){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":if(this.cachedFetchOptions[t]!==e[t])return!1;break;default:throw new Error("Options key ".concat(t," not being checked for equality!"))}return!0}shouldReturnCachedValueFromFetch(e){return!!this.cachedResponse&&(!!function(e){const t=wd(e.participantToken);if(!(null==t?void 0:t.nbf)||!(null==t?void 0:t.exp))return!0;const n=new Date,i=t.nbf*Ed,o=new Date(i),s=t.exp*Ed,r=new Date(s-6e4);return o<=n&&r>n}(this.cachedResponse)&&!this.isSameAsCachedFetchOptions(e))}getCachedResponseJwtPayload(){return this.cachedResponse?wd(this.cachedResponse.participantToken):null}fetch(e){return Fi(this,void 0,void 0,(function*(){const t=yield this.fetchMutex.lock();try{if(this.shouldReturnCachedValueFromFetch(e))return this.cachedResponse.toJson();this.cachedFetchOptions=e;const t=yield this.update(e);return this.cachedResponse=t,t.toJson()}finally{t()}}))}}class Pd extends vd{constructor(e){super(),this.literalOrFn=e}fetch(){return Fi(this,void 0,void 0,(function*(){return"function"==typeof this.literalOrFn?this.literalOrFn():this.literalOrFn}))}}class Id extends Rd{constructor(e){super(),this.customFn=e}update(e){return Fi(this,void 0,void 0,(function*(){const t=this.customFn(e);let n;return n=t instanceof Promise?yield t:t,Si.fromJson(n,{ignoreUnknownFields:!0})}))}}class Od extends Rd{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.url=e,this.endpointOptions=t}createRequestFromOptions(e){var t,n,i;const o=new Ci;for(const s of Object.keys(e))switch(s){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":o[s]=e[s];break;case"participantAttributes":o.participantAttributes=null!==(t=e.participantAttributes)&&void 0!==t?t:{};break;case"agentName":o.roomConfig=null!==(n=o.roomConfig)&&void 0!==n?n:new bn,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Xt),o.roomConfig.agents[0].agentName=e.agentName;break;case"agentMetadata":o.roomConfig=null!==(i=o.roomConfig)&&void 0!==i?i:new bn,0===o.roomConfig.agents.length&&o.roomConfig.agents.push(new Xt),o.roomConfig.agents[0].metadata=e.agentMetadata;break;default:throw new Error("Options key ".concat(s," not being included in forming request!"))}return o}update(e){return Fi(this,void 0,void 0,(function*(){var t;const n=this.createRequestFromOptions(e),i=yield fetch(this.url,Object.assign(Object.assign({},this.endpointOptions),{method:null!==(t=this.endpointOptions.method)&&void 0!==t?t:"POST",headers:Object.assign({"Content-Type":"application/json"},this.endpointOptions.headers),body:n.toJsonString({useProtoFieldName:!0})}));if(!i.ok)throw new Error("Error generating token from endpoint ".concat(this.url,": received ").concat(i.status," / ").concat(yield i.text()));const o=yield i.json();return Si.fromJson(o,{ignoreUnknownFields:!0})}))}}class _d extends Od{constructor(e,t){const{baseUrl:n="https://cloud-api.livekit.io"}=t,i=ji(t,["baseUrl"]);super("".concat(n,"/api/v2/sandbox/connection-details"),Object.assign(Object.assign({},i),{headers:{"X-Sandbox-ID":e}}))}}const Dd={literal:e=>new Pd(e),custom:e=>new Id(e),endpoint(e){return new Od(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})},sandboxTokenServer(e){return new _d(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}};const Md=new Map([["obs virtual camera",{facingMode:"environment",confidence:"medium"}]]),xd=new Map([["iphone",{facingMode:"environment",confidence:"medium"}],["ipad",{facingMode:"environment",confidence:"medium"}]]);function Ad(e){var t;const n=e.trim().toLowerCase();if(""!==n)return Md.has(n)?Md.get(n):null===(t=Array.from(xd.entries()).find((e=>{let[t]=e;return n.includes(t)})))||void 0===t?void 0:t[1]}e.BaseKeyProvider=ds,e.Checker=sd,e.ConnectionCheck=gd,e.ConnectionError=ys,e.CriticalTimers=Ns,e.CryptorError=class extends ls{constructor(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.CryptorErrorReason.InternalError,i=arguments.length>2?arguments[2]:void 0;super(40,t),this.reason=n,this.participantIdentity=i}},e.DataPacket_Kind=yt,e.DataStreamError=Ps,e.DefaultReconnectPolicy=Ui,e.DeviceUnsupportedError=bs,e.DisconnectReason=nt,e.Encryption_Type=pt,e.ExternalE2EEKeyProvider=class extends ds{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(Object.assign(Object.assign({},e),{sharedKey:!0,ratchetWindowSize:0,failureTolerance:-1}))}setKey(e){return Fi(this,void 0,void 0,(function*(){const t="string"==typeof e?yield ss(e):yield rs(e);this.onSetEncryptionKey(t)}))}},e.LivekitError=ls,e.LocalAudioTrack=rc,e.LocalParticipant=Zc,e.LocalTrack=sc,e.LocalTrackPublication=Hc,e.LocalTrackRecorder=oc,e.LocalVideoTrack=yc,e.Mutex=o,e.NegotiationError=Es,e.Participant=Xc,e.ParticipantKind=ut,e.PublishDataError=class extends ls{constructor(e){super(14,null!=e?e:"unable to publish data"),this.name="PublishDataError"}},e.PublishTrackError=ws,e.RemoteAudioTrack=Fc,e.RemoteParticipant=ed,e.RemoteTrack=jc,e.RemoteTrackPublication=$c,e.RemoteVideoTrack=Bc,e.Room=td,e.RpcError=Xa,e.ScreenSharePresets=Xs,e.SignalRequestError=Rs,e.SubscriptionError=ot,e.TokenSource=Dd,e.TokenSourceConfigurable=fd,e.TokenSourceFixed=vd,e.Track=js,e.TrackInvalidError=Ts,e.TrackPublication=Kc,e.TrackType=Xe,e.UnexpectedConnectionState=Ss,e.UnsupportedServer=Cs,e.VideoPreset=Vs,e.VideoPresets=Qs,e.VideoPresets43=Ys,e.areTokenSourceFetchOptionsEqual=function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const i of n)switch(i){case"roomName":case"participantName":case"participantIdentity":case"participantMetadata":case"participantAttributes":case"agentName":case"agentMetadata":if(e[i]!==t[i])return!1;break;default:throw new Error("Options key ".concat(i," not being checked for equality!"))}return!0},e.asEncryptablePacket=cs,e.attachToElement=Fs,e.attributes=od,e.audioCodecs=qs,e.compareVersions=br,e.createAudioAnalyser=function(e,t){const n=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),i=Xr();if(!i)throw new Error("Audio Context not supported on this browser");const o=n.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=i.createMediaStreamSource(new MediaStream([o])),r=i.createAnalyser();r.minDecibels=n.minDecibels,r.maxDecibels=n.maxDecibels,r.fftSize=n.fftSize,r.smoothingTimeConstant=n.smoothingTimeConstant,s.connect(r);const a=new Uint8Array(r.frequencyBinCount);return{calculateVolume:()=>{r.getByteFrequencyData(a);let e=0;for(const t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:r,cleanup:()=>Fi(this,void 0,void 0,(function*(){yield i.close(),n.cloneTrack&&o.stop()}))}},e.createE2EEKey=function(){return window.crypto.getRandomValues(new Uint8Array(32))},e.createKeyMaterialFromBuffer=rs,e.createKeyMaterialFromString=ss,e.createLocalAudioTrack=zc,e.createLocalScreenTracks=function(e){return Fi(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0!==e.resolution||ur()||(e.resolution=Xs.h1080fps30.resolution),void 0===navigator.mediaDevices.getDisplayMedia)throw new bs("getDisplayMedia not supported");const t=ea(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(0===i.length)throw new Ts("no video track found");const o=new yc(i[0],void 0,!1);o.source=js.Source.ScreenShare;const s=[o];if(n.getAudioTracks().length>0){const e=new rc(n.getAudioTracks()[0],void 0,!1);e.source=js.Source.ScreenShareAudio,s.push(e)}return s}))},e.createLocalTracks=Gc,e.createLocalVideoTrack=Jc,e.decodeTokenPayload=wd,e.deriveKeys=function(e,t){return Fi(this,void 0,void 0,(function*(){const n=as(e.algorithm.name,t),i=yield crypto.subtle.deriveKey(n,e,{name:Xo,length:128},!1,["encrypt","decrypt"]);return{material:e,encryptionKey:i}}))},e.detachTrack=Bs,e.facingModeFromDeviceLabel=Ad,e.facingModeFromLocalTrack=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var n;const i=jr(e)?e.mediaStreamTrack:e,o=i.getSettings();let s={facingMode:null!==(n=t.defaultFacingMode)&&void 0!==n?n:"user",confidence:"low"};if("facingMode"in o){const e=o.facingMode;Di.trace("rawFacingMode",{rawFacingMode:e}),e&&"string"==typeof e&&function(e){const t=["user","environment","left","right"];return void 0===e||t.includes(e)}(e)&&(s={facingMode:e,confidence:"high"})}if(["low","medium"].includes(s.confidence)){Di.trace("Try to get facing mode from device label: (".concat(i.label,")"));const e=Ad(i.label);void 0!==e&&(s=e)}return s},e.getBrowser=_s,e.getEmptyAudioStreamTrack=_r,e.getEmptyVideoStreamTrack=function(){return Pr||(Pr=Or()),Pr.clone()},e.getLogger=xi,e.importKey=function(e){return Fi(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:Xo},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))},e.isAudioCodec=function(e){return qs.includes(e)},e.isAudioTrack=Fr,e.isBackupCodec=Gs,e.isBackupVideoCodec=Hs,e.isBrowserSupported=rr,e.isE2EESupported=ns,e.isInsertableStreamSupported=os,e.isLocalParticipant=Gr,e.isLocalTrack=jr,e.isRemoteParticipant=function(e){return!e.isLocal},e.isRemoteTrack=Wr,e.isScriptTransformSupported=is,e.isVideoCodec=Mr,e.isVideoFrame=function(e){return"type"in e},e.isVideoTrack=Br,e.needsRbspUnescaping=function(e){for(var t=0;t=3&&!e[i]&&!e[i+1]&&3==e[i+2]?(t.push(e[i++]),t.push(e[i++]),i++):t.push(e[i++]);return new Uint8Array(t)},e.protocolVersion=16,e.ratchet=function(e,t){return Fi(this,void 0,void 0,(function*(){const n=as(e.algorithm.name,t);return crypto.subtle.deriveBits(n,e,256)}))},e.setLogExtension=function(t,n){(n?[n]:Mi).forEach((n=>{const i=n.methodFactory;n.methodFactory=(n,o,s)=>{const r=i(n,o,s),a=e.LogLevel[n],c=a>=o&&a{n?r(e,n):r(e),c&&t(a,e,n)}},n.setLevel(n.getLevel())}))},e.setLogLevel=function(e,t){if(t)_i.getLogger(t).setLevel(e);else for(const t of Mi)t.setLevel(e)},e.supportsAV1=nr,e.supportsAdaptiveStream=function(){return void 0!==typeof ResizeObserver&&void 0!==typeof IntersectionObserver},e.supportsAudioOutputSelection=function(){return sr()},e.supportsDynacast=function(){return er()},e.supportsVP9=ir,e.version=As,e.videoCodecs=Ks,e.writeRbsp=function(e){const t=[];for(var n=0,i=0;i=2&&(t.push(3),n=0),t.push(o),0==o?++n:n=0}return new Uint8Array(t)}})); -//# sourceMappingURL=livekit-client.umd.js.map diff --git a/web/desktop/js/lib/marked.min.js b/web/desktop/js/lib/marked.min.js deleted file mode 100644 index b4e0d73b2..000000000 --- a/web/desktop/js/lib/marked.min.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * marked v15.0.12 - a markdown parser - * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ -(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; -"use strict";var H=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var we=Object.prototype.hasOwnProperty;var ye=(l,e)=>{for(var t in e)H(l,t,{get:e[t],enumerable:!0})},Re=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Te(e))!we.call(l,s)&&s!==t&&H(l,s,{get:()=>e[s],enumerable:!(n=be(e,s))||n.enumerable});return l};var Se=l=>Re(H({},"__esModule",{value:!0}),l);var kt={};ye(kt,{Hooks:()=>L,Lexer:()=>x,Marked:()=>E,Parser:()=>b,Renderer:()=>$,TextRenderer:()=>_,Tokenizer:()=>S,defaults:()=>w,getDefaults:()=>z,lexer:()=>ht,marked:()=>k,options:()=>it,parse:()=>pt,parseInline:()=>ct,parser:()=>ut,setOptions:()=>ot,use:()=>lt,walkTokens:()=>at});module.exports=Se(kt);function z(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var w=z();function N(l){w=l}var I={exec:()=>null};function h(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(s,i)=>{let r=typeof i=="string"?i:i.source;return r=r.replace(m.caret,"$1"),t=t.replace(s,r),n},getRegex:()=>new RegExp(t,e)};return n}var m={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}#`),htmlBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}<(?:[a-z].*>|!--)`,"i")},$e=/^(?:[ \t]*(?:\n|$))+/,_e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Le=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,O=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ze=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,F=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,oe=h(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Me=h(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Q=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Pe=/^[^\n]+/,U=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Ae=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ee=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,F).getRegex(),v="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/|$))/,Ce=h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",K).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=h(Q).replace("hr",O).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Ie=h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",le).getRegex(),X={blockquote:Ie,code:_e,def:Ae,fences:Le,heading:ze,hr:O,html:Ce,lheading:oe,list:Ee,newline:$e,paragraph:le,table:I,text:Pe},re=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",O).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Oe={...X,lheading:Me,table:re,paragraph:h(Q).replace("hr",O).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",re).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},Be={...X,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:I,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(Q).replace("hr",O).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",oe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ve=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ae=/^( {2,}|\\)\n(?!\s*$)/,De=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,ue=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,je=h(ue,"u").replace(/punct/g,D).getRegex(),Fe=h(ue,"u").replace(/punct/g,pe).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Qe=h(he,"gu").replace(/notPunctSpace/g,ce).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Ue=h(he,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Ge).replace(/punct/g,pe).getRegex(),Ke=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ce).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Xe=h(/\\(punct)/,"gu").replace(/punct/g,D).getRegex(),We=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Je=h(K).replace("(?:-->|$)","-->").getRegex(),Ve=h("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Je).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ye=h(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=h(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",U).getRegex(),ge=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",U).getRegex(),et=h("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",ge).getRegex(),J={_backpedal:I,anyPunctuation:Xe,autolink:We,blockSkip:Ne,br:ae,code:ve,del:I,emStrongLDelim:je,emStrongRDelimAst:Qe,emStrongRDelimUnd:Ke,escape:qe,link:Ye,nolink:ge,punctuation:Ze,reflink:ke,reflinkSearch:et,tag:Ve,text:De,url:I},tt={...J,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},j={...J,emStrongRDelimAst:Ue,emStrongLDelim:Fe,url:h(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},fe=l=>st[l];function R(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,fe);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(i,r,o)=>{let a=!1,c=r;for(;--c>=0&&o[c]==="\\";)a=!a;return a?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length0?-2:-1}function me(l,e,t,n,s){let i=e.href,r=e.title||null,o=l[1].replace(s.other.outputLinkReplace,"$1");n.state.inLink=!0;let a={type:l[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:r,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,a}function rt(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(` -`).map(i=>{let r=i.match(t.other.beginningSpace);if(r===null)return i;let[o]=r;return o.length>=s.length?i.slice(s.length):i}).join(` -`)}var S=class{options;rules;lexer;constructor(e){this.options=e||w}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:A(n,` -`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=rt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=A(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:A(t[0],` -`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=A(t[0],` -`).split(` -`),s="",i="",r=[];for(;n.length>0;){let o=!1,a=[],c;for(c=0;c1,i={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let r=this.rules.other.listItemRegex(n),o=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=t[2].split(` -`,1)[0].replace(this.rules.other.listReplaceTabs,Z=>" ".repeat(3*Z.length)),g=e.split(` -`,1)[0],T=!d.trim(),f=0;if(this.options.pedantic?(f=2,u=d.trimStart()):T?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,u=d.slice(f),f+=t[1].length),T&&this.rules.other.blankLine.test(g)&&(p+=g+` -`,e=e.substring(g.length+1),c=!0),!c){let Z=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),se=this.rules.other.headingBeginRegex(f),xe=this.rules.other.htmlBeginRegex(f);for(;e;){let G=e.split(` -`,1)[0],C;if(g=G,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),C=g):C=g.replace(this.rules.other.tabCharGlobal," "),ne.test(g)||se.test(g)||xe.test(g)||Z.test(g)||te.test(g))break;if(C.search(this.rules.other.nonSpaceChar)>=f||!g.trim())u+=` -`+C.slice(f);else{if(T||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ne.test(d)||se.test(d)||te.test(d))break;u+=` -`+g}!T&&!g.trim()&&(T=!0),p+=G+` -`,e=e.substring(G.length+1),d=C.slice(f)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(o=!0));let y=null,ee;this.options.gfm&&(y=this.rules.other.listIsTask.exec(u),y&&(ee=y[0]!=="[ ] ",u=u.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:p,task:!!y,checked:ee,loose:!1,text:u,tokens:[]}),i.raw+=p}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c=0;cd.type==="space"),u=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=u}if(i.loose)for(let c=0;c({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` -`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let r=A(n.slice(0,-1),"\\");if((n.length-r.length)%2===0)return}else{let r=de(t[2],"()");if(r===-2)return;if(r>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let s=t[2],i="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],i=r[3])}else i=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),me(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[s.toLowerCase()];if(!i){let r=n[0].charAt(0);return{type:"text",raw:r,text:r}}return me(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let r=[...s[0]].length-1,o,a,c=r,p=0,u=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,t=t.slice(-1*e.length+r);(s=u.exec(t))!=null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(a=[...o].length,s[3]||s[4]){c+=a;continue}else if((s[5]||s[6])&&r%3&&!((r+a)%3)){p+=a;continue}if(c-=a,c>0)continue;a=Math.min(a,a+c+p);let d=[...s[0]][0].length,g=e.slice(0,r+s.index+d+a);if(Math.min(r,a)%2){let f=g.slice(1,-1);return{type:"em",raw:g,text:f,tokens:this.lexer.inlineTokens(f)}}let T=g.slice(2,-2);return{type:"strong",raw:g,text:T,tokens:this.lexer.inlineTokens(T)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||w,this.options.tokenizer=this.options.tokenizer||new S,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:B.normal,inline:P.normal};this.options.pedantic?(t.block=B.pedantic,t.inline=P.pedantic):this.options.gfm&&(t.block=B.gfm,this.options.breaks?t.inline=P.breaks:t.inline=P.gfm),this.tokenizer.rules=t}static get rules(){return{block:B,inline:P}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` -`),this.blockTokens(e,this.tokens);for(let t=0;t(s=r.call({lexer:this},e,t))?(e=e.substring(s.raw.length),t.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let r=t.at(-1);s.raw.length===1&&r!==void 0?r.raw+=` -`:t.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="paragraph"||r?.type==="text"?(r.raw+=` -`+s.raw,r.text+=` -`+s.text,this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="paragraph"||r?.type==="text"?(r.raw+=` -`+s.raw,r.text+=` -`+s.raw,this.inlineQueue.at(-1).src=r.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title});continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),t.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let r=1/0,o=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},o),typeof a=="number"&&a>=0&&(r=Math.min(r,a))}),r<1/0&&r>=0&&(i=e.substring(0,r+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let r=t.at(-1);n&&r?.type==="paragraph"?(r.raw+=` -`+s.raw,r.text+=` -`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s),n=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let r=t.at(-1);r?.type==="text"?(r.raw+=` -`+s.raw,r.text+=` -`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(e){let r="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(r);break}else throw new Error(r)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,s=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,s.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let i=!1,r="";for(;e;){i||(r=""),i=!1;let o;if(this.options.extensions?.inline?.some(c=>(o=c.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let c=t.at(-1);o.type==="text"&&c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,r)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let a=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},p),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(a=e.substring(0,c+1))}if(o=this.tokenizer.inlineText(a)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(r=o.raw.slice(-1)),i=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):t.push(o);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return t}};var $=class{options;parser;constructor(e){this.options=e||w}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` -`;return s?'
'+(n?i:R(i,!0))+`
-`:"
"+(n?i:R(i,!0))+`
-`}blockquote({tokens:e}){return`
-${this.parser.parse(e)}
-`}html({text:e}){return e}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} -`}hr(e){return`
-`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o -`+s+" -`}listitem(e){let t="";if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=n+" "+R(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • -`}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    -`}table(e){let t="",n="";for(let i=0;i${s}`),` - -`+t+` -`+s+`
    -`}tablerow({text:e}){return` -${e} -`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` -`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${R(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=V(e);if(i===null)return s;e=i;let r='
    ",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=V(e);if(i===null)return R(n);e=i;let r=`${n}{let o=i[r].flat(1/0);n=n.concat(this.walkTokens(o,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let r=t.renderers[i.name];r?t.renderers[i.name]=function(...o){let a=i.renderer.apply(this,o);return a===!1&&(a=r.apply(this,o)),a}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[i.level];r?r.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),s.extensions=t),n.renderer){let i=this.defaults.renderer||new $(this.defaults);for(let r in n.renderer){if(!(r in i))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=n.renderer[o],c=i[o];i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u||""}}s.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new S(this.defaults);for(let r in n.tokenizer){if(!(r in i))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=n.tokenizer[o],c=i[o];i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u}}s.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new L;for(let r in n.hooks){if(!(r in i))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=n.hooks[o],c=i[o];L.passThroughHooks.has(r)?i[o]=p=>{if(this.defaults.async)return Promise.resolve(a.call(i,p)).then(d=>c.call(i,d));let u=a.call(i,p);return c.call(i,u)}:i[o]=(...p)=>{let u=a.apply(i,p);return u===!1&&(u=c.apply(i,p)),u}}s.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,r=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(r.call(this,o)),i&&(a=a.concat(i.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let i={...s},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));r.hooks&&(r.hooks.options=r,r.hooks.block=e);let a=r.hooks?r.hooks.provideLexer():e?x.lex:x.lexInline,c=r.hooks?r.hooks.provideParser():e?b.parse:b.parseInline;if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(p=>a(p,r)).then(p=>r.hooks?r.hooks.processAllTokens(p):p).then(p=>r.walkTokens?Promise.all(this.walkTokens(p,r.walkTokens)).then(()=>p):p).then(p=>c(p,r)).then(p=>r.hooks?r.hooks.postprocess(p):p).catch(o);try{r.hooks&&(n=r.hooks.preprocess(n));let p=a(n,r);r.hooks&&(p=r.hooks.processAllTokens(p)),r.walkTokens&&this.walkTokens(p,r.walkTokens);let u=c(p,r);return r.hooks&&(u=r.hooks.postprocess(u)),u}catch(p){return o(p)}}}onError(e,t){return n=>{if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+R(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var M=new E;function k(l,e){return M.parse(l,e)}k.options=k.setOptions=function(l){return M.setOptions(l),k.defaults=M.defaults,N(k.defaults),k};k.getDefaults=z;k.defaults=w;k.use=function(...l){return M.use(...l),k.defaults=M.defaults,N(k.defaults),k};k.walkTokens=function(l,e){return M.walkTokens(l,e)};k.parseInline=M.parseInline;k.Parser=b;k.parser=b.parse;k.Renderer=$;k.TextRenderer=_;k.Lexer=x;k.lexer=x.lex;k.Tokenizer=S;k.Hooks=L;k.parse=k;var it=k.options,ot=k.setOptions,lt=k.use,at=k.walkTokens,ct=k.parseInline,pt=k,ut=b.parse,ht=x.lex; - -if(__exports != exports)module.exports = exports;return module.exports})); diff --git a/web/desktop/js/mock-data.js b/web/desktop/js/mock-data.js deleted file mode 100644 index daf01bdd0..000000000 --- a/web/desktop/js/mock-data.js +++ /dev/null @@ -1,46 +0,0 @@ -const mockUsers = [ - { - id: 'user1', - name: 'John Doe', - email: 'john@example.com', - avatar: '👨' - }, - { - id: 'user2', - name: 'Jane Smith', - email: 'jane@example.com', - avatar: '👩' - } -]; - -const mockBots = [ - { - id: 'default_bot', - name: 'General Bot', - description: 'Main assistant bot' - } -]; - -const mockSessions = [ - { - id: 'session1', - title: 'First Chat', - created_at: new Date().toISOString() - }, - { - id: 'session2', - title: 'Project Discussion', - created_at: new Date(Date.now() - 86400000).toISOString() - } -]; - -const mockAuthResponse = { - user_id: mockUsers[0].id, - session_id: mockSessions[0].id -}; - -const mockSuggestions = [ - { text: "What can you do?", context: "capabilities" }, - { text: "Show my files", context: "drive" }, - { text: "Create a task", context: "tasks" } -]; diff --git a/web/desktop/mail/data.js b/web/desktop/mail/data.js deleted file mode 100644 index b626a6d32..000000000 --- a/web/desktop/mail/data.js +++ /dev/null @@ -1,29 +0,0 @@ -export const mails = [ - { - id: "6c84fb90-12c4-11e1-840d-7b25c5ee775a", - name: "William Smith", - email: "williamsmith@example.com", - subject: "Meeting Tomorrow", - text: "Hi, let's have a meeting tomorrow to discuss the project...", - date: "2023-10-22T09:00:00", - read: true, - labels: ["meeting", "work", "important"], - }, - // Additional emails would go here -]; - -export const accounts = [ - { - label: "Alicia Koch", - email: "alicia@example.com", - icon: "📧", - } -]; - -export const contacts = [ - { - name: "Emma Johnson", - email: "emma.johnson@example.com", - }, - // Additional contacts would go here -]; diff --git a/web/desktop/mail/index.html b/web/desktop/mail/index.html index 7f6aadfcb..87e4b95ed 100644 --- a/web/desktop/mail/index.html +++ b/web/desktop/mail/index.html @@ -1,94 +1,64 @@ - - - - Email Client - - - - - - -