wasmrun 0.19.0

A WebAssembly Runtime
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
use thiserror::Error;

/// The main error type for Wasmrun operations
#[derive(Error, Debug)]
pub enum WasmrunError {
    /// I/O related errors
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Path-related errors
    #[error("Path error: {message}")]
    Path { message: String },

    /// File not found
    #[error("File not found: {path}")]
    FileNotFound { path: String },

    /// Directory not found
    #[error("Directory not found: {path}")]
    DirectoryNotFound { path: String },

    /// Invalid file format
    #[error("Invalid file format: {path} - {reason}")]
    InvalidFileFormat { path: String, reason: String },

    /// WASM-specific errors
    #[error(transparent)]
    Wasm(#[from] WasmError),

    /// Compilation errors
    #[error(transparent)]
    Compilation(#[from] CompilationError),

    /// Server errors
    #[error(transparent)]
    Server(#[from] ServerError),

    /// Command execution errors
    #[error(transparent)]
    Command(#[from] CommandError),

    /// Configuration errors
    #[error(transparent)]
    Config(#[from] ConfigError),

    /// Language detection errors
    #[error("Language detection failed: {message}")]
    #[allow(dead_code)] // TODO: Use for advanced language detection
    LanguageDetection { message: String },

    /// Multiple tools missing
    #[error("Missing required tools: {tools:?}")]
    MissingTools { tools: Vec<String> },

    /// Generic error with context
    #[error("{context}: {source}")]
    WithContext {
        context: String,
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
}

/// WASM-specific errors
#[derive(Error, Debug)]
pub enum WasmError {
    /// Invalid WASM magic bytes
    #[error("Invalid WASM magic bytes in file: {path}")]
    InvalidMagicBytes { path: String },

    /// WASM module validation failed
    #[error("WASM module validation failed: {reason}")]
    ValidationFailed { reason: String },

    /// wasm-bindgen detection
    #[error("wasm-bindgen module detected but JavaScript file not found")]
    WasmBindgenJsNotFound,
}

/// Compilation-related errors
#[derive(Error, Debug)]
pub enum CompilationError {
    /// Language not supported
    #[error("Language not supported: {language}")]
    UnsupportedLanguage { language: String },

    /// Build tool not found
    #[error("Build tool not found: {tool}. Please install {tool} to compile {language} projects")]
    BuildToolNotFound { tool: String, language: String },

    /// Build failed
    #[error("Build failed for {language} project: {reason}")]
    BuildFailed { language: String, reason: String },

    /// Tool execution failed
    #[error("Failed to execute {tool}: {reason}")]
    ToolExecutionFailed { tool: String, reason: String },

    /// Project structure invalid
    #[error("Invalid {language} project structure: {reason}")]
    InvalidProjectStructure { language: String, reason: String },

    /// Missing entry file
    #[error("No entry file found for {language} project. Expected one of: {candidates:?}")]
    MissingEntryFile {
        language: String,
        candidates: Vec<String>,
    },

    /// Output directory creation failed
    #[error("Failed to create output directory: {path}")]
    OutputDirectoryCreationFailed { path: String },

    /// Optimization level invalid
    #[error("Invalid optimization level: {level}. Valid options: {valid_options:?}")]
    #[allow(dead_code)]
    InvalidOptimizationLevel {
        level: String,
        valid_options: Vec<String>,
    },
}

/// Server-related errors
#[derive(Error, Debug)]
pub enum ServerError {
    /// Server startup failed
    #[error("Failed to start server on port {port}: {reason}")]
    StartupFailed { port: u16, reason: String },

    /// Request handling failed
    #[error("Failed to handle request: {reason}")]
    RequestHandlingFailed { reason: String },

    /// Server not running
    #[error("No server is currently running")]
    NotRunning,

    /// Failed to stop server
    #[error("Failed to stop server with PID {pid}: {reason}")]
    StopFailed { pid: u32, reason: String },
}

/// Command execution errors
#[derive(Error, Debug)]
pub enum CommandError {
    /// Invalid arguments
    #[error("Invalid command arguments: {message}")]
    InvalidArguments { message: String },
}

/// Configuration errors
#[derive(Error, Debug)]
pub enum ConfigError {
    /// Invalid configuration value
    #[error("Invalid configuration value: {message}")]
    InvalidValue { message: String },

    /// Missing required configuration
    #[error("Missing required configuration: {key}")]
    MissingRequired { key: String },

    /// Configuration parse error
    #[error("Failed to parse configuration: {message}")]
    ParseError { message: String },

    /// Configuration file not found
    #[error("Configuration file not found: {path}")]
    FileNotFound { path: String },
}

/// Result type alias for Wasmrun operations
pub type Result<T> = std::result::Result<T, WasmrunError>;

/// Specialized result types for different modules
pub type CompilationResult<T> = std::result::Result<T, CompilationError>;

impl WasmrunError {
    /// new path error
    pub fn path(message: impl Into<String>) -> Self {
        Self::Path {
            message: message.into(),
        }
    }

    /// file not found error
    pub fn file_not_found(path: impl Into<String>) -> Self {
        Self::FileNotFound { path: path.into() }
    }

    /// directory not found error
    pub fn directory_not_found(path: impl Into<String>) -> Self {
        Self::DirectoryNotFound { path: path.into() }
    }

    /// Invalid file format error
    pub fn invalid_file_format(path: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::InvalidFileFormat {
            path: path.into(),
            reason: reason.into(),
        }
    }

    /// language detection error
    #[allow(dead_code)] // TODO: Use for advanced language detection
    pub fn language_detection(message: impl Into<String>) -> Self {
        Self::LanguageDetection {
            message: message.into(),
        }
    }

    /// missing tools error
    pub fn missing_tools(tools: Vec<String>) -> Self {
        Self::MissingTools { tools }
    }

    /// Add context to an error
    pub fn add_context<E>(context: impl Into<String>, error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self::WithContext {
            context: context.into(),
            source: Box::new(error),
        }
    }

    /// Check if this error is recoverable
    #[allow(dead_code)] // TODO: Future error recovery features
    pub fn is_recoverable(&self) -> bool {
        match self {
            WasmrunError::FileNotFound { .. } => false,
            WasmrunError::DirectoryNotFound { .. } => false,
            WasmrunError::MissingTools { .. } => false,
            _ => false,
        }
    }

    /// Get user-friendly error message
    #[allow(dead_code)] // TODO: Future user-friendly error messages
    pub fn user_message(&self) -> String {
        match self {
            WasmrunError::FileNotFound { path } => {
                format!("File not found: {path}\n💡 Check the file path and try again")
            }
            WasmrunError::DirectoryNotFound { path } => {
                format!("Directory not found: {path}\n💡 Check the directory path and try again")
            }
            WasmrunError::MissingTools { tools } => {
                format!(
                    "Missing required tools: {}\n💡 Please install these tools to continue",
                    tools.join(", ")
                )
            }
            WasmrunError::Wasm(WasmError::WasmBindgenJsNotFound) => {
                "This appears to be a wasm-bindgen module\n💡 Try running the corresponding .js file instead".to_string()
            }
            _ => self.to_string(),
        }
    }

    /// Get suggested actions for the error
    #[allow(dead_code)] // TODO: Future error suggestions system
    pub fn suggestions(&self) -> Vec<String> {
        match self {
            WasmrunError::MissingTools { tools } => tools
                .iter()
                .map(|tool| format!("Install {tool} using your package manager"))
                .collect(),
            WasmrunError::Compilation(CompilationError::MissingEntryFile {
                candidates, ..
            }) => {
                vec![
                    format!("Create one of these entry files: {}", candidates.join(", ")),
                    "Check your project structure".to_string(),
                    "Refer to the language documentation".to_string(),
                ]
            }
            _ => vec![],
        }
    }
}

impl WasmError {
    /// new validation failed error
    pub fn validation_failed(reason: impl Into<String>) -> Self {
        Self::ValidationFailed {
            reason: reason.into(),
        }
    }
}

impl CompilationError {
    /// new build failed error
    #[allow(dead_code)] // TODO: Use for compilation error handling
    pub fn build_failed(language: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::BuildFailed {
            language: language.into(),
            reason: reason.into(),
        }
    }
}

impl ServerError {
    /// new startup failed error
    pub fn startup_failed(port: u16, reason: impl Into<String>) -> Self {
        Self::StartupFailed {
            port,
            reason: reason.into(),
        }
    }
}

impl CommandError {
    /// new invalid arguments error
    pub fn invalid_arguments(message: impl Into<String>) -> Self {
        Self::InvalidArguments {
            message: message.into(),
        }
    }
}

impl From<&str> for WasmrunError {
    fn from(message: &str) -> Self {
        WasmrunError::Path {
            message: message.to_string(),
        }
    }
}

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

    #[test]
    fn test_wasmrun_error_path() {
        let error = WasmrunError::path("test path error");
        match error {
            WasmrunError::Path { message } => {
                assert_eq!(message, "test path error");
            }
            _ => panic!("Expected Path error variant"),
        }
    }

    #[test]
    fn test_wasmrun_error_file_not_found() {
        let error = WasmrunError::file_not_found("/path/to/file.wasm");
        match error {
            WasmrunError::FileNotFound { path } => {
                assert_eq!(path, "/path/to/file.wasm");
            }
            _ => panic!("Expected FileNotFound error variant"),
        }
    }

    #[test]
    fn test_wasmrun_error_directory_not_found() {
        let error = WasmrunError::directory_not_found("/path/to/dir");
        match error {
            WasmrunError::DirectoryNotFound { path } => {
                assert_eq!(path, "/path/to/dir");
            }
            _ => panic!("Expected DirectoryNotFound error variant"),
        }
    }

    #[test]
    fn test_wasmrun_error_invalid_file_format() {
        let error = WasmrunError::invalid_file_format("file.txt", "not a wasm file");
        match error {
            WasmrunError::InvalidFileFormat { path, reason } => {
                assert_eq!(path, "file.txt");
                assert_eq!(reason, "not a wasm file");
            }
            _ => panic!("Expected InvalidFileFormat error variant"),
        }
    }

    #[test]
    fn test_wasmrun_error_language_detection() {
        let error = WasmrunError::language_detection("could not detect language");
        match error {
            WasmrunError::LanguageDetection { message } => {
                assert_eq!(message, "could not detect language");
            }
            _ => panic!("Expected LanguageDetection error variant"),
        }
    }

    #[test]
    fn test_wasmrun_error_missing_tools() {
        let tools = vec!["cargo".to_string(), "rustup".to_string()];
        let error = WasmrunError::missing_tools(tools.clone());
        match error {
            WasmrunError::MissingTools { tools: error_tools } => {
                assert_eq!(error_tools, tools);
            }
            _ => panic!("Expected MissingTools error variant"),
        }
    }

    #[test]
    fn test_wasmrun_error_is_recoverable() {
        assert!(!WasmrunError::file_not_found("test").is_recoverable());
        assert!(!WasmrunError::directory_not_found("test").is_recoverable());
        assert!(!WasmrunError::missing_tools(vec!["tool".to_string()]).is_recoverable());
    }

    #[test]
    fn test_wasmrun_error_user_message() {
        let error = WasmrunError::file_not_found("test.wasm");
        let message = error.user_message();
        assert!(message.contains("test.wasm"));
        assert!(message.contains("💡"));
    }

    #[test]
    fn test_wasmrun_error_from_str() {
        let error = WasmrunError::from("test error");
        match error {
            WasmrunError::Path { message } => {
                assert_eq!(message, "test error");
            }
            _ => panic!("Expected Path error variant"),
        }
    }

    #[test]
    fn test_wasm_error_validation_failed() {
        let error = WasmError::validation_failed("invalid magic bytes");
        match error {
            WasmError::ValidationFailed { reason } => {
                assert_eq!(reason, "invalid magic bytes");
            }
            _ => panic!("Expected ValidationFailed error variant"),
        }
    }

    #[test]
    fn test_compilation_error_build_failed() {
        let error = CompilationError::build_failed("Rust", "cargo build failed");
        match error {
            CompilationError::BuildFailed { language, reason } => {
                assert_eq!(language, "Rust");
                assert_eq!(reason, "cargo build failed");
            }
            _ => panic!("Expected BuildFailed error variant"),
        }
    }

    #[test]
    fn test_server_error_startup_failed() {
        let error = ServerError::startup_failed(8080, "port already in use");
        match error {
            ServerError::StartupFailed { port, reason } => {
                assert_eq!(port, 8080);
                assert_eq!(reason, "port already in use");
            }
            _ => panic!("Expected StartupFailed error variant"),
        }
    }

    #[test]
    fn test_command_error_invalid_arguments() {
        let error = CommandError::invalid_arguments("missing file path");
        let CommandError::InvalidArguments { message } = error;
        assert_eq!(message, "missing file path");
    }
}