wasm-rquickjs 0.1.1

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
use crate::conversions::generate_conversions;
use crate::exports::generate_export_impls;
use crate::imports::generate_import_modules;
use crate::skeleton::{
    copy_skeleton_lock, copy_skeleton_sources, generate_app_manifest, generate_cargo_toml,
};
use crate::wit::{add_get_script_import, add_wizer_init_export};
use anyhow::{Context, anyhow};
use camino::{Utf8Path, Utf8PathBuf};
use heck::{ToSnakeCase, ToUpperCamelCase};
use proc_macro2::{Ident, Span};
use std::cell::RefCell;
use std::collections::{BTreeSet, VecDeque};
use wit_parser::{
    Function, Interface, InterfaceId, PackageId, PackageName, PackageSourceMap, Resolve, TypeDef,
    TypeId, TypeOwner, WorldId, WorldItem,
};

mod conversions;
mod exports;
mod imports;
mod javascript;
#[cfg(feature = "optimize")]
mod optimize;
mod rust_bindgen;
mod skeleton;
mod types;
mod typescript;
mod wit;

#[cfg(feature = "optimize")]
pub use optimize::optimize_component;

/// Write `contents` to `path` only if the file doesn't exist or its current content differs.
/// This preserves file timestamps when content hasn't changed, avoiding unnecessary recompilation.
pub(crate) fn write_if_changed(
    path: impl AsRef<std::path::Path>,
    contents: impl AsRef<[u8]>,
) -> std::io::Result<()> {
    let path = path.as_ref();
    let contents = contents.as_ref();
    if let Ok(existing) = std::fs::read(path)
        && existing == contents
    {
        return Ok(());
    }
    std::fs::write(path, contents)
}

/// Copy a file from `src` to `dst` only if the destination doesn't exist or its content differs.
pub(crate) fn copy_if_changed(
    src: impl AsRef<std::path::Path>,
    dst: impl AsRef<std::path::Path>,
) -> std::io::Result<()> {
    let src = src.as_ref();
    let dst = dst.as_ref();
    let src_contents = std::fs::read(src)?;
    if let Ok(existing) = std::fs::read(dst)
        && existing == src_contents
    {
        return Ok(());
    }
    std::fs::write(dst, src_contents)
}

/// Specifies how a given user-defined JS module gets embedded into the generated Rust crate.
#[derive(Debug, Clone)]
pub enum EmbeddingMode {
    /// Points to a JS module file that is going to be embedded into the generated Rust crate
    EmbedFile(Utf8PathBuf),
    /// The JS module is going to be fetched run-time through an imported WIT interface
    Composition,
}

/// Specifies a JS module to be evaluated in the generated component.
#[derive(Debug, Clone)]
pub struct JsModuleSpec {
    pub name: String,
    pub mode: EmbeddingMode,
}

impl JsModuleSpec {
    pub fn file_name(&self) -> String {
        self.name.replace('/', "_") + ".js"
    }
}

