plexus-macros 0.8.1

Procedural macros for Plexus RPC activations
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
//! # plexus-macros
//!
//! Procedural macros for **Plexus RPC** activations. Your Rust function
//! signature IS the schema — the macros extract method names, parameter
//! types, return types, doc comments, deprecation metadata, child routing,
//! and typed request extraction from the source.
//!
//! See the crate-level [`README`](https://github.com/hypermemetic/plexus-macros/blob/main/README.md)
//! for a comprehensive example covering every option, a deep-dive on
//! request forwarding (`PlexusRequest` + `request = ...`), and a
//! per-macro reference.
//!
//! # Quick example
//!
//! ```ignore
//! use futures::Stream;
//! use async_stream::stream;
//! use plexus_macros::PlexusRequest;
//!
//! #[derive(PlexusRequest)]
//! pub struct BashRequest {
//!     #[from_cookie("access_token")]
//!     auth_token: String,
//! }
//!
//! pub struct Bash;
//!
//! #[plexus_macros::activation(            // namespace "bash", implicitly
//!     version = "1.0.0",
//!     description = "Execute bash commands and stream output",
//!     request = BashRequest,
//! )]
//! impl Bash {
//!     /// Execute a bash command and stream output.
//!     #[plexus_macros::method]
//!     async fn execute(
//!         &self,
//!         command: String,
//!         #[activation_param] auth_token: String,
//!     ) -> impl Stream<Item = String> + Send + 'static {
//!         let _ = (command, auth_token);
//!         stream! { yield "ok".into(); }
//!     }
//! }
//! ```
//!
//! # Macros at a glance
//!
//! | Macro | Purpose |
//! |---|---|
//! | `#[plexus_macros::activation]` | Turn an `impl` block into a Plexus RPC activation — and, with `client`, emit its typed client. |
//! | `#[plexus_macros::method]` | Mark a method as an RPC endpoint. |
//! | `#[plexus_macros::child]` | Register a child activation for `ChildRouter` dispatch. |
//! | `#[plexus_macros::removed_in]` | Companion to `#[deprecated]` carrying the removal version. |
//! | `#[derive(PlexusRequest)]` | Typed extraction from `RawRequestContext`. |
//! | `#[derive(HandleEnum)]` | Type-safe handle enums for an activation. |
//! | `#[derive(plexus_macros::Deserialize)]` | An internally tagged event's `Deserialize`, its `type` read first (serde's `Deserialize` otherwise). |
//!
//! # A method's return type is its contract (0.7)
//!
//! | signature | cardinality | schema `returns` / `error` / `progress` |
//! |---|---|---|
//! | `-> T` | one | T / — / — |
//! | `-> Result<T, E>` | one | T / E / — |
//! | `-> impl Stream<Item = T>` | many | T / — / — |
//! | `-> impl Stream<Item = Result<T, E>>` | many | T / E / — |
//! | `-> impl Stream<Item = Progress<T, P>>` | many | T / — / P |
//! | `-> impl Stream<Item = Result<Progress<T, P>, E>>` | many | T / E / P |
//!
//! A Result item travels as data, `{"ok": t}` or `{"err": e}`; a
//! `Progress::Update(p)` as a progress frame. The namespace is the stem of
//! `impl FooActivation` (MACRO-13; `namespace = "..."` overrides it).
//! `#[method(returns(..))]` and `#[derive(StreamEvent)]` are gone, and
//! `#[method(streaming)]` is a deprecated no-op on a stream form. See the
//! README's per-macro reference.
//!
//! Deprecated surfaces still accepted: `#[hub_methods]`, `#[hub_method]`, the
//! `hub` and `children = [...]` flags on `#[activation]`. See the migration
//! section of the README.
//!
//! ## Crate version (UMB-2)
//!
//! This crate is `proc-macro = true`, which means it can only export macro
//! attributes — `pub const VERSION` etc. are forbidden by the compiler. The
//! `plexus-rpc` umbrella reads `plexus-macros`'s version via a build-time
//! environment variable populated from `Cargo.toml`'s dependency pin
//! (see `plexus-rpc/build.rs`).

mod codegen;
mod credential;
mod handle_enum;
mod parse;
mod request;
mod type_first;


use codegen::generate_all;
use parse::HubMethodsAttrs;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, punctuated::Punctuated, Expr, ExprLit, FnArg, ItemFn, ItemImpl, Lit, Meta,
    MetaNameValue, Pat, ReturnType, Token, Type,
};

