ferro-inertia 0.2.24

Server-side Inertia.js adapter for Rust web frameworks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Inertia response generation.

use crate::config::InertiaConfig;
use crate::manifest::resolve_assets;
use crate::request::InertiaRequest;
use crate::shared::InertiaShared;
use serde::Serialize;

/// Framework-agnostic HTTP response.
///
/// Convert this to your framework's response type.
#[derive(Debug, Clone)]
pub struct InertiaHttpResponse {
    /// HTTP status code
    pub status: u16,
    /// Response headers as (name, value) pairs
    pub headers: Vec<(String, String)>,
    /// Response body
    pub body: String,
    /// Content type
    pub content_type: &'static str,
}

impl InertiaHttpResponse {
    /// Create a JSON response with Inertia headers.
    pub fn json(body: impl Into<String>) -> Self {
        Self {
            status: 200,
            headers: vec![
                ("X-Inertia".to_string(), "true".to_string()),
                ("Vary".to_string(), "X-Inertia".to_string()),
            ],
            body: body.into(),
            content_type: "application/json",
        }
    }

    /// Create a raw JSON response without Inertia headers.
    ///
    /// Used for JSON fallback when a non-Inertia client requests JSON.
    pub fn raw_json(body: impl Into<String>) -> Self {
        Self {
            status: 200,
            headers: vec![],
            body: body.into(),
            content_type: "application/json",
        }
    }

    /// Create an HTML response.
    pub fn html(body: impl Into<String>) -> Self {
        Self {
            status: 200,
            headers: vec![("Vary".to_string(), "X-Inertia".to_string())],
            body: body.into(),
            content_type: "text/html; charset=utf-8",
        }
    }

    /// Create a 409 Conflict response for version mismatch.
    pub fn conflict(location: impl Into<String>) -> Self {
        Self {
            status: 409,
            headers: vec![("X-Inertia-Location".to_string(), location.into())],
            body: String::new(),
            content_type: "text/plain",
        }
    }

    /// Set the HTTP status code.
    pub fn status(mut self, status: u16) -> Self {
        self.status = status;
        self
    }

    /// Add a header to the response.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Create a redirect response for Inertia requests.
    ///
    /// For POST/PUT/PATCH/DELETE requests, uses status 303 (See Other) to force
    /// the browser to follow the redirect with a GET request.
    ///
    /// For GET requests, uses standard 302.
    pub fn redirect(location: impl Into<String>, is_post_like: bool) -> Self {
        // POST/PUT/PATCH/DELETE -> 303 (See Other) forces GET on redirect
        // GET -> 302 (Found) standard redirect
        let status = if is_post_like { 303 } else { 302 };

        Self {
            status,
            headers: vec![
                ("X-Inertia".to_string(), "true".to_string()),
                ("Location".to_string(), location.into()),
            ],
            body: String::new(),
            content_type: "text/plain",
        }
    }
}

/// Main Inertia integration struct.
///
/// Provides methods for rendering Inertia responses in a framework-agnostic way.
pub struct Inertia;

impl Inertia {
    /// Render an Inertia response.
    ///
    /// This is the primary method for returning Inertia responses from handlers.
    /// It automatically:
    /// - Detects XHR vs initial page load
    /// - Filters props for partial reloads
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ferro_inertia::Inertia;
    /// use serde_json::json;
    ///
    /// let response = Inertia::render(&req, "Home", json!({
    ///     "title": "Welcome",
    ///     "user": { "name": "John" }
    /// }));
    /// ```
    pub fn render<R, P>(req: &R, component: &str, props: P) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, None, InertiaConfig::default(), false)
    }

    /// Render an Inertia response with JSON fallback for API clients.
    ///
    /// When enabled, requests with `Accept: application/json` header (but without
    /// `X-Inertia: true`) will receive raw props as JSON instead of HTML.
    ///
    /// This is useful for:
    /// - API testing with curl or Postman
    /// - Hybrid apps that sometimes need raw JSON
    /// - Debug tooling
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ferro_inertia::Inertia;
    /// use serde_json::json;
    ///
    /// // curl -H "Accept: application/json" http://localhost:3000/posts/1
    /// // Returns raw JSON props instead of HTML
    /// let response = Inertia::render_with_json_fallback(&req, "Posts/Show", json!({
    ///     "post": { "id": 1, "title": "Hello" }
    /// }));
    /// ```
    pub fn render_with_json_fallback<R, P>(
        req: &R,
        component: &str,
        props: P,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, None, InertiaConfig::default(), true)
    }

    /// Render an Inertia response with shared props.
    pub fn render_with_shared<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: &InertiaShared,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(
            req,
            component,
            props,
            Some(shared),
            InertiaConfig::default(),
            false,
        )
    }

    /// Render an Inertia response with custom configuration.
    pub fn render_with_config<R, P>(
        req: &R,
        component: &str,
        props: P,
        config: InertiaConfig,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, None, config, false)
    }

    /// Render an Inertia response with all options.
    pub fn render_with_options<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: Option<&InertiaShared>,
        config: InertiaConfig,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, shared, config, false)
    }

    /// Render an Inertia response with all options and JSON fallback.
    pub fn render_with_options_and_json_fallback<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: Option<&InertiaShared>,
        config: InertiaConfig,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, shared, config, true)
    }

    /// Internal render method with all options.
    fn render_internal<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: Option<&InertiaShared>,
        config: InertiaConfig,
        json_fallback: bool,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        let url = req.path().to_string();
        let is_inertia = req.is_inertia();
        let partial_data = req.inertia_partial_data();
        let partial_component = req.inertia_partial_component();

        // Serialize props
        let mut props_value = match serde_json::to_value(&props) {
            Ok(v) => v,
            Err(e) => {
                return InertiaHttpResponse::html(format!("Failed to serialize props: {e}"))
                    .status(500);
            }
        };

        // Merge shared props
        if let Some(shared) = shared {
            shared.merge_into(&mut props_value);
        }

        // Filter props for partial reloads
        if is_inertia {
            if let Some(partial_keys) = partial_data {
                let should_filter = partial_component.map(|pc| pc == component).unwrap_or(false);

                if should_filter {
                    props_value = Self::filter_partial_props(props_value, &partial_keys);
                }
            }
        }

        // Check for JSON fallback before normal Inertia handling
        // If JSON fallback is enabled and request accepts JSON but is not an Inertia request,
        // return raw props as JSON
        if json_fallback && !is_inertia && req.accepts_json() {
            return InertiaHttpResponse::raw_json(
                serde_json::to_string(&props_value).unwrap_or_default(),
            );
        }

        let response = InertiaResponse::new(component, props_value, url).with_config(config);

        // Extract CSRF token from shared props for HTML response
        let csrf = shared.and_then(|s| s.csrf.as_deref());

        if is_inertia {
            response.to_json_response()
        } else {
            response.to_html_response(csrf)
        }
    }

    /// Check if a version conflict should trigger a full reload.
    ///
    /// Returns `Some(response)` with a 409 Conflict if versions don't match.
    pub fn check_version<R: InertiaRequest>(
        req: &R,
        current_version: &str,
        redirect_url: &str,
    ) -> Option<InertiaHttpResponse> {
        if !req.is_inertia() {
            return None;
        }

        if let Some(client_version) = req.inertia_version() {
            if client_version != current_version {
                return Some(InertiaHttpResponse::conflict(redirect_url));
            }
        }

        None
    }

    /// Filter props to only include those requested in partial reload.
    fn filter_partial_props(props: serde_json::Value, partial_keys: &[&str]) -> serde_json::Value {
        match props {
            serde_json::Value::Object(map) => {
                let filtered: serde_json::Map<String, serde_json::Value> = map
                    .into_iter()
                    .filter(|(k, _)| partial_keys.contains(&k.as_str()))
                    .collect();
                serde_json::Value::Object(filtered)
            }
            other => other,
        }
    }
}

