rorpc 0.1.6

Rust oRPC — annotation-driven Axum handlers with automatic TypeScript contract generation
Documentation
//! TypeScript contract and Zod schema generation.
//!
//! Produces a TypeScript file containing:
//! - Zod schema constants for each input/output type (from `ZodTs::zod_ts()`)
//! - An oRPC `contract` object matching the Rust handler structure
//! - Type exports (`export type X = z.infer<typeof XSchema>`)

pub mod contract;
pub mod typescript;

use std::path::Path;

/// Metadata for a single handler used during contract generation.
#[derive(Debug, Clone)]
pub struct HandlerInfo {
    pub name: &'static str,
    pub method: &'static str,
    pub path: &'static str,
    pub input_type_name: &'static str,
    pub query_type_name: Option<&'static str>,
    pub output_type_name: &'static str,
    pub module_path: &'static str,
    pub error_type_name: Option<&'static str>,
    pub stream_event_type_name: Option<&'static str>,
    /// Ordered comma-separated Rust type names for `Path<T>` parameters.
    /// E.g., `"i32"` for one path param, `"i32,String"` for two.
    /// Empty string when no `Path<T>` extractors are present.
    pub path_param_types: &'static str,
}

/// A collected Zod schema string for a single Rust type.
#[derive(Debug, Clone)]
pub struct SchemaEntry {
    pub type_name: &'static str,
    pub zod_ts: String,
}

/// A single error variant for TypeScript `.errors({...})` generation.
#[derive(Debug, Clone)]
pub struct ErrorVariantInfo {
    pub name: &'static str,
    pub data_schema: Option<&'static str>,
}

/// Registration entry for an error enum type.
#[derive(Debug, Clone)]
pub struct ErrorInfo {
    pub type_name: &'static str,
    pub variants: Vec<ErrorVariantInfo>,
}

/// Builder for TypeScript contract generation.
///
/// # Example
///
/// ```no_run
/// rorpc::generate_contract()
///     .output("../client/src/rpc/index.ts")
///     .unwrap();
/// ```
pub struct ContractBuilder {
    handlers: Vec<HandlerInfo>,
    schemas: Vec<SchemaEntry>,
    errors: Vec<ErrorInfo>,
}

impl ContractBuilder {
    pub fn new(handlers: Vec<HandlerInfo>, schemas: Vec<SchemaEntry>) -> Self {
        Self {
            handlers,
            schemas,
            errors: Vec::new(),
        }
    }

    pub fn with_errors(mut self, errors: Vec<ErrorInfo>) -> Self {
        self.errors = errors;
        self
    }

    /// Generate the TypeScript contract and write it to `path`.
    ///
    /// Accepts both absolute and relative paths. Relative paths are resolved against
    /// the current working directory (typically `CARGO_MANIFEST_DIR` at build time).
    pub fn output(self, path: impl AsRef<Path>) -> std::io::Result<()> {
        let path = path.as_ref();

        let content = self.generate();

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(path, content)
    }

    /// Generate the full TypeScript content as a string.
    pub fn generate(self) -> String {
        let imports = typescript::generate_imports();

        // Collect type names that have real schemas (not fallbacks)
        let real_schema_types: std::collections::HashSet<&str> = self
            .schemas
            .iter()
            .filter(|s| !s.zod_ts.contains("z.unknown()"))
            .map(|s| s.type_name)
            .collect();

        let real_schemas = typescript::generate_real_schemas(&self.schemas);
        let placeholder_schemas = generate_missing_placeholders(&self.handlers, &real_schema_types);
        let contract = contract::generate_contract(&self.handlers, &self.errors, &self.schemas);

        let schema_block = match (real_schemas.is_empty(), placeholder_schemas.is_empty()) {
            (true, true) => String::new(),
            (true, false) => placeholder_schemas,
            (false, true) => real_schemas,
            (false, false) => format!("{}\n\n{}", real_schemas, placeholder_schemas),
        };

        format!(
            "// AUTO-GENERATED by rorpc — do not edit manually.\n// Re-generate: rorpc::generate_contract().output(path)\n\n{imports}\n\n{schema_block}\n\n{contract}"
        )
    }
}

