larastvel-core 0.2.2

Larastvel framework core - inspired by Laravel
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! # Blade Directive Compiler
//!
//! A pre-processor that converts Laravel-style `@directive(...)` syntax into
//! Tera-equivalent syntax before the template engine renders the file.
//!
//! ## Supported Directives
//!
//! | Blade | Tera |
//! |---|---|
//! | `@auth` / `@endauth` | `{% if auth_check %}` / `{% endif %}` |
//! | `@guest` / `@endguest` | `{% if not auth_check %}` / `{% endif %}` |
//! | `@if(expr)` / `@elseif(expr)` / `@else` / `@endif` | `{% if expr %}` / `{% elif expr %}` / `{% else %}` / `{% endif %}` |
//! | `@unless(expr)` / `@endunless` | `{% if not (expr) %}` / `{% endif %}` |
//! | `@isset(var)` / `@endisset` | `{% if var is defined %}` / `{% endif %}` |
//! | `@empty(var)` / `@endempty` | `{% if var is empty %}` / `{% endif %}` |
//! | `@foreach($items as $item)` / `@endforeach` | `{% for item in items %}` / `{% endfor %}` |
//! | `@include('name')` | `{% include "name" %}` |
//! | `@error('field')` / `@enderror` | `{% if errors["field"] %}` / `{% endif %}` |
//! | `@csrf` | `<input type="hidden" ...>` |
//! | `@method('VERB')` | `<input type="hidden" ...>` |
//! | `<x-card>` / `<x-slot:name>` | component + slot syntax (see [`super::components`]) |
//!
//! Variable `$` prefixes and `->` accessors are converted automatically:
//! `$user.name` → `user.name`, `$user->name` → `user.name`.
//!
//! ## Context Variables
//!
//! Templates rendered with Blade directives expect these context variables:
//!
//! * `auth_check` — `bool` indicating whether the user is authenticated
//! * `csrf_token` — `&str` containing the current CSRF token
//! * `errors` — `serde_json::Value` or `std::collections::HashMap` of field to error message(s)

use once_cell::sync::Lazy;
use regex::Regex;

/// Convert a Blade expression to a Tera expression.
///
/// Strips `$` prefixes and converts `->` to `.`:
/// - `$user` → `user`
/// - `$user->name` → `user.name`
/// - `!$user` → `not user`
fn blade_expr_to_tera(expr: &str) -> String {
    let s = expr.trim().replace("$", "").replace("->", ".");
    if s.starts_with('!') && !s[1..].trim().starts_with('=') {
        format!("not {}", s[1..].trim())
    } else {
        s
    }
}

/// Parse a `@foreach(...)` argument into a Tera `{% for ... %}` tag.
///
/// Supports:
/// - `@foreach($items as $item)` → `{% for item in items %}`
/// - `@foreach($items as $key => $value)` → `{% for key, value in items %}`
fn foreach_to_tera(args: &str) -> String {
    let args = args.trim();
    if let Some(pos) = args.find(" as ") {
        let collection = blade_expr_to_tera(&args[..pos]);
        let rest = args[pos + 4..].trim();
        if let Some(arrow) = rest.find("=>") {
            let key = blade_expr_to_tera(&rest[..arrow]);
            let value = blade_expr_to_tera(&rest[arrow + 2..]);
            format!("{{% for {key}, {value} in {collection} %}}")
        } else {
            let value = blade_expr_to_tera(rest);
            format!("{{% for {value} in {collection} %}}")
        }
    } else {
        // fallback – emit something parsable
        format!("{{% for _item in {} %}}", blade_expr_to_tera(args))
    }
}

