rustango 0.40.0

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! Named URL reversal — Django's `reverse()` + `get_absolute_url()`.
//! Issue #8.
//!
//! Routes can be registered with a stable name at module-load time
//! via the [`register_url!`] macro, then resolved back to a URL string
//! through [`reverse`]. The shape mirrors Django's URL conf:
//!
//! ```ignore
//! use rustango::register_url;
//! use rustango::urls::reverse;
//! use std::collections::HashMap;
//!
//! // At module scope — registers globally via `inventory`.
//! register_url!("post-detail", "/posts/{id}");
//! register_url!("home", "/");
//!
//! // Anywhere at runtime.
//! let url = reverse("home", &HashMap::new()).unwrap();
//! assert_eq!(url, "/");
//!
//! let mut p = HashMap::new();
//! p.insert("id", "42".to_owned());
//! let url = reverse("post-detail", &p).unwrap();
//! assert_eq!(url, "/posts/42");
//! ```
//!
//! Path-template placeholders use axum 0.8's `{name}` shape. Param
//! values are percent-encoded on substitution so caller-supplied
//! values are safe even when they contain `/` / `?` / `#`. Missing
//! or extra params return a [`ReverseError`] at call time — there's
//! no compile-time check today (would require either codegen or a
//! shared sentinel; queued as a future enhancement).
//!
//! **Manual sync with axum routes**: `register_url!` only registers
//! the *pattern string* with the reverse-lookup table — it does NOT
//! mount a route on any axum `Router`. Callers must keep their
//! axum routing in sync with their `register_url!` calls. A common
//! shape is to put both side-by-side in `src/urls.rs`:
//!
//! ```ignore
//! register_url!("post-detail", "/posts/{id}");
//! pub fn router() -> axum::Router {
//!     axum::Router::new().route("/posts/{id}", get(post_detail_view))
//! }
//! ```
//!
//! **Duplicate names**: two `register_url!("name", ...)` calls in the
//! same binary collide silently — `reverse` picks the first match it
//! finds in the inventory. Call [`duplicates`] at boot to surface any
//! name registered more than once. Future work: a startup validator
//! that turns this into a clean error before the server binds.
//!
//! Namespaced reverse (Django's `reverse("app:detail")` /
//! `include("app.urls", namespace=...)`) is **out of scope for v1**.
//! Use unique per-app name prefixes (`"posts:detail"` / `"users:detail"`)
//! as a manual convention until namespace support lands.

use std::collections::{HashMap, HashSet};

/// A named route — pattern + stable name. Registered at static-init
/// time via [`register_url!`] (which calls `inventory::submit!`
/// under the hood) and looked up by [`reverse`] at runtime.
#[derive(Debug, Clone)]
pub struct NamedRoute {
    /// Stable name used by [`reverse`] / Django's `{% url %}`.
    pub name: &'static str,
    /// axum 0.8 path template — placeholders use `{name}` syntax.
    pub pattern: &'static str,
}

inventory::collect!(NamedRoute);

/// Register a named URL pattern at module-load time. Picks up
/// `rustango::inventory` so callers don't need their own dep.
///
/// ```ignore
/// register_url!("post-detail", "/posts/{id}");
/// ```
#[macro_export]
macro_rules! register_url {
    ($name:expr, $pattern:expr) => {
        $crate::inventory::submit! {
            $crate::urls::NamedRoute {
                name: $name,
                pattern: $pattern,
            }
        }
    };
}

/// Failure modes for [`reverse`].
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ReverseError {
    /// No `register_url!("name", ...)` has run for this name. Either
    /// the registration is in a module that wasn't loaded, or the
    /// name is a typo.
    #[error("no URL registered for name `{0}`")]
    UnknownName(String),

    /// The pattern has a `{param}` placeholder but `params` didn't
    /// include a value for it.
    #[error("URL `{name}` requires placeholder `{{{param}}}` — pass it in `params`")]
    MissingParam { name: String, param: String },

    /// `params` had keys that don't appear in the pattern. Surfaced
    /// to catch typos that would otherwise silently disappear.
    #[error("URL `{name}` doesn't have a `{{{param}}}` placeholder")]
    UnexpectedParam { name: String, param: String },

    /// The registered pattern is malformed — most commonly an
    /// unclosed `{` placeholder. Programmer bug at `register_url!`
    /// time; surfaces from `reverse` so it's at least catchable.
    #[error("URL `{name}` has a malformed pattern: {detail}")]
    MalformedPattern { name: String, detail: String },
}

