saola-kit 0.1.1

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
pub mod hosts;
pub mod route_index;
pub mod router;

pub use hosts::{ContextError, ContextHosts};
pub use route_index::{
    ClientContextMeta, ClientLinkEntry, ClientLinks, ContextLinksRule, ContextSpec, ContextTarget,
    HrefOptions, RouteEntry, RouteIndex,
};
pub use router::{
    ContextRoute, ContextRoutes, SetCurrentContext, SharedRouteIndex, join_uri,
};

const CONTEXT_KEY: &str = "saola.current_context";

/// Registry of declared Saola contexts and routes, used to build a [`RouteIndex`].
#[derive(Debug, Clone, Default)]
pub struct ContextRegistry {
    contexts: Vec<ContextSpec>,
    routes: Vec<RouteEntry>,
}

impl ContextRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_context(&mut self, spec: ContextSpec) -> &mut Self {
        self.contexts.push(spec);
        self
    }

    pub fn add_route(&mut self, entry: RouteEntry) -> &mut Self {
        self.routes.push(entry);
        self
    }

    pub fn contexts(&self) -> &[ContextSpec] {
        &self.contexts
    }

    pub fn routes(&self) -> &[RouteEntry] {
        &self.routes
    }

    pub fn build_index(&self, primary_url: &str) -> Result<RouteIndex, ContextError> {
        let mut sorted_contexts = self.contexts.clone();
        sorted_contexts.sort_by(|a, b| b.priority.cmp(&a.priority).then_with(|| a.slug.cmp(&b.slug)));
        RouteIndex::new(sorted_contexts, self.routes.clone(), primary_url)
    }
}

/// Records the active Saola context slug in the current Laravel request context.
pub fn set_current_context(slug: &str) {
    laravel::context::add_hidden(CONTEXT_KEY, slug);
}

/// Returns the active Saola context slug stored in the current Laravel request context, if any.
pub fn current_context() -> Option<String> {
    laravel::context::get_hidden::<String>(CONTEXT_KEY)
}