autumn-macros 0.9.0

Proc macros for the Autumn web framework
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
//! `#[static_get]` macro implementation.
//!
//! Generates both a regular route companion (`__autumn_route_info_{name}`)
//! AND a static metadata companion (`__autumn_static_meta_{name}`), marking
//! the handler for static pre-rendering at build time.
//!
//! ## Supported forms
//!
//! - `#[static_get("/about")]` -- simple static route
//! - `#[static_get("/posts/{slug}", params = list_slugs)]` -- parameterized
//! - `#[static_get("/posts/{slug}", params = list_slugs, revalidate = 60)]` -- with ISR
//! - `#[static_get("/about", seo(title = "About"))]` -- route-level SEO defaults
//! - `#[static_get("/logo.png", content_type = "application/octet-stream")]` --
//!   declared `Content-Type` (#2403)

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::{Ident, LitInt, LitStr, Token};

/// Attribute names of the body-guard macros that cannot meaningfully gate a
/// `#[static_get]` route. See `static_get_macro`'s rejection of the
/// combination in either attribute order.
///
/// `#[feature_flag]` joined this list alongside the three auth/rate guards
/// (Codex review on #2628, tenth finding): none of the four's pre-body
/// `FromRequestParts` checks run on a cached SSG/ISR hit, served by the
/// static-first middleware before the inner router — and the handler along
/// with it — is ever reached, so a disabled flag would silently fail to
/// hide the cached page, the same failure mode as an unenforced auth
/// guard.
const INCOMPATIBLE_GUARD_ATTRS: [&str; 5] = [
    "secured",
    "step_up",
    "throttle",
    "authorize",
    "feature_flag",
];

/// Error message for `#[secured]`/`#[step_up]`/`#[throttle]`/`#[authorize]`/
/// `#[feature_flag]` combined with `#[static_get]`, in either attribute
/// order.
pub const INCOMPATIBLE_GUARD_MSG: &str = "`#[secured]`/`#[step_up]`/`#[throttle]`/`#[authorize]`/`#[feature_flag]` \
     cannot be combined with `#[static_get]`: cached SSG/ISR responses are served by the \
     static-first middleware before the inner router (session, auth, feature gate) is ever \
     reached, so this guard would not protect a cache hit. Use `AppBuilder::static_gate` to \
     gate pre-rendered pages instead.";

/// Parsed attributes for `#[static_get("/path", params = fn, revalidate = N)]`.
struct StaticGetAttrs {
    path: LitStr,
    params_fn: Option<syn::Path>,
    revalidate: Option<u64>,
    /// Route-level SEO meta tag defaults from the `seo(...)` argument (#1182).
    seo: crate::parse::SeoAttrArgs,
    /// Declared `Content-Type` from `content_type = "..."` (#2403).
    content_type: Option<LitStr>,
}

/// A byte of an RFC 9110 token.
fn is_token_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
}

/// Take a non-empty run of token bytes off the front of `bytes`.
fn take_token(bytes: &[u8]) -> Option<&[u8]> {
    let len = bytes.iter().take_while(|b| is_token_byte(**b)).count();
    (len > 0).then(|| &bytes[len..])
}

/// Take a quoted string (with `\` escapes) off the front of `bytes`.
/// Returns `None` when the string is not closed.
fn take_quoted(bytes: &[u8]) -> Option<&[u8]> {
    let mut i = 1;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 2,
            b'"' => return Some(&bytes[i + 1..]),
            _ => i += 1,
        }
    }
    None
}

/// Drop leading spaces and tabs.
fn skip_ows(bytes: &[u8]) -> &[u8] {
    let len = bytes
        .iter()
        .take_while(|b| **b == b' ' || **b == b'\t')
        .count();
    &bytes[len..]
}

/// `true` when `value` is `type/subtype` plus zero or more `; name=value`
/// parameters, as RFC 9110 defines them.
fn is_media_type(value: &str) -> bool {
    let Some(rest) = take_token(skip_ows(value.as_bytes())) else {
        return false;
    };
    let Some(mut rest) = rest.strip_prefix(b"/").and_then(take_token).map(skip_ows) else {
        return false;
    };
    while !rest.is_empty() {
        let param = rest
            .strip_prefix(b";")
            .map(skip_ows)
            .and_then(take_token)
            .and_then(|r| r.strip_prefix(b"="));
        let after_value = param.and_then(|r| {
            if r.first() == Some(&b'"') {
                take_quoted(r)
            } else {
                take_token(r)
            }
        });
        match after_value {
            Some(r) => rest = skip_ows(r),
            None => return false,
        }
    }
    true
}