/// Snapshot of the route registry — every entry registered via
/// [`register_url!`] across every loaded module. Useful for boot-time
/// diagnostics (see [`duplicates`]) or admin endpoints that surface
/// the URL map.
#[must_use]
pub fn all_routes() -> Vec<&'static NamedRoute> {
    inventory::iter::<NamedRoute>.into_iter().collect()
}

/// List every name that's been registered more than once. Empty
/// vec on a clean registry. Call at app boot — duplicates surface
/// as silent "first wins" otherwise.
///
/// ```ignore
/// let dups = rustango::urls::duplicates();
/// if !dups.is_empty() {
///     panic!("duplicate URL registrations: {dups:?}");
/// }
/// ```
#[must_use]
pub fn duplicates() -> Vec<&'static str> {
    let mut seen: std::collections::HashMap<&'static str, usize> = std::collections::HashMap::new();
    for r in inventory::iter::<NamedRoute> {
        *seen.entry(r.name).or_insert(0) += 1;
    }
    let mut out: Vec<&'static str> = seen
        .into_iter()
        .filter_map(|(name, count)| (count > 1).then_some(name))
        .collect();
    out.sort_unstable();
    out
}

/// Resolve a registered name + parameters into a concrete URL string.
///
/// Substitutes every `{name}` placeholder in the pattern with the
/// corresponding entry in `params`, percent-encoding the value so the
/// resulting URL is safe to use as a `Location` header or template
/// link. Extra `params` keys that don't appear in the pattern surface
/// as [`ReverseError::UnexpectedParam`] — strict by default so typos
/// don't disappear.
///
/// # Errors
/// - [`ReverseError::UnknownName`] if no route matches `name`.
/// - [`ReverseError::MissingParam`] if a placeholder has no value.
/// - [`ReverseError::UnexpectedParam`] if `params` has an extra key.
pub fn reverse(name: &str, params: &HashMap<&str, String>) -> Result<String, ReverseError> {
    let route = inventory::iter::<NamedRoute>
        .into_iter()
        .find(|r| r.name == name)
        .ok_or_else(|| ReverseError::UnknownName(name.to_owned()))?;
    substitute(name, route.pattern, params)
}

/// Same as [`reverse`] but with `String` keys — convenience for the
/// JSON / template-tag path where keys come from dynamic input.
///
/// # Errors
/// As [`reverse`].
pub fn reverse_owned(name: &str, params: &HashMap<String, String>) -> Result<String, ReverseError> {
    let route = inventory::iter::<NamedRoute>
        .into_iter()
        .find(|r| r.name == name)
        .ok_or_else(|| ReverseError::UnknownName(name.to_owned()))?;
    let borrowed: HashMap<&str, String> = params
        .iter()
        .map(|(k, v)| (k.as_str(), v.clone()))
        .collect();
    substitute(name, route.pattern, &borrowed)
}

