nextrs 0.3.2

A Next.js-style React routing framework for Rust built on Axum.
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
use axum::Router;
use axum::body::Body;
use axum::extract::Request;
use axum::response::{Html, IntoResponse, Response};
use axum::routing::get;
use bytes::Bytes;
use std::convert::Infallible;
use std::sync::Arc;

use crate::conventions::{
    LayoutFn, MiddlewareFn, MiddlewareResult, NotFoundEntry, RouteEntry, RouteRegistry,
};
use crate::prefetch::PrefetchConfig;

/// Internal sentinel that gets substituted into composed layouts so we can
/// split the result into the "before children" and "after children" halves.
/// Chosen to be unlikely in real content; the framework owns this string.
const NX_CONTENT_MARKER: &str = "<!--__nx_content__-->";

/// CSS id assigned to the slot div that initially holds the loading content.
const NX_SLOT_ID: &str = "__nx_slot__";

/// CSS id assigned to the `<template>` element holding the late page content.
const NX_PAGE_ID: &str = "__nx_page__";

/// Inline script that swaps the loading slot for the page template. Script
/// elements moved out of a `<template>` are inert in browsers, so the swapper
/// recreates them before insertion. That lets streamed React pages execute
/// their final page bundle after `props.rs` resolves.
const NX_SWAP_SCRIPT: &str = concat!(
    "<script>(function(){",
    "var s=document.getElementById('__nx_slot__');",
    "var t=document.getElementById('__nx_page__');",
    "if(!s||!t)return;",
    "var c=t.content.cloneNode(true);",
    "c.querySelectorAll('script').forEach(function(o){",
    "var n=document.createElement('script');",
    "for(var i=0;i<o.attributes.length;i++){var a=o.attributes[i];n.setAttribute(a.name,a.value);}",
    "n.text=o.text;",
    "o.replaceWith(n);",
    "});",
    "s.replaceWith(c);",
    "t.remove();",
    "})();</script>",
);

/// Collects all layouts from root down to the target path.
fn collect_layouts_for_path<'a>(entries: &'a [RouteEntry], target_path: &str) -> Vec<&'a LayoutFn> {
    let mut layouts = Vec::new();

    let mut sorted_entries: Vec<&RouteEntry> =
        entries.iter().filter(|e| e.layout.is_some()).collect();
    sorted_entries.sort_by_key(|e| route_depth(&e.path));

    for entry in sorted_entries {
        if entry_applies_to_path(&entry.path, target_path) {
            if let Some(ref layout) = entry.layout {
                layouts.push(layout);
            }
        }
    }

    layouts
}

/// Collects all middleware from root down to the target path.
fn collect_middlewares_for_path<'a>(
    entries: &'a [RouteEntry],
    target_path: &str,
) -> Vec<&'a MiddlewareFn> {
    let mut middlewares = Vec::new();

    let mut sorted_entries: Vec<&RouteEntry> =
        entries.iter().filter(|e| e.middleware.is_some()).collect();
    sorted_entries.sort_by_key(|e| route_depth(&e.path));

    for entry in sorted_entries {
        if entry_applies_to_path(&entry.path, target_path) {
            if let Some(ref middleware) = entry.middleware {
                middlewares.push(middleware);
            }
        }
    }

    middlewares
}

fn route_depth(path: &str) -> usize {
    if path == "/" {
        0
    } else {
        path.matches('/').count()
    }
}

