allframe-macros 0.1.27

Procedural macros for AllFrame framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! AllFrame Procedural Macros
//!
//! This crate provides compile-time code generation for AllFrame,
//! including dependency injection, OpenAPI schema generation, and more.

#![deny(warnings)]

mod allframe_handler;
mod api;
mod arch;
mod cqrs;
mod di;
mod error;
mod health;
mod otel;
mod resilience;
mod saga;
mod security;
mod tauri_compat;

use proc_macro::TokenStream;

// Note: The `provide` attribute is handled directly by `di_container` macro
// It doesn't need a separate proc_macro_attribute since it's consumed during
// parsing

/// Compile-time dependency injection container
///
/// Generates a container with automatic dependency resolution at compile time.
///
/// # Attributes
///
/// - `#[provide(expr)]` - Use custom expression for initialization
/// - `#[provide(from_env)]` - Load from environment using `FromEnv` trait
/// - `#[provide(singleton)]` - Shared instance (default)
/// - `#[provide(transient)]` - New instance on each access
/// - `#[provide(async)]` - Async initialization using `AsyncInit` trait
/// - `#[depends(field1, field2)]` - Explicit dependencies
///
/// # Example (Sync)
/// ```ignore
/// #[di_container]
/// struct AppContainer {
///     database: DatabaseService,
///     repository: UserRepository,
/// }
///
/// let container = AppContainer::new();
/// ```
///
/// # Example (Async)
/// ```ignore
/// #[di_container]
/// struct AppContainer {
///     #[provide(from_env)]
///     config: Config,
///
///     #[provide(singleton, async)]
///     #[depends(config)]
///     database: DatabasePool,
///
///     #[provide(transient)]
///     service: MyService,
/// }
///
/// let container = AppContainer::build().await?;
/// ```
#[proc_macro_attribute]
pub fn di_container(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    di::di_container_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// API handler with auto OpenAPI generation
///
/// Generates OpenAPI 3.1 schema for the annotated function.
///
/// # Example
/// ```ignore
/// #[api_handler(path = "/users", method = "POST", description = "Create user")]
/// async fn create_user(req: CreateUserRequest) -> CreateUserResponse {
///     // handler implementation
/// }
///
/// // Generated function:
/// // fn create_user_openapi_schema() -> String { /* JSON schema */ }
/// ```
#[proc_macro_attribute]
pub fn api_handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    api::api_handler_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a type as part of the Domain layer (Layer 1)
///
/// Domain entities contain pure business logic with no infrastructure
/// dependencies.
///
/// # Example
/// ```ignore
/// #[domain]
/// struct User {
///     id: UserId,
///     email: Email,
/// }
/// ```
#[proc_macro_attribute]
pub fn domain(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    arch::domain_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a type as part of the Repository layer (Layer 2)
///
/// Repositories handle data access and can depend on Domain entities.
///
/// # Example
/// ```ignore
/// #[repository]
/// trait UserRepository: Send + Sync {
///     async fn find(&self, id: UserId) -> Option<User>;
/// }
/// ```
#[proc_macro_attribute]
pub fn repository(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    arch::repository_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a type as part of the Use Case layer (Layer 3)
///
/// Use cases orchestrate application logic and can depend on Repositories and
/// Domain.
///
/// # Example
/// ```ignore
/// #[use_case]
/// struct GetUserUseCase {
///     repo: Arc<dyn UserRepository>,
/// }
/// ```
#[proc_macro_attribute]
pub fn use_case(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    arch::use_case_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a type as part of the Handler layer (Layer 4)
///
/// Handlers are entry points (HTTP/gRPC/GraphQL) and can only depend on Use
/// Cases. Handlers CANNOT depend on Repositories directly - they must go
/// through Use Cases.
///
/// # Example
/// ```ignore
/// #[handler]
/// struct GetUserHandler {
///     use_case: Arc<GetUserUseCase>,
/// }
/// ```
#[proc_macro_attribute]
pub fn handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    arch::handler_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a struct as a Command (CQRS write operation)
///
/// Commands represent write operations that change state and produce events.
///
/// # Example
/// ```ignore
/// #[command]
/// struct CreateUserCommand {
///     email: String,
///     name: String,
/// }
/// ```
#[proc_macro_attribute]
pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    cqrs::command_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a struct as a Query (CQRS read operation)
///
/// Queries represent read operations that don't change state.
///
/// # Example
/// ```ignore
/// #[query]
/// struct GetUserQuery {
///     user_id: String,
/// }
/// ```
#[proc_macro_attribute]
pub fn query(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    cqrs::query_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks an enum or struct as an Event
///
/// Events represent immutable facts that have occurred in the system.
///
/// # Example
/// ```ignore
/// #[event]
/// enum UserEvent {
///     Created { user_id: String, email: String },
///     Updated { user_id: String, email: String },
/// }
/// ```
#[proc_macro_attribute]
pub fn event(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    cqrs::event_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a function as a Command Handler
///
/// Command handlers process commands and produce events.
///
/// # Example
/// ```ignore
/// #[command_handler]
/// async fn handle_create_user(cmd: CreateUserCommand) -> Result<Vec<Event>, String> {
///     Ok(vec![Event::UserCreated { ... }])
/// }
/// ```
#[proc_macro_attribute]
pub fn command_handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    cqrs::command_handler_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a function as a Query Handler
///
/// Query handlers process queries and return data from projections.
///
/// # Example
/// ```ignore
/// #[query_handler]
/// async fn handle_get_user(query: GetUserQuery) -> Result<Option<User>, String> {
///     Ok(Some(user))
/// }
/// ```
#[proc_macro_attribute]
pub fn query_handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    cqrs::query_handler_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a function to be automatically traced with OpenTelemetry
///
/// Automatically creates spans with proper context propagation.
///
/// # Example
/// ```ignore
/// #[traced]
/// async fn fetch_user(user_id: String) -> Result<User, Error> {
///     // Span created automatically with name "fetch_user"
///     // Span includes function arguments as attributes
///     Ok(user)
/// }
/// ```
#[proc_macro_attribute]
pub fn traced(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    otel::traced_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Derive macro for automatic gRPC status conversion
///
/// Generates `From<Error> for tonic::Status` implementation.
/// Use `#[grpc(CODE)]` on variants to specify the gRPC status code.
///
/// # Example
/// ```ignore
/// use allframe_macros::GrpcError;
/// use thiserror::Error;
///
/// #[derive(Error, Debug, GrpcError)]
/// pub enum AppError {
///     #[error("Unauthenticated: {0}")]
///     #[grpc(UNAUTHENTICATED)]
///     Unauthenticated(String),
///
///     #[error("Rate limited")]
///     #[grpc(RESOURCE_EXHAUSTED)]
///     RateLimited,
///
///     #[error("Not found: {0}")]
///     #[grpc(NOT_FOUND)]
///     NotFound(String),
///
///     #[error("Internal error: {0}")]
///     #[grpc(INTERNAL)]
///     Internal(String),
/// }
///
/// // Auto-generates: impl From<AppError> for tonic::Status
/// ```
///
/// # Supported gRPC Codes
/// - `OK`, `CANCELLED`, `UNKNOWN`, `INVALID_ARGUMENT`
/// - `DEADLINE_EXCEEDED`, `NOT_FOUND`, `ALREADY_EXISTS`
/// - `PERMISSION_DENIED`, `RESOURCE_EXHAUSTED`, `FAILED_PRECONDITION`
/// - `ABORTED`, `OUT_OF_RANGE`, `UNIMPLEMENTED`, `INTERNAL`
/// - `UNAVAILABLE`, `DATA_LOSS`, `UNAUTHENTICATED`
#[proc_macro_derive(GrpcError, attributes(grpc))]
pub fn grpc_error(input: TokenStream) -> TokenStream {
    let input = proc_macro2::TokenStream::from(input);

    error::grpc_error_impl(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Derive macro for automatic HealthCheck implementation
///
/// Generates the `HealthCheck` trait implementation by collecting all fields
/// that implement the `Dependency` trait.
///
/// # Example
/// ```ignore
/// use allframe_macros::HealthCheck;
/// use allframe_core::health::{Dependency, DependencyStatus};
///
/// struct RedisDependency { /* ... */ }
/// impl Dependency for RedisDependency { /* ... */ }
///
/// struct DatabaseDependency { /* ... */ }
/// impl Dependency for DatabaseDependency { /* ... */ }
///
/// #[derive(HealthCheck)]
/// struct AppHealth {
///     #[health(timeout = "5s", critical = true)]
///     redis: RedisDependency,
///
///     #[health(timeout = "10s", critical = false)]
///     database: DatabaseDependency,
///
///     #[health(skip)]
///     config: Config, // Not a dependency
/// }
///
/// // Auto-generates:
/// // impl HealthCheck for AppHealth { ... }
/// ```
///
/// # Attributes
/// - `#[health(skip)]` - Skip this field from health checks
/// - `#[health(critical = true)]` - Mark dependency as critical (default: true)
/// - `#[health(timeout = "5s")]` - Set check timeout (default: 5s)
#[proc_macro_derive(HealthCheck, attributes(health))]
pub fn health_check(input: TokenStream) -> TokenStream {
    let input = proc_macro2::TokenStream::from(input);

    health::health_check_impl(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Derive macro for automatic Obfuscate implementation
///
/// Generates the `Obfuscate` trait implementation that safely logs struct
/// fields, obfuscating those marked with `#[sensitive]`.
///
/// # Example
/// ```ignore
/// use allframe_macros::Obfuscate;
///
/// #[derive(Obfuscate)]
/// struct DatabaseConfig {
///     host: String,
///     port: u16,
///     #[sensitive]
///     password: String,
///     #[sensitive]
///     api_key: String,
/// }
///
/// let config = DatabaseConfig {
///     host: "localhost".to_string(),
///     port: 5432,
///     password: "secret".to_string(),
///     api_key: "sk_live_abc123".to_string(),
/// };
///
/// // Output: "DatabaseConfig { host: "localhost", port: 5432, password: ***, api_key: *** }"
/// println!("{}", config.obfuscate());
/// ```
///
/// # Attributes
/// - `#[sensitive]` - Mark field as sensitive, will be displayed as `***`
/// - `#[obfuscate(with = "function_name")]` - Use custom function to obfuscate
#[proc_macro_derive(Obfuscate, attributes(sensitive, obfuscate))]
pub fn obfuscate(input: TokenStream) -> TokenStream {
    let input = proc_macro2::TokenStream::from(input);

    security::obfuscate_impl(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Attribute macro for automatic retry with exponential backoff
///
/// Wraps an async function with retry logic using `RetryExecutor`.
///
/// # Example
/// ```ignore
/// use allframe_macros::retry;
///
/// #[retry(max_retries = 3, initial_interval_ms = 100)]
/// async fn fetch_data() -> Result<String, std::io::Error> {
///     // This will be retried up to 3 times on failure
///     reqwest::get("https://api.example.com/data")
///         .await?
///         .text()
///         .await
/// }
/// ```
///
/// # Parameters
/// - `max_retries` - Maximum retry attempts (default: 3)
/// - `initial_interval_ms` - Initial backoff in milliseconds (default: 500)
/// - `max_interval_ms` - Maximum backoff in milliseconds (default: 30000)
/// - `multiplier` - Backoff multiplier (default: 2.0)
#[proc_macro_attribute]
pub fn retry(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    resilience::retry_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Attribute macro for circuit breaker pattern
///
/// Wraps a function with circuit breaker logic for fail-fast behavior.
///
/// # Example
/// ```ignore
/// use allframe_macros::circuit_breaker;
///
/// #[circuit_breaker(name = "external_api", failure_threshold = 5)]
/// async fn call_external_api() -> Result<String, std::io::Error> {
///     // After 5 failures, the circuit opens and calls fail fast
///     external_service::call().await
/// }
/// ```
///
/// # Parameters
/// - `name` - Circuit breaker name (default: function name)
/// - `failure_threshold` - Failures before opening (default: 5)
/// - `success_threshold` - Successes to close in half-open (default: 3)
/// - `timeout_ms` - Time before half-open in milliseconds (default: 30000)
#[proc_macro_attribute]
pub fn circuit_breaker(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    resilience::circuit_breaker_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Attribute macro for rate limiting
///
/// Wraps a function with rate limiting using token bucket algorithm.
///
/// # Example
/// ```ignore
/// use allframe_macros::rate_limited;
///
/// #[rate_limited(rps = 100, burst = 10)]
/// fn handle_request() -> Result<Response, std::io::Error> {
///     // Limited to 100 requests per second with burst of 10
///     process_request()
/// }
/// ```
///
/// # Parameters
/// - `rps` - Requests per second (default: 100)
/// - `burst` - Burst capacity (default: 10)
#[proc_macro_attribute]
pub fn rate_limited(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    resilience::rate_limited_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a struct as a saga step with automatic Debug and SagaStep trait
/// implementation
///
/// Reduces boilerplate by generating:
/// - Debug impl (skipping #[inject] fields)
/// - SagaStep trait impl with metadata methods
/// - Placeholder execute/compensate methods (user implements in separate impl
///   block)
///
/// # Attributes
///
/// - `#[inject]` - Mark fields that should be dependency injected (skipped in
///   Debug)
///
/// # Example
/// ```ignore
/// #[saga_step(name = "ValidateIndex", timeout_seconds = 10, requires_compensation = false)]
/// struct ValidateIndexStep {
///     #[inject] index_repository: Arc<dyn IndexRepository>,
///     user_id: String,
///     index_id: Uuid,
/// }
///
/// impl ValidateIndexStep {
///     async fn execute(&self, ctx: &SagaContext) -> StepExecutionResult {
///         // actual logic
///         Ok(StepExecutionResult::success())
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn saga_step(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    saga::saga_step_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Marks a struct as a saga container with automatic Saga trait implementation
///
/// Reduces boilerplate by generating:
/// - Constructor accepting all #[inject] dependencies
/// - Saga trait implementation
/// - Automatic dependency injection setup
///
/// # Attributes
///
/// - `#[saga_data]` - Mark the field containing saga data (one per struct)
/// - `#[inject]` - Mark fields that should be dependency injected
///
/// # Example
/// ```ignore
/// #[saga(name = "RebalancingSaga")]
/// struct RebalancingSaga {
///     #[saga_data]
///     data: RebalancingSagaData,
///
///     #[inject]
///     index_repository: Arc<dyn IndexRepository>,
///     #[inject]
///     trade_service: Arc<TradeService>,
/// }
/// ```
#[proc_macro_attribute]
pub fn saga(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    saga::saga_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Defines the workflow for a saga using an enum
///
/// Generates step vector construction from enum variants.
/// Each enum variant corresponds to a step struct (e.g., `ValidateIndex` ->
/// `ValidateIndexStep`).
///
/// # Example
/// ```ignore
/// #[saga_workflow(RebalancingSaga)]
/// enum RebalancingWorkflow {
///     ValidateIndex,
///     FetchBalances,
///     ExecuteTrades,
///     UpdateBalances,
///     EmitCompletionEvent,
/// }
/// ```
#[proc_macro_attribute]
pub fn saga_workflow(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    saga::saga_workflow_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Derive macro for type-safe step output extraction
///
/// Generates:
/// - `from_context(ctx, step_name)` method for extracting typed output
/// - `Into<StepExecutionResult>` impl for returning typed output
///
/// # Example
/// ```ignore
/// #[derive(StepOutput)]
/// struct ValidateAndCreateTradeOutput {
///     trade_id: Uuid,
///     idempotency_key: String,
/// }
///
/// // In step execute method:
/// let output: ValidateAndCreateTradeOutput = ValidateAndCreateTradeOutput {
///     trade_id: trade.id,
///     idempotency_key: trade.idempotency_key,
/// };
/// return output.into(); // Converts to StepExecutionResult
///
/// // In another step:
/// let output = ValidateAndCreateTradeOutput::from_context(ctx, "ValidateAndCreateTrade")?;
/// let trade_id = output.trade_id;
/// ```
#[proc_macro_derive(StepOutput)]
pub fn derive_step_output(input: TokenStream) -> TokenStream {
    let input = proc_macro2::TokenStream::from(input);

    saga::derive_step_output(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Extract step output with type safety and error handling
///
/// Note: This proc-macro provides guidance but doesn't implement a declarative
/// macro. Use the StepOutput trait for type-safe extraction instead.
///
/// # Example
/// ```ignore
/// // Type-safe extraction using StepOutput derive
/// #[derive(StepOutput)]
/// struct ValidateAndCreateTradeOutput {
///     trade_id: Uuid,
///     amount: f64,
/// }
///
/// let output = ValidateAndCreateTradeOutput::from_context(ctx, "ValidateAndCreateTrade")?;
/// let trade_id = output.trade_id;
///
/// // Or access raw JSON
/// let raw_output = ctx.get_step_output("ValidateAndCreateTrade");
/// ```
#[proc_macro]
pub fn extract_output(input: TokenStream) -> TokenStream {
    let input = proc_macro2::TokenStream::from(input);

    saga::extract_output_impl(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Tauri command compatibility macro
///
/// Transforms a function with individual Tauri-style parameters into an
/// AllFrame handler. Generates a `{FnName}Args` struct with `#[derive(Deserialize)]`
/// and rewrites the function to accept that struct, making it directly usable with
/// `router.register_with_args()`.
///
/// This enables incremental migration from Tauri commands: keep the same function
/// body and parameter names, just swap `#[tauri::command]` for `#[tauri_compat]`.
///
/// # Example
///
/// ```ignore
/// use allframe_macros::tauri_compat;
///
/// // Before (Tauri):
/// // #[tauri::command]
/// // async fn greet(name: String, age: u32) -> String { ... }
///
/// // After (AllFrame):
/// #[tauri_compat]
/// async fn greet(name: String, age: u32) -> String {
///     format!(r#"{{"greeting":"Hello {}, age {}"}}"#, name, age)
/// }
///
/// // Generates `GreetArgs { name: String, age: u32 }` and rewrites greet to
/// // accept `GreetArgs`. Register with:
/// // router.register_with_args::<GreetArgs>("greet", |args| greet(args));
/// ```
///
/// # Option parameters
///
/// `Option<T>` parameters get `#[serde(default)]` automatically, matching
/// Tauri's behavior where optional params can be omitted from the frontend call.
///
/// # State parameters
///
/// Parameters with type `State<...>` are recognized as injected state and kept
/// as separate function parameters (not included in the args struct).
#[proc_macro_attribute]
pub fn tauri_compat(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    tauri_compat::tauri_compat_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Mark a function as an AllFrame router handler.
///
/// This attribute suppresses `dead_code` warnings that occur because the Rust
/// compiler cannot trace function usage through `router.register("name", handler_fn)`
/// closure chains. It also validates the handler signature at compile time.
///
/// # Basic handler
///
/// ```ignore
/// #[allframe_handler]
/// async fn get_user() -> String {
///     r#"{"name":"Alice"}"#.to_string()
/// }
///
/// router.register("get_user", get_user);
/// ```
///
/// # Streaming handler
///
/// ```ignore
/// use allframe_core::router::StreamSender;
///
/// #[allframe_handler(streaming)]
/// async fn stream_data(tx: StreamSender) -> String {
///     tx.send("chunk".to_string()).await.ok();
///     "done".to_string()
/// }
///
/// router.register_streaming("stream_data", stream_data);
/// ```
///
/// # Validation
///
/// - Function must be `async`
/// - `streaming` handlers must have a `StreamSender` parameter
/// - Non-streaming handlers must not have a `StreamSender` parameter
#[proc_macro_attribute]
pub fn allframe_handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr = proc_macro2::TokenStream::from(attr);
    let item = proc_macro2::TokenStream::from(item);

    allframe_handler::allframe_handler_impl(attr, item)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_macros_crate_compiles() {
        assert!(true);
    }
}