boatramp-types 0.2.2

Shared, wasm-clean wire types + routing/config logic for boatramp (used by the server, CLI, and the edge Worker so the wire format and routing can't drift)
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
//! Request routing: turn a request path + [`DeployConfig`] + the manifest's file
//! set into an [`Outcome`]. Pure and synchronous so it is easy to unit-test; the
//! server turns the outcome into an HTTP response (conditional/range/headers).
//!
//! Order (Vercel-style, files win over rewrites):
//! 1. trailing-slash normalization → redirect
//! 2. explicit redirects (first match)
//! 3. resolve the request path to a file (clean-URLs + directory index)
//! 4. rewrites as a fallback for unmatched paths (proxy if absolute, else
//!    serve the rewritten internal path — this is how SPA fallback works)
//! 5. not found (with optional custom error document)

use std::collections::BTreeMap;

use crate::config::{DeployConfig, TrailingSlash};
use crate::file::FileEntry;
use crate::matcher::Pattern;
use crate::predicate::{EvalEnv, RequestContext};

/// What to do with a request, before HTTP concerns (conditional/range/headers).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// Redirect to `location` with `status`.
    Redirect {
        /// `Location` header value.
        location: String,
        /// 3xx status.
        status: u16,
    },
    /// Serve a resolved file (status 200).
    File {
        /// Resolved manifest key (for MIME overrides by extension).
        path: String,
        /// The manifest entry to stream.
        entry: FileEntry,
    },
    /// Reverse-proxy to an absolute URL.
    Proxy {
        /// Upstream URL.
        url: String,
    },
    /// Not found; `error` is the resolved custom error document, if configured.
    NotFound {
        /// Custom 404 document (resolved key + entry) to serve with status 404.
        error: Option<(String, FileEntry)>,
    },
}

/// An [`Outcome`] plus the response `Vary` header names any conditional rule the
/// resolver evaluated depends on (so a per-language / per-cookie redirect is not
/// cached across visitors). `vary` is empty for a purely path-based resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolveResult {
    /// What to do with the request.
    pub outcome: Outcome,
    /// Deduplicated `Vary` header names (lower-cased) — see the type doc.
    pub vary: Vec<String>,
}

/// Resolve a request path to an [`Outcome`], ignoring conditional (`when`) rules
/// that need request context — a convenience for path-only callers/tests. Prefer
/// [`resolve_ctx`] on the request path so `when` predicates evaluate.
pub fn resolve(
    config: &DeployConfig,
    files: &BTreeMap<String, FileEntry>,
    request_path: &str,
) -> Outcome {
    resolve_ctx(config, files, request_path, &RequestContext::default()).outcome
}

/// Resolve a request to an [`Outcome`], evaluating each redirect/rewrite's
/// optional `when` predicate against `ctx`. A rule applies only when its path
/// pattern matches **and** its condition (if any) is true; the returned `vary`
/// carries the request dimensions those conditions read.
pub fn resolve_ctx(
    config: &DeployConfig,
    files: &BTreeMap<String, FileEntry>,
    request_path: &str,
    ctx: &RequestContext,
) -> ResolveResult {
    let path = if request_path.starts_with('/') {
        request_path.to_string()
    } else {
        format!("/{request_path}")
    };
    // Collapse `.`/`..`/`//` segments before any routing/lookup so a request
    // can't reach a manifest key via a non-canonical path, and `..` can never
    // climb above the deploy root (path hardening / audit).
    let path = normalize_dot_segments(&path);

    let mut vary: Vec<String> = Vec::new();
    // `file_exists(p)` mirrors real serving (clean-URLs + directory index), so a
    // predicate asks "would this path serve a file in *this* deploy?".
    let file_exists = |p: &str| resolve_file(config, files, p).is_some();

    let finish = |outcome: Outcome, mut vary: Vec<String>| {
        vary.sort();
        vary.dedup();
        ResolveResult { outcome, vary }
    };

    if let Some(location) = normalize_trailing_slash(config, &path) {
        return finish(
            Outcome::Redirect {
                location,
                status: 308,
            },
            vary,
        );
    }

    for redirect in &config.redirects {
        let Some(m) = Pattern::compile_with(&redirect.from, config.case_insensitive)
            .ok()
            .and_then(|p| p.match_path(&path))
        else {
            continue;
        };
        if !eval_when(&redirect.when, ctx, &path, &file_exists, &mut vary) {
            continue; // path matched but the condition is false — keep looking
        }
        let to = interpolate_to(&redirect.to, ctx, &path, &file_exists, &mut vary);
        return finish(
            Outcome::Redirect {
                location: m.expand(&to),
                status: redirect.status,
            },
            vary,
        );
    }

    if let Some((path, entry)) = resolve_file(config, files, &path) {
        return finish(Outcome::File { path, entry }, vary);
    }

    for rewrite in &config.rewrites {
        let Some(m) = Pattern::compile_with(&rewrite.from, config.case_insensitive)
            .ok()
            .and_then(|p| p.match_path(&path))
        else {
            continue;
        };
        if !eval_when(&rewrite.when, ctx, &path, &file_exists, &mut vary) {
            continue;
        }
        let to = interpolate_to(&rewrite.to, ctx, &path, &file_exists, &mut vary);
        let target = m.expand(&to);
        if is_absolute_url(&target) {
            return finish(Outcome::Proxy { url: target }, vary);
        }
        if let Some((path, entry)) = resolve_file(config, files, &target) {
            return finish(Outcome::File { path, entry }, vary);
        }
    }

    let error = config.error_documents.get(&404).and_then(|doc| {
        let key = doc.trim_start_matches('/').to_string();
        files.get(&key).map(|entry| (key, entry.clone()))
    });
    finish(Outcome::NotFound { error }, vary)
}