/// Parsed attributes for hub_method (standalone version)
struct HubMethodAttrs {
    name: Option<String>,
    /// Explicit description from `description = "..."`. When `Some`, this wins over
    /// `///` doc comments. When `None`, doc comments are used as the default.
    description: Option<String>,
    /// Base crate path for imports (default: "crate")
    crate_path: String,
}

impl Parse for HubMethodAttrs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut name = None;
        let mut description: Option<String> = None;
        let mut crate_path = "crate".to_string();

        if !input.is_empty() {
            let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;

            for meta in metas {
                // RETURNS-8: the removed attributes fail here too, not only
                // inside `#[activation]`.
                match &meta {
                    Meta::List(list) if list.path.is_ident("returns") => {
                        return Err(syn::Error::new_spanned(&list.path, parse::RETURNS_REMOVED));
                    }
                    _ => {}
                }
                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
                    if path.is_ident("name") {
                        if let Expr::Lit(ExprLit {
                            lit: Lit::Str(s), ..
                        }) = value
                        {
                            name = Some(s.value());
                        }
                    } else if path.is_ident("description") {
                        if let Expr::Lit(ExprLit {
                            lit: Lit::Str(s), ..
                        }) = value
                        {
                            description = Some(s.value());
                        }
                    } else if path.is_ident("crate_path") {
                        if let Expr::Lit(ExprLit {
                            lit: Lit::Str(s), ..
                        }) = value
                        {
                            crate_path = s.value();
                        }
                    }
                }
            }
        }

        Ok(HubMethodAttrs { name, description, crate_path })
    }
}

