0
# WASI Runtime
1
2
Core runtime management for executing WebAssembly modules with WASI (WebAssembly System Interface) support. The WASI class handles the complete lifecycle of WebAssembly program execution, providing system interface capabilities, I/O management, and environment configuration.
3
4
## Capabilities
5
6
### WASI Class
7
8
Main class for managing WASI WebAssembly execution environments.
9
10
```typescript { .api }
11
/**
12
* WASI execution environment for WebAssembly modules
13
*/
14
class WASI {
15
/**
16
* Create a new WASI instance with configuration
17
* @param config - WASI configuration options
18
*/
19
constructor(config: WasiConfig);
20
21
/** Access to the in-memory filesystem */
22
readonly fs: MemFS;
23
24
/**
25
* Get WASI imports for a WebAssembly module
26
* @param module - WebAssembly module to get imports for
27
* @returns Object containing WASI imports for instantiation
28
*/
29
getImports(module: WebAssembly.Module): object;
30
31
/**
32
* Instantiate a WebAssembly module with WASI support
33
* @param module_or_instance - WebAssembly module or existing instance
34
* @param imports - Additional imports to merge with WASI imports
35
* @returns WebAssembly instance ready for execution
36
*/
37
instantiate(module_or_instance: any, imports?: object): WebAssembly.Instance;
38
39
/**
40
* Start WASI program execution
41
* @param instance - Optional WebAssembly instance (if not provided, uses last instantiated)
42
* @returns Exit code from the WASI program (0 for success)
43
*/
44
start(instance?: WebAssembly.Instance): number;
45
46
/**
47
* Get stdout buffer and clear it
48
* @returns Stdout content as Uint8Array
49
*/
50
getStdoutBuffer(): Uint8Array;
51
52
/**
53
* Get stdout as string and clear it
54
* @returns Stdout content as UTF-8 string
55
*/
56
getStdoutString(): string;
57
58
/**
59
* Get stderr buffer and clear it
60
* @returns Stderr content as Uint8Array
61
*/
62
getStderrBuffer(): Uint8Array;
63
64
/**
65
* Get stderr as string and clear it
66
* @returns Stderr content as UTF-8 string
67
*/
68
getStderrString(): string;
69
70
/**
71
* Set stdin buffer for program input
72
* @param buf - Input data as Uint8Array
73
*/
74
setStdinBuffer(buf: Uint8Array): void;
75
76
/**
77
* Set stdin string for program input
78
* @param input - Input data as UTF-8 string
79
*/
80
setStdinString(input: string): void;
81
82
/**
83
* Free WebAssembly resources
84
* Call when done with the WASI instance to clean up memory
85
*/
86
free(): void;
87
}
88
```
89
90
**Usage Examples:**
91
92
```typescript
93
import { init, WASI } from "@wasmer/wasi";
94
95
await init();
96
97
// Basic WASI execution
98
const wasi = new WASI({
99
args: ["program", "--verbose"],
100
env: { DEBUG: "1" }
101
});
102
103
const module = await WebAssembly.compileStreaming(fetch("program.wasm"));
104
await wasi.instantiate(module, {});
105
const exitCode = wasi.start();
106
107
if (exitCode !== 0) {
108
console.error("Program failed:", wasi.getStderrString());
109
} else {
110
console.log("Output:", wasi.getStdoutString());
111
}
112
113
// Advanced usage with custom imports
114
const customImports = {
115
env: {
116
custom_function: () => console.log("Called from WASM!")
117
}
118
};
119
120
const wasiImports = wasi.getImports(module);
121
const instance = await WebAssembly.instantiate(module, {
122
...wasiImports,
123
...customImports
124
});
125
126
wasi.instantiate(instance);
127
wasi.start();
128
```
129
130
### Configuration
131
132
WASI configuration options for customizing the execution environment.
133
134
```typescript { .api }
135
/**
136
* Configuration options for WASI instance
137
*/
138
interface WasiConfig {
139
/**
140
* Command-line arguments passed to the WASI executable
141
* First argument is typically the program name
142
*/
143
readonly args?: string[];
144
145
/**
146
* Additional environment variables made available to the WASI executable
147
* Merged with any existing environment
148
*/
149
readonly env?: Record<string, string>;
150
151
/**
152
* Preopened directories mapped from virtual paths to host paths
153
* Currently used for configuration but may have limited host access in browser environments
154
*/
155
readonly preopens?: Record<string, string>;
156
157
/**
158
* Custom in-memory filesystem instance
159
* If not provided, a new empty filesystem is created
160
*/
161
readonly fs?: MemFS;
162
}
163
```
164
165
**Configuration Examples:**
166
167
```typescript
168
// Basic configuration
169
const basicConfig = {
170
args: ["myprogram"],
171
env: {
172
HOME: "/home/user",
173
PATH: "/usr/bin"
174
}
175
};
176
177
// With custom filesystem
178
import { MemFS } from "@wasmer/wasi";
179
const fs = new MemFS();
180
fs.createDir("/app");
181
fs.createDir("/data");
182
183
const advancedConfig = {
184
args: ["dataprocessor", "--input", "/data/input.txt"],
185
env: {
186
WORKER_THREADS: "4",
187
LOG_LEVEL: "info"
188
},
189
fs: fs
190
};
191
192
const wasi = new WASI(advancedConfig);
193
```
194
195
### Standard I/O Operations
196
197
WASI provides comprehensive standard input/output/error handling with both binary and string interfaces.
198
199
```typescript { .api }
200
// Output retrieval (these methods flush/clear the buffers)
201
getStdoutBuffer(): Uint8Array;
202
getStdoutString(): string;
203
getStderrBuffer(): Uint8Array;
204
getStderrString(): string;
205
206
// Input provision
207
setStdinBuffer(buf: Uint8Array): void;
208
setStdinString(input: string): void;
209
```
210
211
**I/O Examples:**
212
213
```typescript
214
// Providing input to a program
215
wasi.setStdinString("Hello, WASI program!\nThis is input data.\n");
216
217
// Or using binary data
218
const binaryInput = new TextEncoder().encode("Binary input data");
219
wasi.setStdinBuffer(binaryInput);
220
221
// Running and capturing output
222
const exitCode = wasi.start();
223
224
// Get output (these calls clear the buffers)
225
const stdout = wasi.getStdoutString();
226
const stderr = wasi.getStderrString();
227
228
console.log("Program output:", stdout);
229
if (stderr) {
230
console.error("Program errors:", stderr);
231
}
232
233
// For binary output handling
234
const stdoutBytes = wasi.getStdoutBuffer();
235
const stderrBytes = wasi.getStderrBuffer();
236
```
237
238
### Error Handling
239
240
```typescript { .api }
241
/**
242
* Error class representing aborted WASI instruction execution
243
*/
244
class WasmerRuntimeError extends Error {
245
// Standard Error properties available
246
}
247
```
248
249
Common error scenarios:
250
251
- **Initialization Error**: Calling WASI methods before `init()`
252
- **Module Instantiation Error**: Invalid WebAssembly module or missing imports
253
- **Runtime Error**: WASI program crashes or invalid system calls
254
- **Invalid Instance Error**: Calling `start()` without proper instantiation
255
256
**Error Handling Examples:**
257
258
```typescript
259
try {
260
await init();
261
const wasi = new WASI({ args: ["program"] });
262
263
const module = await WebAssembly.compileStreaming(fetch("program.wasm"));
264
await wasi.instantiate(module, {});
265
266
const exitCode = wasi.start();
267
268
if (exitCode !== 0) {
269
const stderr = wasi.getStderrString();
270
throw new Error(`Program exited with code ${exitCode}: ${stderr}`);
271
}
272
273
} catch (error) {
274
if (error instanceof WasmerRuntimeError) {
275
console.error("WASI runtime error:", error.message);
276
} else {
277
console.error("General error:", error);
278
}
279
}
280
```