/// Check a declared `Content-Type`.
///
/// The byte rule is the runtime rule (`usable_recorded_content_type`):
/// non-blank, visible ASCII or tab. Keep both in step. A test in `autumn`
/// pins the runtime byte set. The value must also be a well-formed media type.
fn validate_content_type(lit: &LitStr) -> syn::Result<()> {
    let value = lit.value();
    let legal = |b: u8| b == b'\t' || (0x20..0x7f).contains(&b);
    if value.trim().is_empty() || !value.bytes().all(legal) || !is_media_type(&value) {
        return Err(syn::Error::new(
            lit.span(),
            "`content_type` must be a media type, \
             e.g. `content_type = \"application/rss+xml\"`.",
        ));
    }
    Ok(())
}

impl Parse for StaticGetAttrs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let path: LitStr = input.parse()?;

        let mut params_fn = None;
        let mut revalidate = None;
        let mut seo = crate::parse::SeoAttrArgs::default();
        let mut seen_seo = false;
        let mut content_type: Option<LitStr> = None;

        while input.peek(Token![,]) {
            let _comma: Token![,] = input.parse()?;

            // Allow trailing comma
            if input.is_empty() {
                break;
            }

            let key: Ident = input.parse()?;

            // `seo(...)` is the one call-shaped argument; everything else is
            // `key = value`, so branch before consuming the `=`.
            if key == "seo" {
                if !input.peek(syn::token::Paren) {
                    return Err(syn::Error::new(
                        key.span(),
                        "`seo` takes parenthesized keys, e.g. \
                         `seo(title = \"About\", description = \"…\")`.",
                    ));
                }
                if seen_seo {
                    return Err(syn::Error::new(
                        key.span(),
                        "duplicate `seo(...)` argument. Declare all SEO keys in one `seo(...)`.",
                    ));
                }
                seen_seo = true;
                seo = crate::parse::SeoAttrArgs::parse_group(input)?;
                continue;
            }

            let _eq: Token![=] = input.parse()?;

            match key.to_string().as_str() {
                "params" => {
                    let path: syn::Path = input.parse()?;
                    params_fn = Some(path);
                }
                "revalidate" => {
                    let lit: LitInt = input.parse()?;
                    revalidate = Some(lit.base10_parse::<u64>()?);
                }
                "content_type" => {
                    if content_type.is_some() {
                        return Err(syn::Error::new(
                            key.span(),
                            "duplicate `content_type` argument.",
                        ));
                    }
                    let lit: LitStr = input.parse()?;
                    validate_content_type(&lit)?;
                    content_type = Some(lit);
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "Unknown attribute `{other}`. Expected `params`, `revalidate`, \
                             `content_type`, or `seo(...)`."
                        ),
                    ));
                }
            }
        }

        Ok(Self {
            path,
            params_fn,
            revalidate,
            seo,
            content_type,
        })
    }
}

