server-less-macros 0.6.0

Proc macros for server-less
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
//! JSON-RPC over HTTP handler generation macro.
//!
//! Generates JSON-RPC 2.0 handlers over HTTP POST with full spec compliance.
//!
//! # JSON-RPC 2.0
//!
//! Implements the JSON-RPC 2.0 specification:
//! - Request: `{"jsonrpc": "2.0", "method": "add", "params": {"a": 5, "b": 3}, "id": 1}`
//! - Response: `{"jsonrpc": "2.0", "result": 8, "id": 1}`
//! - Error: `{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": 1}`
//! - Notification (no response): `{"jsonrpc": "2.0", "method": "log", "params": {"msg": "hello"}}`
//!
//! # Features
//!
//! - Single requests and batch requests
//! - Notifications (requests without `id`)
//! - Both sync and async methods
//! - Positional and named parameters
//!
//! # Generated Methods
//!
//! - `jsonrpc_methods() -> Vec<String>` - List of available methods
//! - `jsonrpc_handle_async(&self, request: Value).await` - Handle request (async)
//! - `jsonrpc_router(self) -> axum::Router` - HTTP server at /rpc
//!
//! # Example
//!
//! ```ignore
//! use server_less::jsonrpc;
//!
//! #[derive(Clone)]
//! struct Calculator;
//!
//! #[jsonrpc(path = "/rpc")]
//! impl Calculator {
//!     /// Add two numbers
//!     fn add(&self, a: i32, b: i32) -> i32 {
//!         a + b
//!     }
//!
//!     /// Subtract two numbers
//!     fn subtract(&self, a: i32, b: i32) -> i32 {
//!         a - b
//!     }
//! }
//!
//! // Use it:
//! let calc = Calculator;
//! let app = calc.jsonrpc_router();
//!
//! // Client POST to /rpc:
//! // {"jsonrpc": "2.0", "method": "add", "params": {"a": 5, "b": 3}, "id": 1}
//! // Response:
//! // {"jsonrpc": "2.0", "result": 8, "id": 1}
//! ```

use crate::app::extract_app_meta;
use crate::server_attrs::{has_server_hidden, has_server_skip, validate_server_attrs};
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use server_less_parse::{MethodInfo, extract_methods, get_impl_name, partition_methods};
use server_less_rpc::{self, AsyncHandling};
use syn::{ItemImpl, Token, parse::Parse};

// Import Context helpers
use crate::context::partition_context_params;

/// Arguments for the #[jsonrpc] attribute
#[derive(Default)]
pub(crate) struct JsonRpcArgs {
    pub path: Option<String>,
}

impl Parse for JsonRpcArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = JsonRpcArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match ident.to_string().as_str() {
                "path" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.path = Some(lit.value());
                }
                other => {
                    const VALID: &[&str] = &["path"];
                    let suggestion = crate::did_you_mean(other, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        ident.span(),
                        format!("unknown argument `{other}`{suggestion}. Valid arguments: path"),
                    ));
                }
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