/// Compile Blade-style `@directive` syntax into Tera-equivalent syntax.
///
/// This is a simple regex-based pre-processor. It does **not** parse
/// nested structures — it applies replacements top-to-bottom. For the
/// common directive patterns this is sufficient.
///
/// ## Example
///
/// ```rust
/// use larastvel_core::view::blade::compile;
///
/// let result = compile("@csrf");
/// assert!(result.contains("csrf_token"));
/// ```
pub fn compile(input: &str) -> String {
    let mut output = input.to_string();

    // NOTE: order matters – more specific patterns before general ones.

    // --- elseif / if / endif (must come before @else) ---
    static ELSEIF: Lazy<Regex> = Lazy::new(|| Regex::new(r"@elseif\s*\(([^)]*)\)").unwrap());
    output = ELSEIF
        .replace_all(&output, |caps: &regex::Captures| {
            format!("{{% elif {} %}}", blade_expr_to_tera(&caps[1]))
        })
        .to_string();

    static IF_START: Lazy<Regex> = Lazy::new(|| Regex::new(r"@if\s*\(([^)]*)\)").unwrap());
    output = IF_START
        .replace_all(&output, |caps: &regex::Captures| {
            format!("{{% if {} %}}", blade_expr_to_tera(&caps[1]))
        })
        .to_string();

    static ENDIF: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endif\s*$").unwrap());
    output = ENDIF.replace_all(&output, "{% endif %}").to_string();

    // --- unless / endunless ---
    static UNLESS_START: Lazy<Regex> = Lazy::new(|| Regex::new(r"@unless\s*\(([^)]*)\)").unwrap());
    output = UNLESS_START
        .replace_all(&output, |caps: &regex::Captures| {
            format!("{{% if not ({}) %}}", blade_expr_to_tera(&caps[1]))
        })
        .to_string();

    static ENDUNLESS: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endunless\s*$").unwrap());
    output = ENDUNLESS.replace_all(&output, "{% endif %}").to_string();

    // --- isset / endisset ---
    static ISS_START: Lazy<Regex> = Lazy::new(|| Regex::new(r"@isset\s*\(([^)]*)\)").unwrap());
    output = ISS_START
        .replace_all(&output, |caps: &regex::Captures| {
            format!("{{% if {} is defined %}}", blade_expr_to_tera(&caps[1]))
        })
        .to_string();

    static ENDISS: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endisset\s*$").unwrap());
    output = ENDISS.replace_all(&output, "{% endif %}").to_string();

    // --- empty / endempty ---
    static EMPTY_START: Lazy<Regex> = Lazy::new(|| Regex::new(r"@empty\s*\(([^)]*)\)").unwrap());
    output = EMPTY_START
        .replace_all(&output, |caps: &regex::Captures| {
            format!("{{% if {} is empty %}}", blade_expr_to_tera(&caps[1]))
        })
        .to_string();

    static ENDEMPTY: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endempty\s*$").unwrap());
    output = ENDEMPTY.replace_all(&output, "{% endif %}").to_string();

    // --- foreach / endforeach ---
    static FOREACH: Lazy<Regex> = Lazy::new(|| Regex::new(r"@foreach\s*\((.+?)\)").unwrap());
    output = FOREACH
        .replace_all(&output, |caps: &regex::Captures| foreach_to_tera(&caps[1]))
        .to_string();

    static ENDFOREACH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endforeach\s*$").unwrap());
    output = ENDFOREACH.replace_all(&output, "{% endfor %}").to_string();

    // --- include ---
    static INCLUDE: Lazy<Regex> =
        Lazy::new(|| Regex::new(r#"@include\s*\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap());
    output = INCLUDE
        .replace_all(&output, |caps: &regex::Captures| {
            format!(r#"{{% include "{path}" %}}"#, path = &caps[1])
        })
        .to_string();

    // --- auth / endauth ---
    static AUTH_START: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@auth\s*$").unwrap());
    output = AUTH_START
        .replace_all(&output, "{% if auth_check %}")
        .to_string();

    static ENDAUTH: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endauth\s*$").unwrap());
    output = ENDAUTH.replace_all(&output, "{% endif %}").to_string();

    // --- guest / endguest ---
    static GUEST_START: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@guest\s*$").unwrap());
    output = GUEST_START
        .replace_all(&output, "{% if not auth_check %}")
        .to_string();

    static ENDGUEST: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@endguest\s*$").unwrap());
    output = ENDGUEST.replace_all(&output, "{% endif %}").to_string();

    // --- error / enderror ---
    static ERROR_START: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"@error\s*\(\s*'([^']+)'\s*\)").unwrap());
    output = ERROR_START
        .replace_all(&output, |caps: &regex::Captures| {
            let field = &caps[1];
            format!(r#"{{% if errors["{field}"] %}}"#)
        })
        .to_string();

    static ENDERROR: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@enderror\s*$").unwrap());
    output = ENDERROR.replace_all(&output, "{% endif %}").to_string();

    // --- else (generic, inside any if/auth/error block) ---
    static ELSE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\s*@else\s*$").unwrap());
    output = ELSE.replace_all(&output, "{% else %}").to_string();

    // --- csrf ---
    static CSRF: Lazy<Regex> = Lazy::new(|| Regex::new(r"@csrf\b").unwrap());
    output = CSRF
        .replace_all(
            &output,
            r#"<input type="hidden" name="_token" value="{{ csrf_token }}">"#,
        )
        .to_string();

    // --- method ---
    static METHOD: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"@method\s*\(\s*'([^']+)'\s*\)").unwrap());
    output = METHOD
        .replace_all(&output, |caps: &regex::Captures| {
            let method = &caps[1];
            format!(r#"<input type="hidden" name="_method" value="{}">"#, method)
        })
        .to_string();

    output
}

/// Compile a template string and inject the CSRF token value.
///
/// This is a convenience wrapper when you have the CSRF token at hand.
/// Replaces `{{ csrf_token }}` with the actual token value.
pub fn compile_with_csrf(input: &str, csrf_token: &str) -> String {
    let compiled = compile(input);
    compiled.replace("{{ csrf_token }}", csrf_token)
}

/// Convert Laravel's `<x-component>` syntax into `@component(...)` blocks
/// consumed by the component render pipeline (see [`super::components`]).
///
/// - `<x-card title="Hi">body</x-card>` →
///   `@component('components/card.html', {title: "Hi"})body@endcomponent`
/// - `<x-card/>` → a component call with an empty body
/// - `<x-slot:name>` blocks are left untouched (handled by slot extraction).
///
/// Like [`compile`], this is a linear pre-processor — nested components are
/// not supported.
pub fn compile_x_components(input: &str) -> String {
    let mut output = input.to_string();

    // Hold slot blocks aside so the generic x-component patterns below
    // (which would otherwise match `<x-slot:…>`) skip them, then restore.
    let mut held_slots: Vec<String> = Vec::new();
    static X_SLOT: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(?s)<x-slot:([a-zA-Z0-9_-]+)\s*>(.*?)</x-slot\s*>").unwrap());
    output = X_SLOT
        .replace_all(&output, |caps: &regex::Captures| {
            held_slots.push(caps[0].to_string());
            format!("__LARASTVEL_X_SLOT_{}__", held_slots.len() - 1)
        })
        .to_string();

    // Self-closing: <x-card title="Hi" />
    static X_SELF_CLOSING: Lazy<Regex> =
        Lazy::new(|| Regex::new(r"(?s)<x-([a-zA-Z0-9_.-]+)\s*([^>]*?)/>").unwrap());
    output = X_SELF_CLOSING
        .replace_all(&output, |caps: &regex::Captures| {
            component_block(&caps[1], &caps[2], "")
        })
        .to_string();

    // Paired: <x-card title="Hi">body</x-card>. The closing tag name is
    // accepted loosely (the regex crate has no backreferences) — the body
    // ends at the first `</x-` close, which matches the non-nested
    // limitation of this pre-processor.
    static X_PAIRED: Lazy<Regex> = Lazy::new(|| {
        Regex::new(r"(?s)<x-([a-zA-Z0-9_.-]+)\s*([^>]*)>(.*?)</x-[a-zA-Z0-9_.-]+\s*>").unwrap()
    });
    output = X_PAIRED
        .replace_all(&output, |caps: &regex::Captures| {
            component_block(&caps[1], &caps[2], &caps[3])
        })
        .to_string();

    for (i, slot) in held_slots.iter().enumerate() {
        output = output.replace(&format!("__LARASTVEL_X_SLOT_{}__", i), slot);
    }

    output
}

/// Build a `@component('components/<name>.html', {attrs})…@endcomponent`
/// block from an `<x-name attr="v">` tag.
fn component_block(name: &str, attrs_raw: &str, body: &str) -> String {
    static ATTR: Lazy<Regex> =
        Lazy::new(|| Regex::new(r#"([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)""#).unwrap());

    let attrs: Vec<String> = ATTR
        .captures_iter(attrs_raw)
        .map(|caps| format!("{}: {:?}", &caps[1], &caps[2]))
        .collect();

    let template = format!("components/{}.html", name);
    if attrs.is_empty() {
        format!("@component('{}'){}@endcomponent", template, body)
    } else {
        format!(
            "@component('{}', {{ {} }}){}@endcomponent",
            template,
            attrs.join(", "),
            body
        )
    }
}

// =============================================================================
// TESTS
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // --- @auth ---

    #[test]
    fn test_auth_directive() {
        let result = compile("@auth\n<p>Logged in</p>\n@endauth");
        assert!(result.contains("{% if auth_check %}"));
        assert!(result.contains("{% endif %}"));
        assert!(!result.contains("@auth"));
        assert!(!result.contains("@endauth"));
    }

    #[test]
    fn test_auth_with_else() {
        let result = compile("@auth\n<p>A</p>\n@else\n<p>B</p>\n@endauth");
        assert!(result.contains("{% if auth_check %}"));
        assert!(result.contains("{% else %}"));
        assert!(result.contains("{% endif %}"));
    }

    #[test]
    fn test_auth_indented() {
        let result = compile("  @auth\n    <p>Hi</p>\n  @endauth");
        assert!(result.contains("{% if auth_check %}"));
        assert!(result.contains("{% endif %}"));
    }

    // --- @guest ---

    #[test]
    fn test_guest_directive() {
        let result = compile("@guest\n<p>Guest</p>\n@endguest");
        assert!(result.contains("{% if not auth_check %}"));
        assert!(result.contains("{% endif %}"));
        assert!(!result.contains("@guest"));
    }

    // --- @error ---

    #[test]
    fn test_error_directive() {
        let result = compile("@error('email')\n<p>Invalid</p>\n@enderror");
        assert!(result.contains(r#"{% if errors["email"] %}"#));
        assert!(result.contains("{% endif %}"));
        assert!(!result.contains("@error"));
    }

    #[test]
    fn test_error_with_spaces() {
        let result = compile("@error( 'name' )\n<p>Error</p>\n@enderror");
        assert!(result.contains(r#"errors["name"]"#));
    }

    // --- @csrf ---

    #[test]
    fn test_csrf_directive() {
        let result = compile("<form>@csrf</form>");
        assert!(result.contains("csrf_token"));
        assert!(result.contains("_token"));
        assert!(result.contains("type=\"hidden\""));
    }

    #[test]
    fn test_csrf_multiple() {
        let result = compile("@csrf\n@csrf");
        assert_eq!(result.matches("csrf_token").count(), 2);
    }

    #[test]
    fn test_csrf_word_boundary() {
        // @csrf\b should not match inside @csrf_token; only match standalone @csrf
        let result = compile("@csrf_token should be preserved, but @csrf should be replaced");
        // @csrf_token should be preserved as-is (no replacement)
        assert!(result.contains("@csrf_token"));
        // The standalone @csrf should be replaced
        assert!(result.contains("<input"));
        // The replacement also emits the literal string csrf_token
        assert!(result.contains("csrf_token"));
    }

    // --- @method ---

    #[test]
    fn test_method_put() {
        let result = compile("@method('PUT')");
        assert!(result.contains("_method"));
        assert!(result.contains("PUT"));
        assert!(result.contains("type=\"hidden\""));
    }

    #[test]
    fn test_method_delete() {
        let result = compile("@method('DELETE')");
        assert!(result.contains("DELETE"));
    }

    // --- compile_with_csrf ---

    #[test]
    fn test_compile_with_csrf_replaces_token() {
        let result = compile_with_csrf("@csrf", "abc123");
        assert!(result.contains("abc123"));
        assert!(!result.contains("{{ csrf_token }}"));
    }

    // --- mixed directives ---

    #[test]
    fn test_mixed_directives() {
        let input = "\
@auth
    <form method=\"POST\">@csrf</form>
    @error('email')
        <p>{{ message }}</p>
    @enderror
@else
    @guest
        <p>Please log in</p>
    @endguest
@endauth
";
        let result = compile(input);
        assert!(result.contains("{% if auth_check %}"));
        assert!(result.contains("{% else %}"));
        assert!(result.contains("{% endif %}"));
        assert!(result.contains("csrf_token"));
        assert!(result.contains(r#"errors["email"]"#));
        assert!(result.contains("{% if not auth_check %}"));
    }

    // --- @if / @elseif / @endif ---

    #[test]
    fn test_if_basic() {
        let result = compile("@if($user)\n<p>Hi</p>\n@endif");
        assert!(result.contains("{% if user %}"));
        assert!(result.contains("{% endif %}"));
    }

    #[test]
    fn test_if_with_property() {
        let result = compile("@if($user.is_admin)\n<p>Admin</p>\n@endif");
        assert!(result.contains("{% if user.is_admin %}"));
    }

    #[test]
    fn test_if_with_arrow() {
        let result = compile("@if($user->is_admin)\n<p>Admin</p>\n@endif");
        assert!(result.contains("{% if user.is_admin %}"));
    }

    #[test]
    fn test_if_with_negation() {
        let result = compile("@if(!$user)\n<p>Guest</p>\n@endif");
        assert!(result.contains("{% if not user %}"));
    }

    #[test]
    fn test_if_elseif() {
        let result = compile("@if($role == 'admin')\n<p>A</p>\n@elseif($role == 'user')\n<p>U</p>\n@else\n<p>?</p>\n@endif");
        assert!(result.contains("{% if role == 'admin' %}"));
        assert!(result.contains("{% elif role == 'user' %}"));
        assert!(result.contains("{% else %}"));
        assert!(result.contains("{% endif %}"));
    }

    // --- @unless / @endunless ---

    #[test]
    fn test_unless() {
        let result = compile("@unless($user.is_banned)\n<p>Welcome</p>\n@endunless");
        assert!(result.contains("{% if not (user.is_banned) %}"));
        assert!(result.contains("{% endif %}"));
    }

    // --- @isset / @endisset ---

    #[test]
    fn test_isset() {
        let result = compile("@isset($name)\n<p>{{ name }}</p>\n@endisset");
        assert!(result.contains("{% if name is defined %}"));
        assert!(result.contains("{% endif %}"));
    }

    // --- @empty / @endempty ---

    #[test]
    fn test_empty() {
        let result = compile("@empty($items)\n<p>No items</p>\n@endempty");
        assert!(result.contains("{% if items is empty %}"));
        assert!(result.contains("{% endif %}"));
    }

    // --- @foreach / @endforeach ---

    #[test]
    fn test_foreach_basic() {
        let result = compile("@foreach($users as $user)\n<p>{{ user }}</p>\n@endforeach");
        assert!(result.contains("{% for user in users %}"));
        assert!(result.contains("{% endfor %}"));
    }

    #[test]
    fn test_foreach_key_value() {
        let result = compile(
            "@foreach($roles as $name => $role)\n<p>{{ name }}: {{ role }}</p>\n@endforeach",
        );
        assert!(result.contains("{% for name, role in roles %}"));
        assert!(result.contains("{% endfor %}"));
    }

    // --- @include ---

    #[test]
    fn test_include_single_quotes() {
        let result = compile("@include('partials.header')");
        assert_eq!(result.trim(), r#"{% include "partials.header" %}"#);
    }

    #[test]
    fn test_include_double_quotes() {
        let result = compile(r#"@include("partials.footer")"#);
        assert_eq!(result.trim(), r#"{% include "partials.footer" %}"#);
    }

    // --- no directives (passthrough) ---

    #[test]
    fn test_no_directives_passthrough() {
        let input = "<h1>Hello</h1>\n<p>{{ name }}</p>";
        let result = compile(input);
        assert_eq!(result, input);
    }
}