componentize-qjs-cli 0.2.2

CLI for converting JavaScript to WebAssembly components using QuickJS
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
//! Shared test harness for componentize-qjs integration tests.
#![allow(dead_code)]

use std::fs;
use std::path::PathBuf;
use std::sync::OnceLock;

use tempfile::TempDir;
use wasmtime::component::{Component, Instance, Linker, ResourceTable, Val};
use wasmtime::{Config, Engine, Store};
use wasmtime_wasi::p2::pipe::{MemoryInputPipe, MemoryOutputPipe};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};

use componentize_qjs::{ComponentizeOpts, Runtime};

pub struct WasiCtxState {
    pub wasi: WasiCtx,
    pub table: ResourceTable,
}

impl WasiView for WasiCtxState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

pub fn engine() -> &'static Engine {
    static ENGINE: OnceLock<Engine> = OnceLock::new();
    ENGINE.get_or_init(|| {
        let mut config = Config::new();
        #[cfg(feature = "component-model-async")]
        config.wasm_component_model_async(true);
        config.wasm_component_model(true);
        Engine::new(&config).expect("Failed to create engine")
    })
}

pub fn async_engine() -> &'static Engine {
    static ENGINE: OnceLock<Engine> = OnceLock::new();
    ENGINE.get_or_init(|| {
        let mut config = Config::new();
        config.wasm_component_model(true);
        config.wasm_component_model_async(true);
        config.wasm_component_model_async_builtins(true);
        config.wasm_component_model_async_stackful(true);
        Engine::new(&config).expect("Failed to create async engine")
    })
}

pub struct Expectation {
    pub func_name: String,
    pub params: Vec<Val>,
    pub expected: Val,
}

/// Builder for constructing and running component tests.
pub struct TestCase {
    wit: Option<String>,
    wit_dir: Option<PathBuf>,
    world_name: Option<String>,
    script: Option<String>,
    stub_wasi: bool,
    env_vars: Vec<(String, String)>,
    stdin: Option<String>,
    expectations: Vec<Expectation>,
}

impl TestCase {
    pub fn new() -> Self {
        Self {
            wit: None,
            wit_dir: None,
            world_name: None,
            script: None,
            stub_wasi: false,
            env_vars: Vec::new(),
            stdin: None,
            expectations: Vec::new(),
        }
    }

    /// Set inline WIT source (written to a temp file).
    pub fn wit(mut self, wit: &str) -> Self {
        self.wit = Some(wit.to_string());
        self
    }

    /// Set path to a WIT directory (with deps/).
    pub fn wit_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.wit_dir = Some(path.into());
        self
    }

    /// Select a specific world from the WIT package.
    pub fn world(mut self, name: &str) -> Self {
        self.world_name = Some(name.to_string());
        self
    }

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

    pub fn stub_wasi(mut self) -> Self {
        self.stub_wasi = true;
        self
    }

    /// Add an environment variable visible to the WASI context.
    pub fn env(mut self, key: &str, value: &str) -> Self {
        self.env_vars.push((key.to_string(), value.to_string()));
        self
    }

    /// Set bytes visible through WASI stdin.
    pub fn stdin(mut self, input: &str) -> Self {
        self.stdin = Some(input.to_string());
        self
    }

    /// Register an expected function call: name, params, and expected return value.
    pub fn expect_call(mut self, name: &str, params: Vec<Val>, expected: Val) -> Self {
        self.expectations.push(Expectation {
            func_name: name.to_string(),
            params,
            expected,
        });
        self
    }

    /// Build the component and return a live instance ready for calls.
    pub fn build(self) -> anyhow::Result<ComponentInstance> {
        let dir = TempDir::new()?;

        let wit_path = if let Some(ref wit_dir) = self.wit_dir {
            wit_dir.clone()
        } else {
            let p = dir.path().join("test.wit");
            fs::write(&p, self.wit.as_deref().unwrap())?;
            p
        };

        let opts = ComponentizeOpts {
            wit_path: &wit_path,
            js_source: self.script.as_deref().unwrap(),
            world_name: self.world_name.as_deref(),
            stub_wasi: self.stub_wasi,
            disable_gc: false,
            runtime: Runtime::Default,
        };

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;

        let wasm = rt.block_on(componentize_qjs::componentize(&opts))?;
        ComponentInstance::from_wasm_with_stdin(wasm, self.env_vars, self.stdin, self.expectations)
    }

    /// Build the component and return an async-capable instance.
    pub async fn build_async(self) -> anyhow::Result<AsyncComponentInstance> {
        let dir = TempDir::new()?;

        let wit_path = if let Some(ref wit_dir) = self.wit_dir {
            wit_dir.clone()
        } else {
            let p = dir.path().join("test.wit");
            fs::write(&p, self.wit.as_deref().unwrap())?;
            p
        };

        let opts = ComponentizeOpts {
            wit_path: &wit_path,
            js_source: self.script.as_deref().unwrap(),
            world_name: self.world_name.as_deref(),
            stub_wasi: self.stub_wasi,
            disable_gc: false,
            runtime: Runtime::Default,
        };

        let wasm = componentize_qjs::componentize(&opts).await?;

        AsyncComponentInstance::from_wasm_with_stdin(wasm, self.env_vars, self.stdin).await
    }
}

