diff --git a/src/api/socket.rs b/src/api/socket.rs index 6462af71f..c85e44710 100644 --- a/src/api/socket.rs +++ b/src/api/socket.rs @@ -1,16 +1,27 @@ //! Socket.IO (Engine.IO v4) WebSocket URL for the TinyHumans backend. +use url::Url; + /// Build a Socket.IO WebSocket URL from an HTTP(S) API base (e.g. `https://api.tinyhumans.ai`). pub fn websocket_url(http_or_https_base: &str) -> String { - let base = http_or_https_base.trim_end_matches('/'); - let ws_base = if base.starts_with("https://") { - base.replacen("https://", "wss://", 1) - } else if base.starts_with("http://") { - base.replacen("http://", "ws://", 1) - } else { - base.to_string() + let Ok(mut url) = Url::parse(http_or_https_base) else { + return http_or_https_base.to_string(); }; - format!("{}/socket.io/?EIO=4&transport=websocket", ws_base) + + let scheme = match url.scheme() { + "https" => "wss", + "http" => "ws", + other => other, + } + .to_string(); + + let _ = url.set_scheme(&scheme); + + // Ensure path ends with /socket.io/ and includes required query params + url.set_path(&format!("{}/socket.io/", url.path().trim_end_matches('/'))); + url.set_query(Some("EIO=4&transport=websocket")); + + url.to_string() } #[cfg(test)]