/// Generates a Rust wrapper crate for a combination of a WIT package and a JavaScript module.
///
/// The `wit` parameter should point to a WIT root (holding the WIT package of the component, with
/// optionally a `deps` subdirectory with an arbitrary number of dependencies).
///
/// The `js_modules` parameter must point to at least one JavaScript module that implements the WIT package,
/// and optionally additional modules that get imported during the initialization of the component. It is
/// always the first in the list that is considered the one containing the implementation of the WIT exports.
///
/// The `output` parameter is the root directory where the generated Rust crate's source code and
/// Cargo manifest is placed.
///
/// If `world` is `None`, the default world is selected and used, otherwise the specified one.
pub fn generate_wrapper_crate(
    wit: &Utf8Path,
    js_modules: &[JsModuleSpec],
    output: &Utf8Path,
    world: Option<&str>,
) -> anyhow::Result<()> {
    // Making sure the target directories exists
    std::fs::create_dir_all(output).context("Failed to create output directory")?;
    std::fs::create_dir_all(output.join("src")).context("Failed to create output/src directory")?;
    std::fs::create_dir_all(output.join("src").join("modules"))
        .context("Failed to create output/src/modules directory")?;

    // Resolving the WIT package (initial parse for Cargo.toml generation)
    let context = GeneratorContext::new(output, wit, world)?;

    // Generating the Cargo.toml file
    generate_cargo_toml(&context)?;

    // Copying the skeleton's Cargo.lock for faster dependency resolution
    copy_skeleton_lock(context.output).context("Failed to copy skeleton Cargo.lock")?;

    // Generating a Golem App Manifest file (for debugging)
    generate_app_manifest(&context)?;

    // Copying the skeleton files
    copy_skeleton_sources(context.output).context("Failed to copy skeleton sources")?;

    // Copying the WIT package to the output directory
    copy_wit_directory(wit, &context.output.join("wit"))
        .context("Failed to copy WIT package to output directory")?;

    if uses_composition(js_modules) {
        add_get_script_import(&context.output.join("wit"), world)
            .context("Failed to add get-script import to the WIT world")?;
    }

    // Add wizer-initialize export for pre-initialization support
    add_wizer_init_export(&context.output.join("wit"), world)
        .context("Failed to add wizer-initialize export to the WIT world")?;

    // Re-resolve the WIT package after modifications (wizer-initialize export was added)
    let modified_wit = output.join("wit");
    let context = GeneratorContext::new(output, &modified_wit, world)?;

    // Copying the JavaScript module to the output directory
    copy_js_modules(js_modules, context.output)
        .context("Failed to copy JavaScript module to output directory")?;

    // Generating the lib.rs file implementing the component exports
    generate_export_impls(&context, js_modules)
        .context("Failed to generate the component export implementations")?;

    // Generating the native modules implementing the component imports
    generate_import_modules(&context).context("Failed to generate the component import modules")?;

    // Generating the conversions.rs file implementing the IntoJs and FromJs typeclass instances
    // This step must be done after `generate_export_impls` to ensure all visited types are registered.
    generate_conversions(&context)
        .context("Failed to generate the IntoJs and FromJs typeclass instances")?;

    Ok(())
}

/// Generates TypeScript module definitions for a given (or default) world of a WIT package.
///
/// Returns the list of generated files.
pub fn generate_dts(
    wit: &Utf8Path,
    output: &Utf8Path,
    world: Option<&str>,
) -> anyhow::Result<Vec<Utf8PathBuf>> {
    // Making sure the target directories exist
    std::fs::create_dir_all(output).context("Failed to create output directory")?;

    // Resolving the WIT package
    let context = GeneratorContext::new(output, wit, world)?;

    let mut result = Vec::new();
    result.extend(
        typescript::generate_export_module(&context)
            .context("Failed to generate the TypeScript module definition for the exports")?,
    );

    // Generating the native modules implementing the component imports
    result.extend(typescript::generate_import_modules(&context).context(
        "Failed to generate the TypeScript module definitions for the imported modules",
    )?);

    Ok(result)
}

struct GeneratorContext<'a> {
    output: &'a Utf8Path,
    wit_source_path: &'a Utf8Path,
    resolve: Resolve,
    root_package: PackageId,
    world: WorldId,
    source_map: PackageSourceMap,
    visited_types: RefCell<BTreeSet<TypeId>>,
    world_name: String,
    types: wit_bindgen_core::Types,
}

impl<'a> GeneratorContext<'a> {
    fn new(output: &'a Utf8Path, wit: &'a Utf8Path, world: Option<&str>) -> anyhow::Result<Self> {
        let mut resolve = Resolve::default();
        let (root_package, source_map) = resolve
            .push_path(wit)
            .context("Failed to resolve WIT package")?;
        let world = resolve
            .select_world(root_package, world)
            .context("Failed to select WIT world")?;

        let world_name = resolve.worlds[world].name.clone();

        let mut types = wit_bindgen_core::Types::default();
        types.analyze(&resolve);

        Ok(Self {
            output,
            wit_source_path: wit,
            resolve,
            root_package,
            world,
            source_map,
            visited_types: RefCell::new(BTreeSet::new()),
            world_name,
            types,
        })
    }

    fn root_package_name(&self) -> String {
        self.resolve.packages[self.root_package].name.to_string()
    }

    fn record_visited_type(&self, type_id: TypeId) {
        self.visited_types.borrow_mut().insert(type_id);
    }

    fn is_exported_interface(&self, interface_id: InterfaceId) -> bool {
        let world = &self.resolve.worlds[self.world];
        world
            .exports
            .iter()
            .any(|(_, item)| matches!(item, WorldItem::Interface { id, .. } if id == &interface_id))
    }