/// Evaluate a rule's optional `when` predicate against the request. Returns
/// whether the rule fires (a rule with no `when` always does), accumulating the
/// predicate's `Vary` dimensions into `vary` when the path already matched — the
/// outcome depended on them regardless of the result. A predicate that fails to
/// compile (impossible after `validate` accepted the deploy) fails closed: the
/// rule is skipped.
fn eval_when(
    when: &Option<String>,
    ctx: &RequestContext,
    path: &str,
    file_exists: &dyn Fn(&str) -> bool,
    vary: &mut Vec<String>,
) -> bool {
    let Some(src) = when else { return true };
    match crate::predicate::compile_cached(src) {
        Ok(pred) => {
            vary.extend(pred.vary_headers().iter().cloned());
            pred.eval(&EvalEnv {
                ctx,
                path,
                file_exists,
            })
        }
        Err(_) => false,
    }
}

/// Interpolate a destination's `${…}` request expressions against `ctx`, before
/// the router applies `:name`/`:splat` capture expansion. A destination with no
/// `${…}` is returned unchanged (the common, allocation-free case). Accumulates
/// the interpolated expressions' `Vary` dimensions. A template that fails to
/// compile (impossible after `validate`) is used verbatim.
fn interpolate_to(
    to: &str,
    ctx: &RequestContext,
    path: &str,
    file_exists: &dyn Fn(&str) -> bool,
    vary: &mut Vec<String>,
) -> String {
    if !crate::predicate::Template::is_template(to) {
        return to.to_string();
    }
    match crate::predicate::compile_template_cached(to) {
        Ok(t) => {
            vary.extend(t.vary_headers().iter().cloned());
            t.expand(&EvalEnv {
                ctx,
                path,
                file_exists,
            })
        }
        Err(_) => to.to_string(),
    }
}

/// Find the WebAssembly handler whose route and methods match this request, if
/// any (declaration order wins). Handlers sit **after redirects but before
/// rewrites/static** in the pipeline: the server consults
/// this only when [`resolve`] did not produce a redirect, and dispatches the
/// match in preference to any file/rewrite outcome.
///
/// An empty `methods` list matches every method; otherwise the request
/// `method` must appear in it (case-insensitive).
pub fn match_handler<'a>(
    handlers: &'a [crate::config::HandlerConfig],
    method: &str,
    request_path: &str,
) -> Option<&'a crate::config::HandlerConfig> {
    let path = if request_path.starts_with('/') {
        std::borrow::Cow::Borrowed(request_path)
    } else {
        std::borrow::Cow::Owned(format!("/{request_path}"))
    };
    handlers.iter().find(|handler| {
        let method_ok = handler.methods.is_empty()
            || handler
                .methods
                .iter()
                .any(|m| m.eq_ignore_ascii_case(method));
        method_ok
            && Pattern::compile(&handler.route)
                .map(|pattern| pattern.is_match(&path))
                .unwrap_or(false)
    })
}

