/// Convert a stringified Swift error into the configured source-crate error type.
#[allow(dead_code)]
fn plugin_error_from_string(message: String) -> {{ error_type_path }} {
    {{ plugin_error_constructor }}
}

/// JSON envelope returned by every fallible Swift trait method. Carries `Ok(T)`
/// as `{"ok": <serialised T>}` and `Err(String)` as `{"err": "<message>"}`.
/// Avoids swift-bridge 0.1.59's broken `Result<RustString, RustString>` codegen.
#[allow(dead_code)]
#[derive(::serde::Deserialize)]
#[serde(rename_all = "snake_case")]
enum InboundEnvelope<T> { Ok(T), Err(String) }

/// Deserialise a JSON envelope returned from a Swift FFI shim into a typed Result.
#[allow(dead_code)]
fn decode_inbound_envelope<T>(json: &str) -> std::result::Result<T, {{ error_type_path }}>
where
    T: ::serde::de::DeserializeOwned,
{
    match ::serde_json::from_str::<InboundEnvelope<T>>(json) {
        Ok(InboundEnvelope::Ok(value)) => Ok(value),
        Ok(InboundEnvelope::Err(message)) => Err(plugin_error_from_string(message)),
        Err(e) => Err(plugin_error_from_string(format!("swift returned malformed envelope: {e}"))),
    }
}