pub(crate) fn expand_jsonrpc(args: JsonRpcArgs, mut impl_block: ItemImpl) -> syn::Result<TokenStream2> {
    crate::reject_generic_impl(&impl_block)?;
    // L7: app_meta is extracted to consume the __app_meta attr (preventing it from leaking
    // to downstream macros), but jsonrpc doesn't produce named artifacts that use it.
    let _app_meta = extract_app_meta(&mut impl_block.attrs);
    let struct_name = get_impl_name(&impl_block)?;
    let (impl_generics, _ty_generics, where_clause) = impl_block.generics.split_for_impl();
    let self_ty = &impl_block.self_ty;
    let methods = extract_methods(&impl_block)?;

    let path = args.path.unwrap_or_else(|| "/rpc".to_string());

    for m in &methods {
        validate_server_attrs(m)?;
    }
    let partitioned = partition_methods(&methods, has_server_skip);

    // Separate hidden from visible leaf methods.
    // Hidden methods are still dispatchable but absent from method listings.
    let visible_leaf: Vec<_> = partitioned
        .leaf
        .iter()
        .copied()
        .filter(|m| !has_server_hidden(m))
        .collect();

    let dispatch_arms_async: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let arm = generate_dispatch_arm(m)?;
            let cfg_attrs = &m.cfg_attrs;
            Ok(quote! {
                #(#cfg_attrs)*
                #arm
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;

    let dispatch_arms_sync: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let arm = generate_sync_dispatch_arm(m)?;
            let cfg_attrs = &m.cfg_attrs;
            Ok(quote! {
                #(#cfg_attrs)*
                #arm
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;

    // method_names for jsonrpc_methods() and OpenRPC listing: visible only.
    // Stored as plain strings for use in OpenAPI; also emitted as cfg-gated push statements.
    let method_name_strings: Vec<String> = visible_leaf
        .iter()
        .map(|m| m.wire_name_or(|n| n))
        .collect();
    // Statement-form for jsonrpc_methods() so #[cfg] guards individual names.
    let method_name_stmts: Vec<_> = visible_leaf
        .iter()
        .map(|m| {
            let name = m.wire_name_or(|n| n);
            let cfg_attrs = &m.cfg_attrs;
            quote! {
                #(#cfg_attrs)*
                names.push(#name.to_string());
            }
        })
        .collect();
    // Keep a plain slice for OpenAPI path generation (compile-time known list).
    let method_names = &method_name_strings;

    // Build method documentation (visible methods only)
    let jsonrpc_method_doc_entries: Vec<String> = visible_leaf
        .iter()
        .map(|m| {
            let name = m.wire_name_or(|n| n);
            match &m.docs {
                Some(doc) => format!("- `{name}` — {doc}"),
                None => format!("- `{name}`"),
            }
        })
        .collect();
    let has_jsonrpc_mounts =
        !partitioned.static_mounts.is_empty() || !partitioned.slug_mounts.is_empty();
    let jsonrpc_methods_doc = if jsonrpc_method_doc_entries.is_empty() && !has_jsonrpc_mounts {
        "Get available JSON-RPC method names.".to_string()
    } else {
        let mount_note = if has_jsonrpc_mounts {
            "\n\nAlso includes methods from mounted sub-services."
        } else {
            ""
        };
        format!(
            "Get available JSON-RPC method names.\n\n# Methods\n\n{}{}",
            jsonrpc_method_doc_entries.join("\n"),
            mount_note
        )
    };
    let jsonrpc_router_doc = format!(
        "Create an axum Router with JSON-RPC endpoint at `{}`.\n\n\
         Exposes {} method{}.",
        path,
        method_names.len(),
        if method_names.len() == 1 { "" } else { "s" }
    );

    // Generate mount dispatch arms and method names
    let mount_dispatch_arms: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_dispatch(m))
        .chain(
            partitioned
                .slug_mounts
                .iter()
                .map(|m| generate_slug_mount_dispatch(m)),
        )
        .collect::<syn::Result<Vec<_>>>()?;

    let mount_dispatch_arms_sync: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_dispatch_sync(m))
        .chain(
            partitioned
                .slug_mounts
                .iter()
                .map(|m| generate_slug_mount_dispatch_sync(m)),
        )
        .collect::<syn::Result<Vec<_>>>()?;

    let mount_method_names: Vec<_> = partitioned
        .static_mounts
        .iter()
        .chain(partitioned.slug_mounts.iter())
        .map(|m| generate_mount_method_names(m))
        .collect::<syn::Result<Vec<_>>>()?;

    // Check if any leaf method uses Context
    let uses_context = partitioned.leaf.iter().any(|m| {
        partition_context_params(&m.params)
            .map(|(ctx, _)| ctx.is_some())
            .unwrap_or(false)
    });

    // Mount dispatch inner method — always takes (method, args) without Context.
    // Maps the (i32, String) error from jsonrpc_dispatch down to a plain String
    // for the JsonRpcMount::jsonrpc_mount_dispatch_async interface.
    let mount_dispatch_inner = if uses_context {
        quote! {
            async fn jsonrpc_mount_dispatch_inner(
                &self,
                method: &str,
                args: ::server_less::serde_json::Value,
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                let __ctx = ::server_less::Context::new();
                self.jsonrpc_dispatch(__ctx, method, args).await.map_err(|(_, msg)| msg)
            }
        }
    } else {
        quote! {
            async fn jsonrpc_mount_dispatch_inner(
                &self,
                method: &str,
                args: ::server_less::serde_json::Value,
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                self.jsonrpc_dispatch(method, args).await.map_err(|(_, msg)| msg)
            }
        }
    };

    // Sync mount dispatch inner — returns Err for async-only methods
    let mount_dispatch_sync_inner = quote! {
        /// Internal sync dispatch for mount trait (no Context, returns Err for async-only methods).
        fn jsonrpc_mount_dispatch_sync_inner(
            &self,
            method: &str,
            args: ::server_less::serde_json::Value,
        ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
            match method {
                #(#dispatch_arms_sync)*
                #(#mount_dispatch_arms_sync)*
                _ => Err(format!("Method not found: {}", method)),
            }
        }
    };

    let struct_name_snake = struct_name.to_string().to_lowercase();
    let handler_name = format_ident!("__server_less_jsonrpc_handler_{}", struct_name_snake);

    // Generate dispatch signature and public API based on Context usage.
    // The private jsonrpc_dispatch returns Result<Value, (i32, String)> where
    // the i32 is the JSON-RPC error code, enabling per-error code propagation.
    let (
        dispatch_sig,
        dispatch_call,
        handle_sig,
        handle_single_sig,
        handle_single_call_batch,
        handle_single_call,
        handler_call,
        ctx_creation,
    ) = if uses_context {
        (
            quote! {
                async fn jsonrpc_dispatch(
                    &self,
                    __ctx: ::server_less::Context,
                    method: &str,
                    args: ::server_less::serde_json::Value,
                ) -> ::std::result::Result<::server_less::serde_json::Value, (i32, String)>
            },
            quote! { self.jsonrpc_dispatch(__ctx, method, params).await },
            quote! {
                pub async fn jsonrpc_handle_async(
                    &self,
                    __ctx: ::server_less::Context,
                    request: ::server_less::serde_json::Value,
                ) -> ::server_less::serde_json::Value
            },
            quote! {
                async fn jsonrpc_handle_single(
                    &self,
                    __ctx: ::server_less::Context,
                    request: ::server_less::serde_json::Value,
                ) -> Option<::server_less::serde_json::Value>
            },
            quote! { self.jsonrpc_handle_single(__ctx.clone(), req.clone()).await },
            quote! { self.jsonrpc_handle_single(__ctx, request).await },
            quote! { state.jsonrpc_handle_async(__ctx, request).await },
            quote! {},
        )
    } else {
        (
            quote! {
                async fn jsonrpc_dispatch(
                    &self,
                    method: &str,
                    args: ::server_less::serde_json::Value,
                ) -> ::std::result::Result<::server_less::serde_json::Value, (i32, String)>
            },
            quote! { self.jsonrpc_dispatch(method, params).await },
            quote! {
                pub async fn jsonrpc_handle_async(
                    &self,
                    request: ::server_less::serde_json::Value,
                ) -> ::server_less::serde_json::Value
            },
            quote! {
                async fn jsonrpc_handle_single(
                    &self,
                    request: ::server_less::serde_json::Value,
                ) -> Option<::server_less::serde_json::Value>
            },
            quote! { self.jsonrpc_handle_single(req.clone()).await },
            quote! { self.jsonrpc_handle_single(request).await },
            quote! { state.jsonrpc_handle_async(request).await },
            quote! { let __ctx = ::server_less::Context::new(); },
        )
    };

    let maybe_impl = if crate::is_protocol_impl_emitter(&impl_block, "jsonrpc") {
        quote! { #impl_block }
    } else {
        quote! {}
    };

    Ok(quote! {
        #maybe_impl

        impl #impl_generics ::server_less::JsonRpcMount for #self_ty #where_clause {
            fn jsonrpc_mount_methods() -> Vec<String> {
                Self::jsonrpc_methods()
            }

            fn jsonrpc_mount_dispatch(
                &self,
                method: &str,
                params: ::server_less::serde_json::Value,
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                self.jsonrpc_mount_dispatch_sync_inner(method, params)
            }

            async fn jsonrpc_mount_dispatch_async(
                &self,
                method: &str,
                params: ::server_less::serde_json::Value,
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                self.jsonrpc_mount_dispatch_inner(method, params).await
            }
        }

        impl #impl_generics #self_ty #where_clause {
            #[doc = #jsonrpc_methods_doc]
            pub fn jsonrpc_methods() -> Vec<String> {
                let mut names: Vec<String> = Vec::new();
                #(#method_name_stmts)*
                #(#mount_method_names)*
                names
            }

            /// Handle a JSON-RPC 2.0 request
            #handle_sig {
                #ctx_creation
                if let Some(arr) = request.as_array() {
                    let mut responses = Vec::new();
                    for req in arr {
                        if let Some(resp) = #handle_single_call_batch {
                            responses.push(resp);
                        }
                    }
                    if responses.is_empty() {
                        ::server_less::serde_json::Value::Null
                    } else {
                        ::server_less::serde_json::Value::Array(responses)
                    }
                } else {
                    #handle_single_call
                        .unwrap_or(::server_less::serde_json::Value::Null)
                }
            }

            #handle_single_sig {
                let id = request.get("id").cloned();
                let is_notification = id.is_none();

                let version = request.get("jsonrpc").and_then(|v| v.as_str());
                if version != Some("2.0") {
                    if is_notification {
                        return None;
                    }
                    return Some(Self::jsonrpc_error(-32600, "Invalid Request: missing jsonrpc 2.0", id));
                }

                let method = match request.get("method").and_then(|v| v.as_str()) {
                    Some(m) => m,
                    None => {
                        if is_notification {
                            return None;
                        }
                        return Some(Self::jsonrpc_error(-32600, "Invalid Request: missing method", id));
                    }
                };

                let params = request.get("params")
                    .cloned()
                    .unwrap_or(::server_less::serde_json::json!({}));

                let result = #dispatch_call;

                if is_notification {
                    return None;
                }

                Some(match result {
                    Ok(value) => {
                        ::server_less::serde_json::json!({
                            "jsonrpc": "2.0",
                            "result": value,
                            "id": id
                        })
                    }
                    Err((code, err)) => Self::jsonrpc_error(code, &err, id),
                })
            }

            fn jsonrpc_error(
                code: i32,
                message: &str,
                id: Option<::server_less::serde_json::Value>,
            ) -> ::server_less::serde_json::Value {
                ::server_less::serde_json::json!({
                    "jsonrpc": "2.0",
                    "error": {
                        "code": code,
                        "message": message
                    },
                    "id": id
                })
            }

            #dispatch_sig {
                match method {
                    #(#dispatch_arms_async)*
                    #(#mount_dispatch_arms)*
                    _ => Err((-32601i32, format!("Method not found: {}", method))),
                }
            }

            #mount_dispatch_sync_inner

            #mount_dispatch_inner

            #[doc = #jsonrpc_router_doc]
            pub fn jsonrpc_router(self) -> ::server_less::axum::Router
            where
                Self: Clone + Send + Sync + 'static,
            {
                let state = ::std::sync::Arc::new(self);
                ::server_less::axum::Router::new()
                    .route(#path, ::server_less::axum::routing::post(#handler_name))
                    .with_state(state)
            }

            /// Get OpenAPI paths for this JSON-RPC service (for composition with OpenApiBuilder)
            ///
            /// Returns a single POST endpoint for the JSON-RPC interface.
            pub fn jsonrpc_openapi_paths() -> ::std::vec::Vec<::server_less::OpenApiPath> {
                let methods: Vec<&str> = vec![#(#method_names),*];
                let methods_desc = methods.join(", ");

                vec![
                    ::server_less::OpenApiPath {
                        path: #path.to_string(),
                        method: "post".to_string(),
                        operation: ::server_less::OpenApiOperation {
                            summary: Some(format!("JSON-RPC 2.0 endpoint (methods: {})", methods_desc)),
                            description: None,
                            operation_id: Some("jsonrpc".to_string()),
                            tags: vec!["jsonrpc".to_string()],
                            deprecated: false,
                            parameters: vec![],
                            request_body: Some(::server_less::serde_json::json!({
                                "required": true,
                                "content": {
                                    "application/json": {
                                        "schema": {
                                            "type": "object",
                                            "required": ["jsonrpc", "method"],
                                            "properties": {
                                                "jsonrpc": {
                                                    "type": "string",
                                                    "enum": ["2.0"]
                                                },
                                                "method": {
                                                    "type": "string",
                                                    "enum": methods
                                                },
                                                "params": {
                                                    "type": "object"
                                                },
                                                "id": {
                                                    "oneOf": [
                                                        {"type": "string"},
                                                        {"type": "integer"},
                                                        {"type": "null"}
                                                    ]
                                                }
                                            }
                                        }
                                    }
                                }
                            })),
                            responses: {
                                let mut r = ::server_less::serde_json::Map::new();
                                r.insert("200".to_string(), ::server_less::serde_json::json!({
                                    "description": "JSON-RPC response",
                                    "content": {
                                        "application/json": {
                                            "schema": {
                                                "type": "object",
                                                "properties": {
                                                    "jsonrpc": {"type": "string"},
                                                    "result": {},
                                                    "error": {
                                                        "type": "object",
                                                        "properties": {
                                                            "code": {"type": "integer"},
                                                            "message": {"type": "string"}
                                                        }
                                                    },
                                                    "id": {}
                                                }
                                            }
                                        }
                                    }
                                }));
                                r.insert("204".to_string(), ::server_less::serde_json::json!({
                                    "description": "Notification (no response)"
                                }));
                                r
                            },
                            extra: ::server_less::serde_json::Map::new(),
                        },
                    }
                ]
            }
        }

        async fn #handler_name(
            ::server_less::axum::extract::State(state): ::server_less::axum::extract::State<::std::sync::Arc<#self_ty>>,
            __context_headers: ::server_less::axum::http::HeaderMap,
            ::server_less::axum::Json(request): ::server_less::axum::Json<::server_less::serde_json::Value>,
        ) -> impl ::server_less::axum::response::IntoResponse {
            use ::server_less::axum::response::IntoResponse;

            // Extract Context from headers
            let mut __ctx = ::server_less::Context::new();
            for (name, value) in __context_headers.iter() {
                if let Ok(value_str) = value.to_str() {
                    __ctx.set(name.as_str(), value_str);
                }
            }
            if let Some(request_id) = __context_headers.get("x-request-id")
                .and_then(|v| v.to_str().ok())
            {
                __ctx.set_request_id(request_id);
            }

            let response = #handler_call;
            if response.is_null() {
                ::server_less::axum::http::StatusCode::NO_CONTENT.into_response()
            } else {
                ::server_less::axum::Json(response).into_response()
            }
        }
    })
}