/// Resolve a path to a file, applying clean-URLs and the directory index.
fn resolve_file(
    config: &DeployConfig,
    files: &BTreeMap<String, FileEntry>,
    path: &str,
) -> Option<(String, FileEntry)> {
    let key = path.trim_start_matches('/');
    let ci = config.case_insensitive;

    if let Some(hit) = lookup(files, key, ci) {
        return Some(hit);
    }

    if config.clean_urls && !key.is_empty() && !last_segment(key).contains('.') {
        let html = format!("{key}.html");
        if let Some(hit) = lookup(files, &html, ci) {
            return Some(hit);
        }
    }

    let base = key.trim_end_matches('/');
    for index in &config.index {
        let candidate = if base.is_empty() {
            index.clone()
        } else {
            format!("{base}/{index}")
        };
        if let Some(hit) = lookup(files, &candidate, ci) {
            return Some(hit);
        }
    }

    None
}

/// Look up a manifest key — exact, or (when `case_insensitive`) the first key
/// that matches ignoring ASCII case. The stored key's original case is returned
/// (the served path preserves the deploy's casing).
fn lookup(
    files: &BTreeMap<String, FileEntry>,
    key: &str,
    case_insensitive: bool,
) -> Option<(String, FileEntry)> {
    if let Some(entry) = files.get(key) {
        return Some((key.to_string(), entry.clone()));
    }
    if case_insensitive {
        if let Some((k, entry)) = files.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)) {
            return Some((k.clone(), entry.clone()));
        }
    }
    None
}

/// Compute a redirect target enforcing the trailing-slash policy, or `None`.
fn normalize_trailing_slash(config: &DeployConfig, path: &str) -> Option<String> {
    match config.trailing_slash {
        TrailingSlash::Preserve => None,
        TrailingSlash::Always => {
            if path != "/" && !path.ends_with('/') && !last_segment(path).contains('.') {
                Some(format!("{path}/"))
            } else {
                None
            }
        }
        TrailingSlash::Never => {
            if path != "/" && path.ends_with('/') {
                Some(path.trim_end_matches('/').to_string())
            } else {
                None
            }
        }
    }
}

/// Collapse `.` and `..` segments (and empty segments from `//`) in an
/// absolute path, RFC 3986-style. `..` never climbs above the root, so the
/// result is always a clean absolute path rooted at `/` — it cannot reference
/// anything outside the deploy. A trailing `/` (or trailing `.`/`..`) is
/// preserved as a trailing slash so the directory-index / trailing-slash policy
/// still applies.
fn normalize_dot_segments(path: &str) -> String {
    let trailing = path.ends_with('/')
        || path.ends_with("/.")
        || path.ends_with("/..")
        || path == "."
        || path == "..";
    let mut out: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "" | "." => {} // skip empty (`//`) and current-dir segments
            ".." => {
                out.pop(); // climb one level; popping past root is a no-op
            }
            other => out.push(other),
        }
    }
    let mut normalized = format!("/{}", out.join("/"));
    if trailing && !normalized.ends_with('/') {
        normalized.push('/');
    }
    normalized
}

fn last_segment(path: &str) -> &str {
    path.trim_end_matches('/').rsplit('/').next().unwrap_or("")
}

fn is_absolute_url(target: &str) -> bool {
    target.starts_with("http://") || target.starts_with("https://")
}

/// A smart default `Cache-Control` for a served file, applied only
/// when the deploy config sets no blanket `cache.default` — explicit config and
/// header rules always win. Two heuristics:
///
/// * **fingerprinted assets** — a content-hashed filename (`app.4f3a2b2c.js`,
///   `index-a1b2c3d4.css`) never changes under that name, so it is safe to cache
///   forever: `public, max-age=31536000, immutable`.
/// * **HTML** — the entry documents that reference those assets must be
///   re-fetched to pick up a new deploy: `public, max-age=0, must-revalidate`.
///
/// Anything else returns `None` (no default imposed).
pub fn cache_control_default(
    served_path: &str,
    content_type: Option<&str>,
) -> Option<&'static str> {
    if is_fingerprinted(served_path) {
        Some("public, max-age=31536000, immutable")
    } else if is_html(served_path, content_type) {
        Some("public, max-age=0, must-revalidate")
    } else {
        None
    }
}

