Skip to main content

livewire/
provider.rs

1//! The service provider an application adds to use Livewire.
2//!
3//! The provider freezes the application's component registrations into one registry, shares it
4//! through the container, registers the `.livewire` engine, adds the endpoints, and injects the
5//! runtime into pages that rendered a component.
6
7use std::sync::{Arc, Mutex, OnceLock};
8
9use laravel::config::{Config, Env};
10use laravel::container::{Container, Registrar};
11use laravel::foundation::ServiceProvider;
12use laravel::http::{Middleware, Next};
13use laravel::http::{Request, Response};
14
15use crate::assets::FrontendAssets;
16use crate::config::LivewireConfig;
17use crate::context::LivewireRequest;
18use crate::engine::LivewireEngine;
19use crate::frontend::Endpoints;
20use crate::registry::ComponentRegistry;
21
22/// Registers an application's Livewire components.
23///
24/// ```ignore
25/// use livewire::LivewireServiceProvider;
26///
27/// let provider = LivewireServiceProvider::new(|components| {
28///     components.register::<Counter>("counter").expect("unique");
29/// });
30/// ```
31pub struct LivewireServiceProvider<F> {
32    configure: Mutex<Option<F>>,
33    registry: OnceLock<Arc<ComponentRegistry>>,
34}
35
36impl<F> LivewireServiceProvider<F> {
37    /// Creates the provider, which adds the components `configure` registers.
38    pub fn new(configure: F) -> Self {
39        Self {
40            configure: Mutex::new(Some(configure)),
41            registry: OnceLock::new(),
42        }
43    }
44
45    /// The registry the provider froze, once the application registered its services.
46    #[must_use]
47    pub fn registry(&self) -> Option<&Arc<ComponentRegistry>> {
48        self.registry.get()
49    }
50}
51
52impl<F> std::fmt::Debug for LivewireServiceProvider<F> {
53    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        formatter
55            .debug_struct("LivewireServiceProvider")
56            .field("registry", &self.registry.get().map(|registry| registry.names().len()))
57            .finish_non_exhaustive()
58    }
59}
60
61impl<F> ServiceProvider for LivewireServiceProvider<F>
62where
63    F: FnOnce(&mut ComponentRegistry) + Send + 'static,
64{
65    fn config(&self, config: &mut Config, env: &Env) {
66        config.discover(env!("CARGO_CRATE_NAME"), env);
67
68        if config.get::<LivewireConfig>().is_none() {
69            config.set(LivewireConfig::default());
70        }
71    }
72
73    fn register(&self, app: &mut Registrar) {
74        let mut registry = ComponentRegistry::new(LivewireConfig::of(app.config()).clone());
75
76        if let Some(configure) = self.configure.lock().ok().and_then(|mut slot| slot.take()) {
77            configure(&mut registry);
78        }
79
80        let registry = Arc::new(registry);
81        let endpoints = Endpoints::new(app.config().app.key.as_deref().unwrap_or("livewire"));
82        let assets = Arc::new(FrontendAssets::new(registry.config(), endpoints.clone()));
83
84        app.instance(Arc::clone(&registry));
85        app.instance(Arc::clone(&assets));
86
87        app.views()
88            .engine("livewire", LivewireEngine::new(Arc::clone(&registry)));
89
90        // An ordinary page renders components and puts the runtime on itself with the same
91        // functions a component view uses.
92        let page_registry = Arc::clone(&registry);
93        app.views().minijinja(move |environment| {
94            crate::engine::register_functions(environment, &page_registry);
95        });
96
97        crate::routes::register(app.routing(), endpoints, registry.config().upload_throttle());
98
99        app.commands().add::<crate::commands::MakeLivewire>();
100        app.commands().add::<crate::commands::LivewireMake>();
101        app.commands().add::<crate::commands::LivewireConfigCommand>();
102        app.commands().add::<crate::commands::ConfigureS3UploadCleanup>();
103        app.commands().add::<crate::commands::Layout>();
104        app.commands().add::<crate::commands::Convert>();
105        app.commands().add::<crate::commands::Publish>();
106        app.commands().add::<crate::commands::Stubs>();
107
108        app.middleware().append(RememberPage);
109
110        if registry.config().inject_assets {
111            app.middleware().append(InjectAssets {
112                assets: Arc::clone(&assets),
113                inject: true,
114            });
115        }
116
117        let _ = self.registry.set(registry);
118    }
119
120    async fn boot(&self, app: &Container) -> laravel::Result<()> {
121        use laravel_core::context::Internals as _;
122
123        let context = laravel_core::context::Context::current()
124            .ok_or_else(|| laravel::Error::msg("Livewire boots inside the application"))?;
125
126        // A missing or invalid key would let a browser forge a snapshot, so the application does
127        // not start without one.
128        context.encrypter().map_err(|error| {
129            laravel::Error::msg(format!(
130                "Livewire needs a valid application encryption key to sign snapshots: {error}"
131            ))
132        })?;
133
134        let registry = app.resolve::<Arc<ComponentRegistry>>().await?;
135
136        for location in &registry.config().component_locations {
137            let path = app.config().app.base_path.join(location);
138            if !path.exists() {
139                tracing::debug!(
140                    path = %path.display(),
141                    "the configured component location does not exist yet"
142                );
143            }
144        }
145
146        Ok(())
147    }
148}
149
150/// Remembers the page a request renders, so its components record where they were mounted.
151#[derive(Debug)]
152pub struct RememberPage;
153
154impl Middleware for RememberPage {
155    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
156        // The request is read apart and put back untouched: nothing here consumes the body, and a
157        // page render is what needs remembering.
158        let http = request.into_http();
159        let method = http.method().as_str().to_owned();
160        let (parts, body) = http.into_parts();
161        let request = Request::from_http(laravel::axum::http::Request::from_parts(parts, body));
162
163        // Every request that renders a page is remembered, whatever its method, so a page a form
164        // submission re-renders carries its route context too. The browser sends the Livewire
165        // header only to the update and upload endpoints, which render no page.
166        if request.header("x-livewire").is_none()
167            && let Some(livewire) = crate::context::LivewireRequest::current()
168        {
169            livewire.remember_page(request.path(), &method, &request.origin());
170        }
171
172        Ok(next.run(request).await)
173    }
174}
175
176/// Injects the runtime into pages that rendered a component, when the application asks for it.
177#[derive(Debug)]
178pub struct InjectAssets {
179    assets: Arc<FrontendAssets>,
180    inject: bool,
181}
182
183impl Middleware for InjectAssets {
184    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
185        let response = next.run(request).await;
186
187        if !self.inject {
188            return Ok(response);
189        }
190
191        if !LivewireRequest::current().is_some_and(|request| request.has_rendered()) {
192            return Ok(response);
193        }
194
195        let is_html = response
196            .headers()
197            .get("content-type")
198            .and_then(|value| value.to_str().ok())
199            .is_some_and(|value| value.contains("text/html"));
200
201        if !is_html {
202            return Ok(response);
203        }
204
205        use http_body_util::BodyExt as _;
206
207        let (parts, body) = response.into_http().into_parts();
208        let Ok(collected) = body.collect().await else {
209            return Ok(Response::new("").with_status(laravel::http::StatusCode::INTERNAL_SERVER_ERROR));
210        };
211
212        let html = String::from_utf8_lossy(&collected.to_bytes()).into_owned();
213        let csrf = crate::session::csrf_token().unwrap_or_default();
214        let nonce = laravel::view::csp_nonce();
215        let rendered = LivewireRequest::current();
216
217        let html = inject(&html, &self.assets, &csrf, nonce.as_deref(), rendered.as_deref());
218
219        Ok(Response::from_http(laravel::axum::http::Response::from_parts(
220            parts,
221            laravel::axum::body::Body::from(html),
222        )))
223    }
224}
225
226/// Puts the styles before `</head>` and the scripts before `</body>`, when both are there.
227fn inject(
228    html: &str,
229    assets: &FrontendAssets,
230    csrf: &str,
231    nonce: Option<&str>,
232    rendered: Option<&LivewireRequest>,
233) -> String {
234    let mut html = html.to_owned();
235
236    let styles_done = rendered.is_some_and(LivewireRequest::styles_rendered);
237    let scripts_done = rendered.is_some_and(LivewireRequest::scripts_rendered);
238
239    if !styles_done && let Some(index) = html.rfind("</head>") {
240        let styles = assets.styles().into_string();
241        html.insert_str(index, &styles);
242    }
243
244    if !scripts_done && let Some(index) = html.rfind("</body>") {
245        let scripts = assets.scripts(csrf, nonce, &[]).into_string();
246        html.insert_str(index, &scripts);
247    }
248
249    html
250}