sololc-webhook-sdk 0.1.0

Provides an ergonomic, ultra-high-performance WASI-HTTP Webhook SDK for the Sololc Runtime.
Documentation
//! # Ergonomic HTTP Types for Sololc Webhook
//!
//! Provides higher-level, safe, and idiomatic wrappers around raw WASI-HTTP assets.
//!
//! This module decouples plugin developers from the low-level, resource-managed
//! types generated by `wit-bindgen`, offering a familiar web-framework experience.

use crate::{IncomingRequest, OutgoingResponse, Fields};

/// Represents an ergonomic, high-level wrapper around a raw WASI [`IncomingRequest`].
///
/// Encapsulates the underlying WebAssembly component model resource stream and provides
/// safe, managed accessors to extract metadata like URI paths, query parameters, or methods.
pub struct Request {
    raw: IncomingRequest,
}

impl Request {
    /// Creates a new [`Request`] instance from a raw WASI [`IncomingRequest`].
    ///
    /// This constructor is typically invoked within code expanded by the routing macros
    /// during host-to-guest boundaries transduction.
    pub fn from_wasi(raw: IncomingRequest) -> Self {
        Self { raw }
    }

    /// Extracts the URI path and its associated query string from the request.
    ///
    /// Returns an empty [`String`] if the path with query component is absent or fails to resolve.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use sololc_webhook_sdk::Request;
    /// # fn extract(req: Request) {
    /// let current_path = req.path();
    /// # }
    /// ```
    pub fn path(&self) -> String {
        self.raw.path_with_query().unwrap_or_default()
    }
}

/// Represents an ergonomic, unmanaged HTTP response template.
///
/// Holds the status code, HTTP headers, and a byte vector payload before it is
/// lowered and streamed down to the host runtime via WASI-HTTP.
#[allow(dead_code)]
pub struct Response {
    /// Represents the standard 3-digit HTTP status code.
    pub status: u16,
    /// Represents the collection of HTTP header key-value pairs.
    pub headers: Vec<(String, Vec<u8>)>,
    /// Represents the underlying raw binary buffer of the response body.
    pub body: Vec<u8>,
}

impl Response {
    /// Creates a new [`Response`] initialized with a `application/json` content type.
    ///
    /// Automatically appends the standard JSON header to the collection and converts the
    /// string slice payload into an owned binary vector.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sololc_webhook_sdk::Response;
    ///
    /// let resp = Response::json(200, r#"{"status": "ok"}"#);
    /// assert_eq!(resp.status, 200);
    /// ```
    pub fn json(status: u16, json_str: &str) -> Self {
        Self {
            status,
            headers: vec![("Content-Type".to_string(), b"application/json".to_vec())],
            body: json_str.as_bytes().to_vec(),
        }
    }

    /// Converts the high-level [`Response`] into a raw, system-level [`OutgoingResponse`].
    ///
    /// This method drains the internal structures, builds the WASI-HTTP [`Fields`],
    /// synchronizes headers, sets the status code, and performs a blocking write/flush 
    /// sequence onto the underlying WASI output-stream.
    ///
    /// # Warnings
    ///
    /// This function consumes the [`Response`] instance due to the ownership transferring 
    /// rules of WebAssembly Component Model resources.
    #[allow(dead_code)]
    pub fn into_wasi(self) -> OutgoingResponse {
        let fields = Fields::new();
        for (k, v) in self.headers {
            fields.append(&k, &v).unwrap();
        }
        let wasi_resp = OutgoingResponse::new(fields);
        wasi_resp.set_status_code(self.status).unwrap();
        
        if !self.body.is_empty() {
            if let Ok(body) = wasi_resp.body() {
                if let Ok(body_stream) = body.write() {
                    let _ = body_stream.blocking_write_and_flush(&self.body);
                }
            }
        }
        
        wasi_resp
    }
}