/// Whether a served filename carries a content-hash fingerprint, e.g.
/// `app.4f3a2b2c.js` or `index-a1b2c3d4.css`. Conservative: the token before the
/// extension must be ≥ 8 chars of `[0-9a-zA-Z_-]` and contain **both** a letter
/// and a digit — so plain words (`application.js`) and bare dates
/// (`report-20240115.pdf`) aren't mistaken for hashes and cached for a year.
fn is_fingerprinted(path: &str) -> bool {
    let name = last_segment(path);
    let Some((stem, ext)) = name.rsplit_once('.') else {
        return false;
    };
    if stem.is_empty() || ext.is_empty() {
        return false;
    }
    // The fingerprint is the last `.`/`-`-delimited token of the stem.
    let token = stem.rsplit(['.', '-']).next().unwrap_or("");
    token.len() >= 8
        && token.bytes().any(|b| b.is_ascii_alphabetic())
        && token.bytes().any(|b| b.is_ascii_digit())
        && token
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// Whether the response is HTML, by content type (preferred) or `.htm(l)` name.
fn is_html(path: &str, content_type: Option<&str>) -> bool {
    if let Some(ct) = content_type {
        if ct.split(';').next().map(str::trim) == Some("text/html") {
            return true;
        }
    }
    let name = last_segment(path);
    name.ends_with(".html") || name.ends_with(".htm")
}

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

    #[test]
    fn dot_segments_are_collapsed_and_cannot_escape_root() {
        assert_eq!(normalize_dot_segments("/a/./b"), "/a/b");
        assert_eq!(normalize_dot_segments("/a//b"), "/a/b");
        assert_eq!(normalize_dot_segments("/a/../b"), "/b");
        // `..` past the root is a no-op — no escaping the deploy.
        assert_eq!(normalize_dot_segments("/../../etc/passwd"), "/etc/passwd");
        assert_eq!(normalize_dot_segments("/a/../../b"), "/b");
        // Trailing-slash intent is preserved (for the directory-index policy).
        assert_eq!(normalize_dot_segments("/a/b/"), "/a/b/");
        assert_eq!(normalize_dot_segments("/a/.."), "/");
        assert_eq!(normalize_dot_segments("/"), "/");
    }

    #[test]
    fn resolve_serves_through_dot_segments() {
        let cfg = DeployConfig::default();
        let f = files(&["dir/page.html"]);
        // `/dir/sub/../page.html` collapses to `/dir/page.html` and serves it.
        match resolve(&cfg, &f, "/dir/sub/../page.html") {
            Outcome::File { path, .. } => assert_eq!(path, "dir/page.html"),
            other => panic!("expected file, got {other:?}"),
        }
    }

    #[test]
    fn cache_default_immutable_for_fingerprinted_assets() {
        let immutable = Some("public, max-age=31536000, immutable");
        // Common bundler fingerprint shapes.
        assert_eq!(
            cache_control_default("assets/app.4f3a2b2c.js", None),
            immutable
        );
        assert_eq!(cache_control_default("index-a1b2c3d4.css", None), immutable);
        assert_eq!(
            cache_control_default("main.abcdef12.woff2", None),
            immutable
        );
        assert_eq!(
            cache_control_default("vendor.3f8a9c2e1b7d.js", None),
            immutable
        );
    }

    #[test]
    fn cache_default_skips_non_fingerprinted() {
        // No digit (a word), too short, and a bare date — none are hashes.
        assert_eq!(cache_control_default("application.js", None), None);
        assert_eq!(cache_control_default("app.js", None), None);
        assert_eq!(cache_control_default("report-20240115.pdf", None), None);
        assert_eq!(cache_control_default("style.min.css", None), None);
    }

    #[test]
    fn cache_default_revalidate_for_html() {
        let revalidate = Some("public, max-age=0, must-revalidate");
        assert_eq!(cache_control_default("index.html", None), revalidate);
        assert_eq!(cache_control_default("about.htm", None), revalidate);
        // By content type even when the path has no extension (clean URL).
        assert_eq!(
            cache_control_default("/blog/post", Some("text/html; charset=utf-8")),
            revalidate
        );
    }

    fn entry() -> FileEntry {
        FileEntry {
            hash: "h".into(),
            size: 1,
            content_type: None,
            variants: Default::default(),
        }
    }

    fn files(paths: &[&str]) -> BTreeMap<String, FileEntry> {
        paths.iter().map(|p| (p.to_string(), entry())).collect()
    }

    #[test]
    fn serves_exact_and_index() {
        let files = files(&["index.html", "blog/index.html", "app.js"]);
        let cfg = DeployConfig::default();
        assert!(matches!(
            resolve(&cfg, &files, "/index.html"),
            Outcome::File { .. }
        ));
        assert!(
            matches!(resolve(&cfg, &files, "/"), Outcome::File { path, .. } if path == "index.html")
        );
        assert!(
            matches!(resolve(&cfg, &files, "/blog"), Outcome::File { path, .. } if path == "blog/index.html")
        );
        assert!(matches!(
            resolve(&cfg, &files, "/app.js"),
            Outcome::File { .. }
        ));
    }

    #[test]
    fn clean_urls() {
        let files = files(&["about.html"]);
        let off = DeployConfig::default();
        assert!(matches!(
            resolve(&off, &files, "/about"),
            Outcome::NotFound { .. }
        ));
        let on = DeployConfig {
            clean_urls: true,
            ..Default::default()
        };
        assert!(
            matches!(resolve(&on, &files, "/about"), Outcome::File { path, .. } if path == "about.html")
        );
    }

    #[test]
    fn redirect_with_placeholder() {
        let mut cfg = DeployConfig::default();
        cfg.redirects.push(crate::config::Redirect {
            from: "/old/:slug".into(),
            to: "/new/:slug".into(),
            status: 301,
            when: None,
        });
        assert_eq!(
            resolve(&cfg, &BTreeMap::new(), "/old/hi"),
            Outcome::Redirect {
                location: "/new/hi".into(),
                status: 301
            }
        );
    }

    #[test]
    fn conditional_redirect_honors_when_and_reports_vary() {
        let mut cfg = DeployConfig::default();
        // Send the root to the French tree only when the visitor prefers French.
        cfg.redirects.push(crate::config::Redirect {
            from: "/".into(),
            to: "/fr/".into(),
            status: 302,
            when: Some("prefers_language(['fr','en']) == 'fr'".into()),
        });
        let files = files(&["index.html"]);

        // French visitor → redirected; the outcome varies on Accept-Language.
        let fr = RequestContext {
            accept_languages: vec!["fr".into()],
            ..Default::default()
        };
        let r = resolve_ctx(&cfg, &files, "/", &fr);
        assert_eq!(
            r.outcome,
            Outcome::Redirect {
                location: "/fr/".into(),
                status: 302
            }
        );
        assert_eq!(r.vary, vec!["accept-language".to_string()]);

        // English visitor → NOT redirected (falls through to index.html), but the
        // response still varies on Accept-Language (a French visitor differs).
        let en = RequestContext {
            accept_languages: vec!["en".into()],
            ..Default::default()
        };
        let r = resolve_ctx(&cfg, &files, "/", &en);
        assert!(matches!(r.outcome, Outcome::File { path, .. } if path == "index.html"));
        assert_eq!(r.vary, vec!["accept-language".to_string()]);
    }

    #[test]
    fn conditional_redirect_on_missing_file() {
        let mut cfg = DeployConfig::default();
        // No French translation of this path → send to the English one.
        cfg.redirects.push(crate::config::Redirect {
            from: "/fr/only.html".into(),
            to: "/en/only.html".into(),
            status: 302,
            when: Some("!file_exists(path)".into()),
        });
        let ctx = RequestContext::default();

        // Missing localized file → the redirect fires.
        let missing = files(&["en/only.html"]);
        assert_eq!(
            resolve_ctx(&cfg, &missing, "/fr/only.html", &ctx).outcome,
            Outcome::Redirect {
                location: "/en/only.html".into(),
                status: 302
            }
        );
        // Present localized file → served, no redirect. A file check varies on
        // nothing (it reads only the URL + deploy content).
        let present = files(&["fr/only.html", "en/only.html"]);
        let r = resolve_ctx(&cfg, &present, "/fr/only.html", &ctx);
        assert!(matches!(r.outcome, Outcome::File { path, .. } if path == "fr/only.html"));
        assert!(r.vary.is_empty());
    }

    #[test]
    fn conditional_redirect_to_negotiated_locale_in_one_rule() {
        let mut cfg = DeployConfig::default();
        // A single rule: root → the visitor's preferred locale, via `${…}`
        // interpolation, gated so it only fires for a supported locale.
        cfg.redirects.push(crate::config::Redirect {
            from: "/".into(),
            to: "/${prefers_language(['fr','en','de'])}/".into(),
            status: 302,
            when: Some("prefers_language(['fr','en','de']) != ''".into()),
        });
        let files = files(&["index.html"]);

        let de = RequestContext {
            accept_languages: vec!["de".into()],
            ..Default::default()
        };
        let r = resolve_ctx(&cfg, &files, "/", &de);
        assert_eq!(
            r.outcome,
            Outcome::Redirect {
                location: "/de/".into(),
                status: 302
            }
        );
        assert_eq!(r.vary, vec!["accept-language".to_string()]);

        // A visitor who accepts no supported locale → no redirect (when is false).
        let xx = RequestContext {
            accept_languages: vec!["xx".into()],
            ..Default::default()
        };
        let r = resolve_ctx(&cfg, &files, "/", &xx);
        assert!(matches!(r.outcome, Outcome::File { path, .. } if path == "index.html"));
    }

    #[test]
    fn spa_fallback_via_rewrite() {
        let files = files(&["index.html", "assets/app.js"]);
        let mut cfg = DeployConfig::default();
        cfg.rewrites.push(crate::config::Rewrite {
            from: "/**".into(),
            to: "/index.html".into(),
            status: 200,
            when: None,
        });
        // Real file still wins.
        assert!(
            matches!(resolve(&cfg, &files, "/assets/app.js"), Outcome::File { path, .. } if path == "assets/app.js")
        );
        // Unknown route falls back to index.html.
        assert!(
            matches!(resolve(&cfg, &files, "/deep/route"), Outcome::File { path, .. } if path == "index.html")
        );
    }

    #[test]
    fn case_insensitive_serves_static_redirects_and_misses_when_off() {
        let files = files(&["assets/App.js", "About.html"]);
        // Off (default): exact case only.
        let off = DeployConfig::default();
        assert!(matches!(
            resolve(&off, &files, "/assets/app.js"),
            Outcome::NotFound { .. }
        ));
        // On: case-folded static lookup serves the stored (original-case) key.
        let mut on = DeployConfig {
            case_insensitive: true,
            ..Default::default()
        };
        assert!(
            matches!(resolve(&on, &files, "/assets/app.js"), Outcome::File { path, .. } if path == "assets/App.js")
        );
        // …and redirect rules match case-insensitively.
        on.redirects.push(crate::config::Redirect {
            from: "/Old/:slug".into(),
            to: "/new/:slug".into(),
            status: 301,
            when: None,
        });
        assert_eq!(
            resolve(&on, &files, "/old/hi"),
            Outcome::Redirect {
                location: "/new/hi".into(),
                status: 301
            }
        );
    }

    #[test]
    fn proxy_rewrite() {
        let mut cfg = DeployConfig::default();
        cfg.rewrites.push(crate::config::Rewrite {
            from: "/api/**".into(),
            to: "https://backend/:splat".into(),
            status: 200,
            when: None,
        });
        assert_eq!(
            resolve(&cfg, &BTreeMap::new(), "/api/users/1"),
            Outcome::Proxy {
                url: "https://backend/users/1".into()
            }
        );
    }

    #[test]
    fn custom_404() {
        let files = files(&["404.html"]);
        let mut cfg = DeployConfig::default();
        cfg.error_documents.insert(404, "/404.html".into());
        assert!(matches!(
            resolve(&cfg, &files, "/missing"),
            Outcome::NotFound { error: Some(_) }
        ));
    }

    #[test]
    fn trailing_slash_never_redirects() {
        let cfg = DeployConfig {
            trailing_slash: TrailingSlash::Never,
            ..Default::default()
        };
        assert_eq!(
            resolve(&cfg, &BTreeMap::new(), "/blog/"),
            Outcome::Redirect {
                location: "/blog".into(),
                status: 308
            }
        );
    }

    #[test]
    fn handler_matching_respects_route_and_methods() {
        use crate::config::HandlerConfig;
        let handler = |route: &str, methods: &[&str]| HandlerConfig {
            route: route.into(),
            methods: methods
                .iter()
                .map(std::string::ToString::to_string)
                .collect(),
            component: "h.wasm".into(),
            imports: Vec::new(),
            limits: None,
            env: BTreeMap::new(),
            invoke_targets: Vec::new(),
        };
        let handlers = vec![
            handler("/api/orders/*", &["GET", "POST"]),
            handler("/hooks/*", &[]),
        ];

        // Route + method match.
        assert_eq!(
            match_handler(&handlers, "post", "/api/orders/42").map(|h| h.route.as_str()),
            Some("/api/orders/*")
        );
        // Method not in the list -> no match.
        assert!(match_handler(&handlers, "DELETE", "/api/orders/42").is_none());
        // Empty methods matches any method.
        assert!(match_handler(&handlers, "PUT", "/hooks/x").is_some());
        // No route matches.
        assert!(match_handler(&handlers, "GET", "/static/page").is_none());
    }
}