rejoice 0.12.0

A simple and delightful little web framework for Rust
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
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// HTTP methods that can be handled by route files
const HTTP_METHODS: &[&str] = &["get", "post", "put", "delete", "patch"];

/// Call this from your build.rs to generate file-based routes.
pub fn generate_routes() {
    let routes_dir = Path::new("src/routes");
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");

    // Generate src/routes.rs for rust-analyzer support
    let mut routes_mod = String::new();
    generate_routes_mod(routes_dir, routes_dir, "", &mut routes_mod);
    fs::write("src/routes.rs", &routes_mod).expect("Failed to write src/routes.rs");

    // Collect layouts and routes
    let mut layouts: HashMap<String, String> = HashMap::new();
    let mut routes: Vec<RouteInfo> = Vec::new();

    collect_layouts_and_routes(routes_dir, "", "", &[], &mut layouts, &mut routes);

    let routes_rs_path =
        fs::canonicalize("src/routes.rs").expect("Failed to canonicalize src/routes.rs");

    // Generate stateless version
    let stateless_output = generate_routes_file(&routes_rs_path, &routes, &layouts, true);
    let stateless_path = Path::new(&out_dir).join("routes_generated_stateless.rs");
    fs::write(&stateless_path, &stateless_output)
        .expect("Failed to write routes_generated_stateless.rs");

    // Generate stateful version
    let stateful_output = generate_routes_file(&routes_rs_path, &routes, &layouts, false);
    let stateful_path = Path::new(&out_dir).join("routes_generated_stateful.rs");
    fs::write(&stateful_path, &stateful_output)
        .expect("Failed to write routes_generated_stateful.rs");

    println!("cargo:rerun-if-changed=src/routes");
}

fn generate_routes_file(
    routes_rs_path: &Path,
    routes: &[RouteInfo],
    layouts: &HashMap<String, String>,
    stateless: bool,
) -> String {
    let mut output = String::new();

    output.push_str(&format!("#[path = {:?}]\n", routes_rs_path.display()));
    output.push_str("mod routes;\n\n");

    // Generate wrapper handlers for routes with layouts
    for route in routes {
        for method in &route.methods {
            if let Some(wrapper) = generate_wrapper_handler(route, method, layouts, stateless) {
                output.push_str(&wrapper);
                output.push_str("\n\n");
            }
        }
    }

    // Generate router
    output.push_str("pub fn create_router() -> rejoice::Router<__RejoiceState> {\n");
    output.push_str("    rejoice::Router::new()\n");

    for route in routes {
        let mut method_handlers = Vec::new();

        for method in &route.methods {
            let handler = if has_layouts(route, layouts) {
                format!("wrapper_{}_{}", route.mod_name, method)
            } else {
                format!("routes::{}::{}", route.mod_name, method)
            };
            method_handlers.push((method.as_str(), handler));
        }

        if method_handlers.is_empty() {
            continue;
        }

        if method_handlers.len() == 1 {
            let (method, handler) = &method_handlers[0];
            output.push_str(&format!(
                "        .route({:?}, rejoice::routing::{}({}))\n",
                route.url_path, method, handler
            ));
        } else {
            output.push_str(&format!(
                "        .route({:?}, rejoice::routing::MethodRouter::new()",
                route.url_path
            ));
            for (method, handler) in &method_handlers {
                output.push_str(&format!(".{}({})", method, handler));
            }
            output.push_str(")\n");
        }
    }

    output.push_str("}\n");
    output
}

struct RouteInfo {
    url_path: String,
    mod_name: String,
    dir_path: String,
    params: Vec<String>, // All path parameters (from directories and file name)
    methods: Vec<String>,
}

fn detect_methods(file_path: &Path) -> Vec<String> {
    let content = match fs::read_to_string(file_path) {
        Ok(c) => c,
        Err(_) => return vec![],
    };

    let mut methods = Vec::new();
    for method in HTTP_METHODS {
        let pattern = format!("pub async fn {}(", method);
        if content.contains(&pattern) {
            methods.push(method.to_string());
        }
    }
    methods
}