fn substitute(
    name: &str,
    pattern: &str,
    params: &HashMap<&str, String>,
) -> Result<String, ReverseError> {
    let mut out = String::with_capacity(pattern.len() + 16);
    let mut used: HashSet<String> = HashSet::new();
    let mut chars = pattern.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '{' {
            out.push(c);
            continue;
        }
        // Read until the matching '}'. An unclosed placeholder is a
        // programmer bug in the registered pattern — surface it
        // cleanly via `MalformedPattern`.
        let mut placeholder = String::new();
        let mut closed = false;
        for nc in chars.by_ref() {
            if nc == '}' {
                closed = true;
                break;
            }
            placeholder.push(nc);
        }
        if !closed {
            return Err(ReverseError::MalformedPattern {
                name: name.to_owned(),
                detail: format!("unclosed placeholder starting at `{{{placeholder}`"),
            });
        }
        // Strip axum-style / Django-style type annotations like
        // `{id:int}` — accept both `name` and `type:name` shapes so
        // patterns ported from Django routes work as-is.
        let key = placeholder.split(':').next_back().unwrap_or(&placeholder);
        let value = params.get(key).ok_or_else(|| ReverseError::MissingParam {
            name: name.to_owned(),
            param: key.to_owned(),
        })?;
        out.push_str(&crate::url_codec::url_encode(value));
        used.insert(key.to_owned());
    }
    // Reject extra params (typo-safety).
    for k in params.keys() {
        if !used.contains(*k) {
            return Err(ReverseError::UnexpectedParam {
                name: name.to_owned(),
                param: (*k).to_owned(),
            });
        }
    }
    Ok(out)
}

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

    // Registered at module-init time via the macro. Names are
    // prefixed `__test_` to keep collision risk low if other test
    // files in the binary ever register routes too.
    register_url!("__test_home", "/");
    register_url!("__test_post_detail", "/posts/{id}");
    register_url!("__test_two_args", "/users/{user_id}/posts/{post_id}");
    register_url!("__test_typed_placeholder", "/items/{int:id}");

    fn params(pairs: &[(&'static str, &str)]) -> HashMap<&'static str, String> {
        pairs.iter().map(|(k, v)| (*k, (*v).to_owned())).collect()
    }

    #[test]
    fn reverse_resolves_static_pattern() {
        assert_eq!(reverse("__test_home", &HashMap::new()).unwrap(), "/");
    }

    #[test]
    fn reverse_substitutes_single_placeholder() {
        let p = params(&[("id", "42")]);
        assert_eq!(reverse("__test_post_detail", &p).unwrap(), "/posts/42");
    }

    #[test]
    fn reverse_substitutes_multiple_placeholders() {
        let p = params(&[("user_id", "5"), ("post_id", "10")]);
        assert_eq!(reverse("__test_two_args", &p).unwrap(), "/users/5/posts/10");
    }

    #[test]
    fn reverse_percent_encodes_param_values() {
        // `/` in a value must NOT escape the path segment.
        let p = params(&[("id", "hello world")]);
        let url = reverse("__test_post_detail", &p).unwrap();
        assert_eq!(url, "/posts/hello%20world");
    }

    #[test]
    fn reverse_unknown_name_errors() {
        let err = reverse("nope_doesnt_exist", &HashMap::new()).unwrap_err();
        assert!(matches!(err, ReverseError::UnknownName(ref n) if n == "nope_doesnt_exist"));
    }

    #[test]
    fn reverse_missing_param_errors_with_param_name() {
        let err = reverse("__test_post_detail", &HashMap::new()).unwrap_err();
        match err {
            ReverseError::MissingParam { name, param } => {
                assert_eq!(name, "__test_post_detail");
                assert_eq!(param, "id");
            }
            other => panic!("expected MissingParam, got: {other:?}"),
        }
    }

    #[test]
    fn reverse_unexpected_param_errors() {
        let p = params(&[("id", "1"), ("typo_extra", "x")]);
        let err = reverse("__test_post_detail", &p).unwrap_err();
        assert!(
            matches!(err, ReverseError::UnexpectedParam { ref param, .. } if param == "typo_extra"),
            "got: {err:?}"
        );
    }

    #[test]
    fn reverse_accepts_axum_style_typed_placeholder() {
        // Pattern `/items/{int:id}` — `id` is the parameter name.
        let p = params(&[("id", "7")]);
        assert_eq!(reverse("__test_typed_placeholder", &p).unwrap(), "/items/7");
    }

    #[test]
    fn reverse_owned_takes_string_keyed_params() {
        let mut p: HashMap<String, String> = HashMap::new();
        p.insert("id".into(), "99".into());
        assert_eq!(
            reverse_owned("__test_post_detail", &p).unwrap(),
            "/posts/99"
        );
    }

    // Pattern intentionally malformed — unclosed `{`.
    register_url!("__test_malformed", "/items/{unclosed");

    #[test]
    fn reverse_malformed_pattern_surfaces_dedicated_error() {
        let err = reverse("__test_malformed", &HashMap::new()).unwrap_err();
        match err {
            ReverseError::MalformedPattern { name, detail } => {
                assert_eq!(name, "__test_malformed");
                assert!(detail.contains("unclosed"), "detail: {detail}");
            }
            other => panic!("expected MalformedPattern, got: {other:?}"),
        }
    }

    #[test]
    fn all_routes_returns_at_least_registered_test_routes() {
        let names: Vec<&str> = all_routes().iter().map(|r| r.name).collect();
        for required in [
            "__test_home",
            "__test_post_detail",
            "__test_two_args",
            "__test_typed_placeholder",
            "__test_malformed",
        ] {
            assert!(names.contains(&required), "missing {required}: {names:?}");
        }
    }

    #[test]
    fn duplicates_helper_is_callable() {
        // The test registry has no intentional duplicates among
        // `__test_*` names. Other test files in the same binary may
        // or may not register routes; just confirm the function
        // doesn't panic and returns a Vec of names (sorted).
        let dups = duplicates();
        // Sort property: every two adjacent entries are ordered.
        for w in dups.windows(2) {
            assert!(w[0] <= w[1], "duplicates() must return sorted: {dups:?}");
        }
    }
}

// ============================================================== Tera tag

/// Register Django's `{% url %}` equivalent as a Tera function on
/// `tera`. Call this once at app setup alongside any other Tera
/// configuration. Issue #14.
///
/// Tera doesn't have Django-style `{% tag %}` syntax for arbitrary
/// function calls — it has function-call expressions `{{ func(...) }}`
/// — so the natural mapping is a `url(...)` function with keyword
/// arguments:
///
/// ```jinja
/// <a href="{{ url(name='post-detail', id=42) }}">View post</a>
/// ```
///
/// Equivalent to Django's `{% url 'post-detail' id=42 %}`. For the
/// `{% url 'foo' as my_url %}` capture pattern, use Tera's `{% set %}`:
///
/// ```jinja
/// {% set my_url = url(name='post-detail', id=42) %}
/// <a href="{{ my_url }}">…</a>
/// ```
///
/// Argument parsing:
/// - `name` (required): the registered route name, as a string.
/// - Every other keyword argument: a path parameter, stringified and
///   passed through [`reverse_owned`]. Numbers / bools are accepted
///   and rendered with their `Display` form.
///
/// Errors from [`reverse`] propagate as Tera render errors (rendered
/// as a 500 by [`crate::shortcuts::render`] / [`crate::template_views`]).
#[cfg(feature = "template_views")]
pub fn register_url_tag(tera: &mut tera::Tera) {
    tera.register_function("url", url_tag_fn);
}

#[cfg(feature = "template_views")]
fn url_tag_fn(args: &std::collections::HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
    let name = match args.get("name") {
        Some(tera::Value::String(s)) => s.clone(),
        Some(other) => {
            return Err(tera::Error::msg(format!(
                "url(): `name` must be a string, got: {other:?}"
            )));
        }
        None => return Err(tera::Error::msg("url(): missing required `name` argument")),
    };
    // Every non-`name` arg becomes a path parameter. Coerce numbers /
    // bools / strings via their JSON Display form; reject objects + arrays
    // (path params can't reasonably be composite).
    let mut params: HashMap<String, String> = HashMap::new();
    for (k, v) in args {
        if k == "name" {
            continue;
        }
        let s = match v {
            tera::Value::String(s) => s.clone(),
            tera::Value::Number(n) => n.to_string(),
            tera::Value::Bool(b) => b.to_string(),
            tera::Value::Null => {
                // A null param is almost always a template typo
                // (`{{ url(name='post', id=missing_var) }}` where
                // `missing_var` is undefined). Silently emitting
                // `/posts/` would mask the bug; error explicitly
                // so the developer sees it.
                return Err(tera::Error::msg(format!(
                    "url(): argument `{k}` is null — likely an undefined template variable"
                )));
            }
            other => {
                return Err(tera::Error::msg(format!(
                    "url(): argument `{k}` must be a scalar (string / number / bool), got: {other:?}"
                )));
            }
        };
        params.insert(k.clone(), s);
    }
    reverse_owned(&name, &params)
        .map(tera::Value::String)
        .map_err(|e| tera::Error::msg(e.to_string()))
}

#[cfg(all(test, feature = "template_views"))]
mod tera_tests {
    use super::*;

    register_url!("__test_tag_home", "/");
    register_url!("__test_tag_post", "/posts/{id}");
    register_url!("__test_tag_users_posts", "/users/{user_id}/posts/{post_id}");

    fn setup() -> tera::Tera {
        let mut tera = tera::Tera::default();
        register_url_tag(&mut tera);
        tera
    }

    fn render(tera: &tera::Tera, src: &str) -> String {
        let mut t = tera.clone();
        t.add_raw_template("_", src).unwrap();
        t.render("_", &tera::Context::new()).unwrap()
    }

    #[test]
    fn url_tag_resolves_static_route() {
        let tera = setup();
        assert_eq!(render(&tera, "{{ url(name='__test_tag_home') }}"), "/");
    }

    #[test]
    fn url_tag_substitutes_int_param_via_display() {
        // Tera passes `42` as a number; `url()` stringifies via Display.
        let tera = setup();
        assert_eq!(
            render(&tera, "{{ url(name='__test_tag_post', id=42) }}"),
            "/posts/42"
        );
    }

    #[test]
    fn url_tag_substitutes_string_param() {
        let tera = setup();
        assert_eq!(
            render(&tera, "{{ url(name='__test_tag_post', id='hello') }}"),
            "/posts/hello"
        );
    }

    #[test]
    fn url_tag_substitutes_multiple_params() {
        let tera = setup();
        assert_eq!(
            render(
                &tera,
                "{{ url(name='__test_tag_users_posts', user_id=5, post_id=10) }}"
            ),
            "/users/5/posts/10"
        );
    }

    #[test]
    fn url_tag_set_capture_works_via_tera_set() {
        // Django's `{% url 'foo' as bar %}` shape, ported to Tera's
        // `{% set %}`.
        let tera = setup();
        let src = "{% set u = url(name='__test_tag_post', id=7) %}<a href='{{ u }}'>x</a>";
        assert_eq!(render(&tera, src), "<a href='/posts/7'>x</a>");
    }

    /// Walk a Tera error's `source` chain into one searchable string.
    /// Tera wraps function errors so `format!("{e}")` on the outer
    /// only says "Failed to render '_'" — the actual cause is on
    /// `e.source()`.
    fn full_error_chain(e: &tera::Error) -> String {
        use std::error::Error as _;
        let mut out = format!("{e}");
        let mut cur: Option<&dyn std::error::Error> = e.source();
        while let Some(c) = cur {
            out.push_str(" | ");
            out.push_str(&c.to_string());
            cur = c.source();
        }
        out
    }

    #[test]
    fn url_tag_missing_name_arg_errors() {
        let mut tera = setup();
        tera.add_raw_template("_", "{{ url(id=1) }}").unwrap();
        let err = tera.render("_", &tera::Context::new()).unwrap_err();
        let msg = full_error_chain(&err).to_lowercase();
        assert!(
            msg.contains("name") || msg.contains("url()"),
            "expected error about missing `name`, got: {msg}"
        );
    }

    #[test]
    fn url_tag_unknown_route_propagates_reverse_error() {
        let mut tera = setup();
        tera.add_raw_template("_", "{{ url(name='nope_nope_nope') }}")
            .unwrap();
        let err = tera.render("_", &tera::Context::new()).unwrap_err();
        let msg = full_error_chain(&err).to_lowercase();
        assert!(
            msg.contains("no url registered") || msg.contains("nope_nope_nope"),
            "expected unknown-name error, got: {msg}"
        );
    }

    #[test]
    fn url_tag_non_string_name_errors_clearly() {
        let mut tera = setup();
        tera.add_raw_template("_", "{{ url(name=42) }}").unwrap();
        let err = tera.render("_", &tera::Context::new()).unwrap_err();
        let msg = full_error_chain(&err).to_lowercase();
        assert!(
            msg.contains("name") && msg.contains("string"),
            "expected `name must be a string` error, got: {msg}"
        );
    }

    #[test]
    fn url_tag_null_param_errors_instead_of_emitting_empty_segment() {
        // Regression: a context value set to JSON null hits the
        // function as `Value::Null`. Earlier draft coerced that to ""
        // and emitted `/posts/` — a silent URL bug. Now it errors
        // explicitly so the typo / data hole surfaces.
        let mut tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("v", &serde_json::Value::Null);
        tera.add_raw_template("_", "{{ url(name='__test_tag_post', id=v) }}")
            .unwrap();
        let err = tera.render("_", &ctx).unwrap_err();
        let msg = full_error_chain(&err).to_lowercase();
        assert!(
            msg.contains("null") || msg.contains("undefined"),
            "expected null/undefined error, got: {msg}"
        );
    }
}

// ============================================================== querystring filter

/// Register the Django 5.1 `{% querystring %}` equivalent as a Tera
/// filter. Issue #19. Takes the current querystring as input and
/// returns a new one with the given overrides applied.
///
/// Foundational for paginator / filter-preserving links where you
/// want "the same URL but with `page=3` instead of `page=2`":
///
/// ```jinja
/// <!-- request.query_string = "q=hello&page=1&sort=asc" -->
/// <a href="?{{ request.query_string | querystring(page=2) | safe }}">page 2</a>
/// <!--                                       ↑ → "?q=hello&page=2&sort=asc" -->
/// ```
///
/// Behavior matches Django's [`{% querystring %}`](https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#querystring):
///
/// - Each override either **replaces** the existing key or **appends**
///   a new one. Single value per key.
/// - **`null` value removes the key entirely.** Lets templates drop a
///   query param: `{{ qs | querystring(filter=null) }}`.
/// - Empty result emits an empty string (no leading `?`) so
///   `<a href="{{ '' | querystring() }}">` doesn't dangle a `?`.
/// - Keys and values are percent-encoded on output via
///   [`crate::url_codec::url_encode`].
///
/// Wire it once at app setup:
///
/// ```ignore
/// rustango::urls::register_querystring_filter(&mut tera);
/// ```
#[cfg(feature = "template_views")]
pub fn register_querystring_filter(tera: &mut tera::Tera) {
    tera.register_filter("querystring", querystring_filter);
}

#[cfg(feature = "template_views")]
fn querystring_filter(
    value: &tera::Value,
    args: &HashMap<String, tera::Value>,
) -> tera::Result<tera::Value> {
    let current = value.as_str().unwrap_or("");
    let mut pairs = parse_query_pairs(current);

    for (k, v) in args {
        if matches!(v, tera::Value::Null) {
            // Null = delete every occurrence of this key.
            pairs.retain(|(pk, _)| pk != k);
            continue;
        }
        let s = match v {
            tera::Value::String(s) => s.clone(),
            tera::Value::Number(n) => n.to_string(),
            tera::Value::Bool(b) => b.to_string(),
            other => {
                return Err(tera::Error::msg(format!(
                    "querystring(): argument `{k}` must be a scalar (string / number / bool / null), got: {other:?}"
                )));
            }
        };
        // Match Django's `QueryDict.__setitem__` semantics: if the key
        // already exists, replace IN PLACE (preserve position) +
        // collapse any duplicate occurrences down to one. New keys
        // append at the end.
        let mut found = false;
        let mut i = 0;
        while i < pairs.len() {
            if pairs[i].0 == *k {
                if found {
                    // Already kept the first slot for the override —
                    // drop subsequent duplicates of this key.
                    pairs.remove(i);
                    continue;
                }
                pairs[i].1 = s.clone();
                found = true;
            }
            i += 1;
        }
        if !found {
            pairs.push((k.clone(), s));
        }
    }

    if pairs.is_empty() {
        return Ok(tera::Value::String(String::new()));
    }
    let encoded: Vec<String> = pairs
        .iter()
        .map(|(k, v)| {
            format!(
                "{}={}",
                crate::url_codec::url_encode(k),
                crate::url_codec::url_encode(v)
            )
        })
        .collect();
    Ok(tera::Value::String(format!("?{}", encoded.join("&"))))
}

/// Parse a querystring (with or without the leading `?`) into a
/// list of `(key, value)` pairs preserving original order. Malformed
/// pairs (no `=`, multiple `=`) are passed through with empty / first-
/// `=`-split values — same loose interpretation as browsers.
#[cfg(feature = "template_views")]
fn parse_query_pairs(s: &str) -> Vec<(String, String)> {
    let s = s.trim_start_matches('?');
    if s.is_empty() {
        return Vec::new();
    }
    s.split('&')
        .filter(|chunk| !chunk.is_empty())
        .map(|chunk| match chunk.split_once('=') {
            Some((k, v)) => (
                crate::url_codec::url_decode(k),
                crate::url_codec::url_decode(v),
            ),
            None => (crate::url_codec::url_decode(chunk), String::new()),
        })
        .collect()
}

#[cfg(all(test, feature = "template_views"))]
mod querystring_tests {
    use super::*;

    fn setup() -> tera::Tera {
        let mut tera = tera::Tera::default();
        register_querystring_filter(&mut tera);
        tera
    }

    fn render(tera: &tera::Tera, src: &str, ctx: tera::Context) -> String {
        let mut t = tera.clone();
        t.add_raw_template("_", src).unwrap();
        t.render("_", &ctx).unwrap()
    }

    #[test]
    fn empty_input_with_overrides_emits_new_qs() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "");
        assert_eq!(
            render(&tera, "{{ q | querystring(page=2) | safe }}", ctx),
            "?page=2"
        );
    }

    #[test]
    fn empty_input_with_no_overrides_emits_empty_string() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "");
        assert_eq!(render(&tera, "{{ q | querystring() | safe }}", ctx), "");
    }

    #[test]
    fn override_replaces_existing_key() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "page=1");
        assert_eq!(
            render(&tera, "{{ q | querystring(page=2) | safe }}", ctx),
            "?page=2"
        );
    }

    #[test]
    fn override_preserves_other_keys_and_position() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "q=hello&page=1&sort=asc");
        let out = render(&tera, "{{ q | querystring(page=2) | safe }}", ctx);
        // Django parity: `page` keeps its position (between `q` and
        // `sort`) — the value updates in place rather than moving to
        // the end. Matches `QueryDict.__setitem__` semantics.
        assert_eq!(out, "?q=hello&page=2&sort=asc");
    }

    #[test]
    fn override_collapses_duplicate_existing_keys() {
        // Multi-value input — Django's QueryDict replaces the entire
        // value list with `[new]` so duplicates collapse to one.
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "tag=a&tag=b&tag=c");
        assert_eq!(
            render(&tera, "{{ q | querystring(tag='x') | safe }}", ctx),
            "?tag=x"
        );
    }

    #[test]
    fn override_appends_new_key() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "q=hello");
        assert_eq!(
            render(&tera, "{{ q | querystring(filter='active') | safe }}", ctx),
            "?q=hello&filter=active"
        );
    }

    #[test]
    fn null_override_removes_key() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "q=hello&filter=active");
        ctx.insert("v", &serde_json::Value::Null);
        assert_eq!(
            render(&tera, "{{ q | querystring(filter=v) | safe }}", ctx),
            "?q=hello"
        );
    }

    #[test]
    fn percent_encodes_special_chars_in_output() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "");
        let out = render(
            &tera,
            "{{ q | querystring(name='hello world', special='a/b?c') | safe }}",
            ctx,
        );
        // `' '` → `%20`, `/` → `%2F`, `?` → `%3F`.
        assert!(out.contains("hello%20world"), "got: {out}");
        assert!(out.contains("a%2Fb%3Fc"), "got: {out}");
    }

    #[test]
    fn input_with_leading_question_mark_is_stripped() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "?q=hello&page=1");
        assert_eq!(
            render(&tera, "{{ q | querystring(page=2) | safe }}", ctx),
            "?q=hello&page=2"
        );
    }

    #[test]
    fn bool_and_number_args_stringify_via_display() {
        let tera = setup();
        let mut ctx = tera::Context::new();
        ctx.insert("q", "");
        let out = render(
            &tera,
            "{{ q | querystring(page=2, active=true) | safe }}",
            ctx,
        );
        assert!(out.contains("page=2"), "got: {out}");
        assert!(out.contains("active=true"), "got: {out}");
    }

    #[test]
    fn parse_pairs_handles_trailing_ampersand_and_empty_chunks() {
        // Defensive — browsers sometimes emit `?q=x&` with a trailing
        // separator. Filter out empty chunks.
        let pairs = parse_query_pairs("?q=hello&&page=1&");
        assert_eq!(
            pairs,
            vec![
                ("q".to_owned(), "hello".to_owned()),
                ("page".to_owned(), "1".to_owned()),
            ]
        );
    }

    #[test]
    fn parse_pairs_percent_decodes_keys_and_values() {
        let pairs = parse_query_pairs("q=hello%20world&page=1");
        assert_eq!(pairs[0].1, "hello world");
    }
}