/// Core implementation for the `#[static_get("/path")]` attribute macro.
///
/// Emits:
/// 1. The original `async fn` unchanged.
/// 2. `__autumn_route_info_{name}()` returning `::autumn_web::Route`
///    (identical to what `#[get]` produces).
/// 3. `__autumn_static_meta_{name}()` returning
///    `::autumn_web::static_gen::StaticRouteMeta`.
#[allow(clippy::too_many_lines)]
pub fn static_get_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
    // `#[edge]` would be inert here and silently so: the page is rendered at
    // build time and served from the CDN already (#1790).
    if let Some(err) = crate::edge::reject_if_edge(
        &item,
        "a `#[static_get]` route is already pre-rendered and served CDN-side; \
         `#[edge]` adds nothing",
    ) {
        return err;
    }

    let attrs: StaticGetAttrs = match syn::parse2(attr) {
        Ok(a) => a,
        Err(err) => return err.to_compile_error(),
    };

    let path = &attrs.path;

    // Validate path
    if path.value().is_empty() {
        return syn::Error::new(path.span(), "Route path must not be empty").to_compile_error();
    }

    if !path.value().starts_with('/') {
        let suggested = format!("/{}", path.value());
        return syn::Error::new(
            path.span(),
            format!("Route path must start with '/'. Did you mean \"{suggested}\"?"),
        )
        .to_compile_error();
    }

    // Parameterized routes require a params function
    let has_params = path.value().contains('{');
    if has_params && attrs.params_fn.is_none() {
        return syn::Error::new(
            path.span(),
            "Parameterized static routes require a `params` function. \
             Example: #[static_get(\"/posts/{slug}\", params = list_slugs)]",
        )
        .to_compile_error();
    }

    // Non-parameterized routes should not have a params function
    if !has_params && attrs.params_fn.is_some() {
        return syn::Error::new(
            path.span(),
            "Static route has no path parameters but a `params` function was provided. \
             Either add path parameters or remove the `params` attribute.",
        )
        .to_compile_error();
    }

    // Parse the async handler function
    let (leading_guard_items, mut input_fn) =
        match crate::parse::parse_async_handler_with_leading_items(item) {
            Ok(v) => v,
            Err(err) => return err,
        };

    // Owned rather than borrowed: `input_fn` is mutated below (a marker gets
    // spliced into its body) once the guard checks pass, and these need to
    // outlive that mutable borrow to reach the final `quote!` at the bottom.
    let fn_name = input_fn.sig.ident.clone();
    let route_info_name = format_ident!("__autumn_route_info_{}", fn_name);
    let static_meta_name = format_ident!("__autumn_static_meta_{}", fn_name);
    let vis = input_fn.vis.clone();

    // Honor a `#[public]` marker on the handler so the route audit gate can
    // classify this static route as `public` rather than `unclassified`.
    // Mirrors the standard `#[get]`/`#[post]` route macro (see
    // `crate::route`), which is the only place `is_public` was previously
    // wired.
    let is_public = crate::api_doc::is_public(&input_fn);

    // `#[secured]`/`#[step_up]`/`#[throttle]`/`#[authorize]` cannot
    // meaningfully gate a `#[static_get]` route: cached SSG/ISR responses
    // are served by the static-first middleware *before* the inner router
    // (session, auth) is ever reached (see `AppBuilder::static_gate`'s doc
    // comment in `autumn/src/app.rs`), so a route-level guard here only
    // ever runs on the rare synchronous render/revalidate call, never on a
    // cache hit — the overwhelming majority of live traffic to a cached
    // page. An earlier version of this macro derived `secured: true` from
    // such a guard, which made `routes audit` wrongly certify the page as
    // protected (P1, #2513 Codex review). Reject the combination outright,
    // in both stacking orders, pointing authors at the gate actually built
    // for this: `AppBuilder::static_gate`.
    //
    // `unexpanded_guard_attr` catches `#[static_get]` outermost, the guard
    // still a live attribute below it — confirmed reachable in real
    // compiled code by the identical, already-shipped `#[edge]`-vs-guard
    // rejection's own trybuild fixture (`edge_with_secured.rs`). This scan
    // must also see a guard hidden behind `#[cfg_attr(predicate, secured(..))]`:
    // `cfg_attr` itself is not resolved until after every attribute macro
    // has finished expanding, so a plain `attr.path()` name check sees only
    // `cfg_attr`, never the guard it wraps, letting a feature-gated guard
    // slip past this rejection entirely (Codex review on #2513, ninth
    // finding) — `param_helpers::attr_or_cfg_attr_matches_any` looks inside
    // `cfg_attr`'s own argument list for this reason. But a guard written
    // *above* `#[static_get]` (the more natural order) is a
    // materially different case: by the time the real compiler invokes
    // `static_get_macro`, the guard has already fully expanded and consumed
    // itself, so there is no live attribute left to find, and — contrary to
    // an earlier version of this check — no leading sibling gate item
    // either. Attribute macros are only ever invoked with the tokens of the
    // single item they still decorate, never bundled with a sibling item
    // another macro emitted alongside it (see
    // `param_helpers::extract_fn_item`'s doc comment); `leading_guard_items`
    // being non-empty here is a shape only a test that hand-concatenates
    // macro outputs can produce, never the real compiler (Codex review on
    // #2513, eighth finding — the fix below to the P1 finding on this same
    // line still only checked that unreachable shape). What DOES survive
    // onto the surviving single function is the guard's own signature/body
    // rewrite: `#[secured]`/`#[step_up]`/`#[throttle]` each insert a
    // handler-unique pre-body gate parameter
    // (`param_helpers::has_any_guard_gate_param`), and `#[authorize]` —
    // which inserts no such parameter — leaves its role/policy-check marker
    // directly in the body (`api_doc::extract_secured_info`, the same
    // recovery the `#[get]`/`#[post]` route macro already relies on for
    // this exact scenario).
    let unexpanded_guard_attr = input_fn.attrs.iter().find(|attr| {
        crate::param_helpers::attr_or_cfg_attr_matches_any(attr, &INCOMPATIBLE_GUARD_ATTRS)
    });
    let already_expanded_guard = crate::param_helpers::has_any_guard_gate_param(&input_fn)
        || crate::api_doc::extract_secured_info(&input_fn).0;
    if !leading_guard_items.is_empty() || unexpanded_guard_attr.is_some() || already_expanded_guard
    {
        let err = unexpanded_guard_attr.map_or_else(
            || syn::Error::new_spanned(&input_fn.sig, INCOMPATIBLE_GUARD_MSG),
            |attr| syn::Error::new_spanned(attr, INCOMPATIBLE_GUARD_MSG),
        );
        return err.to_compile_error();
    }

    // No guard is visible by name or by expansion artifact at this point,
    // but a still-pending guard attribute imported under an alias (e.g.
    // `use ::autumn_web::secured as auth;` then `#[auth("admin")]`) is
    // exactly as live and unexpanded as a plainly-spelled one, and
    // completely invisible to `attr_or_cfg_attr_matches_any`'s name-based
    // scan: a proc-macro attribute runs before the compiler resolves
    // imports, so there is no way to ask "does this path actually name
    // `autumn_web::secured`" from here (Codex review on #2513, tenth
    // finding). Leave a marker for that guard's OWN macro to find once IT
    // expands, regardless of what name it was invoked under — see
    // `param_helpers::STATIC_ROUTE_HANDLER_MARKER`'s doc comment.
    crate::param_helpers::prepend_body_const_marker(
        &mut input_fn,
        crate::param_helpers::STATIC_ROUTE_HANDLER_MARKER,
    );

    // No guard is present at this point, so the route is always unsecured.
    let secured = false;
    let required_roles = quote! { &[] };
    let required_scopes = quote! { &[] };

    // Build the revalidate expression
    let revalidate_expr = attrs.revalidate.map_or_else(
        || quote! { ::core::option::Option::None },
        |secs| quote! { ::core::option::Option::Some(#secs) },
    );

    // Build the params_fn expression
    let params_fn_expr = attrs.params_fn.as_ref().map_or_else(
        || quote! { ::core::option::Option::None },
        |pf| {
            quote! {
                ::core::option::Option::Some(
                    |router: ::autumn_web::reexports::axum::Router|
                        -> ::core::pin::Pin<Box<dyn ::core::future::Future<
                            Output = Vec<::autumn_web::static_gen::StaticParams>
                        > + Send>> {
                        Box::pin(#pf(router))
                    }
                )
            }
        },
    );

    let path_value = path.value();
    let path_params = crate::api_doc::extract_path_params(&path_value);
    let path_params_tokens = crate::api_doc::emit_path_param_slice(&path_params);
    let seo_defaults = attrs.seo.emit();
    let content_type_expr = attrs.content_type.as_ref().map_or_else(
        || quote! { ::core::option::Option::None },
        |ct| quote! { ::core::option::Option::Some(#ct) },
    );

    // ── Architecture-graph node (#1747) ─────────────────────────
    // `#[static_get]` builds its own `Route` rather than delegating to
    // `crate::route`, so it registers its own graph node too — marked as a
    // static route, which is the one fact that distinguishes it from a `#[get]`.
    let graph_descriptor =
        crate::graph::emit_route_descriptor(&input_fn, "GET", &quote! { #path }, true);

    quote! {
        #leading_guard_items
        #input_fn

        #graph_descriptor

        #[doc(hidden)]
        #vis fn #route_info_name() -> ::autumn_web::Route {
            ::autumn_web::Route {
                method: ::autumn_web::reexports::http::Method::GET,
                path: #path,
                handler: ::autumn_web::reexports::axum::routing::get(#fn_name),
                name: ::core::stringify!(#fn_name),
                api_doc: ::autumn_web::openapi::ApiDoc {
                    method: "GET",
                    path: #path,
                    operation_id: ::core::stringify!(#fn_name),
                    summary: ::core::option::Option::None,
                    description: ::core::option::Option::None,
                    tags: &[],
                    path_params: #path_params_tokens,
                    request_body: ::core::option::Option::None,
                    response: ::core::option::Option::None,
                    success_status: 200,
                    hidden: false,
                    query_schema: ::core::option::Option::None,
                    secured: #secured,
                    required_roles: #required_roles,
                    required_scopes: #required_scopes,
                    register_schemas: ::core::option::Option::None,
                    api_version: ::core::option::Option::None,
                    public: #is_public,
                    module_path: ::core::module_path!(),
                    source_file: ::core::file!(),
                    source_line: ::core::line!(),
                    ..::core::default::Default::default()
                },
                repository: ::core::option::Option::None,
                idempotency: ::autumn_web::RouteIdempotency::Direct,
                // Live inbound requests to this GET route (a manifest miss, no
                // `dist`, or a cache read that falls through to the dynamic
                // router) inherit the global deadline like any other route, so a
                // slow/hung handler can't bypass `request_timeout_ms`. The
                // build/ISR prerenders that drive this route internally are
                // exempted instead via the `RenderDeadlineExempt` request marker
                // (see `autumn_web::static_gen`), scoping the exemption to those
                // internal renders rather than the live route metadata.
                timeout: ::autumn_web::RouteTimeout::Inherit,
                criticality: ::autumn_web::Criticality::Default,
                api_version: ::core::option::Option::None,
                sunset_opt_out: false,
                seo: #seo_defaults,
            }
        }

        #[doc(hidden)]
        #vis fn #static_meta_name() -> ::autumn_web::static_gen::StaticRouteMeta {
            ::autumn_web::static_gen::StaticRouteMeta {
                path: #path,
                name: ::core::stringify!(#fn_name),
                revalidate: #revalidate_expr,
                params_fn: #params_fn_expr,
                seo: #seo_defaults,
                content_type: #content_type_expr,
            }
        }
    }
}

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

    use super::static_get_macro;

    #[test]
    fn static_get_defaults_public_false() {
        let generated = static_get_macro(
            quote! { "/about" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("public : false"),
            "an unannotated static route must record public = false: {generated}"
        );
        // The handler's module path is captured for audit diagnostics.
        assert!(generated.contains("module_path"));
    }

    #[test]
    fn static_get_rejects_a_secured_guard_expanded_above_it() {
        // `#[secured("admin")]` above `#[static_get]`: the guard expands
        // first and, critically, the real compiler then invokes
        // `static_get_macro` with ONLY the resulting single function's
        // tokens — never bundled with the gate sibling item the guard also
        // emitted (attribute macros are only ever invoked with the one item
        // they still decorate; see `param_helpers::extract_fn_item`'s doc
        // comment). `extract_fn_item` slices out that single function here
        // to reproduce exactly that shape, rather than feeding the whole
        // multi-item `secured_macro` output directly, which is a shape the
        // real compiler never produces (a gap in this test caught by a
        // later Codex pass: the P1 fix this test originally accompanied
        // only checked that unreachable shape via `leading_guard_items` and
        // so never actually closed the false `secured: true` certification
        // it claimed to — eighth finding on #2513). An earlier version of
        // this macro read the guard's role marker via `extract_secured_info`
        // and recorded `secured: true` — but cached SSG/ISR responses are
        // served by the static-first middleware *before* the guard (or the
        // inner router at all) ever runs, so that certification was false
        // for the overwhelming majority of live traffic to the cached page
        // (a cache hit). Reject the combination outright instead.
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                async fn about() -> &'static str { "about" }
            },
        );
        let secured_fn = crate::param_helpers::extract_fn_item(secured, "about");
        let generated = static_get_macro(quote! { "/about" }, quote! { #secured_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "a #[secured] guard stacked above #[static_get] must be a compile error, not a \
             false `secured: true` certification: {generated}"
        );
        assert!(
            generated.contains("cannot be combined with"),
            "the error must explain why the combination is rejected: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_a_live_unexpanded_secured_attribute() {
        // The *other* stacking order: `#[static_get]` outermost, `#[secured]`
        // still a live, unexpanded attribute below it.
        let generated = static_get_macro(
            quote! { "/about" },
            quote! {
                #[secured("admin")]
                async fn about() -> &'static str { "about" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a live, unexpanded #[secured] attribute below #[static_get] must also be a \
             compile error: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_a_secured_attribute_wrapped_in_cfg_attr() {
        // A guard hidden behind `#[cfg_attr(predicate, secured(..))]` below
        // `#[static_get]` is just as live and unexpanded as a bare
        // `#[secured]` attribute in the same position — `cfg_attr` is not
        // resolved until after every attribute macro has finished expanding.
        // Ninth Codex finding on #2513: a scan that only compared
        // `attr.path()` against the guard's own name saw `cfg_attr`, not
        // `secured`, and let this slip through uncaught.
        let generated = static_get_macro(
            quote! { "/private" },
            quote! {
                #[cfg_attr(feature = "auth", secured("admin"))]
                async fn private() -> &'static str { "private" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a #[secured] guard wrapped in #[cfg_attr] below #[static_get] must also be a \
             compile error: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_a_step_up_guard_expanded_above_it() {
        // See `static_get_rejects_a_secured_guard_expanded_above_it`: sliced
        // via `extract_fn_item` to match what the real compiler actually
        // hands `static_get_macro`, not the unreachable bundled shape.
        let stepped_up = crate::step_up::step_up_macro(
            quote! {},
            quote! {
                async fn about() -> &'static str { "about" }
            },
        );
        let stepped_up_fn = crate::param_helpers::extract_fn_item(stepped_up, "about");
        let generated =
            static_get_macro(quote! { "/about" }, quote! { #stepped_up_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "a #[step_up] guard stacked above #[static_get] must be a compile error: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_a_throttle_guard_expanded_above_it() {
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 10, per = "1m" },
            quote! {
                async fn about() -> &'static str { "about" }
            },
        );
        let throttled_fn = crate::param_helpers::extract_fn_item(throttled, "about");
        let generated = static_get_macro(quote! { "/about" }, quote! { #throttled_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "a #[throttle] guard stacked above #[static_get] must be a compile error: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_a_feature_flag_guard_expanded_above_it() {
        // Codex review on #2628, two rounds:
        //
        // Eighth finding: round 3 added `__AutumnFlagGate_` to
        // `param_helpers::GUARD_GATE_TYPE_PREFIXES` so
        // `#[secured]`/`#[step_up]`/`#[throttle]` could see an earlier
        // `#[feature_flag]` gate for idempotency-replay-ownership purposes.
        // `static_get_macro` shared that same broad prefix list for an
        // unrelated question -- "is there a guard here that's incompatible
        // with a static route" -- so `#[feature_flag]` expanded above
        // `#[static_get]` became an order-dependent compile break (the
        // reverse order was never rejected).
        //
        // Tenth finding: a first fix narrowed `static_get_macro`'s check to
        // an auth/rate-only prefix list, making the combination compile.
        // That was wrong in the other direction: none of the four gates'
        // pre-body `FromRequestParts` checks run on a cached SSG/ISR hit
        // (served by the static-first middleware before the handler is
        // ever reached), so a disabled `#[feature_flag]` on a static route
        // would silently fail to hide the cached page -- the same failure
        // mode the three auth/rate guards are already rejected for. The
        // combination must be a compile error in both attribute orders,
        // same as the other three.
        let flagged = crate::feature_flag::feature_flag_macro(
            quote! { "my_flag" },
            quote! {
                async fn about() -> &'static str { "about" }
            },
        );
        let flagged_fn = crate::param_helpers::extract_fn_item(flagged, "about");
        let generated = static_get_macro(quote! { "/about" }, quote! { #flagged_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "a #[feature_flag] gate stacked above #[static_get] must be a compile error, since \
             it would not protect a cached SSG/ISR hit: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_a_live_unexpanded_feature_flag_attribute() {
        // The *other* stacking order: `#[static_get]` outermost,
        // `#[feature_flag]` still a live, unexpanded attribute below it --
        // caught by name via `INCOMPATIBLE_GUARD_ATTRS`, mirroring how the
        // other three guards are rejected in this order.
        let generated = static_get_macro(
            quote! { "/about" },
            quote! {
                #[feature_flag("my_flag")]
                async fn about() -> &'static str { "about" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a #[feature_flag] attribute stacked below #[static_get] must be a compile error: \
             {generated}"
        );
    }

    #[test]
    fn static_get_rejects_an_authorize_guard_expanded_above_it() {
        // `#[authorize]` is the one guard with no pre-body gate parameter —
        // it leaves only a body marker/policy-check statement — so this
        // exercises the `api_doc::extract_secured_info` half of the
        // already-expanded-guard detection, not
        // `param_helpers::has_any_guard_gate_param`.
        let authorized = crate::authorize::authorize_macro(
            quote! { "view", resource = Room },
            quote! {
                async fn about() -> &'static str { "about" }
            },
        );
        let authorized_fn = crate::param_helpers::extract_fn_item(authorized, "about");
        let generated =
            static_get_macro(quote! { "/about" }, quote! { #authorized_fn }).to_string();

        assert!(
            generated.contains("compile_error"),
            "an #[authorize] guard stacked above #[static_get] must be a compile error: {generated}"
        );
    }

    #[test]
    fn static_get_defaults_unsecured_when_no_guard_present() {
        let generated = static_get_macro(
            quote! { "/about" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("secured : false"),
            "an unguarded static route must record secured = false: {generated}"
        );
        assert!(
            generated.contains("required_roles : & []"),
            "an unguarded static route must have no required roles: {generated}"
        );
    }

    #[test]
    fn static_get_marks_public_when_public_attribute_present() {
        // Ordering A: `#[static_get]` outermost, `#[public]` still an attribute below.
        let generated = static_get_macro(
            quote! { "/about" },
            quote! {
                #[public]
                async fn about() -> &'static str { "about" }
            },
        )
        .to_string();
        assert!(
            generated.contains("public : true"),
            "a #[public] static route must record public = true: {generated}"
        );
    }

    // ── seo(...) route-level defaults (#1182) ───────────────────────────────

    #[test]
    fn static_get_defaults_seo_to_empty() {
        let generated = static_get_macro(
            quote! { "/about" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("SeoRouteDefaults :: EMPTY"),
            "a static route without seo(...) must record the empty defaults: {generated}"
        );
    }

    #[test]
    fn static_get_emits_declared_seo_defaults() {
        let generated = static_get_macro(
            quote! { "/about", seo(title = "About", og_type = "website") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("with_title (\"About\")"),
            "seo(title = ...) must populate the static route defaults: {generated}"
        );
        assert!(
            generated.contains("with_og_type (\"website\")"),
            "seo(og_type = ...) must populate the static route defaults: {generated}"
        );
    }

    #[test]
    fn static_get_seo_composes_with_params_and_revalidate() {
        let generated = static_get_macro(
            quote! { "/posts/{slug}", seo(og_type = "article"), params = list_slugs, revalidate = 60 },
            quote! { async fn show() -> &'static str { "post" } },
        )
        .to_string();
        assert!(
            generated.contains("with_og_type (\"article\")"),
            "seo(...) must parse alongside params/revalidate: {generated}"
        );
        assert!(
            generated.contains("list_slugs"),
            "params must still parse after seo(...): {generated}"
        );
        assert!(
            generated.contains("60"),
            "revalidate must still parse after seo(...): {generated}"
        );
    }

    #[test]
    fn static_get_rejects_unknown_seo_key() {
        let generated = static_get_macro(
            quote! { "/about", seo(titel = "About") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "an unknown seo key must be a compile error on static routes: {generated}"
        );
    }

    // ── content_type = "..." declared media type (#2403) ────────────────────

    fn expand(attr: proc_macro2::TokenStream) -> String {
        static_get_macro(attr, quote! { async fn logo() -> &'static str { "logo" } }).to_string()
    }

    #[test]
    fn static_get_defaults_content_type_to_none() {
        let generated = expand(quote! { "/logo.png" });
        assert!(
            generated.contains("content_type : :: core :: option :: Option :: None"),
            "no content_type argument must emit None: {generated}"
        );
    }

    #[test]
    fn static_get_emits_declared_content_type() {
        let generated = expand(quote! { "/logo.png", content_type = "application/octet-stream" });
        assert!(
            generated.contains(
                "content_type : :: core :: option :: Option :: Some (\"application/octet-stream\")"
            ),
            "content_type must reach the static metadata: {generated}"
        );
    }

    #[test]
    fn static_get_content_type_composes_with_other_arguments() {
        let generated = expand(quote! {
            "/posts/{slug}", params = list_slugs, content_type = "text/markdown",
            revalidate = 60, seo(title = "Post")
        });
        assert!(!generated.contains("compile_error"), "{generated}");
        assert!(generated.contains("\"text/markdown\""), "{generated}");
        assert!(generated.contains("list_slugs"), "{generated}");
    }

    #[test]
    fn static_get_rejects_bad_content_type() {
        for bad in [
            quote! { "/a", content_type = "" },
            quote! { "/a", content_type = "   " },
            quote! { "/a", content_type = "text/\u{e9}html" },
            quote! { "/a", content_type = "text/html\r\nX: y" },
            quote! { "/a", content_type = 42 },
            quote! { "/a", content_type = "text" },
            quote! { "/a", content_type = "/" },
            quote! { "/a", content_type = "text/" },
            quote! { "/a", content_type = "/plain" },
            quote! { "/a", content_type = "a/b/c" },
            quote! { "/a", content_type = "image/png, text/html" },
            quote! { "/a", content_type = "text /plain" },
            quote! { "/a", content_type = "text/plain; a=\"b\"; c=d," },
            quote! { "/a", content_type = "text/html; =" },
            quote! { "/a", content_type = "text/html; a=" },
            quote! { "/a", content_type = "text/html; a" },
            quote! { "/a", content_type = "text/html;" },
            quote! { "/a", content_type = "text/html; charset=\"unterminated" },
            quote! { "/a", content_type = "text/html; a=b c" },
            quote! { "/a", content_type = "text/html; a=\"x\"y" },
            quote! { "/a", content_type = "a/b", content_type = "c/d" },
        ] {
            let generated = expand(bad.clone());
            assert!(
                generated.contains("compile_error"),
                "must reject `{bad}`: {generated}"
            );
        }
    }

    #[test]
    fn static_get_accepts_well_formed_media_types() {
        for good in [
            "text/html",
            "application/rss+xml",
            "text/plain; charset=utf-8",
            "application/rss+xml;\tprofile=\"x\"",
            "image/svg+xml",
            "  text/csv  ",
            "text/html; a=\"x\\\"y\"; b=c",
            "text/html ; charset=utf-8",
        ] {
            let generated = expand(quote! { "/a", content_type = #good });
            assert!(!generated.contains("compile_error"), "{good}: {generated}");
        }
    }

    #[test]
    fn static_get_unknown_key_error_lists_content_type() {
        let generated = expand(quote! { "/a", mime = "a/b" });
        assert!(generated.contains("content_type"), "{generated}");
    }

    // `#[static_get]` has its own attribute parser, so the rejection paths the
    // `#[get]` family covers are re-asserted here rather than assumed.

    #[test]
    fn static_get_rejects_duplicate_seo_key() {
        let generated = static_get_macro(
            quote! { "/about", seo(title = "A", title = "B") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "a duplicate seo key must be a compile error on static routes: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_non_string_seo_value() {
        let generated = static_get_macro(
            quote! { "/about", seo(title = 42) },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "a non-string seo value must be a compile error on static routes: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_seo_without_parentheses() {
        let generated = static_get_macro(
            quote! { "/about", seo = "title" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "`seo = ...` must be rejected on static routes too: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_empty_seo_group() {
        let generated = static_get_macro(
            quote! { "/about", seo() },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "an empty seo() must be a compile error on static routes: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_repeated_seo_argument() {
        let generated = static_get_macro(
            quote! { "/about", seo(title = "A"), seo(og_type = "website") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "a second seo(...) argument must be a compile error on static routes: {generated}"
        );
    }

    // ── `#[edge]` is meaningless on a pre-rendered route (#1790) ────────────

    #[test]
    fn static_get_rejects_a_live_edge_attribute() {
        let generated = static_get_macro(
            quote! { "/about" },
            quote! {
                #[edge]
                async fn about() -> &'static str { "about" }
            },
        )
        .to_string();
        assert!(
            generated.contains("compile_error"),
            "#[edge] on a #[static_get] route must be rejected: {generated}"
        );
        assert!(
            generated.contains("already pre-rendered"),
            "the error must explain that the page is already served CDN-side: {generated}"
        );
    }

    #[test]
    fn static_get_rejects_an_expanded_edge_marker() {
        // `#[edge]` written above `#[static_get]`, so it expanded first and
        // left only the `__AUTUMN_EDGE` marker in the body.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! { async fn about() -> &'static str { "about" } },
        );
        let generated = static_get_macro(quote! { "/about" }, edged).to_string();
        assert!(
            generated.contains("compile_error"),
            "an already-expanded #[edge] must be rejected on #[static_get] too: {generated}"
        );
    }

    #[test]
    fn static_get_without_edge_is_untouched() {
        let generated = static_get_macro(
            quote! { "/about" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();
        assert!(
            !generated.contains("compile_error"),
            "an ordinary static route must still compile: {generated}"
        );
        assert!(
            !generated.contains("autumn_edge"),
            "an ordinary static route must not reference autumn_edge: {generated}"
        );
    }

    #[test]
    fn static_get_marks_public_from_expanded_marker() {
        // Ordering B: `#[public]` written above `#[static_get]`, so it expands
        // first and injects the `__AUTUMN_PUBLIC` marker into the body; the
        // static route macro must recognize the marker.
        let public_fn = crate::public::public_macro(
            quote! {},
            quote! { async fn about() -> &'static str { "about" } },
        );
        let generated = static_get_macro(quote! { "/about" }, public_fn).to_string();
        assert!(
            generated.contains("public : true"),
            "a static route macro over an expanded #[public] marker must record public = true: {generated}"
        );
    }
}