pub struct ComponentInstance {
    store: Store<WasiCtxState>,
    inner: Instance,
    stdout: MemoryOutputPipe,
    expectations: Vec<Expectation>,
}

impl ComponentInstance {
    /// Instantiate a component from pre-built wasm bytes.
    pub fn from_wasm(
        wasm: Vec<u8>,
        env_vars: Vec<(String, String)>,
        expectations: Vec<Expectation>,
    ) -> anyhow::Result<Self> {
        Self::from_wasm_with_stdin(wasm, env_vars, None, expectations)
    }

    pub fn from_wasm_with_stdin(
        wasm: Vec<u8>,
        env_vars: Vec<(String, String)>,
        stdin: Option<String>,
        expectations: Vec<Expectation>,
    ) -> anyhow::Result<Self> {
        let engine = engine();
        let component = Component::new(engine, &wasm)?;

        let mut wasi_builder = WasiCtxBuilder::new();
        if !env_vars.is_empty() {
            wasi_builder.inherit_env();
            for (k, v) in &env_vars {
                wasi_builder.env(k, v);
            }
        }
        let stdout = MemoryOutputPipe::new(10000);
        wasi_builder
            .stdin(MemoryInputPipe::new(stdin.unwrap_or_default()))
            .stdout(stdout.clone());
        let wasi = wasi_builder.build();
        let table = ResourceTable::new();
        let mut store = Store::new(engine, WasiCtxState { wasi, table });

        let mut linker = Linker::new(engine);
        wasmtime_wasi::p2::add_to_linker_sync(&mut linker)?;

        let instance = linker.instantiate(&mut store, &component)?;

        Ok(ComponentInstance {
            store,
            inner: instance,
            stdout,
            expectations,
        })
    }

    /// Call an exported function with the given params and return results.
    pub fn call(&mut self, name: &str, params: &[Val], result_count: usize) -> Vec<Val> {
        let func = self
            .inner
            .get_func(&mut self.store, name)
            .unwrap_or_else(|| panic!("export `{name}` not found"));

        let mut results = vec![Val::Bool(false); result_count];
        func.call(&mut self.store, params, &mut results)
            .unwrap_or_else(|e| panic!("calling `{name}` failed: {e}"));

        results
    }

    /// Call an exported function expecting a single return value.
    pub fn call1(&mut self, name: &str, params: &[Val]) -> Val {
        self.call(name, params, 1).into_iter().next().unwrap()
    }

    /// Run all registered expectations, asserting each call matches.
    pub fn run(&mut self) {
        let expectations = std::mem::take(&mut self.expectations);

        for exp in expectations {
            let result = self.call1(&exp.func_name, &exp.params);
            assert_eq!(
                result, exp.expected,
                "calling `{}`: expected {:?}, got {:?}",
                exp.func_name, exp.expected, result
            );
        }
    }

