mrapids 0.1.31

Your OpenAPI, but executable
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
//! Unified output module for agent-friendly CLI responses
//!
//! This module provides consistent JSON output formatting for all mrapids commands,
//! making it easy for agents and automation tools to parse responses.

#![allow(dead_code)]

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::process;

/// Standard exit codes for mrapids CLI
pub mod exit_codes {
    pub const SUCCESS: i32 = 0;
    pub const GENERAL_ERROR: i32 = 1;
    pub const INVALID_ARGUMENTS: i32 = 2;
    pub const NETWORK_ERROR: i32 = 3;
    pub const AUTH_ERROR: i32 = 4;
    pub const VALIDATION_ERROR: i32 = 5;
    pub const NOT_FOUND: i32 = 6;
    pub const TIMEOUT: i32 = 7;
    pub const PARTIAL_SUCCESS: i32 = 10; // For batch operations
}

/// Environment variable names for mrapids configuration
pub mod env_vars {
    pub const DB_PATH: &str = "MRAPIDS_DB_PATH";
    pub const CONFIG_PATH: &str = "MRAPIDS_CONFIG_PATH";
    pub const SPEC_PATH: &str = "MRAPIDS_SPEC_PATH";
    pub const OUTPUT_FORMAT: &str = "MRAPIDS_OUTPUT";
    pub const AUTH_TOKEN: &str = "MRAPIDS_AUTH_TOKEN";
    pub const BASE_URL: &str = "MRAPIDS_BASE_URL";
    pub const LOG_LEVEL: &str = "MRAPIDS_LOG_LEVEL";
    pub const NO_COLOR: &str = "MRAPIDS_NO_COLOR";
    pub const MACHINE_MODE: &str = "MRAPIDS_MACHINE";
}

/// Unified response envelope for all CLI commands
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseEnvelope<T: Serialize> {
    /// Whether the command succeeded
    pub success: bool,

    /// The command that was executed
    pub command: String,

    /// The actual response data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<T>,

    /// Metadata about the execution
    pub metadata: ResponseMetadata,

    /// Any errors that occurred
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<ErrorDetail>,

    /// Any warnings
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

/// Metadata about the command execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseMetadata {
    /// Run ID (for run command)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_id: Option<String>,

    /// Request ID (for run command)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,

    /// Execution duration in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<f64>,

    /// CLI version
    pub version: String,

    /// Timestamp of execution
    pub timestamp: DateTime<Utc>,

    /// Exit code that will be used
    pub exit_code: i32,
}

/// Detailed error information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorDetail {
    /// Error code (e.g., "NETWORK_ERROR", "AUTH_FAILED")
    pub code: String,

    /// Human-readable error message
    pub message: String,

    /// Additional context
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<String>,

    /// Suggested fix
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suggestion: Option<String>,
}

/// Response specifically for the run command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunResponse {
    /// The operation that was executed
    pub operation: String,

    /// HTTP method used
    pub method: String,

    /// Full URL that was called
    pub url: String,

    /// HTTP status code
    pub status_code: u16,

    /// Status text
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_text: Option<String>,

    /// Response headers
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<serde_json::Value>,

    /// Response body
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,

    /// Response body as raw string (if not JSON)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_raw: Option<String>,

    /// Response size in bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_size_bytes: Option<usize>,

    /// Request details (for debugging)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request: Option<RequestDetails>,
}

/// Request details for debugging
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestDetails {
    /// Request headers sent
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<serde_json::Value>,

    /// Query parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_params: Option<serde_json::Value>,

    /// Path parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path_params: Option<serde_json::Value>,

    /// Request body sent
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<serde_json::Value>,
}

impl<T: Serialize> ResponseEnvelope<T> {
    /// Create a successful response
    pub fn success(command: &str, data: T) -> Self {
        Self {
            success: true,
            command: command.to_string(),
            data: Some(data),
            metadata: ResponseMetadata::new(exit_codes::SUCCESS),
            errors: vec![],
            warnings: vec![],
        }
    }

    /// Create a successful response with run metadata
    pub fn success_with_run(
        command: &str,
        data: T,
        run_id: String,
        request_id: Option<String>,
        duration_ms: f64,
    ) -> Self {
        let mut envelope = Self::success(command, data);
        envelope.metadata.run_id = Some(run_id);
        envelope.metadata.request_id = request_id;
        envelope.metadata.duration_ms = Some(duration_ms);
        envelope
    }

    /// Add a warning
    pub fn with_warning(mut self, warning: &str) -> Self {
        self.warnings.push(warning.to_string());
        self
    }

    /// Output as JSON and exit
    pub fn output_and_exit(self) -> ! {
        let exit_code = self.metadata.exit_code;
        println!(
            "{}",
            serde_json::to_string_pretty(&self).unwrap_or_else(|_| "{}".to_string())
        );
        process::exit(exit_code);
    }

    /// Output as JSON string
    pub fn to_json(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
    }

    /// Output as compact JSON string (single line)
    pub fn to_json_compact(&self) -> String {
        serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
    }
}

/// Create an error response (without generic data type)
pub fn error_response(
    command: &str,
    code: &str,
    message: &str,
    exit_code: i32,
) -> ResponseEnvelope<serde_json::Value> {
    ResponseEnvelope {
        success: false,
        command: command.to_string(),
        data: None,
        metadata: ResponseMetadata::new(exit_code),
        errors: vec![ErrorDetail {
            code: code.to_string(),
            message: message.to_string(),
            context: None,
            suggestion: None,
        }],
        warnings: vec![],
    }
}

