### Install Dependencies and Build Project Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Run these commands to install project dependencies and build the project. ```console npm install npm run build ``` -------------------------------- ### Install Guest Dependencies Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md Installs the necessary Node.js dependencies for the Javascript guest component. ```bash npm install ``` -------------------------------- ### Install ComponentizeJS Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Install the ComponentizeJS library using npm. This is the first step to using it as a Node.js library. ```shell npm install @bytecodealliance/componentize-js ``` -------------------------------- ### Install jco CLI Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Installs the jco command-line tool globally, which is used for transpiling WebAssembly components. ```shell npm install -g @bytecodealliance/jco ``` -------------------------------- ### Install JCO for CLI Componentization Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Install JCO and ComponentizeJS to use the `jco componentize` command. This provides a unified CLI for componentization tasks. ```shell npm install -g @bytecodealliance/jco @bytecodealliance/componentize-js ``` -------------------------------- ### Clean Local Installation Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Use this command to remove the StarlingMonkey installation from a local setup. ```console npm run clean ``` -------------------------------- ### Install Preview2 WASI Shim Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Installs the experimental JavaScript WASI shim from npm, which provides WASI functionality for components running in Node.js. ```shell npm install @bytecodealliance/preview2-shim ``` -------------------------------- ### Install ComponentizeJS Globally for CLI Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Install ComponentizeJS globally to use it as a command-line interface tool. This is an alternative to using it as a library. ```shell npm install -g @bytecodealliance/componentize-js ``` -------------------------------- ### Use ComponentizeJS CLI Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Example of using the ComponentizeJS CLI to compile a JavaScript source file into a WebAssembly component. Specify the WIT file and output path. ```shell componentize-js --wit wit -o component.wasm source.js ``` -------------------------------- ### Use JCO Componentize CLI Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Example of using the `jco componentize` command to compile a JavaScript source file. This command requires specifying the output file and WIT definitions. ```shell jco componentize source.js --wit wit -o component.wasm ``` -------------------------------- ### Componentize JavaScript to Wasm Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Compile JavaScript code into a WebAssembly component. This example demonstrates importing a logger and exporting a sayHello function. ```javascript import { componentize } from '@bytecodealliance/componentize-js'; import { writeFile } from 'node:fs/promises'; const { component } = await componentize (` import { log } from 'local:hello/logger'; export function sayHello (name) { log(`Hello ${name}`); } `, ` package local:hello; interface logger { log: func(msg: string); } world hello { import logger; export say-hello: func(name: string); } `); await writeFile('test.component.wasm', component); ``` -------------------------------- ### Async Component Function Example Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Example of an async exported function that uses fetch. ComponentizeJS automatically handles promise resolution for async functions. ```javascript export async function sayHello (name) { const text = await (await fetch(`http://localhost:8080/${name}`)).text(); console.log(text); } ``` -------------------------------- ### Build Component with Node.js Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Command to execute the Node.js script for building the WebAssembly component. ```shell node componentize.mjs ``` -------------------------------- ### Run Component with Test Script Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md Executes a bash script to run the built WebAssembly component and test its output. ```bash ./test.sh ``` -------------------------------- ### Run All Tests Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Execute this command to run all the tests in the project. ```console npm run test ``` -------------------------------- ### Javascript Component Implementation Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md A Javascript ES module that implements the 'hello' function according to the WIT interface. ```javascript export function hello (name) { return `Hello ${name}`; } ``` -------------------------------- ### Test Component in Node.js Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Runs the transpiled component in Node.js using an ES module import. It calls the 'hello' function with 'ComponentizeJS' and logs the result. ```shell node -e "import('./hello/hello.component.js').then(m => console.log(m.hello('ComponentizeJS')))" ``` -------------------------------- ### Build and Run Component in Wasmtime Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Commands to build and run the WebAssembly component using Wasmtime after setting up the Rust project. ```shell cargo build --release ./target/release/wasmtime-test ``` -------------------------------- ### Run Host with Cargo Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md Builds and runs the Rust host application, which embeds a WebAssembly runtime to execute the component. ```bash cargo run ``` -------------------------------- ### Build for AOT Support Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Execute this command to enable Ahead-of-Time (AOT) compilation support, necessary for using componentize-js with features like npm link or jco. ```console npm run build:weval ``` -------------------------------- ### Build Javascript Component Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md Builds the WebAssembly component from the Javascript source code using the componentize.js script or an npm build script. ```bash node componentize.js ``` ```bash npm run build ``` -------------------------------- ### Run a Specific Test Suite Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Pass a specific test file path as an argument to run a particular test suite using vitest. ```console npm run test -- test/wasi.js ``` -------------------------------- ### componentize Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Converts a JavaScript source file into a WebAssembly component. This function allows for extensive configuration through its options object, enabling fine-grained control over the componentization process. It returns the component binary, a list of used guest imports, and optional debugging information. ```APIDOC ## componentize ### Description Converts a JS source into a component binary. ### Method `componentize(opts: { /** * The path to the file to componentize. * * This file must be a valid JavaScript module, and can import other modules using relative paths. */ sourcePath: string; /** * Path to WIT file or folder */ witPath?: string; /** * Target world name for componentization */ worldName?: string; /** * Path to custom ComponentizeJS engine build to use */ engine?: string; /** * Path to custom weval cache to use */ aotCache?: string; /** * Enable AoT using weval */ enableAot?: boolean; /** * Use a pre-existing path to the `weval` binary, if present */ wevalBin?: string; /** * Use a pre-existing path to the `wizer` binary, if present */ wizerBin?: string; /** * Path to custom Preview2 Adapter */ preview2Adapter?: string; /** * Disable WASI features in the base engine * Disabling all features results in a pure component with no WASI dependence * * - stdio: console.log(), console.error and errors are provided to stderr * - random: Math.random() and crypto.randomBytes() * - clocks: Date.now(), performance.now() * - http: fetch() support * */ disableFeatures?: ('stdio' | 'random' | 'clocks' | 'http' | 'fetch-event')[]; /** * Enable WASI features in the base engine * (no experimental subsystems currently supported) */ enableFeatures?: []; /** * Pass environment variables to the spawned Wizer or Weval Process * If set to true, all host environment variables are passed * To pass only a subset, provide an object with the desired variables */ env?: boolean | Record; /** * Runtime arguments to provide to the StarlingMonkey engine initialization * (see https://github.com/bytecodealliance/StarlingMonkey/blob/main/include/config-parser.h) */ runtimeArgs?: string; /** * Use a debug build * Note that the debug build only includes the names section only for size optimization, and not DWARF * debugging sections, due to a lack of support in Node.js for these debugging workflows currently. */ debugBuild?: boolean; /** * Debug options */ debug?: { /** Whether to enable bindings-specific debugging */ bindings?: boolean; /** Path to debug bindings to use */ bindingsDir?: string; /** Whether to enable binary-specific debugging */ binary?: boolean; /** Path to enable binary-specific debugging */ binaryPath?: string; /** Whether to enable wizer logging */ wizerLogging: false; } }): Promise<{ /** * Component binary */ component: Uint8Array; /** * Used guest imports in JavaScript (excluding those from StarlingMonkey engine) */ imports: [[string, string]][]; /** * Debugging output (only present if enabled) */ debug?: { /** Whether bindings debugging was enabled */ bindings?: boolean; /** Work directory used during processing */ workDir?: string; /** Whether binary debugging was enabled */ binary?: boolean; /** Path to the produced binary */ binaryPath?: string; }; }> ``` -------------------------------- ### ComponentizeJS API Usage Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Builds a WebAssembly component from JavaScript source code and a WIT interface definition using the componentize API. Requires Node.js file system modules. ```js import { componentize } from '@bytecodealliance/componentize-js'; import { readFile, writeFile } from 'node:fs/promises'; const jsSource = await readFile('hello.js', 'utf8'); const witSource = await readFile('hello.wit', 'utf8'); const { component } = await componentize(jsSource, witSource); await writeFile('hello.component.wasm', component); ``` -------------------------------- ### Run Tests with AOT Enabled Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Run tests with Ahead-of-Time (AOT) or weval support enabled. ```console npm run test:weval ``` -------------------------------- ### Transpile Component with jco Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Transpiles a WebAssembly component into JavaScript modules using jco. The `--map` argument directs WASI imports to a specific shim. ```shell jco transpile hello.component.wasm -o hello --map 'wasi-*=@bytecodealliance/preview2-shim/*' ``` -------------------------------- ### Define Output Filenames Source: https://github.com/bytecodealliance/componentizejs/blob/main/CMakeLists.txt Sets the base names for the output WASM files based on the build configuration (Release, Debug, or WEVAL). ```cmake set(OUTPUT_NAME_RELEASE "starlingmonkey_embedding.wasm") set(OUTPUT_NAME_DEBUG "starlingmonkey_embedding.debug.wasm") set(OUTPUT_NAME_WEVAL "starlingmonkey_embedding_weval.wasm") ``` -------------------------------- ### WebAssembly Interface Types (WIT) Definition Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md Defines the interface for the Javascript WebAssembly component, specifying an exported 'hello' function. ```wit package local:hello; world component { export hello: func(name: string) -> string; } ``` -------------------------------- ### Componentize JavaScript Module to WebAssembly Component Source: https://github.com/bytecodealliance/componentizejs/blob/main/README.md Use the `componentize` function to convert a JavaScript source file into a WebAssembly component binary. This function accepts various options to customize the componentization process, including paths for WIT files, target world names, and feature enablement/disablement. ```typescript export function componentize(opts: { /** * The path to the file to componentize. * * This file must be a valid JavaScript module, and can import other modules using relative paths. */ sourcePath: string; /** * Path to WIT file or folder */ witPath?: string; /** * Target world name for componentization */ worldName?: string; /** * Path to custom ComponentizeJS engine build to use */ engine?: string; /** * Path to custom weval cache to use */ aotCache?: string; /** * Enable AoT using weval */ enableAot?: boolean; /** * Use a pre-existing path to the `weval` binary, if present */ wevalBin?: string; /** * Use a pre-existing path to the `wizer` binary, if present */ wizerBin?: string; /** * Path to custom Preview2 Adapter */ preview2Adapter?: string; /** * Disable WASI features in the base engine * Disabling all features results in a pure component with no WASI dependence * * - stdio: console.log(), console.error and errors are provided to stderr * - random: Math.random() and crypto.randomBytes() * - clocks: Date.now(), performance.now() * - http: fetch() support * */ disableFeatures?: ('stdio' | 'random' | 'clocks' | 'http' | 'fetch-event')[]; /** * Enable WASI features in the base engine * (no experimental subsystems currently supported) */ enableFeatures?: []; /** * Pass environment variables to the spawned Wizer or Weval Process * If set to true, all host environment variables are passed * To pass only a subset, provide an object with the desired variables */ env?: boolean | Record; /** * Runtime arguments to provide to the StarlingMonkey engine initialization * (see https://github.com/bytecodealliance/StarlingMonkey/blob/main/include/config-parser.h) */ runtimeArgs?: string; /** * Use a debug build * Note that the debug build only includes the names section only for size optimization, and not DWARF * debugging sections, due to a lack of support in Node.js for these debugging workflows currently. */ debugBuild?: boolean; /** * Debug options */ debug?: { /** Whether to enable bindings-specific debugging */ bindings?: boolean; /** Path to debug bindings to use */ bindingsDir?: string; /** Whether to enable binary-specific debugging */ binary?: boolean; /** Path to enable binary-specific debugging */ binaryPath?: string; /** Whether to enable wizer logging */ wizerLogging: false; } }): Promise<{ /** * Component binary */ component: Uint8Array; /** * Used guest imports in JavaScript (excluding those from StarlingMonkey engine) */ imports: [[string, string]][]; /** * Debugging output (only present if enabled) */ debug?: { /** Whether bindings debugging was enabled */ bindings?: boolean; /** Work directory used during processing */ workDir?: string; /** Whether binary debugging was enabled */ binary?: boolean; /** Path to the produced binary */ binaryPath?: string; }; }> ``` -------------------------------- ### Specify Component Path for Host Source: https://github.com/bytecodealliance/componentizejs/blob/main/examples/hello-world/README.md Sets the COMPONENT_WASM_PATH environment variable to specify the absolute path to the component's WASM file when running the Rust host or its binary. ```bash COMPONENT_WASM_PATH=/absolute/path/to/hello.component.wasm cargo run ``` ```bash COMPONENT_WASM_PATH=/absolute/path/to/hello.component.wasm path/to/wasmtime-test ``` -------------------------------- ### Component Interface Definition (WIT) Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Defines the interface for a component, specifying exported functions and their signatures. ```wit package local:hello; world hello { export hello: func(name: string) -> string; } ``` -------------------------------- ### Set StarlingMonkey Source Directory Source: https://github.com/bytecodealliance/componentizejs/blob/main/CMakeLists.txt Determines the source directory for StarlingMonkey, either from an environment variable or a default path. Ensures the path exists and is absolute. ```cmake if (DEFINED ENV{STARLINGMONKEY_SRC}) set(STARLINGMONKEY_SRC $ENV{STARLINGMONKEY_SRC}) if (EXISTS ${STARLINGMONKEY_SRC}) cmake_path(ABSOLUTE_PATH STARLINGMONKEY_SRC) endif() if (NOT EXISTS ${STARLINGMONKEY_SRC}) message(FATAL_ERROR "StarlingMonkey source not found at `$ENV{STARLINGMONKEY_SRC}`.") endif() else() set(STARLINGMONKEY_SRC ${CMAKE_CURRENT_SOURCE_DIR}/StarlingMonkey) endif() ``` -------------------------------- ### Create Custom Target for Embedding Source: https://github.com/bytecodealliance/componentizejs/blob/main/CMakeLists.txt Defines a custom target 'starlingmonkey_embedding' that depends on the raw WASM file and copies it to the final output location. ```cmake add_custom_target(starlingmonkey_embedding DEPENDS ${EMBEDDING_DEP} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/starling-raw.wasm/starling-raw.wasm ${OUTPUT_FILENAME} ) ``` -------------------------------- ### Select Output Filename Based on Build Type Source: https://github.com/bytecodealliance/componentizejs/blob/main/CMakeLists.txt Chooses the final output filename based on the CMAKE_BUILD_TYPE or the WEVAL flag. Updates the embedding dependency if WEVAL is enabled. ```cmake if(CMAKE_BUILD_TYPE STREQUAL "Debug" OR CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo") set(OUTPUT_FILENAME ${OUTPUT_NAME_DEBUG}) elseif(WEVAL) set(OUTPUT_FILENAME ${OUTPUT_NAME_WEVAL}) set(EMBEDDING_DEP "starling-ics.wevalcache") else() set(OUTPUT_FILENAME ${OUTPUT_NAME_RELEASE}) endif() ``` -------------------------------- ### Node.js Package JSON for Modules Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Configures a Node.js project to interpret all .js and .mjs files as ES modules, which is necessary for using import statements. ```json { "type": "module" } ``` -------------------------------- ### Strip Debug Symbols for RelWithDebInfo Source: https://github.com/bytecodealliance/componentizejs/blob/main/CMakeLists.txt Adds a post-build command to the 'starlingmonkey_embedding' target to strip debug symbols when the build type is 'RelWithDebInfo'. ```cmake if(CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo") add_custom_command(TARGET starlingmonkey_embedding POST_BUILD COMMAND ${WASM_TOOLS_BIN} strip ${OUTPUT_FILENAME} -d ".debug_(info|loc|ranges|abbrev|line|str)" -o ${OUTPUT_FILENAME} VERBATIM ) endif() ``` -------------------------------- ### Configure package.json for ES Modules Source: https://github.com/bytecodealliance/componentizejs/blob/main/EXAMPLE.md Appends '"type": "module"' to an existing package.json file to ensure ES module interpretation. This prevents 'SyntaxError: Cannot use import statement outside a module'. ```json "type": "module", ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.