fn collect_layouts_and_routes(
    dir: &Path,
    url_prefix: &str,
    mod_prefix: &str,
    accumulated_params: &[String], // Track params from parent directories
    layouts: &mut HashMap<String, String>,
    routes: &mut Vec<RouteInfo>,
) {
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };

    let mut entries: Vec<_> = entries.flatten().collect();
    entries.sort_by_key(|e| e.path());

    let dir_path = mod_prefix.replace('_', "/");

    for entry in entries {
        let path = entry.path();
        let file_name = path.file_name().unwrap().to_str().unwrap();

        if path.is_dir() {
            // Handle dynamic directory segments like [id]
            let (dir_mod_name, url_segment, new_param) =
                if file_name.starts_with('[') && file_name.ends_with(']') {
                    let param_name = &file_name[1..file_name.len() - 1];
                    (
                        format!("param_{}", param_name),
                        format!(":{}", param_name),
                        Some(param_name.to_string()),
                    )
                } else {
                    (file_name.to_string(), file_name.replace('_', "-"), None)
                };
            let new_url_prefix = format!("{}/{}", url_prefix, url_segment);
            let new_mod_prefix = if mod_prefix.is_empty() {
                dir_mod_name
            } else {
                format!("{}_{}", mod_prefix, dir_mod_name)
            };
            // Accumulate params from directory hierarchy
            let mut new_params = accumulated_params.to_vec();
            if let Some(p) = new_param {
                new_params.push(p);
            }
            collect_layouts_and_routes(
                &path,
                &new_url_prefix,
                &new_mod_prefix,
                &new_params,
                layouts,
                routes,
            );
        } else if file_name.ends_with(".rs") && file_name != "mod.rs" {
            let stem = path.file_stem().unwrap().to_str().unwrap();

            if stem == "layout" {
                let layout_mod_name = if mod_prefix.is_empty() {
                    "layout".to_string()
                } else {
                    format!("{}_layout", mod_prefix)
                };
                layouts.insert(dir_path.clone(), layout_mod_name);
                continue;
            }

            let (file_mod_name, route_segment, file_param) =
                if stem.starts_with('[') && stem.ends_with(']') {
                    let param_name = &stem[1..stem.len() - 1];
                    (
                        format!("param_{}", param_name),
                        format!(":{}", param_name),
                        Some(param_name.to_string()),
                    )
                } else {
                    let url_segment = stem.replace('_', "-");
                    (stem.to_string(), url_segment, None)
                };

            let url_path = if stem == "index" {
                if url_prefix.is_empty() {
                    "/".to_string()
                } else {
                    url_prefix.to_string()
                }
            } else {
                format!("{}/{}", url_prefix, route_segment)
            };

            let full_mod_name = if mod_prefix.is_empty() {
                file_mod_name
            } else {
                format!("{}_{}", mod_prefix, file_mod_name)
            };

            let methods = detect_methods(&path);

            // Combine accumulated directory params with file-level param
            let mut all_params = accumulated_params.to_vec();
            if let Some(p) = file_param {
                all_params.push(p);
            }

            routes.push(RouteInfo {
                url_path,
                mod_name: full_mod_name,
                dir_path: dir_path.clone(),
                params: all_params,
                methods,
            });
        }
    }
}

fn has_layouts(route: &RouteInfo, layouts: &HashMap<String, String>) -> bool {
    get_layout_chain(route, layouts).is_some()
}

fn get_layout_chain(route: &RouteInfo, layouts: &HashMap<String, String>) -> Option<Vec<String>> {
    let mut chain = Vec::new();

    if let Some(layout_mod) = layouts.get("") {
        chain.push(layout_mod.clone());
    }

    if !route.dir_path.is_empty() {
        let parts: Vec<&str> = route.dir_path.split('/').collect();
        let mut current_path = String::new();

        for part in parts {
            if !current_path.is_empty() {
                current_path.push('/');
            }
            current_path.push_str(part);

            if let Some(layout_mod) = layouts.get(&current_path) {
                chain.push(layout_mod.clone());
            }
        }
    }

    if chain.is_empty() { None } else { Some(chain) }
}