/// Create an error response with suggestion
pub fn error_with_suggestion(
    command: &str,
    code: &str,
    message: &str,
    suggestion: &str,
    exit_code: i32,
) -> ResponseEnvelope<serde_json::Value> {
    ResponseEnvelope {
        success: false,
        command: command.to_string(),
        data: None,
        metadata: ResponseMetadata::new(exit_code),
        errors: vec![ErrorDetail {
            code: code.to_string(),
            message: message.to_string(),
            context: None,
            suggestion: Some(suggestion.to_string()),
        }],
        warnings: vec![],
    }
}

impl ResponseMetadata {
    pub fn new(exit_code: i32) -> Self {
        Self {
            run_id: None,
            request_id: None,
            duration_ms: None,
            version: env!("CARGO_PKG_VERSION").to_string(),
            timestamp: Utc::now(),
            exit_code,
        }
    }
}

impl ErrorDetail {
    pub fn new(code: &str, message: &str) -> Self {
        Self {
            code: code.to_string(),
            message: message.to_string(),
            context: None,
            suggestion: None,
        }
    }

    pub fn with_context(mut self, context: &str) -> Self {
        self.context = Some(context.to_string());
        self
    }

    pub fn with_suggestion(mut self, suggestion: &str) -> Self {
        self.suggestion = Some(suggestion.to_string());
        self
    }
}

/// Global output configuration
#[derive(Debug, Clone, Default)]
pub struct OutputConfig {
    /// Output as JSON
    pub json: bool,
    /// Machine mode (no colors, no decorations)
    pub machine: bool,
    /// Quiet mode (errors only)
    pub quiet: bool,
    /// Verbose mode
    pub verbose: bool,
    /// No color output
    pub no_color: bool,
}

impl OutputConfig {
    /// Load from environment variables
    pub fn from_env() -> Self {
        Self {
            json: std::env::var("MRAPIDS_JSON")
                .map(|v| v == "1" || v.to_lowercase() == "true")
                .unwrap_or(false)
                || std::env::var(env_vars::OUTPUT_FORMAT)
                    .map(|v| v.to_lowercase() == "json")
                    .unwrap_or(false),
            machine: std::env::var(env_vars::MACHINE_MODE)
                .map(|v| v == "1" || v.to_lowercase() == "true")
                .unwrap_or(false),
            quiet: std::env::var("MRAPIDS_QUIET")
                .map(|v| v == "1" || v.to_lowercase() == "true")
                .unwrap_or(false),
            verbose: std::env::var("MRAPIDS_VERBOSE")
                .map(|v| v == "1" || v.to_lowercase() == "true")
                .unwrap_or(false),
            no_color: std::env::var(env_vars::NO_COLOR)
                .map(|v| v == "1" || v.to_lowercase() == "true")
                .unwrap_or(false),
        }
    }

    /// Check if we should output decorations (banners, spinners)
    pub fn show_decorations(&self) -> bool {
        !self.machine && !self.json && !self.quiet
    }

    /// Check if colors should be used
    pub fn use_colors(&self) -> bool {
        !self.no_color && !self.machine && !self.json
    }
}

/// Check if JSON output mode is enabled globally
/// This checks environment variables set by main.rs from CLI args
pub fn is_json_mode() -> bool {
    std::env::var("MRAPIDS_JSON")
        .map(|v| v == "1" || v.to_lowercase() == "true")
        .unwrap_or(false)
        || std::env::var("MRAPIDS_OUTPUT")
            .map(|v| v.to_lowercase() == "json")
            .unwrap_or(false)
}

/// Check if machine mode is enabled globally
pub fn is_machine_mode() -> bool {
    std::env::var("MRAPIDS_MACHINE")
        .map(|v| v == "1" || v.to_lowercase() == "true")
        .unwrap_or(false)
}

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

    #[test]
    fn test_success_response() {
        let response = ResponseEnvelope::success("run", serde_json::json!({"status": "ok"}));
        assert!(response.success);
        assert_eq!(response.command, "run");
        assert_eq!(response.metadata.exit_code, exit_codes::SUCCESS);
    }

    #[test]
    fn test_error_response() {
        let response = error_response(
            "run",
            "NETWORK_ERROR",
            "Connection failed",
            exit_codes::NETWORK_ERROR,
        );
        assert!(!response.success);
        assert_eq!(response.errors.len(), 1);
        assert_eq!(response.errors[0].code, "NETWORK_ERROR");
        assert_eq!(response.metadata.exit_code, exit_codes::NETWORK_ERROR);
    }

    #[test]
    fn test_success_with_run() {
        let response = ResponseEnvelope::success_with_run(
            "run",
            serde_json::json!({"data": "test"}),
            "abc123".to_string(),
            Some("req_xyz".to_string()),
            150.5,
        );
        assert!(response.success);
        assert_eq!(response.metadata.run_id, Some("abc123".to_string()));
        assert_eq!(response.metadata.request_id, Some("req_xyz".to_string()));
        assert_eq!(response.metadata.duration_ms, Some(150.5));
    }

    #[test]
    fn test_json_serialization() {
        let response = ResponseEnvelope::success("test", serde_json::json!({"key": "value"}));
        let json = response.to_json();
        assert!(json.contains("\"success\": true"));
        assert!(json.contains("\"command\": \"test\""));
    }

    #[test]
    fn test_output_config_from_env() {
        // Default config
        let config = OutputConfig::default();
        assert!(!config.json);
        assert!(!config.machine);
        assert!(config.show_decorations());
    }

    #[test]
    fn test_exit_codes() {
        assert_eq!(exit_codes::SUCCESS, 0);
        assert_eq!(exit_codes::GENERAL_ERROR, 1);
        assert_eq!(exit_codes::NETWORK_ERROR, 3);
        assert_eq!(exit_codes::PARTIAL_SUCCESS, 10);
    }
}