/// Generate response handling for the private `jsonrpc_dispatch` method.
///
/// Unlike `server_less_rpc::generate_json_response`, this produces
/// `Result<Value, (i32, String)>` so that the JSON-RPC error code is preserved.
/// For `Result<T, E: IntoErrorCode>` returns, the code is taken from
/// `IntoErrorCode::jsonrpc_code()`. For other returns, `-32603` (internal error)
/// is used as the fallback.
fn generate_jsonrpc_json_response(method: &MethodInfo) -> TokenStream2 {
    let ret = &method.return_info;

    if ret.is_unit {
        quote! {
            Ok(::server_less::serde_json::json!({"success": true}))
        }
    } else if ret.is_stream {
        quote! {
            {
                use ::server_less::futures::StreamExt;
                let collected: Vec<_> = result.collect().await;
                Ok(::server_less::serde_json::to_value(collected)
                    .map_err(|e| (-32603i32, format!("Serialization error: {}", e)))
                    .map_err(|e| e)?)
            }
        }
    } else if ret.is_iterator {
        // Collect iterator into Vec before serializing (Iterator doesn't implement Serialize)
        quote! {
            {
                let __collected: Vec<_> = result.collect();
                ::server_less::serde_json::to_value(&__collected)
                    .map(Ok)
                    .map_err(|e| Err((-32603i32, format!("Serialization error: {}", e))))
                    .unwrap_or_else(|e| e)
            }
        }
    } else if ret.is_result {
        quote! {
            match result {
                Ok(value) => ::server_less::serde_json::to_value(value)
                    .map(Ok)
                    .map_err(|e| Err((-32603i32, format!("Serialization error: {}", e))))
                    .unwrap_or_else(|e| e),
                Err(err) => {
                    let __code = ::server_less::IntoErrorCode::jsonrpc_code(&err);
                    let __msg = ::server_less::IntoErrorCode::message(&err);
                    Err((__code, __msg))
                }
            }
        }
    } else if ret.is_option {
        quote! {
            match result {
                Some(value) => ::server_less::serde_json::to_value(value)
                    .map(Ok)
                    .map_err(|e| Err((-32603i32, format!("Serialization error: {}", e))))
                    .unwrap_or_else(|e| e),
                None => Ok(::server_less::serde_json::Value::Null),
            }
        }
    } else {
        quote! {
            ::server_less::serde_json::to_value(result)
                .map(Ok)
                .map_err(|e| Err((-32603i32, format!("Serialization error: {}", e))))
                .unwrap_or_else(|e| e)
        }
    }
}

