livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The service provider an application adds to use Livewire.
//!
//! The provider freezes the application's component registrations into one registry, shares it
//! through the container, registers the `.livewire` engine, adds the endpoints, and injects the
//! runtime into pages that rendered a component.

use std::sync::{Arc, Mutex, OnceLock};

use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::http::{Middleware, Next};
use laravel::http::{Request, Response};

use crate::assets::FrontendAssets;
use crate::config::LivewireConfig;
use crate::context::LivewireRequest;
use crate::engine::LivewireEngine;
use crate::frontend::Endpoints;
use crate::registry::ComponentRegistry;

/// Registers an application's Livewire components.
///
/// ```ignore
/// use livewire::LivewireServiceProvider;
///
/// let provider = LivewireServiceProvider::new(|components| {
///     components.register::<Counter>("counter").expect("unique");
/// });
/// ```
pub struct LivewireServiceProvider<F> {
    configure: Mutex<Option<F>>,
    registry: OnceLock<Arc<ComponentRegistry>>,
}

impl<F> LivewireServiceProvider<F> {
    /// Creates the provider, which adds the components `configure` registers.
    pub fn new(configure: F) -> Self {
        Self {
            configure: Mutex::new(Some(configure)),
            registry: OnceLock::new(),
        }
    }

    /// The registry the provider froze, once the application registered its services.
    #[must_use]
    pub fn registry(&self) -> Option<&Arc<ComponentRegistry>> {
        self.registry.get()
    }
}

impl<F> std::fmt::Debug for LivewireServiceProvider<F> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("LivewireServiceProvider")
            .field("registry", &self.registry.get().map(|registry| registry.names().len()))
            .finish_non_exhaustive()
    }
}

impl<F> ServiceProvider for LivewireServiceProvider<F>
where
    F: FnOnce(&mut ComponentRegistry) + Send + 'static,
{
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);

        if config.get::<LivewireConfig>().is_none() {
            config.set(LivewireConfig::default());
        }
    }

    fn register(&self, app: &mut Registrar) {
        let mut registry = ComponentRegistry::new(LivewireConfig::of(app.config()).clone());

        if let Some(configure) = self.configure.lock().ok().and_then(|mut slot| slot.take()) {
            configure(&mut registry);
        }

        let registry = Arc::new(registry);
        let endpoints = Endpoints::new(app.config().app.key.as_deref().unwrap_or("livewire"));
        let assets = Arc::new(FrontendAssets::new(registry.config(), endpoints.clone()));

        app.instance(Arc::clone(&registry));
        app.instance(Arc::clone(&assets));

        app.views()
            .engine("livewire", LivewireEngine::new(Arc::clone(&registry)));

        // An ordinary page renders components and puts the runtime on itself with the same
        // functions a component view uses.
        let page_registry = Arc::clone(&registry);
        app.views().minijinja(move |environment| {
            crate::engine::register_functions(environment, &page_registry);
        });

        crate::routes::register(app.routing(), endpoints, registry.config().upload_throttle());

        app.commands().add::<crate::commands::MakeLivewire>();
        app.commands().add::<crate::commands::LivewireMake>();
        app.commands().add::<crate::commands::LivewireConfigCommand>();
        app.commands().add::<crate::commands::ConfigureS3UploadCleanup>();
        app.commands().add::<crate::commands::Layout>();
        app.commands().add::<crate::commands::Convert>();
        app.commands().add::<crate::commands::Publish>();
        app.commands().add::<crate::commands::Stubs>();

        app.middleware().append(RememberPage);

        if registry.config().inject_assets {
            app.middleware().append(InjectAssets {
                assets: Arc::clone(&assets),
                inject: true,
            });
        }

        let _ = self.registry.set(registry);
    }

    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        use laravel_core::context::Internals as _;

        let context = laravel_core::context::Context::current()
            .ok_or_else(|| laravel::Error::msg("Livewire boots inside the application"))?;

        // A missing or invalid key would let a browser forge a snapshot, so the application does
        // not start without one.
        context.encrypter().map_err(|error| {
            laravel::Error::msg(format!(
                "Livewire needs a valid application encryption key to sign snapshots: {error}"
            ))
        })?;

        let registry = app.resolve::<Arc<ComponentRegistry>>().await?;

        for location in &registry.config().component_locations {
            let path = app.config().app.base_path.join(location);
            if !path.exists() {
                tracing::debug!(
                    path = %path.display(),
                    "the configured component location does not exist yet"
                );
            }
        }

        Ok(())
    }
}

/// Remembers the page a request renders, so its components record where they were mounted.
#[derive(Debug)]
pub struct RememberPage;

impl Middleware for RememberPage {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        // The request is read apart and put back untouched: nothing here consumes the body, and a
        // page render is what needs remembering.
        let http = request.into_http();
        let method = http.method().as_str().to_owned();
        let (parts, body) = http.into_parts();
        let request = Request::from_http(laravel::axum::http::Request::from_parts(parts, body));

        // Every request that renders a page is remembered, whatever its method, so a page a form
        // submission re-renders carries its route context too. The browser sends the Livewire
        // header only to the update and upload endpoints, which render no page.
        if request.header("x-livewire").is_none()
            && let Some(livewire) = crate::context::LivewireRequest::current()
        {
            livewire.remember_page(request.path(), &method, &request.origin());
        }

        Ok(next.run(request).await)
    }
}

/// Injects the runtime into pages that rendered a component, when the application asks for it.
#[derive(Debug)]
pub struct InjectAssets {
    assets: Arc<FrontendAssets>,
    inject: bool,
}

impl Middleware for InjectAssets {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let response = next.run(request).await;

        if !self.inject {
            return Ok(response);
        }

        if !LivewireRequest::current().is_some_and(|request| request.has_rendered()) {
            return Ok(response);
        }

        let is_html = response
            .headers()
            .get("content-type")
            .and_then(|value| value.to_str().ok())
            .is_some_and(|value| value.contains("text/html"));

        if !is_html {
            return Ok(response);
        }

        use http_body_util::BodyExt as _;

        let (parts, body) = response.into_http().into_parts();
        let Ok(collected) = body.collect().await else {
            return Ok(Response::new("").with_status(laravel::http::StatusCode::INTERNAL_SERVER_ERROR));
        };

        let html = String::from_utf8_lossy(&collected.to_bytes()).into_owned();
        let csrf = crate::session::csrf_token().unwrap_or_default();
        let nonce = laravel::view::csp_nonce();
        let rendered = LivewireRequest::current();

        let html = inject(&html, &self.assets, &csrf, nonce.as_deref(), rendered.as_deref());

        Ok(Response::from_http(laravel::axum::http::Response::from_parts(
            parts,
            laravel::axum::body::Body::from(html),
        )))
    }
}

/// Puts the styles before `</head>` and the scripts before `</body>`, when both are there.
fn inject(
    html: &str,
    assets: &FrontendAssets,
    csrf: &str,
    nonce: Option<&str>,
    rendered: Option<&LivewireRequest>,
) -> String {
    let mut html = html.to_owned();

    let styles_done = rendered.is_some_and(LivewireRequest::styles_rendered);
    let scripts_done = rendered.is_some_and(LivewireRequest::scripts_rendered);

    if !styles_done && let Some(index) = html.rfind("</head>") {
        let styles = assets.styles().into_string();
        html.insert_str(index, &styles);
    }

    if !scripts_done && let Some(index) = html.rfind("</body>") {
        let scripts = assets.scripts(csrf, nonce, &[]).into_string();
        html.insert_str(index, &scripts);
    }

    html
}