/// Generate placeholder schemas only for types that don't have real schemas.
fn generate_missing_placeholders(
    handlers: &[HandlerInfo],
    real_schema_types: &std::collections::HashSet<&str>,
) -> String {
    use std::collections::BTreeSet;

    let mut unique_types: BTreeSet<String> = BTreeSet::new();

    for handler in handlers {
        let mut type_names = vec![handler.input_type_name, handler.output_type_name];
        if let Some(query_type) = handler.query_type_name {
            type_names.push(query_type);
        }
        for type_str in type_names {
            if !typescript::is_primitive_type_name(type_str) {
                for t in extract_base_types(type_str) {
                    if !real_schema_types.contains(t.as_str()) {
                        unique_types.insert(t);
                    }
                }
            }
        }
    }

    if unique_types.is_empty() {
        return String::new();
    }

    let mut lines = vec![
        "// ⚠️  Placeholder schemas — add #[derive(ZodTs)] to your types for real schemas"
            .to_string(),
        String::new(),
    ];

    for type_name in unique_types {
        let schema_name = typescript::to_schema_name(&type_name);
        let base_name = typescript::base_type_name(&type_name);
        lines.push(format!(
            "// TODO: add #[derive(ZodTs)] to {base_name} in Rust"
        ));
        lines.push(format!(
            "export const {schema_name} = z.unknown(); // {type_name}"
        ));
        lines.push(format!(
            "export type {base_name} = z.infer<typeof {schema_name}>;"
        ));
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Extract all concrete type names from a potentially complex type signature.
/// `"Result<Json<Vec<Planet>>, E>"` → `["Planet"]`
/// Skips `Sse<...>` streaming types — handled separately in contract generation.
fn extract_base_types(type_str: &str) -> Vec<String> {
    let cleaned = type_str.replace(' ', "");

    if cleaned.starts_with("Sse<") {
        return vec![];
    }

    // Unwrap Result<T, E> → T
    let inner = if cleaned.starts_with("Result<") {
        rorpc_parse::types::extract_first_generic_arg_string(&cleaned)
            .map(|s| s.to_string())
            .unwrap_or(cleaned.clone())
    } else {
        cleaned.clone()
    };

    // Unwrap Json<T> → T
    let inner = if inner.starts_with("Json<") && inner.ends_with('>') {
        inner[5..inner.len() - 1].to_string()
    } else {
        inner
    };

    if inner.starts_with("Vec<") && inner.ends_with('>') {
        let elem = &inner[4..inner.len() - 1];
        if !typescript::is_primitive_type_name(elem) {
            vec![elem.to_string()]
        } else {
            vec![]
        }
    } else if inner.starts_with("Option<") && inner.ends_with('>') {
        let elem = &inner[7..inner.len() - 1];
        if !typescript::is_primitive_type_name(elem) {
            vec![elem.to_string()]
        } else {
            vec![]
        }
    } else if !typescript::is_primitive_type_name(&inner) && !inner.is_empty() && inner != "()" {
        vec![inner]
    } else {
        vec![]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_handler(name: &'static str, method: &'static str, path: &'static str) -> HandlerInfo {
        HandlerInfo {
            name,
            method,
            path,
            input_type_name: "()",
            query_type_name: None,
            output_type_name: "String",
            module_path: "test::handlers",
            error_type_name: None,
            stream_event_type_name: None,
            path_param_types: "",
        }
    }

    #[test]
    fn accepts_relative_paths_with_parent_dirs() {
        let builder = ContractBuilder::new(vec![make_handler("ping", "GET", "/ping")], vec![]);
        // Should not panic - relative paths with .. are allowed for legitimate use cases
        // like frontend directories outside the Rust workspace
        let temp_dir = std::env::temp_dir();
        let result = builder.output(temp_dir.join("test-output.ts"));
        // We only care that it doesn't reject the path - actual write may fail in test env
        assert!(result.is_ok() || result.unwrap_err().kind() != std::io::ErrorKind::InvalidInput);
    }

    #[test]
    fn accepts_multiple_parent_dirs_in_path() {
        // Test that paths with multiple .. components work (e.g., frontend outside workspace)
        let builder = ContractBuilder::new(
            vec![make_handler("test", "GET", "/test")],
            vec![],
        );
        
        let temp_dir = std::env::temp_dir();
        let test_file = temp_dir.join("rorpc-test-multiple-parents.ts");
        
        // Create a nested directory structure to test ../../.. navigation
        let nested = temp_dir.join("a").join("b").join("c");
        std::fs::create_dir_all(&nested).ok();
        
        // Use relative path with multiple .. to write outside nested dir
        let relative_from_nested = "../../../rorpc-test-multiple-parents.ts";
        let full_path = nested.join(relative_from_nested);
        
        let result = builder.output(&full_path);
        
        // Verify it works (doesn't reject with InvalidInput) - use as_ref to avoid move
        let is_valid = result.as_ref().map(|_| true).unwrap_or_else(|e| e.kind() != std::io::ErrorKind::InvalidInput);
        assert!(is_valid, "Path with multiple .. should be accepted");
        
        // If write succeeded, verify file was created in correct location
        if result.is_ok() {
            assert!(test_file.exists(), "File should exist at resolved path");
            std::fs::remove_file(test_file).ok();
        }
        
        // Cleanup
        std::fs::remove_dir_all(temp_dir.join("a")).ok();
    }

    #[test]
    fn accepts_deep_parent_navigation() {
        // Test extreme case: ../../../../../../../../ (many levels up)
        let builder = ContractBuilder::new(
            vec![make_handler("extreme", "GET", "/extreme")],
            vec![],
        );
        
        let temp_dir = std::env::temp_dir();
        let test_output = temp_dir.join("rorpc-deep-navigation-test.ts");
        
        // Create very nested structure
        let deeply_nested = temp_dir
            .join("level1")
            .join("level2")
            .join("level3")
            .join("level4")
            .join("level5");
        std::fs::create_dir_all(&deeply_nested).ok();
        
        // Navigate all the way back up
        let relative = "../../../../../rorpc-deep-navigation-test.ts";
        let path_from_deep = deeply_nested.join(relative);
        
        let result = builder.output(&path_from_deep);
        
        // Use as_ref to avoid move
        let is_valid = result.as_ref().map(|_| true).unwrap_or_else(|e| e.kind() != std::io::ErrorKind::InvalidInput);
        assert!(is_valid, "Deep parent navigation (../../../../..) should be accepted");
        
        if result.is_ok() && test_output.exists() {
            std::fs::remove_file(test_output).ok();
        }
        
        std::fs::remove_dir_all(temp_dir.join("level1")).ok();
    }

    #[test]
    fn generates_with_no_schemas() {
        let builder = ContractBuilder::new(vec![make_handler("ping", "GET", "/ping")], vec![]);
        let output = builder.generate();
        assert!(output.contains("AUTO-GENERATED"));
        assert!(output.contains("ping"));
    }

    #[test]
    fn generates_with_real_schemas() {
        let builder = ContractBuilder::new(
            vec![make_handler("list_planets", "POST", "/planet/list")],
            vec![SchemaEntry {
                type_name: "Planet",
                zod_ts: "export const PlanetSchema = z.object({ id: z.number().int() });"
                    .to_string(),
            }],
        );
        let output = builder.generate();
        assert!(output.contains("PlanetSchema"));
        assert!(output.contains("z.object"));
        assert!(output.contains("listPlanets"));
    }
}