/// Generate jsonrpc-specific param extraction that produces `(i32, String)` errors.
///
/// Like `server_less_rpc::generate_param_extraction` but maps errors to `(i32, String)`
/// suitable for use in `jsonrpc_dispatch` which returns `Result<Value, (i32, String)>`.
fn generate_jsonrpc_param_extraction(param: &server_less_parse::ParamInfo) -> TokenStream2 {
    let name = &param.name;
    let name_str = param.name_str();
    let ty = &param.ty;

    if param.is_optional {
        // Extract inner type from Option<T> for error message
        let inner_ty: syn::Type = if let syn::Type::Path(ref type_path) = *ty {
            if let Some(seg) = type_path.path.segments.last() {
                if seg.ident == "Option" {
                    if let syn::PathArguments::AngleBracketed(ref args) = seg.arguments {
                        if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
                            inner.clone()
                        } else {
                            ty.clone()
                        }
                    } else {
                        ty.clone()
                    }
                } else {
                    ty.clone()
                }
            } else {
                ty.clone()
            }
        } else {
            ty.clone()
        };
        let inner_ty_str = quote::quote!(#inner_ty).to_string().replace(" ", "");
        quote! {
            let #name: #ty = match args.get(#name_str) {
                None => None,
                Some(__v) if __v.is_null() => None,
                Some(__v) => match ::server_less::serde_json::from_value(__v.clone()) {
                    Ok(__val) => Some(__val),
                    Err(__e) => return Err((-32602i32, format!(
                        "Optional parameter '{}' has invalid type (expected {}): {}", #name_str, #inner_ty_str, __e
                    ))),
                },
            };
        }
    } else {
        let ty_str = quote::quote!(#ty).to_string().replace(" ", "");
        quote! {
            let __val = args.get(#name_str)
                .ok_or_else(|| (-32602i32, format!("Missing required parameter: {} (expected {})", #name_str, #ty_str)))?
                .clone();
            let #name: #ty = ::server_less::serde_json::from_value::<#ty>(__val)
                .map_err(|e| (-32602i32, format!("Invalid parameter {} (expected {}): {}", #name_str, #ty_str, e)))?;
        }
    }
}

/// Generate a sync dispatch arm for the mount trait's sync inner dispatch.
///
/// Returns `Err` for async-only methods, mirroring the WsMount sync pattern.
fn generate_sync_dispatch_arm(
    method: &MethodInfo,
) -> syn::Result<TokenStream2> {
    let method_name_str = method.wire_name_or(|n| n);

    // Partition Context vs regular parameters
    let (context_param, regular_params) = partition_context_params(&method.params)?;

    // If no Context, use default RPC dispatch with AsyncHandling::Error
    if context_param.is_none() {
        return Ok(server_less_rpc::generate_dispatch_arm(
            method,
            None,
            AsyncHandling::Error,
        ));
    }

    // For Context methods: extract regular params but inject a fresh Context
    let param_extractions = server_less_rpc::generate_param_extractions_for(&regular_params);
    let unknown_warn =
        server_less_rpc::generate_unknown_param_warning(&method_name_str, &regular_params);

    let mut arg_exprs = Vec::new();
    for param in &method.params {
        if crate::context::should_inject_context(&param.ty, &method.params) {
            arg_exprs.push(quote! { ::server_less::Context::new() });
        } else {
            let name = &param.name;
            arg_exprs.push(quote! { #name });
        }
    }

    let call =
        server_less_rpc::generate_method_call_with_args(method, arg_exprs, AsyncHandling::Error);
    let response = server_less_rpc::generate_json_response(method);

    Ok(quote! {
        #method_name_str => {
            #unknown_warn
            #(#param_extractions)*
            #call
            #response
        }
    })
}

/// Generate an async dispatch arm for the private `jsonrpc_dispatch` method.
///
/// Returns `Result<Value, (i32, String)>` arms so that JSON-RPC error codes
/// are propagated from `IntoErrorCode` implementations.
fn generate_dispatch_arm(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let method_name_str = method.wire_name_or(|n| n);

    // Partition Context vs regular parameters
    let (context_param, regular_params) = partition_context_params(&method.params)?;

    let response = generate_jsonrpc_json_response(method);

    if context_param.is_none() {
        // No Context injection: generate jsonrpc-specific param extractions and call directly
        let param_extractions: Vec<_> = method
            .params
            .iter()
            .map(generate_jsonrpc_param_extraction)
            .collect();
        let all_param_refs: Vec<&server_less_parse::ParamInfo> = method.params.iter().collect();
        let unknown_warn =
            server_less_rpc::generate_unknown_param_warning(&method_name_str, &all_param_refs);
        let call = server_less_rpc::generate_method_call(method, AsyncHandling::Await);
        return Ok(quote! {
            #method_name_str => {
                #unknown_warn
                #(#param_extractions)*
                #call
                #response
            }
        });
    }

    // Generate extractions only for regular params (Context is already in scope as __ctx)
    let param_extractions: Vec<_> = regular_params
        .iter()
        .map(|p| generate_jsonrpc_param_extraction(p))
        .collect();
    let unknown_warn =
        server_less_rpc::generate_unknown_param_warning(&method_name_str, &regular_params);

    // Build argument list: Context first (if present), then regular params in order
    let mut arg_exprs = Vec::new();
    for param in &method.params {
        if crate::context::should_inject_context(&param.ty, &method.params) {
            arg_exprs.push(quote! { __ctx.clone() });
        } else {
            let name = &param.name;
            arg_exprs.push(quote! { #name });
        }
    }

    let call =
        server_less_rpc::generate_method_call_with_args(method, arg_exprs, AsyncHandling::Await);

    Ok(quote! {
        #method_name_str => {
            #unknown_warn
            #(#param_extractions)*
            #call
            #response
        }
    })
}

/// Generate mount method names contribution for jsonrpc_methods().
fn generate_mount_method_names(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}.", mount_name);
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(quote! {
        {
            let child_methods = <#inner_ty as ::server_less::JsonRpcMount>::jsonrpc_mount_methods();
            for child_name in child_methods {
                let prefixed = format!("{}{}", #mount_prefix, child_name);
                names.push(prefixed);
            }
        }
    })
}

/// Generate dispatch for a static mount (`fn foo(&self) -> &T`) — async version.
///
/// Maps the `Result<Value, String>` from `jsonrpc_mount_dispatch_async` into
/// `Result<Value, (i32, String)>` to match the private `jsonrpc_dispatch` return type.
fn generate_static_mount_dispatch(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}.", mount_name);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(quote! {
        __method if __method.starts_with(#mount_prefix) => {
            let __stripped = &__method[#mount_prefix.len()..];
            let __delegate = self.#method_name();
            <#inner_ty as ::server_less::JsonRpcMount>::jsonrpc_mount_dispatch_async(__delegate, __stripped, args).await
                .map_err(|msg| (-32603i32, msg))
        }
    })
}

/// Generate dispatch for a static mount (`fn foo(&self) -> &T`) — sync version.
fn generate_static_mount_dispatch_sync(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}.", mount_name);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(quote! {
        __method if __method.starts_with(#mount_prefix) => {
            let __stripped = &__method[#mount_prefix.len()..];
            let __delegate = self.#method_name();
            <#inner_ty as ::server_less::JsonRpcMount>::jsonrpc_mount_dispatch(__delegate, __stripped, args)
        }
    })
}

/// Generate dispatch for a slug mount (`fn foo(&self, id: Id) -> &T`) — async version.
///
/// Maps the `Result<Value, String>` from `jsonrpc_mount_dispatch_async` into
/// `Result<Value, (i32, String)>` to match the private `jsonrpc_dispatch` return type.
fn generate_slug_mount_dispatch(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}.", mount_name);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    // Use jsonrpc-specific param extraction so errors produce (i32, String)
    let slug_extractions: Vec<_> = method
        .params
        .iter()
        .map(generate_jsonrpc_param_extraction)
        .collect();
    let slug_names: Vec<_> = method.params.iter().map(|p| &p.name).collect();

    Ok(quote! {
        __method if __method.starts_with(#mount_prefix) => {
            let __stripped = &__method[#mount_prefix.len()..];
            #(#slug_extractions)*
            let __delegate = self.#method_name(#(#slug_names),*);
            <#inner_ty as ::server_less::JsonRpcMount>::jsonrpc_mount_dispatch_async(__delegate, __stripped, args).await
                .map_err(|msg| (-32603i32, msg))
        }
    })
}

/// Generate dispatch for a slug mount (`fn foo(&self, id: Id) -> &T`) — sync version.
fn generate_slug_mount_dispatch_sync(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}.", mount_name);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    let slug_extractions: Vec<_> = method
        .params
        .iter()
        .map(server_less_rpc::generate_param_extraction)
        .collect();
    let slug_names: Vec<_> = method.params.iter().map(|p| &p.name).collect();

    Ok(quote! {
        __method if __method.starts_with(#mount_prefix) => {
            let __stripped = &__method[#mount_prefix.len()..];
            #(#slug_extractions)*
            let __delegate = self.#method_name(#(#slug_names),*);
            <#inner_ty as ::server_less::JsonRpcMount>::jsonrpc_mount_dispatch(__delegate, __stripped, args)
        }
    })
}