fn entry_applies_to_path(entry_path: &str, target_path: &str) -> bool {
    entry_path == "/"
        || target_path == entry_path
        || target_path
            .strip_prefix(entry_path)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

/// Render the chain of layouts around a content marker and split the result
/// into (before_children, after_children) halves. When concatenated as
/// `before + content + after`, the result is identical to applying the layouts
/// directly around `content`.
fn layout_shell(layouts: &[&LayoutFn]) -> (String, String) {
    let mut shell = NX_CONTENT_MARKER.to_string();
    // Innermost layout wraps first; outer layouts wrap the result.
    for layout in layouts.iter().rev() {
        shell = layout(&shell);
    }
    let mut parts = shell.splitn(2, NX_CONTENT_MARKER);
    let before = parts.next().unwrap_or("").to_string();
    let after = parts.next().unwrap_or("").to_string();
    (before, after)
}

/// Build an Axum router from a [`RouteRegistry`], with a `public/` directory
/// served as a fallback for paths the router doesn't match.
///
/// If `public_dir` exists, requests that miss every route are served from it
/// via `tower-http::services::ServeDir`. If the directory doesn't exist this
/// is equivalent to [`build_router`] — useful for crates that may not have any
/// static assets yet.
///
/// On Vercel this fallback is irrelevant: the CDN matches static files
/// *before* the catch-all rewrite to the function. This helper exists so dev
/// (where the function-equivalent is `cargo run`) resolves the same URLs the
/// same way as production.
pub fn build_router_with_public(
    registry: RouteRegistry,
    public_dir: impl AsRef<std::path::Path>,
) -> Router {
    use axum::handler::HandlerWithoutStateExt;

    // Mirror `build_router`'s default: prefetch on. Build the route table on its
    // own so the not-found surfaces can be wired as the fallback below.
    let prefetch = Arc::new(PrefetchConfig::default());
    let entries = Arc::new(registry.entries);
    let not_found = Arc::new(registry.not_found);
    let router = build_route_table(Arc::clone(&entries), Arc::clone(&prefetch));
    let path = public_dir.as_ref();

    if path.is_dir() {
        // ServeDir is tried for unmatched paths; when it misses, fall through to
        // the not-found surfaces (if any) rather than ServeDir's bare 404.
        if not_found.is_empty() {
            router
                .fallback_service(tower_http::services::ServeDir::new(path))
                .layer(axum::middleware::map_response(declare_utf8_charset))
        } else {
            let nf_entries = Arc::clone(&entries);
            let nf_list = Arc::clone(&not_found);
            let nf_prefetch = Arc::clone(&prefetch);
            let nf_handler = move |req: Request| {
                let entries = Arc::clone(&nf_entries);
                let not_found = Arc::clone(&nf_list);
                let prefetch = Arc::clone(&nf_prefetch);
                async move { render_not_found(&entries, &not_found, &prefetch, req).await }
            };
            let serve = tower_http::services::ServeDir::new(path)
                .not_found_service(nf_handler.into_service());
            router
                .fallback_service(serve)
                .layer(axum::middleware::map_response(declare_utf8_charset))
        }
    } else {
        with_not_found_fallback(router, entries, not_found, prefetch)
    }
}

/// ServeDir guesses mime types without a charset (`text/plain`, not
/// `text/plain; charset=utf-8`), and browsers fall back to Latin-1 for bare
/// text types — garbling any non-ASCII byte. Everything this server produces
/// is UTF-8 (Rust strings, files we author), so say so.
async fn declare_utf8_charset(mut resp: Response) -> Response {
    let Some(ct) = resp.headers().get(http::header::CONTENT_TYPE) else {
        return resp;
    };
    let Ok(ct) = ct.to_str() else { return resp };
    if ct.starts_with("text/") && !ct.contains("charset") {
        let with_charset = format!("{}; charset=utf-8", ct);
        if let Ok(value) = http::HeaderValue::from_str(&with_charset) {
            resp.headers_mut().insert(http::header::CONTENT_TYPE, value);
        }
    }
    resp
}

/// Build an Axum router from a [`RouteRegistry`], with speculative-navigation
/// (prefetch) injection on by default. See [`build_router_with_prefetch`] to
/// customize or disable it.
pub fn build_router(registry: RouteRegistry) -> Router {
    build_router_with_prefetch(registry, PrefetchConfig::default())
}

/// Build an Axum router from a [`RouteRegistry`] with an explicit
/// [`PrefetchConfig`].
///
/// The framework injects a `<script type="speculationrules">` into the `<head>`
/// of every full-document page response so same-origin links are speculatively
/// fetched (or prerendered) by the browser — no client-side JS. Pass
/// [`PrefetchConfig::OFF`] to disable.
pub fn build_router_with_prefetch(registry: RouteRegistry, prefetch: PrefetchConfig) -> Router {
    let entries = Arc::new(registry.entries);
    let not_found = Arc::new(registry.not_found);
    let prefetch = Arc::new(prefetch);
    let router = build_route_table(Arc::clone(&entries), Arc::clone(&prefetch));
    with_not_found_fallback(router, entries, not_found, prefetch)
}

/// Build just the route table (matched routes, no fallback) from the registry's
/// entries, with the given prefetch config threaded into page rendering.
fn build_route_table(entries: Arc<Vec<RouteEntry>>, prefetch: Arc<PrefetchConfig>) -> Router {
    let mut router = Router::new();

    for i in 0..entries.len() {
        let entries_clone = Arc::clone(&entries);
        let path = entries[i].path.clone();

        let has_page = entries[i].page.is_some();
        let has_methods = !entries[i].methods.is_empty();

        if has_page {
            let entries_for_get = Arc::clone(&entries_clone);
            let prefetch_for_get = Arc::clone(&prefetch);
            let path_for_get = path.clone();
            let idx = i;

            router = router.route(
                &path,
                get(move |req: Request| {
                    let entries = Arc::clone(&entries_for_get);
                    let prefetch = Arc::clone(&prefetch_for_get);
                    let path = path_for_get.clone();
                    async move { render_route(entries, prefetch, idx, path, req).await }
                }),
            );
        }

        if has_methods {
            for (j, (method, _)) in entries[i].methods.iter().enumerate() {
                let entries_for_method = Arc::clone(&entries_clone);
                let method_clone = method.clone();
                let idx = i;

                let path_for_method = path.clone();

                let handler = move |req: Request| {
                    let entries = Arc::clone(&entries_for_method);
                    let path = path_for_method.clone();
                    async move { handle_method_route(entries, idx, j, path, req).await }
                };

                router = router.route(
                    &path,
                    axum::routing::on(method_to_filter(&method_clone), handler),
                );
            }
        }
    }

    router
}

/// Install the not-found surfaces as the router's fallback, if any exist.
/// With none registered, the router keeps Axum's default bare `404`.
fn with_not_found_fallback(
    router: Router,
    entries: Arc<Vec<RouteEntry>>,
    not_found: Arc<Vec<NotFoundEntry>>,
    prefetch: Arc<PrefetchConfig>,
) -> Router {
    if not_found.is_empty() {
        return router;
    }
    router.fallback(move |req: Request| {
        let entries = Arc::clone(&entries);
        let not_found = Arc::clone(&not_found);
        let prefetch = Arc::clone(&prefetch);
        async move { render_not_found(&entries, &not_found, &prefetch, req).await }
    })
}

/// Render the not-found surface for an unmatched request. Picks the entry whose
/// declaring path is the *deepest* ancestor of the requested path (so
/// `/admin/x` prefers an `/admin` not-found over the root one), wraps it in that
/// segment's layouts, and responds `404`. Falls back to a bare `404` when no
/// not-found surface covers the path.
///
/// Per-directory middleware does not run here — middleware is scoped to matched
/// routes, and an unmatched path matched none.
async fn render_not_found(
    entries: &[RouteEntry],
    not_found: &[NotFoundEntry],
    prefetch: &PrefetchConfig,
    req: Request,
) -> Response {
    let path = req.uri().path().to_string();
    let chosen = not_found
        .iter()
        .filter(|nf| entry_applies_to_path(&nf.path, &path))
        .max_by_key(|nf| route_depth(&nf.path));

    let Some(nf) = chosen else {
        return http::StatusCode::NOT_FOUND.into_response();
    };

    let layouts = collect_layouts_for_path(entries, &nf.path);
    let (before, after) = layout_shell(&layouts);
    // Same speculation-rules injection as a normal page response (no-op for
    // head-less fragments / when prefetch is off).
    let before = prefetch.inject_into_head(before);
    let body = (nf.render)(req).await;
    let full = format!("{}{}{}", before, body, after);

    (http::StatusCode::NOT_FOUND, Html(full)).into_response()
}

async fn render_route(
    entries: Arc<Vec<RouteEntry>>,
    prefetch: Arc<PrefetchConfig>,
    idx: usize,
    path: String,
    req: Request,
) -> Response {
    let req = match run_middlewares(&entries, &path, req).await {
        Ok(req) => req,
        Err(response) => return response,
    };

    let layouts = collect_layouts_for_path(&entries, &path);
    let (before, after) = layout_shell(&layouts);
    // Inject the speculation-rules <script> into <head>. A no-op for head-less
    // fragments and when prefetch is off, so both the streaming and
    // non-streaming branches below can use `before` directly.
    let before = prefetch.inject_into_head(before);

    let has_loading = entries[idx].loading.is_some();

    if has_loading {
        let loading_html = entries[idx].loading.as_ref().unwrap()();
        let slot_div = format!(r#"<div id="{}">{}</div>"#, NX_SLOT_ID, loading_html);

        let stream = async_stream::stream! {
            yield Ok::<Bytes, Infallible>(Bytes::from(before));
            yield Ok(Bytes::from(slot_div));

            let page_html = entries[idx].page.as_ref().unwrap()(req).await;
            let swap_chunk = format!(
                r#"<template id="{}">{}</template>{}"#,
                NX_PAGE_ID, page_html, NX_SWAP_SCRIPT,
            );
            yield Ok(Bytes::from(swap_chunk));

            yield Ok(Bytes::from(after));
        };

        Response::builder()
            .header("content-type", "text/html; charset=utf-8")
            .body(Body::from_stream(stream))
            .unwrap()
    } else {
        let page_html = entries[idx].page.as_ref().unwrap()(req).await;
        let full = format!("{}{}{}", before, page_html, after);
        Html(full).into_response()
    }
}

async fn handle_method_route(
    entries: Arc<Vec<RouteEntry>>,
    idx: usize,
    method_idx: usize,
    path: String,
    req: Request,
) -> Response {
    let req = match run_middlewares(&entries, &path, req).await {
        Ok(req) => req,
        Err(response) => return response,
    };

    let route_fn = &entries[idx].methods[method_idx].1;
    route_fn(req).await
}

async fn run_middlewares(
    entries: &[RouteEntry],
    path: &str,
    mut req: Request,
) -> Result<Request, Response> {
    for middleware in collect_middlewares_for_path(entries, path) {
        match middleware(req).await {
            MiddlewareResult::Continue(next_req) => req = next_req,
            MiddlewareResult::Response(response) => return Err(response),
        }
    }

    Ok(req)
}

fn method_to_filter(method: &http::Method) -> axum::routing::MethodFilter {
    match *method {
        http::Method::GET => axum::routing::MethodFilter::GET,
        http::Method::POST => axum::routing::MethodFilter::POST,
        http::Method::PUT => axum::routing::MethodFilter::PUT,
        http::Method::DELETE => axum::routing::MethodFilter::DELETE,
        http::Method::PATCH => axum::routing::MethodFilter::PATCH,
        http::Method::HEAD => axum::routing::MethodFilter::HEAD,
        http::Method::OPTIONS => axum::routing::MethodFilter::OPTIONS,
        _ => axum::routing::MethodFilter::GET,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::conventions::{
        RouteEntry, RouteRegistry, static_layout, static_loading, static_page,
    };
    use axum::body::Body;
    use http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};
    use tower::ServiceExt;

    async fn body_to_string(body: Body) -> String {
        let bytes = body.collect().await.unwrap().to_bytes();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    fn dyn_page(content: &'static str) -> crate::conventions::PageFn {
        Box::new(move |_req| Box::pin(async move { content.to_string() }))
    }

    fn slow_dyn_page(content: &'static str, ms: u64) -> crate::conventions::PageFn {
        Box::new(move |_req| {
            Box::pin(async move {
                tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
                content.to_string()
            })
        })
    }

    fn dyn_layout(class: &'static str) -> crate::conventions::LayoutFn {
        Box::new(move |children| format!("<div class=\"{}\">{}</div>", class, children))
    }

    // -- Round 2 / synchronous render -----------------------------------------

    #[tokio::test]
    async fn build_router_with_public_serves_static_files_on_route_miss() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("hello.txt"), "hi from public").unwrap();

        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("home")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router_with_public(registry, tmp.path());

        // Route hit still wins.
        let resp = app
            .clone()
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_to_string(resp.into_body()).await, "home");

        // Path with no matching route falls through to ServeDir.
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/hello.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_to_string(resp.into_body()).await, "hi from public");
    }

    #[tokio::test]
    async fn build_router_with_public_skips_serve_dir_when_path_missing() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("home")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router_with_public(registry, "/nonexistent/path/for/test");
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/missing.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_page_without_loading_returns_content() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("<h1>Home</h1>")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(body_to_string(resp.into_body()).await, "<h1>Home</h1>");
    }

    #[tokio::test]
    async fn test_layout_wraps_page_content() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("<h1>Home</h1>")),
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<div class=\"root\"><h1>Home</h1></div>",
        );
    }

    #[tokio::test]
    async fn test_nested_layouts_compose() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(dyn_page("<h1>Dash</h1>")),
            layout: Some(dyn_layout("dash")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<div class=\"root\"><div class=\"dash\"><h1>Dash</h1></div></div>",
        );
    }

    #[tokio::test]
    async fn test_three_level_layout_nesting() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: None,
            layout: Some(dyn_layout("dash")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard/settings".to_string(),
            page: Some(dyn_page("settings-page")),
            layout: Some(dyn_layout("settings")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard/settings")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<div class=\"root\"><div class=\"dash\"><div class=\"settings\">settings-page</div></div></div>",
        );
    }

    #[tokio::test]
    async fn test_dynamic_path_segments() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/users/{id}".to_string(),
            page: Some(dyn_page("<h1>User Profile</h1>")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/users/42")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<h1>User Profile</h1>"
        );
    }

    #[tokio::test]
    async fn test_multiple_routes() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("home")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/about".to_string(),
            page: Some(dyn_page("about")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);

        let resp1 = app
            .clone()
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(body_to_string(resp1.into_body()).await, "home");

        let resp2 = app
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(body_to_string(resp2.into_body()).await, "about");
    }

    // -- Round 2: static (`.html`) handlers compose with the framework --------

    #[tokio::test]
    async fn test_static_page_renders() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/about".to_string(),
            page: Some(static_page("<h1>About</h1>")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/about")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(body_to_string(resp.into_body()).await, "<h1>About</h1>");
    }

    #[tokio::test]
    async fn test_static_layout_wraps_static_page() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(static_page("<h1>Home</h1>")),
            layout: Some(static_layout("<html><body>{{children}}</body></html>")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<html><body><h1>Home</h1></body></html>",
        );
    }

    #[tokio::test]
    async fn test_layout_shell_split_around_marker() {
        let layouts: Vec<crate::conventions::LayoutFn> = vec![
            static_layout("<html>{{children}}</html>"),
            static_layout("<body>{{children}}</body>"),
        ];
        let refs: Vec<&crate::conventions::LayoutFn> = layouts.iter().collect();
        let (before, after) = layout_shell(&refs);
        assert_eq!(before, "<html><body>");
        assert_eq!(after, "</body></html>");
    }

    // -- Round 4: mixed static / dynamic compose correctly --------------------

    #[tokio::test]
    async fn test_static_layout_with_dynamic_page() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("<h1>Hi</h1>")),
            layout: Some(static_layout("<main>{{children}}</main>")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<main><h1>Hi</h1></main>",
        );
    }

    #[tokio::test]
    async fn test_dynamic_layout_with_static_page() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(static_page("<h1>Hi</h1>")),
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<div class=\"root\"><h1>Hi</h1></div>",
        );
    }

    #[tokio::test]
    async fn test_mixed_static_and_dynamic_nested_layouts() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: Some(static_layout("<html>{{children}}</html>")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(dyn_page("page")),
            layout: Some(dyn_layout("dash")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(
            body_to_string(resp.into_body()).await,
            "<html><div class=\"dash\">page</div></html>",
        );
    }

    // -- Streaming (loading) --------------------------------------------------

    #[tokio::test]
    async fn test_loading_stream_contains_loading_then_page() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(slow_dyn_page("<h1>Dashboard</h1>", 30)),
            layout: Some(static_layout("<html>{{children}}</html>")),
            loading: Some(static_loading("<p>Loading...</p>")),
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let body = body_to_string(resp.into_body()).await;

        // All the expected pieces appear in the right order
        let layout_open = body.find("<html>").expect("layout open");
        let slot_div = body.find("__nx_slot__").expect("slot div");
        let loading = body.find("Loading...").expect("loading text");
        let page_template = body.find("__nx_page__").expect("page template");
        let dashboard = body.find("<h1>Dashboard</h1>").expect("page content");
        let swap_script = body.find("<script>").expect("swap script");
        let layout_close = body.find("</html>").expect("layout close");

        assert!(layout_open < slot_div);
        assert!(slot_div < loading);
        assert!(loading < page_template);
        assert!(page_template < dashboard);
        assert!(dashboard < swap_script);
        assert!(swap_script < layout_close);
    }

    #[tokio::test]
    async fn test_loading_stream_yields_multiple_frames() {
        // Confirm the response is actually streamed (multiple body frames),
        // not coalesced into a single chunk before the page resolved.
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(slow_dyn_page("<h1>D</h1>", 30)),
            layout: None,
            loading: Some(static_loading("L")),
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let mut body = resp.into_body();
        let mut frames = 0;
        while let Some(Ok(_)) = http_body_util::BodyExt::frame(&mut body).await {
            frames += 1;
        }
        assert!(
            frames > 1,
            "expected streamed body, got {} frame(s)",
            frames
        );
    }

    #[tokio::test]
    async fn test_loading_arrives_before_page_resolves() {
        // The whole point of streaming is that the loading shell reaches the
        // client BEFORE the page handler finishes. We verify by reading body
        // frames with timestamps and asserting:
        //   1. The loading shell shows up well before the page sleep elapses.
        //   2. The page content shows up only after the sleep — i.e. the
        //      response is genuinely incremental, not buffered.
        use std::time::{Duration, Instant};

        let page_sleep_ms = 200;
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(slow_dyn_page("PAGE_CONTENT", page_sleep_ms)),
            layout: None,
            loading: Some(static_loading("LOADING_SHELL")),
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let start = Instant::now();
        let mut body = resp.into_body();

        // Drain frames, capturing each frame's content and the time it arrived.
        let mut frames: Vec<(Duration, String)> = Vec::new();
        while let Some(Ok(frame)) = http_body_util::BodyExt::frame(&mut body).await {
            if let Ok(data) = frame.into_data() {
                let elapsed = start.elapsed();
                let text = String::from_utf8(data.to_vec()).unwrap();
                frames.push((elapsed, text));
            }
        }

        assert!(
            frames.len() >= 2,
            "expected ≥2 frames, got {}: {:?}",
            frames.len(),
            frames
        );

        // The loading shell must appear in some frame that arrived BEFORE the
        // sleep elapsed — that's the proof of incremental streaming.
        let loading_arrival = frames
            .iter()
            .find(|(_, text)| text.contains("LOADING_SHELL"))
            .map(|(t, _)| *t)
            .expect("no frame contained LOADING_SHELL");
        assert!(
            loading_arrival < Duration::from_millis(page_sleep_ms / 2),
            "loading shell arrived at {}ms, expected <{}ms (page_sleep_ms/2)",
            loading_arrival.as_millis(),
            page_sleep_ms / 2,
        );

        // The page content must appear in some frame that arrived AFTER the
        // sleep — proves we're actually waiting on the page, not pre-buffering.
        let page_arrival = frames
            .iter()
            .find(|(_, text)| text.contains("PAGE_CONTENT"))
            .map(|(t, _)| *t)
            .expect("no frame contained PAGE_CONTENT");
        assert!(
            page_arrival >= Duration::from_millis(page_sleep_ms),
            "page chunk arrived at {}ms, expected ≥{}ms (after page sleep)",
            page_arrival.as_millis(),
            page_sleep_ms,
        );
    }

    #[tokio::test]
    async fn test_loading_with_nested_layouts() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(slow_dyn_page("<h1>D</h1>", 10)),
            layout: Some(dyn_layout("dash")),
            loading: Some(static_loading("loading-shell")),
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let body = body_to_string(resp.into_body()).await;

        // Both layouts wrap the loading shell; the page swap arrives later.
        assert!(body.contains("<div class=\"root\"><div class=\"dash\">"));
        assert!(body.contains("loading-shell"));
        assert!(body.contains("<h1>D</h1>"));
        // Layout close happens after everything.
        assert!(body.ends_with("</div></div>"));
    }

    // -- Middleware -----------------------------------------------------------

    #[tokio::test]
    async fn test_middleware_redirect_prevents_loading_stream() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/reviews".to_string(),
            page: Some(slow_dyn_page("PAGE_CONTENT", 30)),
            layout: None,
            loading: Some(static_loading("LOADING_SHELL")),
            middleware: Some(Box::new(|_req| {
                Box::pin(async {
                    MiddlewareResult::response(axum::response::Redirect::to("/auth/login"))
                })
            })),
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/reviews")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            resp.headers().get(http::header::LOCATION).unwrap(),
            "/auth/login",
        );
        let body = body_to_string(resp.into_body()).await;
        assert!(!body.contains("LOADING_SHELL"));
        assert!(!body.contains("PAGE_CONTENT"));
    }

    #[tokio::test]
    async fn test_middleware_continue_preserves_loading_stream() {
        use std::time::{Duration, Instant};

        let page_sleep_ms = 200;
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/reviews".to_string(),
            page: Some(slow_dyn_page("PAGE_CONTENT", page_sleep_ms)),
            layout: None,
            loading: Some(static_loading("LOADING_SHELL")),
            middleware: Some(Box::new(|req| {
                Box::pin(async { MiddlewareResult::next(req) })
            })),
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/reviews")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let start = Instant::now();
        let mut body = resp.into_body();
        let mut frames: Vec<(Duration, String)> = Vec::new();
        while let Some(Ok(frame)) = http_body_util::BodyExt::frame(&mut body).await {
            if let Ok(data) = frame.into_data() {
                frames.push((start.elapsed(), String::from_utf8(data.to_vec()).unwrap()));
            }
        }

        let loading_arrival = frames
            .iter()
            .find(|(_, text)| text.contains("LOADING_SHELL"))
            .map(|(t, _)| *t)
            .expect("no frame contained LOADING_SHELL");
        assert!(loading_arrival < Duration::from_millis(page_sleep_ms / 2));

        let page_arrival = frames
            .iter()
            .find(|(_, text)| text.contains("PAGE_CONTENT"))
            .map(|(t, _)| *t)
            .expect("no frame contained PAGE_CONTENT");
        assert!(page_arrival >= Duration::from_millis(page_sleep_ms));
    }

    #[tokio::test]
    async fn test_nested_middlewares_run_root_to_leaf() {
        let order = Arc::new(Mutex::new(Vec::new()));

        let root_order = Arc::clone(&order);
        let dashboard_order = Arc::clone(&order);
        let settings_order = Arc::clone(&order);

        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: None,
            loading: None,
            middleware: Some(Box::new(move |req| {
                let order = Arc::clone(&root_order);
                Box::pin(async move {
                    order.lock().unwrap().push("root");
                    MiddlewareResult::next(req)
                })
            })),
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: None,
            layout: None,
            loading: None,
            middleware: Some(Box::new(move |req| {
                let order = Arc::clone(&dashboard_order);
                Box::pin(async move {
                    order.lock().unwrap().push("dashboard");
                    MiddlewareResult::next(req)
                })
            })),
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/dashboard/settings".to_string(),
            page: Some(dyn_page("settings")),
            layout: None,
            loading: None,
            middleware: Some(Box::new(move |req| {
                let order = Arc::clone(&settings_order);
                Box::pin(async move {
                    order.lock().unwrap().push("settings");
                    MiddlewareResult::next(req)
                })
            })),
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard/settings")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(body_to_string(resp.into_body()).await, "settings");
        assert_eq!(
            *order.lock().unwrap(),
            vec!["root", "dashboard", "settings"],
        );
    }

    #[tokio::test]
    async fn test_middleware_can_modify_request_for_page() {
        #[derive(Clone)]
        struct Tenant(&'static str);

        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/reviews".to_string(),
            page: Some(Box::new(|req| {
                Box::pin(async move {
                    req.extensions()
                        .get::<Tenant>()
                        .map(|tenant| tenant.0)
                        .unwrap_or("missing")
                        .to_string()
                })
            })),
            layout: None,
            loading: None,
            middleware: Some(Box::new(|mut req| {
                Box::pin(async move {
                    req.extensions_mut().insert(Tenant("acme"));
                    MiddlewareResult::next(req)
                })
            })),
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/reviews")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(body_to_string(resp.into_body()).await, "acme");
    }

    // -- not-found surfaces ---------------------------------------------------

    #[tokio::test]
    async fn test_not_found_renders_with_layout_and_404() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("home")),
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add_not_found("/", static_page("nope"));

        let app = build_router(registry);

        // Matched route is unaffected.
        let ok = app
            .clone()
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(ok.status(), StatusCode::OK);

        // Unmatched path renders the not-found wrapped in the root layout.
        let nf = app
            .oneshot(
                Request::builder()
                    .uri("/does/not/exist")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(nf.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            body_to_string(nf.into_body()).await,
            "<div class=\"root\">nope</div>",
        );
    }

    #[tokio::test]
    async fn test_deepest_not_found_wins() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add(RouteEntry {
            path: "/admin".to_string(),
            page: None,
            layout: Some(dyn_layout("admin")),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add_not_found("/", static_page("root-404"));
        registry.add_not_found("/admin", static_page("admin-404"));

        let app = build_router(registry);

        // Path under /admin picks the /admin surface, wrapped in root+admin layouts.
        let under_admin = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/admin/missing")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(under_admin.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            body_to_string(under_admin.into_body()).await,
            "<div class=\"root\"><div class=\"admin\">admin-404</div></div>",
        );

        // A path outside /admin falls to the root surface (root layout only).
        let elsewhere = app
            .oneshot(
                Request::builder()
                    .uri("/other")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(elsewhere.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            body_to_string(elsewhere.into_body()).await,
            "<div class=\"root\">root-404</div>",
        );
    }

    #[tokio::test]
    async fn test_no_not_found_yields_bare_404() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("home")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/nope").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        assert_eq!(body_to_string(resp.into_body()).await, "");
    }

    #[tokio::test]
    async fn test_not_found_surface_gets_prefetch_in_head() {
        // A not-found wrapped in a layout with a <head> is a full document, so
        // it gets the speculation-rules script just like a normal page.
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: None,
            layout: Some(static_layout(
                "<html><head></head><body>{{children}}</body></html>",
            )),
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add_not_found("/", static_page("missing"));

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/nope").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        let body = body_to_string(resp.into_body()).await;
        assert!(body.contains("speculationrules"));
        assert!(body.contains("missing"));
    }

    #[tokio::test]
    async fn test_public_dir_miss_falls_through_to_not_found() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("hello.txt"), "hi from public").unwrap();

        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("home")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![],
        });
        registry.add_not_found("/", static_page("custom-404"));

        let app = build_router_with_public(registry, tmp.path());

        // Static file still served.
        let file = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/hello.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(file.status(), StatusCode::OK);
        assert_eq!(body_to_string(file.into_body()).await, "hi from public");

        // Missing file falls through ServeDir to the not-found surface.
        let missing = app
            .oneshot(
                Request::builder()
                    .uri("/missing.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(missing.status(), StatusCode::NOT_FOUND);
        assert_eq!(body_to_string(missing.into_body()).await, "custom-404");
    }

    // -- API routes -----------------------------------------------------------

    #[tokio::test]
    async fn test_route_methods() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/api/users".to_string(),
            page: None,
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![(
                http::Method::POST,
                Box::new(|_req| {
                    Box::pin(async { (StatusCode::CREATED, "created").into_response() })
                }),
            )],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/users")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::CREATED);
        assert_eq!(body_to_string(resp.into_body()).await, "created");
    }

    #[tokio::test]
    async fn test_page_and_route_on_same_path() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/contact".to_string(),
            page: Some(dyn_page("<form>contact form</form>")),
            layout: None,
            loading: None,
            middleware: None,
            methods: vec![(
                http::Method::POST,
                Box::new(|_req| {
                    Box::pin(async { (StatusCode::OK, "form submitted").into_response() })
                }),
            )],
        });

        let app = build_router(registry);

        let get_resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/contact")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            body_to_string(get_resp.into_body()).await,
            "<form>contact form</form>",
        );

        let post_resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/contact")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            body_to_string(post_resp.into_body()).await,
            "form submitted"
        );
    }

    #[tokio::test]
    async fn test_middleware_applies_to_route_methods() {
        let handler_called = Arc::new(AtomicBool::new(false));
        let handler_called_for_route = Arc::clone(&handler_called);

        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/api/reviews".to_string(),
            page: None,
            layout: None,
            loading: None,
            middleware: Some(Box::new(|_req| {
                Box::pin(async { MiddlewareResult::response(StatusCode::UNAUTHORIZED) })
            })),
            methods: vec![(
                http::Method::POST,
                Box::new(move |_req| {
                    let handler_called = Arc::clone(&handler_called_for_route);
                    Box::pin(async move {
                        handler_called.store(true, Ordering::SeqCst);
                        (StatusCode::CREATED, "created").into_response()
                    })
                }),
            )],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/reviews")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert!(!handler_called.load(Ordering::SeqCst));
    }

    // -- Prefetch / speculation rules -----------------------------------------

    #[tokio::test]
    async fn test_prefetch_injected_into_full_document_head() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("<h1>Home</h1>")),
            layout: Some(static_layout(
                "<html><head><title>t</title></head><body>{{children}}</body></html>",
            )),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        // Default config has prefetch ON.
        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        let body = body_to_string(resp.into_body()).await;

        assert!(body.contains(r#"type="speculationrules""#));
        assert!(body.contains(r#""eagerness":"moderate""#));
        // Inside <head>, before the page content.
        let script = body.find("speculationrules").unwrap();
        let head_close = body.find("</head>").unwrap();
        let content = body.find("<h1>Home</h1>").unwrap();
        assert!(script < head_close);
        assert!(head_close < content);
    }

    #[tokio::test]
    async fn test_prefetch_not_injected_into_headless_fragment() {
        // No <head> → a fragment; output stays byte-identical to no-prefetch.
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("<h1>Hi</h1>")),
            layout: Some(dyn_layout("root")),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        let body = body_to_string(resp.into_body()).await;
        assert_eq!(body, "<div class=\"root\"><h1>Hi</h1></div>");
        assert!(!body.contains("speculationrules"));
    }

    #[tokio::test]
    async fn test_prefetch_off_emits_no_script() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/".to_string(),
            page: Some(dyn_page("<h1>Home</h1>")),
            layout: Some(static_layout(
                "<html><head></head><body>{{children}}</body></html>",
            )),
            loading: None,
            middleware: None,
            methods: vec![],
        });

        let app = build_router_with_prefetch(registry, PrefetchConfig::OFF);
        let resp = app
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap();
        let body = body_to_string(resp.into_body()).await;
        assert!(!body.contains("speculationrules"));
        assert_eq!(body, "<html><head></head><body><h1>Home</h1></body></html>");
    }

    #[tokio::test]
    async fn test_prefetch_injected_in_streaming_path() {
        let mut registry = RouteRegistry::new();
        registry.add(RouteEntry {
            path: "/dashboard".to_string(),
            page: Some(slow_dyn_page("<h1>D</h1>", 10)),
            layout: Some(static_layout(
                "<html><head></head><body>{{children}}</body></html>",
            )),
            loading: Some(static_loading("loading")),
            middleware: None,
            methods: vec![],
        });

        let app = build_router(registry);
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/dashboard")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = body_to_string(resp.into_body()).await;
        // Injected into the streamed head, before the loading slot.
        let script = body.find("speculationrules").expect("script present");
        let slot = body.find("__nx_slot__").expect("slot present");
        assert!(script < slot);
    }
}