/// Internal response builder.
pub struct InertiaResponse {
    component: String,
    props: serde_json::Value,
    url: String,
    config: InertiaConfig,
}

impl InertiaResponse {
    /// Create a new Inertia response.
    pub fn new(component: impl Into<String>, props: serde_json::Value, url: String) -> Self {
        Self {
            component: component.into(),
            props,
            url,
            config: InertiaConfig::default(),
        }
    }

    /// Set the configuration.
    pub fn with_config(mut self, config: InertiaConfig) -> Self {
        self.config = config;
        self
    }

    /// Build JSON response for XHR requests.
    pub fn to_json_response(&self) -> InertiaHttpResponse {
        let page = serde_json::json!({
            "component": self.component,
            "props": self.props,
            "url": self.url,
            "version": self.config.version,
        });

        InertiaHttpResponse::json(serde_json::to_string(&page).unwrap_or_default())
    }

    /// Build HTML response for initial page loads.
    pub fn to_html_response(&self, csrf_token: Option<&str>) -> InertiaHttpResponse {
        let page_data = serde_json::json!({
            "component": self.component,
            "props": self.props,
            "url": self.url,
            "version": self.config.version,
        });

        // Escape JSON for HTML attribute
        let page_json = serde_json::to_string(&page_data)
            .unwrap_or_default()
            .replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
            .replace('\'', "&#x27;");

        let csrf = csrf_token.unwrap_or("");

        // Use custom template if provided
        if let Some(template) = &self.config.html_template {
            let html = template
                .replace("{page}", &page_json)
                .replace("{csrf}", csrf);
            return InertiaHttpResponse::html(html);
        }

        // Default template
        let html = if self.config.development {
            format!(
                r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{}">
    <title>{}</title>
    <script type="module">
        import RefreshRuntime from '{}/@react-refresh'
        RefreshRuntime.injectIntoGlobalHook(window)
        window.$RefreshReg$ = () => {{}}
        window.$RefreshSig$ = () => (type) => type
        window.__vite_plugin_react_preamble_installed__ = true
    </script>
    <script type="module" src="{}/@vite/client"></script>
    <script type="module" src="{}/{}"></script>
</head>
<body>
    <div id="app" data-page="{}"></div>
</body>
</html>"#,
                csrf,
                self.config.app_name,
                self.config.vite_dev_server,
                self.config.vite_dev_server,
                self.config.vite_dev_server,
                self.config.entry_point,
                page_json
            )
        } else {
            let assets = resolve_assets(&self.config.manifest_path, &self.config.entry_point);

            let css_tags: String = assets
                .css
                .iter()
                .map(|href| format!(r#"    <link rel="stylesheet" href="{href}">"#))
                .collect::<Vec<_>>()
                .join("\n");

            format!(
                r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{csrf}">
    <title>{app_name}</title>
    <script type="module" src="{js_src}"></script>
{css_tags}
</head>
<body>
    <div id="app" data-page="{page_json}"></div>
</body>
</html>"#,
                app_name = self.config.app_name,
                js_src = assets.js,
            )
        };

        InertiaHttpResponse::html(html)
    }
}