    pub fn stdout_bytes(&self) -> Vec<u8> {
        self.stdout.contents().to_vec()
    }

    /// Get the wasmtime instance and store for typed/interface function access.
    pub fn parts(&mut self) -> (&Instance, &mut Store<WasiCtxState>) {
        (&self.inner, &mut self.store)
    }
}

pub fn componentize_qjs() -> assert_cmd::Command {
    assert_cmd::cargo::cargo_bin_cmd!("componentize-qjs")
}

pub struct AsyncComponentInstance {
    store: Store<WasiCtxState>,
    inner: Instance,
    stdout: MemoryOutputPipe,
}

impl AsyncComponentInstance {
    pub async fn from_wasm(wasm: Vec<u8>, env_vars: Vec<(String, String)>) -> anyhow::Result<Self> {
        Self::from_wasm_with_stdin(wasm, env_vars, None).await
    }

    pub async fn from_wasm_with_stdin(
        wasm: Vec<u8>,
        env_vars: Vec<(String, String)>,
        stdin: Option<String>,
    ) -> anyhow::Result<Self> {
        let engine = async_engine();
        let component = Component::new(engine, &wasm)?;

        let mut wasi_builder = WasiCtxBuilder::new();
        if !env_vars.is_empty() {
            wasi_builder.inherit_env();
            for (k, v) in &env_vars {
                wasi_builder.env(k, v);
            }
        }
        let stdout = MemoryOutputPipe::new(10000);
        wasi_builder
            .stdin(MemoryInputPipe::new(stdin.unwrap_or_default()))
            .stdout(stdout.clone());
        let wasi = wasi_builder.build();
        let table = ResourceTable::new();
        let mut store = Store::new(engine, WasiCtxState { wasi, table });

        let mut linker = Linker::new(engine);
        wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
        wasmtime_wasi::p3::add_to_linker(&mut linker)?;

        let instance = linker.instantiate_async(&mut store, &component).await?;

        Ok(AsyncComponentInstance {
            store,
            inner: instance,
            stdout,
        })
    }

    /// Call an exported async function with the given params and return results.
    pub async fn call_async(
        &mut self,
        name: &str,
        params: &[Val],
        result_count: usize,
    ) -> anyhow::Result<Vec<Val>> {
        let func = self
            .inner
            .get_func(&mut self.store, name)
            .unwrap_or_else(|| panic!("export `{name}` not found"));

        let mut results = vec![Val::Bool(false); result_count];
        func.call_async(&mut self.store, params, &mut results)
            .await?;

        Ok(results)
    }

    /// Call an exported async function expecting a single return value.
    pub async fn call1_async(&mut self, name: &str, params: &[Val]) -> anyhow::Result<Val> {
        Ok(self
            .call_async(name, params, 1)
            .await?
            .into_iter()
            .next()
            .unwrap())
    }

    /// Get the wasmtime instance and store for typed function access.
    pub fn parts(&mut self) -> (&Instance, &mut Store<WasiCtxState>) {
        (&self.inner, &mut self.store)
    }

    pub fn stdout_bytes(&self) -> Vec<u8> {
        self.stdout.contents().to_vec()
    }
}

/// Write WIT + JS to a temp dir, run the CLI, return the output wasm path and temp dir.
pub fn run_cli_build(wit: &str, js: &str, extra_args: &[&str]) -> (PathBuf, TempDir) {
    let dir = TempDir::new().unwrap();

    let wit_path = dir.path().join("test.wit");
    fs::write(&wit_path, wit).unwrap();

    let js_path = dir.path().join("test.js");
    fs::write(&js_path, js).unwrap();

    let output = dir.path().join("output.wasm");

    let mut cmd = componentize_qjs();
    cmd.arg("--wit")
        .arg(&wit_path)
        .arg("--js")
        .arg(&js_path)
        .arg("--output")
        .arg(&output);

    for arg in extra_args {
        cmd.arg(arg);
    }

    cmd.assert().success();
    assert!(output.exists(), "Output wasm file should exist");
    (output, dir)
}

pub fn wasi_wit_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/wit")
}