### Start WPT server Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Starts the WPT server for interactive testing. ```console just wpt-server ``` -------------------------------- ### Fetch API Example Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Make HTTP requests using the standard Fetch API. This example demonstrates making a request, reading the response body, and creating a new response with custom headers. ```javascript addEventListener('fetch', async (event) => { const responsePromise = (async () => { // Make an HTTP request const response = await fetch('https://example.com/api/data'); // Read the response body const body = await response.text(); // Create a new response with custom headers return new Response(body, { status: 200, headers: { 'Content-Type': 'text/html', 'X-Custom-Header': 'value' } }); })(); event.respondWith(responsePromise); }); ``` -------------------------------- ### Run integration test server Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/testing.md Starts the test server directly using the wasmtime runtime. ```console wasmtime serve -S common cmake-build-debug/test-server.wasm ``` -------------------------------- ### Clone Repositories Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/spidermonkey.md Initial setup to clone the embedding wrapper and the SpiderMonkey source code. ```console git clone https://github.com/bytecodealliance/spidermonkey-wasi-embedding cd spidermonkey-wasi-embedding/ git clone https://github.com/bytecodealliance/gecko-dev ``` -------------------------------- ### Define a custom builtin in C++ Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md Implement the install function within a namespace matching the project configuration. ```cpp // The extension API is automatically on the include path for builtins. #include "extension-api.h" // The namespace name must match the name passed to `add_builtin` in the CMakeLists.txt namespace my_project::my_builtin { bool install(api::Engine* engine) { printf("installing my-builtin\n"); return true; } } // namespace my_builtin ``` -------------------------------- ### StarlingMonkey Launch Configuration Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/debugger/vscode-dap-extension/README.md Example launch.json configuration for debugging a StarlingMonkey component in VS Code. ```json { "version": "0.2.0", "configurations": [ { "type": "starlingmonkey", "request": "launch", "name": "Debug StarlingMonkey component", "component": "${workspaceFolder}/main.wasm", "program": "${workspaceFolder}/main.js", "stopOnEntry": false, "trace": true } ] } ``` -------------------------------- ### JavaScript Fetch Event Handler Example Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Example JavaScript code that registers a 'fetch' event handler. This is required when creating a specialized runtime component for HTTP server applications. ```javascript addEventListener('fetch', event => { event.respondWith(new Response('Hello, world!')); }); ``` -------------------------------- ### Request and Response Objects Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Create and manipulate Request and Response objects. This example shows creating a request with a body and headers, cloning a request, and creating a response with various body types and headers. ```javascript // Create a Request with body and headers const request = new Request('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token123' }, body: JSON.stringify({ key: 'value' }) }); // Clone a request (body must not be used) const clonedRequest = request.clone(); // Access request properties console.log(request.method); // 'POST' console.log(request.url); // 'https://api.example.com/data' // Create a Response const response = new Response('Hello World', { status: 200, statusText: 'OK', headers: { 'Content-Type': 'text/plain' } }); // Read response body in various formats const text = await response.text(); const json = await response.json(); const arrayBuffer = await response.arrayBuffer(); const blob = await response.blob(); ``` -------------------------------- ### Example JavaScript class Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md A reference JavaScript class structure to be implemented as a native C++ builtin. ```javascript class MyClass { constructor(a, b) { this._a = a; this._b = b; } get prop() { return 42; } method() { return this.a + this.b; } static get static_prop() { return "static"; } static static_method(a, b) { return a + b; } } ``` -------------------------------- ### Perform Cryptographic Operations with Web Crypto API Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Examples for hashing data with SHA-256, importing HMAC keys, signing, and verifying data. Also includes importing RSA public keys. ```javascript // Hash data with SHA-256 const encoder = new TextEncoder(); const data = encoder.encode('hello world'); const hashBuffer = await crypto.subtle.digest('SHA-256', data); const hashArray = new Uint8Array(hashBuffer); // Import an HMAC key const keyData = new Uint8Array([1, 0, 1]); const hmacKey = await crypto.subtle.importKey( 'raw', keyData, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify'] ); // Sign data with HMAC const signature = await crypto.subtle.sign('HMAC', hmacKey, data); // Verify signature const isValid = await crypto.subtle.verify('HMAC', hmacKey, signature, data); console.log('Signature valid:', isValid); // true // Import RSA public key from JWK const rsaPublicKey = await crypto.subtle.importKey( 'jwk', { kty: 'RSA', alg: 'RS256', n: 'base64url-encoded-modulus', e: 'AQAB', ext: true, key_ops: ['verify'] }, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, true, ['verify'] ); ``` -------------------------------- ### Headers API Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Manipulate HTTP headers using the Headers interface. This example demonstrates setting, appending, getting, checking for, iterating over, and deleting headers. ```javascript // Create headers const headers = new Headers(); headers.set('Content-Type', 'application/json'); headers.append('Accept', 'application/json'); headers.append('Accept', 'text/plain'); // Get header values const contentType = headers.get('Content-Type'); // 'application/json' const hasAuth = headers.has('Authorization'); // false // Iterate over headers for (const [key, value] of headers.entries()) { console.log(`${key}: ${value}`); } // Delete a header headers.delete('Accept'); ``` -------------------------------- ### Configure Runtime and Adapter Files Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/CMakeLists.txt Sets up paths for the runtime and adapter WebAssembly files. ```cmake set(RUNTIME_FILE "starling-raw.wasm") set(ADAPTER_FILE "preview1-adapter.wasm") configure_file("componentize.sh.in" "${CMAKE_CURRENT_BINARY_DIR}/componentize.sh" @ONLY) if(EXISTS ${ADAPTER}) configure_file(${ADAPTER} "${CMAKE_CURRENT_BINARY_DIR}/${ADAPTER_FILE}" COPYONLY) endif() ``` -------------------------------- ### Build the project Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Configures a default build directory and builds the project. ```console just build ``` -------------------------------- ### Run Web Platform Tests Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Commands for setting up and running WPT suites. ```console just wpt-setup # prepare WPT hosts just wpt-test # run all tests just wpt-test console/console-log-symbol.any.js # run specific test ``` -------------------------------- ### Create Specialized Components Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Build a raw WebAssembly module and then componentize your JavaScript file using the provided script for faster startup times. Serve the component with wasmtime. ```bash # Build the raw WebAssembly module cmake --build cmake-build-release --target starling-raw.wasm --parallel 8 # Componentize your JavaScript file cd cmake-build-release ./componentize.sh index.js -o index.wasm # Serve the component with wasmtime wasmtime serve -S cli --dir . index.wasm ``` -------------------------------- ### Configure the build Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/building.md Set up the build directory using CMake for either release or debug modes. ```console cmake -S . -B cmake-build-release -DCMAKE_BUILD_TYPE=Release ``` ```console cmake -S . -B cmake-build-debug -DCMAKE_BUILD_TYPE=Debug ``` -------------------------------- ### Configure and run Web Platform Tests Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/testing.md Builds the WPT runtime, updates host files, and executes the test suite. ```console cmake -S . -B cmake-build-debug -DCMAKE_BUILD_TYPE=Debug cmake --build cmake-build-debug --parallel $(nproc) --target wpt-runtime cat deps/wpt-hosts | sudo tee -a /etc/hosts # Required to resolve test server hostnames cd cmake-build-debug ctest -R wpt --verbose # Note: some of the tests run fairly slowly in debug builds, so be patient ``` -------------------------------- ### List available recipes Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Displays a complete list of all available just commands. ```console just --list ``` -------------------------------- ### Manage Development Workflow with Just Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use the just command runner for building, testing, and formatting the project. ```bash # Build the project (debug mode by default) just build # Build in release mode just mode=release build # Componentize and serve a JavaScript file just serve index.js # Run integration tests just test # Run Web Platform Tests just wpt-setup # First time: add WPT hosts to /etc/hosts just wpt-test # Run specific WPT tests just wpt-test console/console-log-symbol.any.js # Start interactive WPT server just wpt-server # Format code just format # Run linter just lint # Clean build directory just clean ``` -------------------------------- ### Create and Manipulate Blobs and Files Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Demonstrates creating Blobs and Files, generating object URLs, fetching with range support, and streaming blob content. ```javascript // Create a Blob const data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const blob = new Blob([data], { type: 'application/octet-stream' }); // Create an object URL for the blob const blobUrl = URL.createObjectURL(blob); // Fetch from blob URL with range support const response = await fetch(blobUrl, { headers: { 'Range': 'bytes=0-4' } }); // response.status === 206 (Partial Content) // Clean up the object URL URL.revokeObjectURL(blobUrl); // Create a File from a Blob const file = new File([blob], 'data.bin', { type: 'application/octet-stream' }); // Stream blob content const stream = blob.stream(); const reader = stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; console.log(`Read ${value.byteLength} bytes`); } ``` -------------------------------- ### Execute Integration and Web Platform Tests Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Commands for building the test server and running test suites via ctest. ```bash # Build the test server cmake --build cmake-build-debug --target integration-test-server # Run all tests with ctest ctest --test-dir cmake-build-debug -j$(nproc) --output-on-failure # Run the integration test server directly wasmtime serve -S common cmake-build-debug/test-server.wasm # Visit http://0.0.0.0:8080/timers or other test endpoints # Run Web Platform Tests cmake --build cmake-build-debug --parallel $(nproc) --target wpt-runtime cat deps/wpt-hosts | sudo tee -a /etc/hosts cd cmake-build-debug ctest -R wpt --verbose # Filter WPT tests WPT_FILTER=fetch ctest -R wpt -v # Update WPT expectations WPT_FLAGS="--update-expectations" ctest -R wpt -v ``` -------------------------------- ### Run Specialized Component with Wasmtime Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Serve a specialized WebAssembly component using `wasmtime serve`. The `-S cli` flag enables CLI-specific features, and `--dir .` makes the current directory available. ```console wasmtime serve -S cli --dir . index.wasm ``` -------------------------------- ### Build the runtime Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/building.md Compile the project using CMake. Adjust the parallel flag based on system CPU cores. ```console # Use cmake-build-debug for the debug build # Change the value for `--parallel` to match the number of CPU cores in your system cmake --build cmake-build-release --parallel 8 --target starling ``` -------------------------------- ### Build and Run StarlingMonkey Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Clone the repository, configure the build with CMake, and build the runtime. Run JavaScript code dynamically or execute a JavaScript file using wasmtime. ```bash # Clone the repository git clone https://github.com/bytecodealliance/StarlingMonkey cd StarlingMonkey # Configure for release build cmake -S . -B cmake-build-release -DCMAKE_BUILD_TYPE=Release # Build the componentized runtime cmake --build cmake-build-release --parallel 8 --target starling # Run JavaScript code dynamically wasmtime -S http cmake-build-release/starling.wasm -e "console.log('hello world')" # Run a JavaScript file wasmtime -S http --dir . cmake-build-release/starling.wasm index.js ``` -------------------------------- ### Create components from JS files Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/building.md Alternative approach to create a WebAssembly component directly from a JavaScript file. ```console cd cmake-build-release ./componentize.sh index.js wasmtime -S http --dir . index.wasm ``` -------------------------------- ### Build JavaScript Component with Debugging Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/debugger/vscode-dap-extension/README.md Command to build a JavaScript component with the required debugging runtime arguments. ```bash componentize-js --wit world.wit -o main.wasm --runtime-args "--enable-script-debugging" main.js ``` -------------------------------- ### Test Workspace Build Commands Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/debugger/vscode-dap-extension/README.md Commands used for building test workspaces in the extension development environment. ```bash componentize-js --wit world.wit -o main.wasm --runtime-args "--enable-script-debugging" main.js ``` ```bash npm run compile ``` -------------------------------- ### Run integration tests Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Builds and executes the project's integration tests. ```console just test ``` -------------------------------- ### Build integration test server Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/testing.md Compiles the integration test server target using CMake. ```console cmake --build cmake-build-debug --target integration-test-server ``` -------------------------------- ### Customize build mode and directory Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Overrides default build modes or directories using parameters. ```console just mode=release build ``` ```console just builddir=mybuilddir mode=release build ``` -------------------------------- ### Clone StarlingMonkey Repository Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Clone the StarlingMonkey repository and navigate into the directory. This is the first step in building the runtime. ```console git clone https://github.com/bytecodealliance/StarlingMonkey cd StarlingMonkey ``` -------------------------------- ### Include Test Configuration Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/CMakeLists.txt Includes the additional test configuration file. ```cmake include("tests/tests.cmake") ``` -------------------------------- ### Serve a JS script Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Loads a JS script during componentization and serves its output using Wasmtime. ```console just serve .js ``` -------------------------------- ### Configure StarlingMonkey with Local Binaries Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/spidermonkey.md Point the StarlingMonkey build system to the custom SpiderMonkey artifacts using an environment variable. ```console export SPIDERMONKEY_BINARIES=/path/to/spidermonkey-wasi-embedding/release cmake -S . -B cmake-build-release -DCMAKE_BUILD_TYPE=Release cmake --build cmake-build-release --parallel 8 ``` -------------------------------- ### Componentize JavaScript Code for Specialized Runtime Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Create a specialized WebAssembly component from a raw StarlingMonkey module and your JavaScript code. This process is done in the build directory and requires a `fetch` event handler in your JS. ```console cd cmake-build-release ./componentize.sh index.js -o index.wasm ``` -------------------------------- ### Register a builtin in CMake Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md Use the add_builtin macro in CMakeLists.txt to include the source file. ```cmake add_builtin(my_project::my_builtin SRC my-builtin.cpp) ``` -------------------------------- ### Configure StarlingMonkey Build (Release) Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Configure the build for a release version of StarlingMonkey using CMake. This command sets up the build environment for optimized performance. ```console cmake -S . -B cmake-build-release -DCMAKE_BUILD_TYPE=Release ``` -------------------------------- ### Implement a Native Class in C++ Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md Defines a native class with instance and static members, including constructor, method, and property implementations. ```cpp #include "my_class.h" namespace builtins { namespace my_class { const JSFunctionSpec MyClass::methods[] = { JS_FN("method", MyClass::method, 0, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec MyClass::properties[] = { JS_PSG("prop", MyClass::prop_get, JSPROP_ENUMERATE), JS_STRING_SYM_PS(toStringTag, "MyClass", JSPROP_READONLY), JS_PS_END, }; const JSFunctionSpec MyClass::static_methods[] = { JS_FN("static_method", MyClass::static_method, 2, JSPROP_ENUMERATE), JS_FS_END, }; const JSPropertySpec MyClass::static_properties[] = { JS_PSG("static_prop", MyClass::static_prop_get, JSPROP_ENUMERATE), JS_PS_END, }; // Constructor implementation bool MyClass::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { CTOR_HEADER("MyClass", 2); RootedObject self(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!self) { return false; } SetReservedSlot(self, Slots::SlotA, args.get(0)); SetReservedSlot(self, Slots::SlotB, args.get(1)); args.rval().setObject(*self); return true; } // Instance method implementation bool MyClass::method(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); double a, b; if (!JS::ToNumber(cx, JS::GetReservedSlot(self, Slots::SlotA), &a) || !JS::ToNumber(cx, JS::GetReservedSlot(self, Slots::SlotB), &b)) { return false; } args.rval().setNumber(a + b); return true; } // Instance property getter implementation bool MyClass::prop_get(JSContext *cx, unsigned argc, JS::Value *vp) { METHOD_HEADER(0); args.rval().setInt32(42); return true; } // Static method implementation bool MyClass::static_method(JSContext *cx, unsigned argc, JS::Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); if (!args.requireAtLeast(cx, "static_method", 2)) { return false; } double a, b; if (!JS::ToNumber(cx, args.get(0), &a) || !JS::ToNumber(cx, args.get(1), &b)) { return false; } args.rval().setNumber(a + b); return true; } // Static property getter implementation bool MyClass::static_prop_get(JSContext *cx, unsigned argc, JS::Value *vp) { CallArgs args = CallArgsFromVp(argc, vp); args.rval().setString(JS_NewStringCopyZ(cx, "static")); return true; } // Class initialization bool MyClass::init_class(JSContext *cx, JS::HandleObject global) { return init_class_impl(cx, global); } bool install(api::Engine *engine) { return MyClass::init_class(engine->cx(), engine->global()); } } // namespace my_class } // namespace builtins ``` -------------------------------- ### Import ECDSA Keys and Sign/Verify Data Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Demonstrates importing ECDSA private and public keys in PKCS8 and SPKI formats, respectively, and performing signing and verification operations. ```javascript // Import ECDSA private key from PKCS8 const ecdsaPrivateKey = await crypto.subtle.importKey( 'pkcs8', privateKeyBuffer, // ArrayBuffer containing PKCS8-encoded key { name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign'] ); // Import ECDSA public key from SPKI const ecdsaPublicKey = await crypto.subtle.importKey( 'spki', publicKeyBuffer, // ArrayBuffer containing SPKI-encoded key { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify'] ); // Sign data const data = new TextEncoder().encode('message to sign'); const signature = await crypto.subtle.sign( { name: 'ECDSA', hash: 'SHA-256' }, ecdsaPrivateKey, data ); // Verify signature const isValid = await crypto.subtle.verify( { name: 'ECDSA', hash: 'SHA-256' }, ecdsaPublicKey, signature, data ); ``` -------------------------------- ### Implement Custom Builtins in C++ Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Define native JavaScript classes by extending BuiltinImpl and implementing constructors using the SpiderMonkey API. ```cpp // my_class.h #ifndef BUILTINS_MY_CLASS_H #define BUILTINS_MY_CLASS_H #include "builtin.h" namespace builtins { namespace my_class { class MyClass : public BuiltinImpl { static bool method(JSContext *cx, unsigned argc, JS::Value *vp); static bool prop_get(JSContext *cx, unsigned argc, JS::Value *vp); public: enum Slots : uint8_t { SlotA, SlotB, Count }; static constexpr const char *class_name = "MyClass"; static constexpr unsigned ctor_length = 2; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool init_class(JSContext *cx, HandleObject global); static bool constructor(JSContext *cx, unsigned argc, Value *vp); }; bool install(api::Engine *engine); } // namespace my_class } // namespace builtins #endif ``` ```cpp // my_class.cpp - Constructor implementation bool MyClass::constructor(JSContext *cx, unsigned argc, JS::Value *vp) { CTOR_HEADER("MyClass", 2); RootedObject self(cx, JS_NewObjectForConstructor(cx, &class_, args)); if (!self) return false; SetReservedSlot(self, Slots::SlotA, args.get(0)); SetReservedSlot(self, Slots::SlotB, args.get(1)); args.rval().setObject(*self); return true; } // Register in CMakeLists.txt // add_builtin(my_project::my_class SRC my-class.cpp) ``` -------------------------------- ### Test the runtime Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/building.md Execute JavaScript code or files using the Wasmtime runtime. ```console wasmtime -S http starling.wasm -e "console.log('hello world')" # or, to load a file: wasmtime -S http --dir . starling.wasm index.js ``` -------------------------------- ### Run integration tests Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/testing.md Executes the integration test suite using ctest. ```console ctest --test-dir cmake-build-debug -j$(nproc) --output-on-failure ``` -------------------------------- ### Define a native class header Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md Declare the native class inheriting from BuiltinImpl and define necessary static methods and properties. ```cpp #ifndef BUILTINS_MY_CLASS_H #define BUILTINS_MY_CLASS_H #include "builtin.h" namespace builtins { namespace my_class { class MyClass : public BuiltinImpl { // Instance methods static bool method(JSContext *cx, unsigned argc, JS::Value *vp); static bool prop_get(JSContext *cx, unsigned argc, JS::Value *vp); // Static methods static bool static_method(JSContext *cx, unsigned argc, JS::Value *vp); static bool static_prop_get(JSContext *cx, unsigned argc, JS::Value *vp); public: enum Slots : uint8_t { SlotA, SlotB, Count }; static constexpr const char *class_name = "MyClass"; static constexpr unsigned ctor_length = 2; static const JSFunctionSpec static_methods[]; static const JSPropertySpec static_properties[]; static const JSFunctionSpec methods[]; static const JSPropertySpec properties[]; static bool init_class(JSContext *cx, HandleObject global); static bool constructor(JSContext *cx, unsigned argc, Value *vp); }; bool install(api::Engine *engine); } // namespace my_class } // namespace builtins #endif // BUILTINS_MY_CLASS_H ``` -------------------------------- ### Build StarlingMonkey Runtime (Release) Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Build the `starling.wasm` runtime module for dynamic JS code loading. Use `cmake-build-debug` for a debug build. ```console # Use cmake-build-debug for the debug build cmake --build cmake-build-release -t starling --parallel $(nproc) ``` -------------------------------- ### Fetch test output via curl Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Retrieves the output of a specific test file from the running server. ```console curl http://127.0.0.1:7676/console/console-log-symbol.any.js ``` -------------------------------- ### Configure StarlingMonkey Build (Debug) Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Configure the build for a debug version of StarlingMonkey using CMake. This is useful for development and troubleshooting. ```console cmake -S . -B cmake-build-debug -DCMAKE_BUILD_TYPE=Debug ``` -------------------------------- ### Manage Timers and Microtasks Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Schedule code execution using standard timer functions or queue microtasks. ```javascript // Set a timeout const timeoutId = setTimeout(() => { console.log('Executed after 1 second'); }, 1000); // Clear the timeout before it executes clearTimeout(timeoutId); // Set an interval let count = 0; const intervalId = setInterval(() => { count++; console.log(`Interval tick ${count}`); if (count >= 10) { clearInterval(intervalId); } }, 100); // Queue a microtask queueMicrotask(() => { console.log('Microtask executed'); }); ``` -------------------------------- ### Filter Web Platform Tests Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/testing.md Runs a subset of WPT tests matching the specified filter string. ```console WPT_FILTER=fetch ctest -R wpt -v ``` -------------------------------- ### Build Raw StarlingMonkey Wasm Module (Release) Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Build the `starling-raw.wasm` module, which is a core WebAssembly module used for creating specialized components. Use `cmake-build-debug` for a debug build. ```console # Use cmake-build-debug for the debug build cmake --build cmake-build-release -t starling-raw.wasm --parallel $(nproc) ``` -------------------------------- ### Checkout SpiderMonkey Revision Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/spidermonkey.md Switch the local gecko-dev repository to the specific commit version required by the project. ```console git checkout `cat ../gecko-revision` # now edit the source ``` -------------------------------- ### Define Componentize Function Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/CMakeLists.txt Creates a custom command and target to componentize JavaScript sources into WebAssembly. ```cmake function(componentize OUTPUT) set(options) set(oneValueArgs) set(multiValueArgs SOURCES) cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) list(TRANSFORM ARG_SOURCES PREPEND ${CMAKE_CURRENT_SOURCE_DIR}/) list(JOIN ARG_SOURCES " " SOURCES) get_target_property(RUNTIME_DIR starling-raw.wasm BINARY_DIR) add_custom_command( OUTPUT ${OUTPUT}.wasm WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${RUNTIME_DIR}/componentize.sh ${SOURCES} -o ${OUTPUT}.wasm DEPENDS ${ARG_SOURCES} ${RUNTIME_DIR}/componentize.sh starling-raw.wasm VERBATIM ) add_custom_target(${OUTPUT} DEPENDS ${OUTPUT}.wasm) endfunction() ``` -------------------------------- ### Encode and Decode Text with TextEncoder/TextDecoder Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Shows how to encode strings to UTF-8 bytes and decode bytes back to strings. Also demonstrates decoding Latin-1 encoded bytes. ```javascript // Encode text to UTF-8 bytes const encoder = new TextEncoder(); const encoded = encoder.encode('Hello, World! 🌍'); console.log(encoded); // Uint8Array // Decode UTF-8 bytes to text const decoder = new TextDecoder('utf-8'); const decoded = decoder.decode(encoded); console.log(decoded); // 'Hello, World! 🌍' // Handle Latin-1 encoded bytes const latin1Decoder = new TextDecoder('iso-8859-1'); const bytes = new Uint8Array([0xE9]); // é in Latin-1 const text = latin1Decoder.decode(bytes); ``` -------------------------------- ### Run JavaScript Code with StarlingMonkey Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/README.md Execute JavaScript code directly or load a JS file using the built StarlingMonkey runtime. The `-S http` flag enables HTTP-related features. ```console wasmtime -S http cmake-build-release/starling.wasm -e "console.log('hello world')" # or, to load a file: wasmtime -S http --dir . starling.wasm index.js ``` -------------------------------- ### Process Data with Streams Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Handle data streams using ReadableStream, WritableStream, and TransformStream. ```javascript // Create a ReadableStream const readable = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); controller.enqueue(new Uint8Array([4, 5, 6])); controller.close(); } }); // Read from stream const reader = readable.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; console.log('Chunk:', value); } // Pipe through a TransformStream const transform = new TransformStream({ transform(chunk, controller) { // Double each byte const doubled = chunk.map(b => b * 2); controller.enqueue(doubled); } }); // Pipe body through transform const response = await fetch('https://example.com/data'); const transformedStream = response.body.pipeThrough(transform); // Use tee() to split a stream const [stream1, stream2] = readable.tee(); ``` -------------------------------- ### Build TypeScript Component with Debugging Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/debugger/vscode-dap-extension/README.md Configuration for the package.json scripts section to compile and componentize TypeScript code with debugging enabled. ```json "scripts": { "compile": "mkdirp out && tsc && componentize-js --wit world.wit -o out/main2.wasm --runtime-args \"--enable-script-debugging\" dist/main2.js" } ``` -------------------------------- ### Log Messages with Console API Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use standard console methods for logging and debugging. ```javascript // Basic logging console.log('Info message'); console.warn('Warning message'); console.error('Error message'); // Log objects console.log({ key: 'value', nested: { a: 1 } }); // Log with formatting console.log('Count: %d, Name: %s', 42, 'StarlingMonkey'); ``` -------------------------------- ### Force CMake reconfiguration Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/just.md Forces a reconfigure of the build directory to resolve target mismatch issues. ```console just reconfigure=true wpt-build ``` -------------------------------- ### Cancel Fetch Requests with AbortController Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use AbortController and AbortSignal to cancel fetch requests. Includes timeout-based cancellation. ```javascript addEventListener('fetch', async (event) => { const controller = new AbortController(); const signal = controller.signal; // Set a timeout to abort after 500ms const timeoutId = setTimeout(() => controller.abort(), 500); try { const response = await fetch('https://api.example.com/slow-endpoint', { signal }); clearTimeout(timeoutId); event.respondWith(response); } catch (err) { if (err.name === 'AbortError') { event.respondWith(new Response('Request timed out', { status: 408 })); } else { throw err; } } }); ``` -------------------------------- ### Compress and Decompress Data Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use CompressionStream and DecompressionStream for data processing. ```javascript // Compress data with gzip const data = new TextEncoder().encode('Hello, compressed world!'); const compressionStream = new CompressionStream('gzip'); const compressedStream = new ReadableStream({ start(controller) { controller.enqueue(data); controller.close(); } }).pipeThrough(compressionStream); // Read compressed data const compressedReader = compressedStream.getReader(); const chunks = []; while (true) { const { done, value } = await compressedReader.read(); if (done) break; chunks.push(value); } // Decompress data const decompressionStream = new DecompressionStream('gzip'); const decompressedStream = new ReadableStream({ start(controller) { chunks.forEach(chunk => controller.enqueue(chunk)); controller.close(); } }).pipeThrough(decompressionStream); ``` -------------------------------- ### Encode and Decode Base64 Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use atob and btoa for string conversion, or custom functions for ArrayBuffer handling. ```javascript // Encode string to Base64 const encoded = btoa('Hello, World!'); console.log(encoded); // 'SGVsbG8sIFdvcmxkIQ==' // Decode Base64 to string const decoded = atob('SGVsbG8sIFdvcmxkIQ=='); console.log(decoded); // 'Hello, World!' // Encode binary data to Base64 function arrayBufferToBase64(buffer) { const bytes = new Uint8Array(buffer); let binary = ''; for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary); } // Decode Base64 to binary data function base64ToArrayBuffer(b64) { const binary = atob(b64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes.buffer; } ``` -------------------------------- ### Verify Instance Type Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md Uses is_instance to validate that a JSObject is an instance of the expected builtin class. ```cpp JSString *MyObject::my_method(JSObject *self) { MOZ_ASSERT(is_instance(self)); return JS::GetReservedSlot(self, Slots::MySlot).toString(); } ``` -------------------------------- ### Rebuild SpiderMonkey Artifacts Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/spidermonkey.md Compile the modified SpiderMonkey source into release artifacts. ```console cd ../ # back to spidermonkey-wasi-embedding ./rebuild.sh release ``` -------------------------------- ### Parse and Manipulate URLs Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use URL and URLSearchParams to manage web addresses and query parameters. ```javascript // Parse a URL const url = new URL('https://example.com:8080/path?query=value#hash'); console.log(url.protocol); // 'https:' console.log(url.host); // 'example.com:8080' console.log(url.pathname); // '/path' console.log(url.search); // '?query=value' console.log(url.hash); // '#hash' // Modify URL components url.pathname = '/new-path'; url.searchParams.set('newParam', 'newValue'); console.log(url.href); // Work with URLSearchParams const params = new URLSearchParams('foo=1&bar=2'); params.append('foo', '3'); params.set('baz', '4'); console.log(params.toString()); // 'foo=1&foo=3&bar=2&baz=4' console.log(params.getAll('foo')); // ['1', '3'] console.log(params.size); // 4 // Iterate over params for (const [key, value] of params.entries()) { console.log(`${key}: ${value}`); } ``` -------------------------------- ### Pass custom flags to WPT runner Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/getting-started/testing.md Executes WPT tests with additional flags, such as updating expectations. ```console WPT_FLAGS="--update-expectations" ctest -R wpt -v ``` -------------------------------- ### Configure Weval Compilation Cache Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/CMakeLists.txt Conditionally builds an IC cache using Weval if the WEVAL flag is enabled. ```cmake if(WEVAL) include("weval") file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/null.js "function main() {}") add_custom_target( starling-ics.wevalcache ALL WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMAND rm -f starling-ics.wevalcache COMMAND echo ./null.js | ${WEVAL_BIN} weval --dir . --show-stats --cache starling-ics.wevalcache -w -i starling-raw.wasm -o /dev/null DEPENDS starling-raw.wasm VERBATIM ) set(WEVAL_CACHE_FILE "starling-ics.wevalcache") set(AOT 1) else() set(AOT 0) endif() ``` -------------------------------- ### Invoke Componentize Function Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/CMakeLists.txt Executes the componentize function for specific test cases and the main starling target. ```cmake componentize(smoke-test SOURCES tests/cases/smoke/smoke.js) componentize(starling) ``` -------------------------------- ### Define JSClass Structure Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/docs/src/developer/builtins-cpp.md Defines the static JSClass structure used for native class registration. ```cpp static constexpr JSClass class_{ Impl::class_name, JSCLASS_HAS_RESERVED_SLOTS(static_cast(Impl::Slots::Count)) | class_flags, &class_ops, }; ``` -------------------------------- ### Apply Test Result Visibility Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/tests/wpt-harness/results-page.template.html Toggles CSS classes on the results container to filter displayed test outcomes based on user selection. ```javascript let currentValue = "unexpected"; function applyVisibility(visibility) { document.querySelector("#results").classList.toggle(currentValue); currentValue = visibility; document.querySelector("#results").classList.toggle(currentValue); } document.querySelectorAll('input[name="result-visibility"]').forEach(input => { if (input.checked) { applyVisibility(input.id); } input.addEventListener("change", event => applyVisibility(event.target.id)) }); ``` -------------------------------- ### Manipulate FormData and Performance APIs in JavaScript Source: https://context7.com/bytecodealliance/starlingmonkey/llms.txt Use FormData for HTTP request payloads and the Performance API for high-resolution timing. ```javascript // Create FormData const formData = new FormData(); formData.append('username', 'john'); formData.append('email', 'john@example.com'); formData.append('file', new Blob(['content']), 'file.txt'); // Use with fetch const response = await fetch('https://example.com/submit', { method: 'POST', body: formData }); // Iterate over form data for (const [key, value] of formData.entries()) { console.log(`${key}: ${value}`); } ``` ```javascript // Get current high-resolution timestamp const start = performance.now(); // ... do some work ... const end = performance.now(); console.log(`Operation took ${end - start} milliseconds`); ``` -------------------------------- ### Update Test Summary Source: https://github.com/bytecodealliance/starlingmonkey/blob/main/tests/wpt-harness/results-page.template.html Updates the DOM to hide the pending indicator and display the final test pass rate and duration. ```javascript document.getElementById("pending").style.display = "none"; let summary = document.getElementById("summary"); summary.textContent = "Done. Pass rate: {pass} / {total} (took {duration}ms)"; summary.style.display = "block"; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.