fn generate_wrapper_handler(
    route: &RouteInfo,
    method: &str,
    layouts: &HashMap<String, String>,
    stateless: bool,
) -> Option<String> {
    let chain = get_layout_chain(route, layouts)?;

    let mut output = String::new();

    // Function signature - Req must be last since it implements FromRequest (consumes body)
    if !route.params.is_empty() {
        // Build Path extractor for multiple params
        let params_tuple = if route.params.len() == 1 {
            route.params[0].clone()
        } else {
            format!("({})", route.params.join(", "))
        };
        let params_type = if route.params.len() == 1 {
            "String".to_string()
        } else {
            format!("({})", vec!["String"; route.params.len()].join(", "))
        };

        output.push_str(&format!(
            "async fn wrapper_{}_{}(\n    rejoice::State(state): rejoice::State<__RejoiceState>,\n    rejoice::Path({params_tuple}): rejoice::Path<{params_type}>,\n    req: rejoice::Req,\n) -> rejoice::Res {{\n",
            route.mod_name, method
        ));

        output.push_str("    let res = rejoice::Res::new();\n");
        let params_args = route.params.join(", ");
        if stateless {
            output.push_str(&format!(
                "    let _ = state;\n    let res = routes::{}::{}(req.clone(), res, {params_args}).await;\n",
                route.mod_name, method
            ));
        } else {
            output.push_str(&format!(
                "    let res = routes::{}::{}(state.clone(), req.clone(), res, {params_args}).await;\n",
                route.mod_name, method
            ));
        }
    } else {
        output.push_str(&format!(
            "async fn wrapper_{}_{}(\n    rejoice::State(state): rejoice::State<__RejoiceState>,\n    req: rejoice::Req,\n) -> rejoice::Res {{\n",
            route.mod_name, method
        ));

        output.push_str("    let res = rejoice::Res::new();\n");
        if stateless {
            output.push_str(&format!(
                "    let _ = state;\n    let res = routes::{}::{}(req.clone(), res).await;\n",
                route.mod_name, method
            ));
        } else {
            output.push_str(&format!(
                "    let res = routes::{}::{}(state.clone(), req.clone(), res).await;\n",
                route.mod_name, method
            ));
        }
    }

    // Layout wrapping (only for HTML responses)
    output.push_str("    if !res.is_html() { return res; }\n");
    output.push_str("    let html_content = res.take_html().unwrap();\n");
    output.push_str("    let children: rejoice::Children = rejoice::PreEscaped(html_content);\n");

    for (i, layout_mod) in chain.iter().rev().enumerate() {
        let children_var = if i == 0 {
            "children".to_string()
        } else {
            format!("children_{}", i)
        };
        let next_children_var = format!("children_{}", i + 1);

        if stateless {
            output.push_str(&format!(
                "    let layout_res = routes::{}::layout(req.clone(), rejoice::Res::new(), {}).await;\n",
                layout_mod, children_var
            ));
        } else {
            output.push_str(&format!(
                "    let layout_res = routes::{}::layout(state.clone(), req.clone(), rejoice::Res::new(), {}).await;\n",
                layout_mod, children_var
            ));
        }

        output.push_str("    if !layout_res.is_html() { return layout_res; }\n");

        if i < chain.len() - 1 {
            output.push_str(&format!(
                "    let {}: rejoice::Children = rejoice::PreEscaped(layout_res.take_html().unwrap());\n",
                next_children_var
            ));
        } else {
            output.push_str("    layout_res\n");
        }
    }

    output.push('}');
    Some(output)
}

fn generate_routes_mod(base_dir: &Path, dir: &Path, mod_prefix: &str, output: &mut String) {
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };

    let mut entries: Vec<_> = entries.flatten().collect();
    entries.sort_by_key(|e| e.path());

    for entry in entries {
        let path = entry.path();
        let file_name = path.file_name().unwrap().to_str().unwrap();

        if path.is_dir() {
            // Handle dynamic directory segments like [id]
            let dir_mod_name = if file_name.starts_with('[') && file_name.ends_with(']') {
                let param_name = &file_name[1..file_name.len() - 1];
                format!("param_{}", param_name)
            } else {
                file_name.to_string()
            };
            let new_prefix = if mod_prefix.is_empty() {
                dir_mod_name
            } else {
                format!("{}_{}", mod_prefix, dir_mod_name)
            };
            generate_routes_mod(base_dir, &path, &new_prefix, output);
        } else if file_name.ends_with(".rs") && file_name != "mod.rs" {
            let stem = path.file_stem().unwrap().to_str().unwrap();

            let file_mod_name = if stem.starts_with('[') && stem.ends_with(']') {
                let param = &stem[1..stem.len() - 1];
                format!("param_{}", param)
            } else {
                stem.to_string()
            };

            let full_mod_name = if mod_prefix.is_empty() {
                file_mod_name
            } else {
                format!("{}_{}", mod_prefix, file_mod_name)
            };

            let rel_path = path.strip_prefix(base_dir).unwrap();
            // Use forward slashes for #[path] attribute (works on all platforms)
            let rel_path_str = rel_path
                .components()
                .map(|c| c.as_os_str().to_string_lossy())
                .collect::<Vec<_>>()
                .join("/");
            output.push_str(&format!("#[path = \"routes/{}\"]\n", rel_path_str));
            output.push_str(&format!("pub mod {};\n", full_mod_name));
        }
    }
}