livewire-rust 0.1.5

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! The routes the package registers: the browser's update endpoint, and the built runtime it loads.

use std::sync::Arc;

use laravel::container::Inject;
use laravel::http::{Response, StatusCode};
use laravel::routing::{Params, Routing};

use crate::assets::FrontendAssets;
use crate::frontend::Endpoints;

/// Registers every Livewire route on the application's routing definition.
#[expect(
    clippy::needless_pass_by_value,
    reason = "the routes take the endpoints so the provider does not have to clone them"
)]
pub fn register(
    routing: &mut Routing,
    endpoints: Endpoints,
    upload_throttle: Option<laravel::http::middleware::Throttle>,
) {
    let prefix = endpoints.prefix().to_owned();
    let update = endpoints.update();

    let js_route = endpoints.module_js_route();
    let css_route = endpoints.module_css_route();

    routing.routes(move |route| {
        route.get(&format!("{prefix}/livewire.js"), livewire_js);
        route.get(&format!("{prefix}/livewire.min.js"), livewire_min_js);
        route.get(&format!("{prefix}/livewire.csp.min.js"), livewire_csp_min_js);
        route.get(&format!("{prefix}/livewire.min.js.map"), livewire_min_map);
        route.get(&format!("{prefix}/livewire.csp.min.js.map"), livewire_csp_min_map);
        route.get(&js_route, component_script);
        route.get(&css_route, component_style);
    });

    // The update endpoint always runs the `web` group, so the session and the CSRF check apply,
    // and always requires the browser runtime's headers.
    let upload = endpoints.upload();
    let preview = endpoints.preview();

    routing.web(move |route| {
        route.post(&update, crate::handlers::update);
        let upload_route = route.post(&upload, crate::uploads::store);

        if let Some(throttle) = upload_throttle {
            upload_route.middleware(throttle);
        }
        route.get(&preview, crate::uploads::preview);
    });
}

/// Serves the unminified runtime, which a debug page loads.
async fn livewire_js(assets: Inject<Arc<FrontendAssets>>) -> Response {
    serve("livewire.js", &assets)
}

/// Serves the minified runtime.
async fn livewire_min_js(assets: Inject<Arc<FrontendAssets>>) -> Response {
    serve("livewire.min.js", &assets)
}

/// Serves the minified CSP-safe runtime.
async fn livewire_csp_min_js(assets: Inject<Arc<FrontendAssets>>) -> Response {
    serve("livewire.csp.min.js", &assets)
}

/// Serves the minified runtime's source map.
async fn livewire_min_map(assets: Inject<Arc<FrontendAssets>>) -> Response {
    serve("livewire.min.js.map", &assets)
}

/// Serves the minified CSP-safe runtime's source map.
async fn livewire_csp_min_map(assets: Inject<Arc<FrontendAssets>>) -> Response {
    serve("livewire.csp.min.js.map", &assets)
}

/// Serves a component's JavaScript module.
async fn component_script(file: Params<String>) -> Response {
    serve_module(&file.0, ModuleKind::Script)
}

/// Serves a component's CSS module, scoped or global.
async fn component_style(file: Params<String>) -> Response {
    serve_module(&file.0, ModuleKind::Style)
}

/// Which module a request asks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ModuleKind {
    Script,
    Style,
}

/// Serves the module file a component name maps to, or `404` when the component has none.
///
/// Nothing outside the application's component directories can be reached: the name is normalized
/// before it becomes a path, and a name that would escape is a `404` rather than a read.
fn serve_module(file: &str, kind: ModuleKind) -> Response {
    let (encoded, global) = match (kind, file.strip_suffix(".global.css")) {
        (ModuleKind::Style, Some(name)) => (name, true),
        (ModuleKind::Style, None) => match file.strip_suffix(".css") {
            Some(name) => (name, false),
            None => return error(StatusCode::NOT_FOUND),
        },
        (ModuleKind::Script, _) => match file.strip_suffix(".js") {
            Some(name) => (name, false),
            None => return error(StatusCode::NOT_FOUND),
        },
    };

    let name = crate::frontend::decode_component_name(encoded);

    let Ok(name) = crate::registry::normalize_name(&name) else {
        return error(StatusCode::NOT_FOUND);
    };

    if name.is_empty() {
        return error(StatusCode::NOT_FOUND);
    }

    let Some(path) = module_path(&name, kind, global) else {
        return error(StatusCode::NOT_FOUND);
    };

    let Ok(bytes) = std::fs::read(&path) else {
        return error(StatusCode::NOT_FOUND);
    };

    let content_type = match kind {
        ModuleKind::Script => "application/javascript; charset=utf-8",
        ModuleKind::Style => "text/css; charset=utf-8",
    };

    let mut response = Response::new(bytes);
    if let Ok(value) = content_type.parse() {
        response.headers_mut().insert("content-type", value);
    }

    response
}

/// Where a component's module file lives, in the first directory that holds one.
fn module_path(name: &str, kind: ModuleKind, global: bool) -> Option<std::path::PathBuf> {
    use laravel_core::context::Internals as _;

    let context = laravel_core::context::Context::current()?;
    let base = context.config().app.base_path.clone();
    let config = crate::config::LivewireConfig::of(context.config());

    let relative: std::path::PathBuf = name.split(['.', ':']).filter(|part| !part.is_empty()).collect();
    let extension = match (kind, global) {
        (ModuleKind::Script, _) => "js",
        (ModuleKind::Style, true) => "global.css",
        (ModuleKind::Style, false) => "css",
    };

    for root in [&config.view_path, &config.component_path] {
        let candidate = base.join(root).join(&relative).with_extension(extension);
        if candidate.is_file() {
            return Some(candidate);
        }
    }

    None
}

/// An empty response with a status.
fn error(status: StatusCode) -> Response {
    Response::new("").with_status(status)
}

fn serve(file: &str, assets: &FrontendAssets) -> Response {
    match assets.bundle(file) {
        Some(bytes) => {
            let content_type = if file.ends_with(".map") {
                "application/json"
            } else {
                "application/javascript; charset=utf-8"
            };

            let mut response = Response::new(bytes.to_vec());
            if let Ok(value) = content_type.parse() {
                response.headers_mut().insert("content-type", value);
            }
            if let Ok(value) = "public, max-age=31536000, immutable".parse() {
                response.headers_mut().insert("cache-control", value);
            }

            response
        }
        None => Response::new("").with_status(StatusCode::NOT_FOUND),
    }
}