Skip to main content

plexus_macros/
lib.rs

1//! # plexus-macros
2//!
3//! Procedural macros for **Plexus RPC** activations. Your Rust function
4//! signature IS the schema — the macros extract method names, parameter
5//! types, return types, doc comments, deprecation metadata, child routing,
6//! and typed request extraction from the source.
7//!
8//! See the crate-level [`README`](https://github.com/hypermemetic/plexus-macros/blob/main/README.md)
9//! for a comprehensive example covering every option, a deep-dive on
10//! request forwarding (`PlexusRequest` + `request = ...`), and a
11//! per-macro reference.
12//!
13//! # Quick example
14//!
15//! ```ignore
16//! use futures::Stream;
17//! use async_stream::stream;
18//! use plexus_macros::PlexusRequest;
19//!
20//! #[derive(PlexusRequest)]
21//! pub struct BashRequest {
22//!     #[from_cookie("access_token")]
23//!     auth_token: String,
24//! }
25//!
26//! pub struct Bash;
27//!
28//! #[plexus_macros::activation(
29//!     namespace = "bash",
30//!     version = "1.0.0",
31//!     description = "Execute bash commands and stream output",
32//!     request = BashRequest,
33//! )]
34//! impl Bash {
35//!     /// Execute a bash command and stream output.
36//!     #[plexus_macros::method(streaming)]
37//!     async fn execute(
38//!         &self,
39//!         command: String,
40//!         #[activation_param] auth_token: String,
41//!     ) -> impl Stream<Item = String> + Send + 'static {
42//!         let _ = (command, auth_token);
43//!         stream! { yield "ok".into(); }
44//!     }
45//! }
46//! ```
47//!
48//! # Macros at a glance
49//!
50//! | Macro | Purpose |
51//! |---|---|
52//! | `#[plexus_macros::activation]` | Turn an `impl` block into a Plexus RPC activation — and, with `client`, emit its typed client. |
53//! | `#[plexus_macros::method]` | Mark a method as an RPC endpoint. |
54//! | `#[plexus_macros::child]` | Register a child activation for `ChildRouter` dispatch. |
55//! | `#[plexus_macros::removed_in]` | Companion to `#[deprecated]` carrying the removal version. |
56//! | `#[derive(PlexusRequest)]` | Typed extraction from `RawRequestContext`. |
57//! | `#[derive(HandleEnum)]` | Type-safe handle enums for an activation. |
58//!
59//! Deprecated surfaces kept through 0.5.x (removed in 0.6): `#[hub_methods]`,
60//! `#[hub_method]`, `#[derive(StreamEvent)]`, the `hub` and `children = [...]`
61//! flags on `#[activation]`. See the migration section of the README.
62//!
63//! ## Crate version (UMB-2)
64//!
65//! This crate is `proc-macro = true`, which means it can only export macro
66//! attributes — `pub const VERSION` etc. are forbidden by the compiler. The
67//! `plexus-rpc` umbrella reads `plexus-macros`'s version via a build-time
68//! environment variable populated from `Cargo.toml`'s dependency pin
69//! (see `plexus-rpc/build.rs`).
70
71mod codegen;
72mod credential;
73mod handle_enum;
74mod parse;
75mod request;
76mod stream_event;
77
78
79use codegen::generate_all;
80use parse::HubMethodsAttrs;
81use proc_macro::TokenStream;
82use proc_macro2::TokenStream as TokenStream2;
83use quote::{format_ident, quote};
84use syn::{
85    parse::{Parse, ParseStream},
86    parse_macro_input, punctuated::Punctuated, Expr, ExprLit, FnArg, ItemFn, ItemImpl, Lit, Meta,
87    MetaNameValue, Pat, ReturnType, Token, Type,
88};
89
90/// Parsed attributes for hub_method (standalone version)
91struct HubMethodAttrs {
92    name: Option<String>,
93    /// Explicit description from `description = "..."`. When `Some`, this wins over
94    /// `///` doc comments. When `None`, doc comments are used as the default.
95    description: Option<String>,
96    /// Base crate path for imports (default: "crate")
97    crate_path: String,
98}
99
100impl Parse for HubMethodAttrs {
101    fn parse(input: ParseStream) -> syn::Result<Self> {
102        let mut name = None;
103        let mut description: Option<String> = None;
104        let mut crate_path = "crate".to_string();
105
106        if !input.is_empty() {
107            let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
108
109            for meta in metas {
110                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
111                    if path.is_ident("name") {
112                        if let Expr::Lit(ExprLit {
113                            lit: Lit::Str(s), ..
114                        }) = value
115                        {
116                            name = Some(s.value());
117                        }
118                    } else if path.is_ident("description") {
119                        if let Expr::Lit(ExprLit {
120                            lit: Lit::Str(s), ..
121                        }) = value
122                        {
123                            description = Some(s.value());
124                        }
125                    } else if path.is_ident("crate_path") {
126                        if let Expr::Lit(ExprLit {
127                            lit: Lit::Str(s), ..
128                        }) = value
129                        {
130                            crate_path = s.value();
131                        }
132                    }
133                }
134            }
135        }
136
137        Ok(HubMethodAttrs { name, description, crate_path })
138    }
139}
140
141/// Attribute macro for individual methods within a `#[plexus::activation]` impl block.
142///
143/// # Example
144///
145/// ```ignore
146/// #[plexus::activation(namespace = "bash")]
147/// impl Bash {
148///     /// Execute a bash command
149///     #[plexus::method]
150///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> {
151///         // ...
152///     }
153/// }
154/// ```
155///
156/// # Authorization arguments (R-1 / AUTHZ-CORE-2)
157///
158/// - `scope = "..."` — explicit required scope, emitted into the generated
159///   `MethodSchema.requires_credential`. Repeatable: `scope = "x.y",
160///   scope = "x.z"` means the caller must satisfy **ALL** listed scopes
161///   (conjunction — AND, not OR). Literals are validated at compile time
162///   against the AUTHZ-CORE-4 scope grammar (dot-separated `[a-z][a-z0-9_]*`
163///   segments, optional trailing `.*` segment wildcard, or bare `*`).
164/// - `public` — the method is exempt from the default-deny gate; emitted as
165///   `MethodSchema.public = true`. Mixing `public` with `scope = "..."` is a
166///   compile error (a public method has no required scope to enforce).
167/// - Neither — the implicit `<activation>.<method>` scope rule applies at
168///   registry-build time (AUTHZ-CORE-4); the schema carries no
169///   `requires_credential` for the implicit case.
170#[proc_macro_attribute]
171pub fn method(attr: TokenStream, item: TokenStream) -> TokenStream {
172    let args = parse_macro_input!(attr as HubMethodAttrs);
173    let input_fn = parse_macro_input!(item as ItemFn);
174
175    match hub_method_impl(args, input_fn) {
176        Ok(tokens) => tokens.into(),
177        Err(e) => e.to_compile_error().into(),
178    }
179}
180
181/// Deprecated: use `plexus::method` instead.
182#[deprecated(since = "0.5.0", note = "Use `plexus::method` instead")]
183#[proc_macro_attribute]
184pub fn hub_method(attr: TokenStream, item: TokenStream) -> TokenStream {
185    method(attr, item)
186}
187
188/// Attribute macro for individual **child** methods within a
189/// `#[plexus_macros::activation]` impl block.
190///
191/// Two method shapes are accepted:
192///
193/// | Shape | Role | Example |
194/// |---|---|---|
195/// | `fn NAME(&self) -> Child` (no args) | Static child — routing name is the method name | `fn mercury(&self) -> Mercury` |
196/// | `fn NAME(&self, name: &str) -> Option<Child>` (sync or async) | Dynamic fallback dispatcher | `fn planet(&self, name: &str) -> Option<Planet>` |
197///
198/// The enclosing `#[plexus_macros::activation]` macro collects all `#[child]`
199/// methods and generates a `ChildRouter` impl whose `get_child(name)`
200/// dispatches over them. `#[child]` methods are **not** exposed as Plexus RPC
201/// methods — they contribute only to `ChildRouter` routing.
202///
203/// # Example
204///
205/// ```ignore
206/// #[plexus_macros::activation(namespace = "solar")]
207/// impl Solar {
208///     #[plexus_macros::child]
209///     fn mercury(&self) -> Mercury { self.mercury.clone() }
210///
211///     #[plexus_macros::child]
212///     async fn planet(&self, name: &str) -> Option<Planet> {
213///         self.lookup_planet(name).await
214///     }
215/// }
216/// ```
217///
218/// Used standalone (outside an `#[activation]` block) this attribute is a
219/// no-op that returns the function unchanged.
220#[proc_macro_attribute]
221pub fn child(_attr: TokenStream, item: TokenStream) -> TokenStream {
222    // Outside of #[plexus_macros::activation] this attribute does nothing;
223    // the activation macro strips it and collects the method into the
224    // generated ChildRouter impl.
225    item
226}
227
228/// Companion attribute to Rust's built-in `#[deprecated]` for carrying a
229/// `removed_in = "VERSION"` hint that rustc doesn't recognize.
230///
231/// Rust's `#[deprecated(since = "X", note = "Y")]` supports only `since` and
232/// `note`. This companion attribute supplies the removal version that the
233/// `plexus-macros` codegen folds into the method's `DeprecationInfo.removed_in`
234/// field on the emitted `MethodSchema`.
235///
236/// # Example
237///
238/// ```ignore
239/// #[deprecated(since = "0.5", note = "use `new_method` instead")]
240/// #[plexus_macros::removed_in("0.6")]
241/// #[plexus_macros::method]
242/// async fn legacy(&self) -> impl Stream<Item = String> + Send + 'static {
243///     // ...
244/// }
245/// ```
246///
247/// # Requirements
248///
249/// `#[plexus_macros::removed_in]` is only meaningful when paired with
250/// `#[deprecated]`. The `#[plexus_macros::activation]` macro emits a compile
251/// error when it encounters `#[removed_in]` on a method that doesn't also
252/// carry `#[deprecated]`.
253///
254/// As a standalone attribute (outside an `#[activation]` block) this is a
255/// no-op that returns the item unchanged — the activation macro parses and
256/// strips it during codegen.
257#[proc_macro_attribute]
258pub fn removed_in(attr: TokenStream, item: TokenStream) -> TokenStream {
259    // When `#[plexus_macros::removed_in("X")]` is placed OUTSIDE
260    // `#[plexus_macros::activation(...)]` on the same impl block, the
261    // `removed_in` proc macro runs BEFORE the activation macro (outer
262    // attrs expand first), so a naive no-op implementation would consume
263    // the attribute before the activation macro ever sees it.
264    //
265    // Workaround: emit a synthetic `#[doc(hidden)]` marker attribute on
266    // the item's attr list that encodes the removed_in value. The
267    // activation / method codegen scans for this marker as an equivalent
268    // signal to the companion attribute and uses it to populate
269    // `DeprecationInfo.removed_in`.
270    //
271    // Stable rustc treats `#[doc(hidden)]` as a regular doc attribute and
272    // the sentinel payload rides along in the same literal string.
273    let attr_str: String = match syn::parse::<syn::LitStr>(attr.clone()) {
274        Ok(s) => s.value(),
275        Err(_) => {
276            // Not a bare string literal — just let the item pass through
277            // and let the activation/method layer produce the proper error.
278            return item;
279        }
280    };
281    let marker = format!("__plexus_removed_in:{}", attr_str);
282    let item_ts: proc_macro2::TokenStream = item.into();
283    let marker_lit = proc_macro2::Literal::string(&marker);
284    let out = quote::quote! {
285        #[doc(hidden)]
286        #[doc = #marker_lit]
287        #item_ts
288    };
289    out.into()
290}
291
292fn hub_method_impl(args: HubMethodAttrs, input_fn: ItemFn) -> syn::Result<TokenStream2> {
293    // Extract method name (from attr or function name)
294    let method_name = args
295        .name
296        .unwrap_or_else(|| input_fn.sig.ident.to_string());
297
298    // Resolve description: explicit `description = "..."` wins over `///` doc
299    // comments; if neither is present, description is the empty string.
300    let description = match args.description {
301        Some(explicit) => explicit,
302        None => extract_doc_comment(&input_fn),
303    };
304
305    // Extract input type from first parameter (if any)
306    let input_type = extract_input_type(&input_fn)?;
307
308    // Extract return type
309    let return_type = extract_return_type(&input_fn)?;
310
311    // Function name for the schema function
312    let fn_name = &input_fn.sig.ident;
313    let schema_fn_name = format_ident!("{}_schema", fn_name);
314
315    // Parse crate path
316    let crate_path: syn::Path = syn::parse_str(&args.crate_path)
317        .map_err(|e| syn::Error::new_spanned(&input_fn.sig, format!("Invalid crate_path: {}", e)))?;
318
319    // Generate the schema function
320    let schema_fn = generate_schema_fn(
321        &schema_fn_name,
322        &method_name,
323        &description,
324        input_type.as_ref(),
325        &return_type,
326        &crate_path,
327    );
328
329    // Return the original function plus the schema function
330    Ok(quote! {
331        #input_fn
332
333        #schema_fn
334    })
335}
336
337fn extract_doc_comment(input_fn: &ItemFn) -> String {
338    // Delegate to the shared helper so the standalone `#[method]` macro path
339    // follows the same doc-comment extraction rule as the in-activation path:
340    // lines joined with '\n', common leading whitespace stripped.
341    parse::extract_doc_description(&input_fn.attrs).unwrap_or_default()
342}
343
344fn extract_input_type(input_fn: &ItemFn) -> syn::Result<Option<Type>> {
345    // Skip self parameter, get first real parameter
346    for arg in &input_fn.sig.inputs {
347        match arg {
348            FnArg::Receiver(_) => continue, // Skip &self
349            FnArg::Typed(pat_type) => {
350                // Skip context-like parameters
351                if let Pat::Ident(ident) = &*pat_type.pat {
352                    let name = ident.ident.to_string();
353                    if name == "ctx" || name == "context" || name == "self_" {
354                        continue;
355                    }
356                }
357                return Ok(Some((*pat_type.ty).clone()));
358            }
359        }
360    }
361
362    Ok(None)
363}
364
365fn extract_return_type(input_fn: &ItemFn) -> syn::Result<Type> {
366    match &input_fn.sig.output {
367        ReturnType::Default => Err(syn::Error::new_spanned(
368            &input_fn.sig,
369            "hub_method requires a return type",
370        )),
371        ReturnType::Type(_, ty) => Ok((*ty.clone()).clone()),
372    }
373}
374
375fn generate_schema_fn(
376    fn_name: &syn::Ident,
377    method_name: &str,
378    description: &str,
379    input_type: Option<&Type>,
380    return_type: &Type,
381    crate_path: &syn::Path,
382) -> TokenStream2 {
383    // Z2H-2: the standalone `#[method]` macro has no activation-level shim
384    // module, so resolve the dep roots absolutely: through the plexus-rpc
385    // umbrella's `__deps` re-exports when the consumer depends on it, or the
386    // extern prelude (today's semantics) otherwise.
387    let (serde_json_root, schemars_root) =
388        match codegen::umbrella_crate(proc_macro2::Span::call_site()) {
389            Some(umbrella) => (
390                quote! { ::#umbrella::__deps::serde_json },
391                quote! { ::#umbrella::__deps::schemars },
392            ),
393            None => (quote! { serde_json }, quote! { schemars }),
394        };
395
396    let input_schema = if let Some(input_ty) = input_type {
397        quote! {
398            Some(#serde_json_root::to_value(#schemars_root::schema_for!(#input_ty)).unwrap())
399        }
400    } else {
401        quote! { None }
402    };
403
404    let _ = return_type; // Will be used for protocol schema in future
405    let _ = crate_path;
406
407    quote! {
408        /// Generated schema function for this hub method
409        #[allow(dead_code)]
410        pub fn #fn_name() -> #serde_json_root::Value {
411            #serde_json_root::json!({
412                "name": #method_name,
413                "description": #description,
414                "input": #input_schema,
415            })
416        }
417    }
418}
419
420/// Attribute macro for impl blocks defining a Plexus activation.
421///
422/// Generates:
423/// - Method enum for schema extraction
424/// - Activation trait implementation
425/// - RPC server trait and implementation
426///
427/// # Attributes
428///
429/// - `namespace = "..."` (required) - The activation namespace
430/// - `version = "..."` (optional, default: "1.0.0") - Version string
431/// - `description = "..."` (optional) - Activation description
432/// - `crate_path = "..."` (optional, default: "crate") - Path to substrate crate
433/// - `client` (optional flag) - also emit the typed client (MACRO-2, below)
434/// - `server_cfg = "<cfg predicate>"` (optional) - compile the server half
435///   only under that `cfg` (MACRO-2, below)
436///
437/// # Example
438///
439/// ```ignore
440/// #[plexus::activation(namespace = "bash", version = "1.0.0", description = "Execute bash commands")]
441/// impl Bash {
442///     /// Execute a bash command and stream output
443///     #[plexus::method]
444///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> + Send + 'static {
445///         self.executor.execute(&command).await
446///     }
447/// }
448/// ```
449///
450/// # The typed client (`client`, `server_cfg`) — MACRO-2
451///
452/// The macro already knows, when it runs, every method's wire name, its
453/// parameters and its `Stream<Item = E>` event type. With `client` it also
454/// emits a **typed client** for the activation, so a Rust consumer never
455/// hand-writes a call site or hand-mirrors an event type:
456///
457/// ```ignore
458/// #[plexus_macros::activation(namespace = "tickets", client)]
459/// impl Tickets { /* unchanged */ }
460///
461/// // emitted beside the impl:
462/// let client = TicketsClient::new(transport);          // any plexus_client::Transport
463/// let mut watch = client.watch(Some("MACRO".into()));  // EventStream<'_, TicketsEvent>
464/// let all = client.list_all(None, None, None).await?;  // Vec<TicketsEvent>
465/// ```
466///
467/// The client is generic over the transport, so the emitted code names none
468/// of them; its parameter and event types are the activation's own, so a
469/// change to either is a compile error in every consumer.
470///
471/// **Requires** the consuming crate to depend on `plexus-client`. A
472/// proc-macro crate cannot check that for you at expansion time in general,
473/// but the path is resolved through `proc-macro-crate`, so a missing
474/// dependency is reported at the `client` flag rather than as an unresolved
475/// import in code you did not write.
476///
477/// **`server_cfg = "..."`** puts the *server* half of the expansion — the
478/// impl block, the method enum, the `Activation` impl, the jsonrpsee trait —
479/// behind a `cfg`, while the client half stays unconditional. That is what
480/// makes an activation crate reachable from `wasm32-unknown-unknown`:
481///
482/// ```ignore
483/// // Cargo.toml: server deps are optional and behind `feature = "server"`.
484/// // plexus-macros itself stays non-optional — a proc-macro crate is built
485/// // for the host, so it costs a wasm32 build nothing.
486/// #[plexus_macros::activation(
487///     namespace = "tickets",
488///     client,
489///     server_cfg = "feature = \"server\"",
490/// )]
491/// impl Tickets { /* .. */ }
492/// ```
493///
494/// A consumer then says one line — `tickets-api = { version = "..",
495/// default-features = false }` — and gets the types and the client, with no
496/// tokio, jsonrpsee or plexus-core anywhere in its tree. Gating your own
497/// struct definition and server-only imports is still yours to do; the macro
498/// only gates its own output.
499///
500/// Both flags are opt-in: an activation that names neither expands exactly
501/// as it did before.
502#[proc_macro_attribute]
503pub fn activation(attr: TokenStream, item: TokenStream) -> TokenStream {
504    let args = parse_macro_input!(attr as HubMethodsAttrs);
505    let input_impl = parse_macro_input!(item as ItemImpl);
506
507    match generate_all(args, input_impl) {
508        Ok(tokens) => tokens.into(),
509        Err(e) => e.to_compile_error().into(),
510    }
511}
512
513/// Deprecated: use `plexus::activation` instead.
514#[deprecated(since = "0.5.0", note = "Use `plexus::activation` instead")]
515#[proc_macro_attribute]
516pub fn hub_methods(attr: TokenStream, item: TokenStream) -> TokenStream {
517    activation(attr, item)
518}
519
520/// Derive macro for declaring credential-bearing fields on a return-type
521/// struct or enum (per `AUTHZ-CRED-MACRO-1`).
522///
523/// Apply `#[derive(Credentials)]` to a struct or enum. Within the item,
524/// annotate each credential-bearing field with the helper attribute
525/// `#[credential(kind = "...", attach_as = "...", ...)]` carrying the
526/// per-field metadata. The field's type must be `Credential<T>` (the sealed
527/// wrapper from `plexus_auth_core`); any other type produces a compile
528/// error citing the wrapper requirement.
529///
530/// **Why a derive macro and not a freestanding attribute macro?** Stable Rust
531/// proc-macros cannot intercept attribute macros applied directly to struct
532/// fields; only derive-helper attributes can appear there. See
533/// `plans/AUTHZ/AUTHZ-CRED-MACRO-1-RUN-NOTES.md` for the rationale.
534///
535/// # Example
536///
537/// ```ignore
538/// use plexus_auth_core::{
539///     AttachmentSite, Credential, CredentialKind, CredentialScheme,
540///     HeaderName, MethodPath, Scope,
541/// };
542///
543/// // `CredentialFieldMarker` lands in plexus-auth-core in a follow-up; for
544/// // now the macro emits code that references it by name and consumers
545/// // provide the definition (see run-notes).
546///
547/// #[derive(plexus_macros::Credentials, serde::Serialize)]
548/// pub struct LoginEvent {
549///     pub user_id: String,
550///
551///     #[credential(
552///         kind = "bearer",
553///         attach_as = "header:authorization",
554///         scheme = "Bearer ",
555///     )]
556///     pub session: Credential<String>,
557/// }
558/// ```
559///
560/// # Clauses
561///
562/// | Clause | Required? | Notes |
563/// |---|---|---|
564/// | `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. |
565/// | `attach_as = "<spec>"` | required | One of `"header:<name>"`, `"cookie:<name>"`, `"first_frame:<setup-method>:<param>"`, `"in_rpc_param:<name>"`. |
566/// | `scheme = "<prefix>"` | optional | E.g. `"Bearer "` (trailing space significant). |
567/// | `scopes = ["a.b", ...]` | optional, default empty | List of scope identifiers. |
568/// | `refresh_via = "<method-path>"` | optional | E.g. `"auth.refresh"`. |
569/// | `revoke_via = "<method-path>"` | optional | E.g. `"auth.logout"`. |
570/// | `sensitive` | optional flag | Accepted for clarity; credentials are always sensitive. |
571///
572/// # Emitted artifacts
573///
574/// The macro emits two free functions in the same module:
575///
576/// - `fn __plexus_credential_marker_for_<TypeIdent>() -> Vec<CredentialFieldMarker>`
577/// - `fn __plexus_sensitive_fields_for_<TypeIdent>() -> Vec<(Option<&'static str>, &'static str)>`
578///
579/// The consumer (per `AUTHZ-CRED-CORE-3`) calls the first function during
580/// schema build; the second mirrors the implicit `#[sensitive]` rule for the
581/// redaction pipeline (per `AUTHZ-PRIVACY-2`).
582///
583/// The emitted code requires `CredentialFieldMarker`, `CredentialKind`,
584/// `AttachmentSite`, `CredentialScheme`, `Scope`, `MethodPath`, `HeaderName`,
585/// `CookieName`, `ParamName`, and `CredentialKindName` to be in scope at the
586/// emission site. Importing `plexus_auth_core::*` (or the equivalent named
587/// imports) at the top of the consuming module satisfies all but
588/// `CredentialFieldMarker`, which lands in `plexus_auth_core` in a follow-up.
589#[proc_macro_derive(Credentials, attributes(credential))]
590pub fn credentials_derive(input: TokenStream) -> TokenStream {
591    credential::expand_credentials_derive(input)
592}
593
594/// **DEPRECATED**: This derive macro is no longer needed.
595///
596/// With the caller-wraps streaming architecture, event types no longer need to
597/// implement `ActivationStreamItem`. Just use plain domain types with standard
598/// derives:
599///
600/// ```ignore
601/// #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
602/// #[serde(tag = "event", rename_all = "snake_case")]
603/// pub enum MyEvent {
604///     Data { value: String },
605///     Complete { result: i32 },
606/// }
607/// ```
608///
609/// The wrapping happens at the call site via `wrap_stream()`.
610#[deprecated(
611    since = "0.2.0",
612    note = "No longer needed - use plain domain types with Serialize/Deserialize"
613)]
614#[proc_macro_derive(StreamEvent, attributes(stream_event, terminal))]
615pub fn stream_event_derive(input: TokenStream) -> TokenStream {
616    stream_event::derive(input)
617}
618
619/// Derive macro for type-safe handle creation and parsing.
620///
621/// Generates:
622/// - `to_handle(&self) -> Handle` - converts enum variant to Handle
623/// - `impl TryFrom<&Handle>` - parses Handle back to enum variant
624/// - `impl From<EnumName> for Handle` - convenience conversion
625///
626/// # Attributes
627///
628/// Enum-level (required):
629/// - `plugin_id = "CONSTANT_NAME"` - Name of the constant holding the plugin UUID
630/// - `version = "1.0.0"` - Semantic version for handles
631/// - `crate_path = "..."` (optional, default: "plexus_core") - Path to plexus_core crate
632/// - `plugin_id_type = "Type<Args>"` (optional) - Concrete type whose associated
633///   constant `plugin_id` names. Use this when the owning activation is generic
634///   (e.g. `Cone<P: HubContext = NoParent>`) to pin the instantiation and avoid
635///   E0283 "cannot infer type" errors. Pairs with `plugin_id` — e.g.
636///   `plugin_id = "Cone::PLUGIN_ID", plugin_id_type = "Cone<NoParent>"` emits
637///   `<Cone<NoParent>>::PLUGIN_ID`.
638///
639/// Variant-level:
640/// - `method = "..."` (required) - The handle.method value
641/// - `table = "..."` (optional) - SQLite table name (for future resolution)
642/// - `key = "..."` (optional) - Primary key column (for future resolution)
643///
644/// # Example
645///
646/// ```ignore
647/// use hub_macro::HandleEnum;
648/// use uuid::Uuid;
649///
650/// pub const MY_PLUGIN_ID: Uuid = uuid::uuid!("550e8400-e29b-41d4-a716-446655440000");
651///
652/// #[derive(HandleEnum)]
653/// #[handle(plugin_id = "MY_PLUGIN_ID", version = "1.0.0")]
654/// pub enum MyPluginHandle {
655///     #[handle(method = "event", table = "events", key = "id")]
656///     Event { event_id: String },
657///
658///     #[handle(method = "message")]
659///     Message { message_id: String, role: String },
660/// }
661///
662/// // Usage:
663/// let handle_enum = MyPluginHandle::Event { event_id: "evt-123".into() };
664/// let handle: Handle = handle_enum.to_handle();
665/// // handle.method == "event"
666/// // handle.meta == ["evt-123"]
667///
668/// // Parsing back:
669/// let parsed = MyPluginHandle::try_from(&handle)?;
670/// ```
671#[proc_macro_derive(HandleEnum, attributes(handle))]
672pub fn handle_enum_derive(input: TokenStream) -> TokenStream {
673    handle_enum::derive(input)
674}
675
676/// Derive macro for typed HTTP/WebSocket request extraction.
677///
678/// Generates `impl PlexusRequest` (extraction) and `impl schemars::JsonSchema`
679/// (with `x-plexus-source` extensions) for the annotated struct.
680///
681/// # Field annotations
682///
683/// - `#[from_cookie("name")]` — extract from named cookie
684/// - `#[from_header("name")]` — extract from named HTTP header
685/// - `#[from_query("name")]` — extract from named URI query parameter
686/// - `#[from_peer]` — copy `ctx.peer` (peer socket address)
687/// - `#[from_auth_context]` — copy `ctx.auth` (auth context)
688/// - (no annotation) — `Default::default()`
689///
690/// # Example
691///
692/// ```ignore
693/// use plexus_macros::PlexusRequest;
694///
695/// #[derive(PlexusRequest)]
696/// struct MyRequest {
697///     #[from_cookie("access_token")]
698///     auth_token: String,
699///
700///     #[from_header("origin")]
701///     origin: Option<String>,
702///
703///     #[from_peer]
704///     peer_addr: Option<std::net::SocketAddr>,
705/// }
706/// ```
707#[proc_macro_derive(
708    PlexusRequest,
709    attributes(from_cookie, from_header, from_query, from_peer, from_auth_context)
710)]
711pub fn plexus_request_derive(input: TokenStream) -> TokenStream {
712    request::derive(input)
713}
714
715/// No-op `JsonSchema` derive — used when plexus-macros is aliased as `schemars`
716/// in dev-dependencies to prevent duplicate `impl JsonSchema` conflicts with
717/// `#[derive(PlexusRequest)]` (which generates its own `impl JsonSchema`).
718///
719/// When plexus-macros is aliased as schemars in dev-deps:
720/// ```toml
721/// [dev-dependencies]
722/// schemars = { path = "../plexus-macros", package = "plexus-macros", features = ["schemars-compat"] }
723/// ```
724/// then `#[derive(schemars::JsonSchema)]` invokes THIS derive instead of the real schemars derive,
725/// producing no output, so only `PlexusRequest`'s `impl JsonSchema` exists.
726#[cfg(feature = "schemars-compat")]
727#[proc_macro_derive(JsonSchema, attributes(schemars, serde))]
728pub fn json_schema_noop_derive(_input: TokenStream) -> TokenStream {
729    // Intentionally produces no output.
730    // PlexusRequest already generates impl JsonSchema with x-plexus-source extensions.
731    TokenStream::new()
732}