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;
pub struct LivewireServiceProvider<F> {
configure: Mutex<Option<F>>,
registry: OnceLock<Arc<ComponentRegistry>>,
}
impl<F> LivewireServiceProvider<F> {
pub fn new(configure: F) -> Self {
Self {
configure: Mutex::new(Some(configure)),
registry: OnceLock::new(),
}
}
#[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(®istry));
app.instance(Arc::clone(&assets));
app.views()
.engine("livewire", LivewireEngine::new(Arc::clone(®istry)));
let page_registry = Arc::clone(®istry);
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"))?;
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 ®istry.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(())
}
}
#[derive(Debug)]
pub struct RememberPage;
impl Middleware for RememberPage {
async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
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));
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)
}
}
#[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),
)))
}
}
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
}