    fn is_exported_type(&self, type_id: TypeId) -> bool {
        if let Some(typ) = self.resolve.types.get(type_id) {
            match &typ.owner {
                TypeOwner::World(world_id) => {
                    if world_id == &self.world {
                        let world = &self.resolve.worlds[self.world];
                        world
                            .exports
                            .iter()
                            .any(|(_, item)| matches!(item, WorldItem::Type(id) if id == &type_id))
                    } else {
                        false
                    }
                }
                TypeOwner::Interface(interface_id) => self.is_exported_interface(*interface_id),
                TypeOwner::None => false,
            }
        } else {
            false
        }
    }

    fn bindgen_type_info(&self, type_id: TypeId) -> wit_bindgen_core::TypeInfo {
        self.types.get(type_id)
    }

    fn get_imported_interface(
        &self,
        interface_id: &InterfaceId,
    ) -> anyhow::Result<ImportedInterface<'_>> {
        let interface = &self.resolve.interfaces[*interface_id];
        let name = interface
            .name
            .as_ref()
            .ok_or_else(|| anyhow!("Interface import does not have a name"))?
            .as_str();

        let functions = interface
            .functions
            .iter()
            .map(|(name, f)| (name.as_str(), f))
            .collect();

        let package_id = interface
            .package
            .ok_or_else(|| anyhow!("Anonymous interface imports are not supported yet"))?;
        let package = self
            .resolve
            .packages
            .get(package_id)
            .ok_or_else(|| anyhow!("Could not find package of imported interface {name}"))?;
        let package_name = &package.name;

        Ok(ImportedInterface {
            package_name: Some(package_name),
            name: name.to_string(),
            functions,
            interface: Some(interface),
            interface_id: Some(*interface_id),
        })
    }

    fn typ(&self, type_id: TypeId) -> anyhow::Result<&TypeDef> {
        self.resolve
            .types
            .get(type_id)
            .ok_or_else(|| anyhow!("Unknown type id: {type_id:?}"))
    }
}

pub struct ImportedInterface<'a> {
    package_name: Option<&'a PackageName>,
    name: String,
    functions: Vec<(&'a str, &'a Function)>,
    interface: Option<&'a Interface>,
    interface_id: Option<InterfaceId>,
}

impl<'a> ImportedInterface<'a> {
    pub fn module_name(&self) -> anyhow::Result<String> {
        let package_name = self
            .package_name
            .ok_or_else(|| anyhow!("imported interface has no package name"))?;
        let interface_name = &self.name;

        Ok(format!(
            "{}_{}",
            package_name.to_string().to_snake_case(),
            interface_name.to_snake_case()
        ))
    }

    pub fn rust_interface_name(&self) -> Ident {
        let interface_name = format!("Js{}Module", self.name.to_upper_camel_case());
        Ident::new(&interface_name, Span::call_site())
    }

    pub fn name_and_interface(&self) -> Option<(&str, &Interface)> {
        self.interface
            .map(|interface| (self.name.as_str(), interface))
    }

    pub fn fully_qualified_interface_name(&self) -> String {
        if let Some(package_name) = &self.package_name {
            package_name.interface_id(&self.name)
        } else {
            self.name.clone()
        }
    }

    pub fn interface_stack(&self) -> VecDeque<InterfaceId> {
        self.interface_id.iter().cloned().collect()
    }
}

/// Recursively copies a WIT directory to `<output>/wit`.
fn copy_wit_directory(wit: &Utf8Path, output: &Utf8Path) -> anyhow::Result<()> {
    std::fs::create_dir_all(output)?;
    copy_dir_if_changed(wit.as_std_path(), output.as_std_path())
        .context("Failed to copy WIT directory")?;
    Ok(())
}

fn copy_dir_if_changed(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if src_path.is_dir() {
            copy_dir_if_changed(&src_path, &dst_path)?;
        } else {
            copy_if_changed(&src_path, &dst_path)?;
        }
    }
    Ok(())
}

/// Copies the JS module files to `<output>/src/<name>.js`.
fn copy_js_modules(js_modules: &[JsModuleSpec], output: &Utf8Path) -> anyhow::Result<()> {
    for module in js_modules {
        if let EmbeddingMode::EmbedFile(source) = &module.mode {
            let filename = module.file_name();
            let js_dest = output.join("src").join(filename);
            copy_if_changed(source, js_dest)
                .context(format!("Failed to copy JavaScript module {}", module.name))?;
        }
    }
    Ok(())
}

/// Checks if any of the provided JS modules uses composition mode.
fn uses_composition(js_module_spec: &[JsModuleSpec]) -> bool {
    js_module_spec
        .iter()
        .any(|m| matches!(m.mode, EmbeddingMode::Composition))
}