/// Attribute macro for individual methods within a `#[plexus::activation]` impl block.
///
/// # Example
///
/// ```ignore
/// #[plexus::activation]                    // namespace "bash", implicitly
/// impl Bash {
///     /// Execute a bash command
///     #[plexus::method]
///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> {
///         // ...
///     }
/// }
/// ```
///
/// # The return type is the contract (RETURNS-8)
///
/// Six forms: `-> T`, `-> Result<T, E>`, `-> impl Stream<Item = T>`,
/// `-> impl Stream<Item = Result<T, E>>`, `-> impl Stream<Item = Progress<T,
/// P>>`, `-> impl Stream<Item = Result<Progress<T, P>, E>>`. A plain return
/// yields one item, `impl Stream` many; `Result` and `Progress` are
/// recognised by name. Any other return type is a compile error that lists
/// the six. `returns(..)` is removed (a compile error); `streaming` is a
/// deprecated no-op on a stream form and an error on a one-item one.
///
/// # Authorization arguments (R-1 / AUTHZ-CORE-2)
///
/// - `scope = "..."` — explicit required scope, emitted into the generated
///   `MethodSchema.requires_credential`. Repeatable: `scope = "x.y",
///   scope = "x.z"` means the caller must satisfy **ALL** listed scopes
///   (conjunction — AND, not OR). Literals are validated at compile time
///   against the AUTHZ-CORE-4 scope grammar (dot-separated `[a-z][a-z0-9_]*`
///   segments, optional trailing `.*` segment wildcard, or bare `*`).
/// - `input_window = N` (BIDIR-6) — on a method with an `Input<T>` parameter,
///   the credit it grants (default 64). `input_max_buffered = N`: the bytes
///   held past which it grants no credit until drained (default 64 MiB). `input_max_items = N`,
///   `input_max_bytes = N`: limits over the call's life, none unless given.
///   An `Input<T>` is at most one, top-level, and not one of the params:
///   `MethodSchema.input` is `T`'s schema, and the client takes a stream.
/// - `public` — the method is exempt from the default-deny gate; emitted as
///   `MethodSchema.public = true`. Mixing `public` with `scope = "..."` is a
///   compile error (a public method has no required scope to enforce).
/// - Neither — the implicit `<activation>.<method>` scope rule applies at
///   registry-build time (AUTHZ-CORE-4); the schema carries no
///   `requires_credential` for the implicit case.
#[proc_macro_attribute]
pub fn method(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as HubMethodAttrs);
    let input_fn = parse_macro_input!(item as ItemFn);

    match hub_method_impl(args, input_fn) {
        Ok(tokens) => tokens.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// Deprecated: use `plexus::method` instead.
#[deprecated(since = "0.5.0", note = "Use `plexus::method` instead")]
#[proc_macro_attribute]
pub fn hub_method(attr: TokenStream, item: TokenStream) -> TokenStream {
    method(attr, item)
}

/// Attribute macro for individual **child** methods within a
/// `#[plexus_macros::activation]` impl block.
///
/// Two method shapes are accepted:
///
/// | Shape | Role | Example |
/// |---|---|---|
/// | `fn NAME(&self) -> Child` (no args) | Static child — routing name is the method name | `fn mercury(&self) -> Mercury` |
/// | `fn NAME(&self, name: &str) -> Option<Child>` (sync or async) | Dynamic fallback dispatcher | `fn planet(&self, name: &str) -> Option<Planet>` |
///
/// The enclosing `#[plexus_macros::activation]` macro collects all `#[child]`
/// methods and generates a `ChildRouter` impl whose `get_child(name)`
/// dispatches over them. `#[child]` methods are **not** exposed as Plexus RPC
/// methods — they contribute only to `ChildRouter` routing.
///
/// # Example
///
/// ```ignore
/// #[plexus_macros::activation(namespace = "solar")]
/// impl Solar {
///     #[plexus_macros::child]
///     fn mercury(&self) -> Mercury { self.mercury.clone() }
///
///     #[plexus_macros::child]
///     async fn planet(&self, name: &str) -> Option<Planet> {
///         self.lookup_planet(name).await
///     }
/// }
/// ```
///
/// # How the child inherits its caller (MACRO-20)
///
/// `forward = "same_service" | "identity_only" | "pass_through" | "anonymous"`
/// picks the policy the emitted `ChildRouter::forward_policy_for` hands
/// the child. A static child defaults to `same_service`: the same service as
/// its parent, it keeps the caller whole (principal stamp, session,
/// ceiling). Write `#[plexus_macros::child(forward = "identity_only")]` for a
/// deputy that must not see the caller's session. A dynamic child keeps the
/// framework default (`IdentityOnly`) unless it names one.
///
/// Used standalone (outside an `#[activation]` block) this attribute is a
/// no-op that returns the function unchanged.
#[proc_macro_attribute]
pub fn child(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // Outside of #[plexus_macros::activation] this attribute does nothing;
    // the activation macro strips it and collects the method into the
    // generated ChildRouter impl.
    item
}

/// Companion attribute to Rust's built-in `#[deprecated]` for carrying a
/// `removed_in = "VERSION"` hint that rustc doesn't recognize.
///
/// Rust's `#[deprecated(since = "X", note = "Y")]` supports only `since` and
/// `note`. This companion attribute supplies the removal version that the
/// `plexus-macros` codegen folds into the method's `DeprecationInfo.removed_in`
/// field on the emitted `MethodSchema`.
///
/// # Example
///
/// ```ignore
/// #[deprecated(since = "0.5", note = "use `new_method` instead")]
/// #[plexus_macros::removed_in("0.6")]
/// #[plexus_macros::method]
/// async fn legacy(&self) -> impl Stream<Item = String> + Send + 'static {
///     // ...
/// }
/// ```
///
/// # Requirements
///
/// `#[plexus_macros::removed_in]` is only meaningful when paired with
/// `#[deprecated]`. The `#[plexus_macros::activation]` macro emits a compile
/// error when it encounters `#[removed_in]` on a method that doesn't also
/// carry `#[deprecated]`.
///
/// As a standalone attribute (outside an `#[activation]` block) this is a
/// no-op that returns the item unchanged — the activation macro parses and
/// strips it during codegen.
#[proc_macro_attribute]
pub fn removed_in(attr: TokenStream, item: TokenStream) -> TokenStream {
    // When `#[plexus_macros::removed_in("X")]` is placed OUTSIDE
    // `#[plexus_macros::activation(...)]` on the same impl block, the
    // `removed_in` proc macro runs BEFORE the activation macro (outer
    // attrs expand first), so a naive no-op implementation would consume
    // the attribute before the activation macro ever sees it.
    //
    // Workaround: emit a synthetic `#[doc(hidden)]` marker attribute on
    // the item's attr list that encodes the removed_in value. The
    // activation / method codegen scans for this marker as an equivalent
    // signal to the companion attribute and uses it to populate
    // `DeprecationInfo.removed_in`.
    //
    // Stable rustc treats `#[doc(hidden)]` as a regular doc attribute and
    // the sentinel payload rides along in the same literal string.
    let attr_str: String = match syn::parse::<syn::LitStr>(attr.clone()) {
        Ok(s) => s.value(),
        Err(_) => {
            // Not a bare string literal — just let the item pass through
            // and let the activation/method layer produce the proper error.
            return item;
        }
    };
    let marker = format!("__plexus_removed_in:{}", attr_str);
    let item_ts: proc_macro2::TokenStream = item.into();
    let marker_lit = proc_macro2::Literal::string(&marker);
    let out = quote::quote! {
        #[doc(hidden)]
        #[doc = #marker_lit]
        #item_ts
    };
    out.into()
}

fn hub_method_impl(args: HubMethodAttrs, input_fn: ItemFn) -> syn::Result<TokenStream2> {
    // Extract method name (from attr or function name)
    let method_name = args
        .name
        .unwrap_or_else(|| input_fn.sig.ident.to_string());

    // Resolve description: explicit `description = "..."` wins over `///` doc
    // comments; if neither is present, description is the empty string.
    let description = match args.description {
        Some(explicit) => explicit,
        None => extract_doc_comment(&input_fn),
    };

    // Extract input type from first parameter (if any)
    let input_type = extract_input_type(&input_fn)?;

    // Extract return type
    let return_type = extract_return_type(&input_fn)?;

    // Function name for the schema function
    let fn_name = &input_fn.sig.ident;
    let schema_fn_name = format_ident!("{}_schema", fn_name);

    // Parse crate path
    let crate_path: syn::Path = syn::parse_str(&args.crate_path)
        .map_err(|e| syn::Error::new_spanned(&input_fn.sig, format!("Invalid crate_path: {}", e)))?;

    // Generate the schema function
    let schema_fn = generate_schema_fn(
        &schema_fn_name,
        &method_name,
        &description,
        input_type.as_ref(),
        &return_type,
        &crate_path,
    );

    // Return the original function plus the schema function
    Ok(quote! {
        #input_fn

        #schema_fn
    })
}

fn extract_doc_comment(input_fn: &ItemFn) -> String {
    // Delegate to the shared helper so the standalone `#[method]` macro path
    // follows the same doc-comment extraction rule as the in-activation path:
    // lines joined with '\n', common leading whitespace stripped.
    parse::extract_doc_description(&input_fn.attrs).unwrap_or_default()
}

fn extract_input_type(input_fn: &ItemFn) -> syn::Result<Option<Type>> {
    // Skip self parameter, get first real parameter
    for arg in &input_fn.sig.inputs {
        match arg {
            FnArg::Receiver(_) => continue, // Skip &self
            FnArg::Typed(pat_type) => {
                // Skip context-like parameters
                if let Pat::Ident(ident) = &*pat_type.pat {
                    let name = ident.ident.to_string();
                    if name == "ctx" || name == "context" || name == "self_" {
                        continue;
                    }
                }
                return Ok(Some((*pat_type.ty).clone()));
            }
        }
    }

    Ok(None)
}

fn extract_return_type(input_fn: &ItemFn) -> syn::Result<Type> {
    match &input_fn.sig.output {
        ReturnType::Default => Err(syn::Error::new_spanned(
            &input_fn.sig,
            "hub_method requires a return type",
        )),
        ReturnType::Type(_, ty) => Ok((*ty.clone()).clone()),
    }
}

fn generate_schema_fn(
    fn_name: &syn::Ident,
    method_name: &str,
    description: &str,
    input_type: Option<&Type>,
    return_type: &Type,
    crate_path: &syn::Path,
) -> TokenStream2 {
    // Z2H-2: the standalone `#[method]` macro has no activation-level shim
    // module, so resolve the dep roots absolutely: through the plexus-rpc
    // umbrella's `__deps` re-exports when the consumer depends on it, or the
    // extern prelude (today's semantics) otherwise.
    let (serde_json_root, schemars_root) =
        match codegen::umbrella_crate(proc_macro2::Span::call_site()) {
            Some(umbrella) => (
                quote! { ::#umbrella::__deps::serde_json },
                quote! { ::#umbrella::__deps::schemars },
            ),
            None => (quote! { serde_json }, quote! { schemars }),
        };

    let input_schema = if let Some(input_ty) = input_type {
        quote! {
            Some(#serde_json_root::to_value(#schemars_root::schema_for!(#input_ty)).unwrap())
        }
    } else {
        quote! { None }
    };

    let _ = return_type; // Will be used for protocol schema in future
    let _ = crate_path;

    quote! {
        /// Generated schema function for this hub method
        #[allow(dead_code)]
        pub fn #fn_name() -> #serde_json_root::Value {
            #serde_json_root::json!({
                "name": #method_name,
                "description": #description,
                "input": #input_schema,
            })
        }
    }
}

/// Attribute macro for impl blocks defining a Plexus activation.
///
/// Generates:
/// - Method enum for schema extraction
/// - Activation trait implementation
/// - RPC server trait and implementation
///
/// # Attributes
///
/// - `namespace = "..."` - The activation namespace (the name rule below
///   gives it from `impl FooActivation`)
/// - `version = "..."` (optional, default: "1.0.0") - Version string
/// - `description = "..."` (optional) - Activation description
/// - `crate_path = "..."` (optional, default: "crate") - Path to substrate crate
/// - `client` (optional flag) - also emit the typed client (MACRO-2, below)
/// - `server_cfg = "<cfg predicate>"` (optional) - compile the server half
///   only under that `cfg` (MACRO-2, below)
///
/// # Example
///
/// ```ignore
/// #[plexus::activation(namespace = "bash", version = "1.0.0", description = "Execute bash commands")]
/// impl Bash {
///     /// Execute a bash command and stream output
///     #[plexus::method]
///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> + Send + 'static {
///         self.executor.execute(&command).await
///     }
/// }
/// ```
///
/// # The typed client (`client`, `server_cfg`) — MACRO-2, 0.7 shapes RETURNS-9
///
/// The macro already knows, when it runs, every method's wire name, its
/// parameters and its precise contract (cardinality, item, error, progress).
/// With `client` it also emits a **typed client** for the activation, and the
/// activation's **aggregate** `{Ns}Event` (one variant per method, carrying
/// that method's item), so a Rust consumer never hand-writes a call site or
/// hand-mirrors an item type:
///
/// ```ignore
/// #[plexus_macros::activation(client)]                 // namespace "tickets", implicitly
/// impl Tickets { /* unchanged */ }
///
/// // emitted beside the impl: TicketsClient<T>, and TicketsEvent
/// let client = TicketsClient::new(transport);                      // any plexus_client::Transport
/// let health = client.health().await?;                             // one item: Health
/// match client.get("MNG-2".into()).await? { Ok(t) => .., Err(no) => .. }   // one, fallible
/// let rows: Vec<_> = client.list(None, None).try_collect().await?; // many: MethodStream
/// let mut s = client.import(src).with_progress();                  // Frame<item, P>
/// let mut ev = client.watch(None).events();                        // TicketsEvent
/// ```
///
/// `?` is the call failing (`ClientError::Remote(RemoteError)` for the
/// server's typed error frame); a match on the item is the activation's
/// answer. The client is generic over the transport, so the emitted code
/// names none of them; its parameter and item types are the activation's
/// own, so a change to either is a compile error in every consumer. A crate
/// that already defines a type named `{Ns}Event` renames it before turning
/// `client` on.
///
/// **Requires** the consuming crate to depend on `plexus-client`. A
/// proc-macro crate cannot check that for you at expansion time in general,
/// but the path is resolved through `proc-macro-crate`, so a missing
/// dependency is reported at the `client` flag rather than as an unresolved
/// import in code you did not write.
///
/// **`server_cfg = "..."`** puts the *server* half of the expansion — the
/// impl block, the method enum, the `Activation` impl, the jsonrpsee trait —
/// behind a `cfg`, while the client half stays unconditional. That is what
/// makes an activation crate reachable from `wasm32-unknown-unknown`:
///
/// ```ignore
/// // Cargo.toml: server deps are optional and behind `feature = "server"`.
/// // plexus-macros itself stays non-optional — a proc-macro crate is built
/// // for the host, so it costs a wasm32 build nothing.
/// #[plexus_macros::activation(
///     namespace = "tickets",
///     client,
///     server_cfg = "feature = \"server\"",
/// )]
/// impl Tickets { /* .. */ }
/// ```
///
/// A consumer then says one line — `tickets-api = { version = "..",
/// default-features = false }` — and gets the types and the client, with no
/// tokio, jsonrpsee or plexus-core anywhere in its tree. Gating your own
/// struct definition and server-only imports is still yours to do; the macro
/// only gates its own output.
///
/// Both flags are opt-in: an activation that names neither expands exactly
/// as it did before.
///
/// # `#[activation]` needs nothing — MACRO-13
///
/// On `impl FooActivation` the stem `Foo` names everything, every key is an
/// override, and the trait is always emitted (the owner's `always`):
///
/// ```ignore
/// /// A deploy driver.                      // the activation's description
/// #[plexus_macros::activation]
/// impl DriverActivation {
///     /// What this driver can do.          // the method's description
///     pub async fn describe(&self) -> impl Stream<Item = DriverEvent> + Send + 'static { .. }
///     pub fn new() -> Self { .. }           // not async: a plain method
///     async fn helper(&self) -> u32 { .. }  // not pub: a plain method
/// }
/// // namespace "driver"; `pub trait Driver: Send + Sync + 'static` with
/// // `fn describe(&self) -> BoxStream<'static, DriverEvent>`;
/// // `impl Driver for DriverActivation`; `DriverClient<T>`, and
/// // `impl<T: Transport + Clone + Send + Sync + 'static> Driver for DriverClient<T>`.
/// ```
///
/// - **The name rule.** The namespace defaults to the stem in snake_case
///   (`TicketsApiActivation` → `tickets_api`); the client is `FooClient<T>`.
///   `trait = "Bar"` names the trait and the client (and, absent
///   `namespace`, the namespace `bar`) whatever the type is called. A type
///   not named `…Activation`, without `trait = "…"` or `namespace`, does not
///   compile.
/// - **The trait, always.** Each wire method is on it with the parameters a
///   caller passes. Each event type must implement
///   `plexus_client::FromClientError` when there is a client: the client's
///   implementation yields an `Err(ClientError)` as
///   `E::from_client_error(err)` and ends (`String` has it). The activation
///   implements its own trait by cloning itself into each stream (`register`
///   already asks for `Clone`) — unless a wire method takes what the server
///   injects (`auth`, `reach`, `#[from_auth]`, `#[activation_param]`, a
///   bidirectional `ctx`): then only the client implements it.
/// - **Every public method a wire method.** Every `pub async fn` on `&self`
///   returning `impl Stream<Item = E>` is on the wire with no `#[method]`
///   (which stays for its overrides); one returning anything else is a
///   compile error; `methods = marked` restores the `#[method]`-only rule.
/// - **The client without a flag**, whenever the crate depends on
///   `plexus-client`; `client` is accepted with a deprecation warning.
/// - **The `server` feature default.** A crate whose manifest declares a
///   `server` feature gets its server half under `#[cfg(feature =
///   "server")]`; `server_cfg` overrides. The trait and the client are never
///   gated.
/// - **A bodiless activation is a contract.** When every wire method is
///   bodiless (`pub async fn f(&self, ..) -> impl Stream<..>;`), the macro
///   emits `pub struct FooActivation<D: Foo>(Arc<D>)` delegating to `D`,
///   `impl<D: Foo> Foo for FooActivation<D>`, and `Foo::server(self)`:
///   `hub.register(Local::new().server())`, or
///   `hub.register(FooClient::new(transport).server())` for a proxy.
///
/// **Before the renames land.** An activation written before MACRO-13 — a
/// type not named `…Activation`, no `trait = "…"`, its `namespace` given —
/// expands exactly as it did (no trait; the client on the `client` flag;
/// only `#[method]`s on the wire) with a deprecation warning asking for the
/// rename. A later release refuses it.
#[proc_macro_attribute]
pub fn activation(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as HubMethodsAttrs);
    let input_impl = parse_macro_input!(item as ItemImpl);

    match generate_all(args, input_impl) {
        Ok(tokens) => tokens.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// Deprecated: use `plexus::activation` instead.
#[deprecated(since = "0.5.0", note = "Use `plexus::activation` instead")]
#[proc_macro_attribute]
pub fn hub_methods(attr: TokenStream, item: TokenStream) -> TokenStream {
    activation(attr, item)
}

/// Derive macro for declaring credential-bearing fields on a return-type
/// struct or enum (per `AUTHZ-CRED-MACRO-1`).
///
/// Apply `#[derive(Credentials)]` to a struct or enum. Within the item,
/// annotate each credential-bearing field with the helper attribute
/// `#[credential(kind = "...", attach_as = "...", ...)]` carrying the
/// per-field metadata. The field's type must be `Credential<T>` (the sealed
/// wrapper from `plexus_auth_core`); any other type produces a compile
/// error citing the wrapper requirement.
///
/// **Why a derive macro and not a freestanding attribute macro?** Stable Rust
/// proc-macros cannot intercept attribute macros applied directly to struct
/// fields; only derive-helper attributes can appear there. See
/// `plans/AUTHZ/AUTHZ-CRED-MACRO-1-RUN-NOTES.md` for the rationale.
///
/// # Example
///
/// ```ignore
/// use plexus_auth_core::{
///     AttachmentSite, Credential, CredentialKind, CredentialScheme,
///     HeaderName, MethodPath, Scope,
/// };
///
/// // `CredentialFieldMarker` lands in plexus-auth-core in a follow-up; for
/// // now the macro emits code that references it by name and consumers
/// // provide the definition (see run-notes).
///
/// #[derive(plexus_macros::Credentials, serde::Serialize)]
/// pub struct LoginEvent {
///     pub user_id: String,
///
///     #[credential(
///         kind = "bearer",
///         attach_as = "header:authorization",
///         scheme = "Bearer ",
///     )]
///     pub session: Credential<String>,
/// }
/// ```
///
/// # Clauses
///
/// | Clause | Required? | Notes |
/// |---|---|---|
/// | `kind = "<name>"` | required | Closed enum: `"bearer"`, `"cookie"`, `"oauth_access"`, `"oauth_refresh"`, `"oidc_id"`, `"aws_sts"`, `"macaroon"`. The escape valve `kind(other = "<name>")` carries a backend-specific kind. |
/// | `attach_as = "<spec>"` | required | One of `"header:<name>"`, `"cookie:<name>"`, `"first_frame:<setup-method>:<param>"`, `"in_rpc_param:<name>"`. |
/// | `scheme = "<prefix>"` | optional | E.g. `"Bearer "` (trailing space significant). |
/// | `scopes = ["a.b", ...]` | optional, default empty | List of scope identifiers. |
/// | `refresh_via = "<method-path>"` | optional | E.g. `"auth.refresh"`. |
/// | `revoke_via = "<method-path>"` | optional | E.g. `"auth.logout"`. |
/// | `sensitive` | optional flag | Accepted for clarity; credentials are always sensitive. |
///
/// # Emitted artifacts
///
/// The macro emits two free functions in the same module:
///
/// - `fn __plexus_credential_marker_for_<TypeIdent>() -> Vec<CredentialFieldMarker>`
/// - `fn __plexus_sensitive_fields_for_<TypeIdent>() -> Vec<(Option<&'static str>, &'static str)>`
///
/// The consumer (per `AUTHZ-CRED-CORE-3`) calls the first function during
/// schema build; the second mirrors the implicit `#[sensitive]` rule for the
/// redaction pipeline (per `AUTHZ-PRIVACY-2`).
///
/// The emitted code requires `CredentialFieldMarker`, `CredentialKind`,
/// `AttachmentSite`, `CredentialScheme`, `Scope`, `MethodPath`, `HeaderName`,
/// `CookieName`, `ParamName`, and `CredentialKindName` to be in scope at the
/// emission site. Importing `plexus_auth_core::*` (or the equivalent named
/// imports) at the top of the consuming module satisfies all but
/// `CredentialFieldMarker`, which lands in `plexus_auth_core` in a follow-up.
#[proc_macro_derive(Credentials, attributes(credential))]
pub fn credentials_derive(input: TokenStream) -> TokenStream {
    credential::expand_credentials_derive(input)
}

/// Derive macro for type-safe handle creation and parsing.
///
/// Generates:
/// - `to_handle(&self) -> Handle` - converts enum variant to Handle
/// - `impl TryFrom<&Handle>` - parses Handle back to enum variant
/// - `impl From<EnumName> for Handle` - convenience conversion
///
/// # Attributes
///
/// Enum-level (required):
/// - `plugin_id = "CONSTANT_NAME"` - Name of the constant holding the plugin UUID
/// - `version = "1.0.0"` - Semantic version for handles
/// - `crate_path = "..."` (optional, default: "plexus_core") - Path to plexus_core crate
/// - `plugin_id_type = "Type<Args>"` (optional) - Concrete type whose associated
///   constant `plugin_id` names. Use this when the owning activation is generic
///   (e.g. `Cone<P: HubContext = NoParent>`) to pin the instantiation and avoid
///   E0283 "cannot infer type" errors. Pairs with `plugin_id` — e.g.
///   `plugin_id = "Cone::PLUGIN_ID", plugin_id_type = "Cone<NoParent>"` emits
///   `<Cone<NoParent>>::PLUGIN_ID`.
///
/// Variant-level:
/// - `method = "..."` (required) - The handle.method value
/// - `table = "..."` (optional) - SQLite table name (for future resolution)
/// - `key = "..."` (optional) - Primary key column (for future resolution)
///
/// # Example
///
/// ```ignore
/// use hub_macro::HandleEnum;
/// use uuid::Uuid;
///
/// pub const MY_PLUGIN_ID: Uuid = uuid::uuid!("550e8400-e29b-41d4-a716-446655440000");
///
/// #[derive(HandleEnum)]
/// #[handle(plugin_id = "MY_PLUGIN_ID", version = "1.0.0")]
/// pub enum MyPluginHandle {
///     #[handle(method = "event", table = "events", key = "id")]
///     Event { event_id: String },
///
///     #[handle(method = "message")]
///     Message { message_id: String, role: String },
/// }
///
/// // Usage:
/// let handle_enum = MyPluginHandle::Event { event_id: "evt-123".into() };
/// let handle: Handle = handle_enum.to_handle();
/// // handle.method == "event"
/// // handle.meta == ["evt-123"]
///
/// // Parsing back:
/// let parsed = MyPluginHandle::try_from(&handle)?;
/// ```
#[proc_macro_derive(HandleEnum, attributes(handle))]
pub fn handle_enum_derive(input: TokenStream) -> TokenStream {
    handle_enum::derive(input)
}

/// PERF.115-43 · an internally tagged enum's `Deserialize`, its tag read
/// first: in place of serde's, on a house event.
///
/// serde reads an internally tagged enum (`#[serde(tag = "type")]`, every
/// event the house writes) whole into a private buffer before it reads the
/// tag, then reads the variant out of the buffer. Written in serde's place,
/// this derive reads the first key: when it is the tag, the variant is chosen
/// by the tag's value and its fields are read straight from the rest of the
/// object; when it is not, serde reads the object, buffer and all, as it
/// always has. plexus-core writes `type` first, so a client, a hop or a
/// service reading another's events reads them without the buffer.
///
/// ```ignore
/// #[derive(Debug, Clone, serde::Serialize, plexus_macros::Deserialize, schemars::JsonSchema)]
/// #[serde(tag = "type", rename_all = "snake_case")]
/// pub enum TicketsEvent {
///     Health { version: String, count: u64 },
///     Ready,
///     Error { message: String },
/// }
/// ```
///
/// Everything else about the enum is serde's: the derive has serde derive
/// it twice more beside it (`#[serde(remote = …)]`), once as written and
/// once without its tag, so every `#[serde]` attribute (`rename_all`,
/// `rename`, `alias`, `other`, `default`, `skip`, `with`, `flatten`,
/// `deny_unknown_fields`, `expecting`) is read by serde's own code. A struct
/// variant and a unit variant are read straight; a newtype variant, a struct
/// variant with a flattened field and a variant read `with` a function are
/// read by serde's buffered read. What serde refuses is refused in serde's
/// words. A value inside a variant is read by the deserializer itself, so a
/// value only the input can carry (a `RawValue`, a map keyed by numbers)
/// reaches a variant whose tag comes first.
///
/// It is for an internally tagged enum that is not generic, with no
/// untagged variant (one is tried on the whole object once the tagged ones
/// fail, which needs the buffer); anything else is a compile error that says
/// to derive serde's `Deserialize`. The runtime is plexus-client's
/// (`plexus_client::__rt::type_first`), so the deriving crate depends on
/// plexus-client, as every crate with a generated client does.
#[proc_macro_derive(Deserialize, attributes(serde))]
pub fn deserialize_derive(input: TokenStream) -> TokenStream {
    type_first::derive(input)
}

/// Derive macro for typed HTTP/WebSocket request extraction.
///
/// Generates `impl PlexusRequest` (extraction) and `impl schemars::JsonSchema`
/// (with `x-plexus-source` extensions) for the annotated struct.
///
/// # Field annotations
///
/// - `#[from_cookie("name")]` — extract from named cookie
/// - `#[from_header("name")]` — extract from named HTTP header
/// - `#[from_query("name")]` — extract from named URI query parameter
/// - `#[from_peer]` — copy `ctx.peer` (peer socket address)
/// - `#[from_auth_context]` — copy `ctx.auth` (auth context)
/// - (no annotation) — `Default::default()`
///
/// # Example
///
/// ```ignore
/// use plexus_macros::PlexusRequest;
///
/// #[derive(PlexusRequest)]
/// struct MyRequest {
///     #[from_cookie("access_token")]
///     auth_token: String,
///
///     #[from_header("origin")]
///     origin: Option<String>,
///
///     #[from_peer]
///     peer_addr: Option<std::net::SocketAddr>,
/// }
/// ```
#[proc_macro_derive(
    PlexusRequest,
    attributes(from_cookie, from_header, from_query, from_peer, from_auth_context)
)]
pub fn plexus_request_derive(input: TokenStream) -> TokenStream {
    request::derive(input)
}

/// No-op `JsonSchema` derive — used when plexus-macros is aliased as `schemars`
/// in dev-dependencies to prevent duplicate `impl JsonSchema` conflicts with
/// `#[derive(PlexusRequest)]` (which generates its own `impl JsonSchema`).
///
/// When plexus-macros is aliased as schemars in dev-deps:
/// ```toml
/// [dev-dependencies]
/// schemars = { path = "../plexus-macros", package = "plexus-macros", features = ["schemars-compat"] }
/// ```
/// then `#[derive(schemars::JsonSchema)]` invokes THIS derive instead of the real schemars derive,
/// producing no output, so only `PlexusRequest`'s `impl JsonSchema` exists.
#[cfg(feature = "schemars-compat")]
#[proc_macro_derive(JsonSchema, attributes(schemars, serde))]
pub fn json_schema_noop_derive(_input: TokenStream) -> TokenStream {
    // Intentionally produces no output.
    // PlexusRequest already generates impl JsonSchema with x-plexus-source extensions.
    TokenStream::new()
}