Skip to main content

componentize_qjs/
lib.rs

1pub mod codegen;
2pub mod stubwasi;
3
4use std::path::Path;
5
6use anyhow::{Context, Result, anyhow};
7use bytes::Bytes;
8use stubwasi::stub_wasi_imports;
9use wasi_preview1_component_adapter_provider::WASI_SNAPSHOT_PREVIEW1_REACTOR_ADAPTER;
10use wasmtime::component::{Component, Linker, ResourceTable};
11use wasmtime::{Config, Engine, Store};
12use wasmtime_wasi::p2::pipe::{MemoryInputPipe, MemoryOutputPipe};
13use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
14use wasmtime_wizer::{WasmtimeWizerComponent, Wizer};
15use wit_parser::Resolve;
16
17include!(concat!(env!("OUT_DIR"), "/output.rs"));
18
19wasmtime::component::bindgen!({
20    path: "wit/init.wit",
21    world: "init",
22    exports: { default: async },
23});
24
25struct Ctx {
26    wasi: WasiCtx,
27    table: ResourceTable,
28}
29
30impl WasiView for Ctx {
31    fn ctx(&mut self) -> WasiCtxView<'_> {
32        WasiCtxView {
33            ctx: &mut self.wasi,
34            table: &mut self.table,
35        }
36    }
37}
38
39/// Options for componentizing a JavaScript source file.
40pub struct ComponentizeOpts<'a> {
41    /// Path to the WIT file or directory
42    pub wit_path: &'a Path,
43    /// JavaScript source code
44    pub js_source: &'a str,
45    /// World name to use from the WIT (None = default world)
46    pub world_name: Option<&'a str>,
47    /// Stub all WASI imports with traps
48    pub stub_wasi: bool,
49    /// Disable automatic garbage collection in the QuickJS runtime
50    pub disable_gc: bool,
51    /// Runtime to embed before Wizer initialization
52    pub runtime: Runtime<'a>,
53}
54
55/// QuickJS runtime variant to embed in the generated component.
56#[derive(Clone, Copy, Debug)]
57pub enum Runtime<'a> {
58    /// Standard runtime optimized for speed.
59    Default,
60    /// Runtime optimized for smaller generated components.
61    OptSize,
62    /// Caller-provided runtime Wasm bytes.
63    Custom(&'a [u8]),
64}
65
66impl Default for Runtime<'_> {
67    fn default() -> Self {
68        default_builtin_runtime()
69    }
70}
71
72/// Return the built-in runtime selected by Cargo features.
73pub fn default_builtin_runtime() -> Runtime<'static> {
74    if cfg!(feature = "opt-size") {
75        Runtime::OptSize
76    } else {
77        Runtime::Default
78    }
79}
80
81/// Convert JavaScript source code into a WebAssembly component.
82pub async fn componentize(opts: &ComponentizeOpts<'_>) -> Result<Vec<u8>> {
83    let mut resolve = Resolve::default();
84    let (pkg_id, _) = resolve.push_path(opts.wit_path)?;
85    let world_id = resolve.select_world(&[pkg_id], opts.world_name)?;
86
87    let shim = codegen::generate_shim(&resolve, world_id);
88    let mut wit_dylib = wit_dylib::create(&resolve, world_id, None);
89
90    wit_component::embed_component_metadata(
91        &mut wit_dylib,
92        &resolve,
93        world_id,
94        wit_component::StringEncoding::UTF8,
95    )?;
96
97    let pre_wizer_component = wit_component::Linker::default()
98        .validate(true)
99        .library(
100            "componentize_qjs_runtime.wasm",
101            runtime_wasm(opts.runtime),
102            false,
103        )?
104        .library("wit-dylib.wasm", &wit_dylib, false)?
105        .adapter(
106            "wasi_snapshot_preview1",
107            WASI_SNAPSHOT_PREVIEW1_REACTOR_ADAPTER,
108        )?
109        .encode()
110        .context("failed to link and encode component")?;
111
112    let mut component =
113        wizer_init(&pre_wizer_component, &shim, opts.js_source, opts.disable_gc).await?;
114
115    if opts.stub_wasi {
116        component = stub_wasi_imports(&component).context("failed to stub WASI imports")?;
117    }
118
119    Ok(component)
120}
121
122/// Return the built-in default runtime Wasm bytes.
123pub fn default_runtime_wasm() -> &'static [u8] {
124    DEFAULT_RUNTIME_WASM
125}
126
127/// Return the built-in opt-size runtime Wasm bytes.
128pub fn opt_size_runtime_wasm() -> &'static [u8] {
129    OPT_SIZE_RUNTIME_WASM
130}
131
132fn runtime_wasm(runtime: Runtime<'_>) -> &[u8] {
133    match runtime {
134        Runtime::Default => DEFAULT_RUNTIME_WASM,
135        Runtime::OptSize => OPT_SIZE_RUNTIME_WASM,
136        Runtime::Custom(wasm) => wasm,
137    }
138}
139
140async fn wizer_init(component: &[u8], shim: &str, js: &str, disable_gc: bool) -> Result<Vec<u8>> {
141    let stdout = MemoryOutputPipe::new(10000);
142    let stderr = MemoryOutputPipe::new(10000);
143
144    let mut wasi = WasiCtxBuilder::new();
145    let wasi = wasi
146        .stdin(MemoryInputPipe::new(Bytes::new()))
147        .stdout(stdout.clone())
148        .stderr(stderr.clone())
149        .build();
150
151    let table = ResourceTable::new();
152    let mut config = Config::new();
153    config.wasm_component_model(true);
154    config.wasm_component_model_async(true);
155
156    let engine = Engine::new(&config)?;
157    let mut store = Store::new(&engine, Ctx { wasi, table });
158
159    let wizer = Wizer::new();
160    let (cx, instrumented) = wizer.instrument_component(component)?;
161    let comp = Component::new(&engine, &instrumented)?;
162
163    let mut linker = Linker::new(&engine);
164    wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
165    wasmtime_wasi::p3::add_to_linker(&mut linker)?;
166    let instance = linker.instantiate_async(&mut store, &comp).await?;
167
168    let init = Init::new(&mut store, &instance)?;
169    init.call_init(&mut store, shim, js, disable_gc)
170        .await?
171        .map_err(|e| anyhow!("{e}"))
172        .with_context(move || {
173            format!(
174                "{}{}",
175                String::from_utf8_lossy(&stdout.contents()),
176                String::from_utf8_lossy(&stderr.contents())
177            )
178        })?;
179
180    let component = wizer
181        .snapshot_component(
182            cx,
183            &mut WasmtimeWizerComponent {
184                store: &mut store,
185                instance,
186            },
187        )
188        .await?;
189
190    Ok(component)
191}