widevin 0.3.0

Lightweight Rust Devin provider library
Documentation
/// The three error categories exposed by the TypeScript package.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DevinError {
    /// OAuth, callback, or token-exchange failure.
    #[error("{message}")]
    Auth { message: String },
    /// HTTP or HTTP-transport failure. Transport failures use status `0`.
    #[error("{message}")]
    Api {
        message: String,
        status: u16,
        body: Option<String>,
    },
    /// Protobuf, Connect framing, token-store, or other wire-protocol failure.
    #[error("{message}")]
    Protocol { message: String },
}

impl DevinError {
    pub fn auth(message: impl Into<String>) -> Self {
        Self::Auth {
            message: message.into(),
        }
    }

    pub fn api(message: impl Into<String>, status: u16, body: Option<String>) -> Self {
        Self::Api {
            message: message.into(),
            status,
            body,
        }
    }

    pub fn api_transport(message: impl Into<String>) -> Self {
        let detail = message.into();
        Self::api(format!("Devin transport failed: {detail}"), 0, None)
    }

    pub fn protocol(message: impl Into<String>) -> Self {
        Self::Protocol {
            message: message.into(),
        }
    }
}

pub(crate) fn http_error(
    operation: &str,
    status: u16,
    status_text: &str,
    payload: &[u8],
) -> DevinError {
    let detail =
        http_error_detail(payload).map_or_else(String::new, |detail| format!(": {detail}"));
    let status_text = if status_text.is_empty() {
        String::new()
    } else {
        format!(" {status_text}")
    };
    DevinError::api(
        format!("Devin {operation} failed: {status}{status_text}{detail}"),
        status,
        Some(String::from_utf8_lossy(payload).into_owned()),
    )
}

fn http_error_detail(payload: &[u8]) -> Option<String> {
    let mut text = std::str::from_utf8(payload).ok()?.trim().to_owned();
    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&text) {
        if let Some(message) = parsed
            .get("error")
            .and_then(|error| error.get("message"))
            .and_then(serde_json::Value::as_str)
            .or_else(|| parsed.get("error").and_then(serde_json::Value::as_str))
            .or_else(|| parsed.get("message").and_then(serde_json::Value::as_str))
        {
            text = message.into();
        }
    }
    // Match JavaScript whitespace collapse without hiding C1 control bytes.
    if text
        .chars()
        .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t' | '\u{000b}' | '\u{000c}'))
    {
        return None;
    }
    let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
    let lower = text.to_lowercase();
    if text.is_empty() || lower.starts_with("<html") || lower.starts_with("<!doctype html") {
        return None;
    }
    let mut units = 0;
    Some(
        text.chars()
            .take_while(|c| {
                units += c.len_utf16();
                units <= 4096
            })
            .collect(),
    )
}