### Install Build Tools on macOS Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/DEVELOPMENT.md Installs the necessary Xcode Command Line Tools on macOS. These tools are required for building native code, including the Hermes engine. ```bash xcode-select --install ``` -------------------------------- ### Install Build Tools on Linux Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/DEVELOPMENT.md Installs essential build tools on Linux systems. This includes the C++ compiler, CMake, and Ninja build system, which are required for compiling the Hermes engine. ```bash sudo apt-get update && sudo apt-get install -y build-essential cmake ninja-build ``` -------------------------------- ### Run Hermes Bytecode Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Executes a compiled Hermes bytecode file (.hbc) using the `hermes` runtime. This command requires locating the `hermes` executable first. ```bash # Find the hermes binary HERMES=$(find target/release/build -name hermes -type f -executable | head -1) # Run bytecode file $HERMES program.hbc ``` -------------------------------- ### Initialize Git Submodule for Development Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Initializes and updates the `hermes-vendor` git submodule, which is necessary when developing the hermes-engine crate directly from its git repository. This ensures the Hermes source code is available locally. ```bash git submodule update --init --recursive ``` -------------------------------- ### Run Hermes Engine Tests Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Commands to run tests for the hermes-engine crate. This includes standard unit tests and integration tests for the JSI (JavaScript Interface) layer. ```bash cargo test -p hermes-engine cargo test -p hermes-engine --test jsi_rs ``` -------------------------------- ### Compile TypeScript with Optimizations Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Compiles a TypeScript file to Hermes bytecode with optimizations enabled. The `-O` flag activates expensive optimizations, and `-emit-binary` ensures the output is in the binary .hbc format. ```bash # Find the hermesc binary HERMESC=$(find target/release/build -name hermesc -type f | head -1) # Compile TypeScript to bytecode with optimizations $HERMESC -parse-ts -emit-binary -O -out optimized.hbc input.ts ``` -------------------------------- ### Build Hermes Engine Crate with Cargo Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Commands to build the hermes-engine Rust crate. The first build compiles the entire Hermes engine from source, which can take several minutes. Subsequent builds are faster due to Cargo's caching mechanism. ```bash cargo build -p hermes-engine # For release build with optimizations: cargo build -p hermes-engine --release ``` -------------------------------- ### Compile JavaScript to Hermes Bytecode Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Compiles a JavaScript file into Hermes bytecode (.hbc format) using the `hermesc` compiler. The `-emit-binary` flag ensures the output is in binary format, and `-out` specifies the output file name. ```bash # Find the hermesc binary HERMESC=$(find target/release/build -name hermesc -type f | head -1) # Compile JavaScript to bytecode $HERMESC -emit-binary -out output.hbc input.js ``` -------------------------------- ### JSObject Property Manipulation (Rust) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Shows how to interact with JavaScript objects using the `jsi-rs` crate in Rust. This includes creating new objects, getting and setting properties by name, checking for property existence, and deleting properties. ```rust use jsi_rs::{JSRuntime, JSObject, JSValue}; // Assuming runtime is a mutable JSRuntime reference // let mut runtime: JSRuntime = ...; // Create an empty object let mut obj = JSObject::new(&mut runtime); // Set a property let name_value = JSValue::new_string(&mut runtime, "Kermio"); obj.set(&mut runtime, "name", name_value).expect("Failed to set property"); // Get a property if let Some(value) = obj.get(&mut runtime, "name") { if let Some(rust_string) = value.as_string(&mut runtime) { println!("Object name: {}", rust_string); } } // Check if property exists if obj.has(&mut runtime, "name") { println!("Object has 'name' property."); } // Delete a property obj.delete(&mut runtime, "name").expect("Failed to delete property"); ``` -------------------------------- ### Access Object Properties in Rust using Hermes Source: https://context7.com/ovr/kermio/llms.txt Demonstrates how to create JavaScript objects and manipulate their properties using the Hermes Engine in Rust. Supports get, set, has, delete operations and retrieving all property names. Requires the `hermes_engine` crate. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; let mut jsi = runtime.jsi(); // Create a new empty object let obj = jsi.create_object(); // Set properties let value = jsi.create_number(42.0); obj.set(&mut jsi, "count", &value); let name = jsi.create_string("example"); // Convert string to value for setting let name_val = hermes_engine::jsi::JSValue::number(100.0); obj.set(&mut jsi, "id", &name_val); // Check if property exists assert!(obj.has(&mut jsi, "count")); assert!(!obj.has(&mut jsi, "nonexistent")); // Get property value let count = obj.get(&mut jsi, "count"); assert!(count.is_number()); assert_eq!(count.as_number(), 42.0); // Get all property names let names = obj.get_property_names(&mut jsi); println!("Object has {} properties", names.len(&mut jsi)); // Delete property (sets to undefined) obj.delete(&mut jsi, "count"); let deleted = obj.get(&mut jsi, "count"); assert!(deleted.is_undefined()); Ok(()) } ``` -------------------------------- ### Rust ArrayBuffer Management Source: https://github.com/ovr/kermio/blob/master/roadmap.md Manages ArrayBuffer for efficient binary data transfer between Rust and JavaScript. It provides methods to create, get the size of, and access the raw data of an ArrayBuffer. ```rust pub struct JSArrayBuffer { inner: cxx::UniquePtr, } impl JSArrayBuffer { pub fn new(runtime: &mut JSRuntime, size: usize) -> JSArrayBuffer; pub fn size(&self, runtime: &mut JSRuntime) -> usize; pub fn data(&mut self, runtime: &mut JSRuntime) -> &mut [u8]; } ``` -------------------------------- ### Compile TypeScript to Hermes Bytecode Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/CLAUDE.md Compiles a TypeScript file into Hermes bytecode (.hbc format). This requires finding the `hermesc` binary first. The `-parse-ts` flag enables TypeScript parsing, which is enabled by default if the engine is built with `HERMES_PARSE_TS=ON`. ```bash # Find the hermesc binary HERMESC=$(find target/release/build -name hermesc -type f | head -1) # Compile TypeScript to bytecode $HERMESC -parse-ts -emit-binary -out output.hbc input.ts ``` -------------------------------- ### Create and Configure Hermes Runtime with Rust Source: https://context7.com/ovr/kermio/llms.txt Demonstrates creating a Hermes JavaScript runtime with custom configurations using `RuntimeConfigBuilder`. This allows fine-grained control over heap size, language features, and runtime behavior. ```rust use hermes_engine::{Runtime, RuntimeConfig, RuntimeConfigBuilder}; fn main() -> hermes_engine::Result<()> { // Create runtime with default configuration let mut runtime = Runtime::new(RuntimeConfig::default())?; // Create runtime with custom configuration let config = RuntimeConfigBuilder::new() .heap_size(64 << 20, 512 << 20) // 64MB init, 512MB max .enable_eval(true) // Allow eval() .enable_jit(false) // Disable JIT compilation .enable_es6_proxy(true) // Enable ES6 Proxy .enable_es6_block_scoping(true) // Enable let/const .enable_intl(true) // Enable Intl APIs .enable_generator(true) // Enable generator functions .enable_microtask_queue(false) // Disable microtask queue .enable_hermes_internal(true) // Enable HermesInternal .enable_sample_profiling(false) // Disable profiling .native_stack_gap(65536) // Stack gap in bytes .max_num_registers(131072) // Max VM registers .build(); let mut runtime = Runtime::new(config)?; runtime.eval("console.log('Hello from Hermes!')", None)?; Ok(()) } ``` -------------------------------- ### Access JavaScript Object Properties in Rust Source: https://github.com/ovr/kermio/blob/master/roadmap.md Provides methods to get, set, check for, and delete properties of JavaScript objects within a Rust environment. It requires a mutable JSRuntime and the property name as a string. Returns JSValue for gets and results for other operations. ```rust impl JSObject { // Get/set properties pub fn get_property(&self, runtime: &mut JSRuntime, name: &str) -> Result; pub fn set_property(&mut self, runtime: &mut JSRuntime, name: &str, value: JSValue) -> Result<(), String>; pub fn has_property(&self, runtime: &mut JSRuntime, name: &str) -> bool; pub fn delete_property(&mut self, runtime: &mut JSRuntime, name: &str) -> Result<(), String>; // Get property names pub fn get_property_names(&self, runtime: &mut JSRuntime) -> Result; } ``` -------------------------------- ### Prepare and Execute JavaScript Efficiently in Rust Source: https://context7.com/ovr/kermio/llms.txt Illustrates preparing JavaScript code once for parsing and optimization, then executing it multiple times efficiently using `hermes-engine`. This is ideal for performance-critical code paths. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; // Prepare JavaScript code once (parsing and optimization happens here) let prepared = runtime.prepare_javascript( r#" function fibonacci(n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } fibonacci(10); "#, Some("fibonacci.js"), )?; // Execute prepared code multiple times efficiently for _ in 0..100 { let result = runtime.evaluate_prepared_javascript(&prepared)?; assert!(result.is_number()); } Ok(()) } ``` -------------------------------- ### hermes-engine Crate - RuntimeConfig and Builder Source: https://github.com/ovr/kermio/blob/master/roadmap.md Enables full configuration of the Hermes runtime, including heap size, language features, and profiling options. ```APIDOC ## Runtime Configuration (hermes-engine Crate) ### Description Provides comprehensive configuration options for the Hermes JavaScript runtime using `RuntimeConfig` and `RuntimeConfigBuilder`. ### Features - **Heap Size Configuration**: Set minimum, initial, and maximum heap sizes. - **Language Feature Toggles**: Enable/disable features like eval, JIT, ES6 proxy, generators, etc. - **Profiling and Debugging Options**: Configure runtime profiling and debugging capabilities. - **Garbage Collector Configuration**: Fine-tune garbage collection behavior, including thresholds and limits. ``` -------------------------------- ### Implement C++ Objects for JavaScript Exposure Source: https://github.com/ovr/kermio/blob/master/roadmap.md An interface for exposing C++ objects to JavaScript. It defines virtual methods for getting and setting properties, and retrieving property names. This interface is not currently exposed. ```cpp class HostObject { virtual ~HostObject(); // Get property virtual Value get(Runtime&, const PropNameID& name); // Set property virtual void set(Runtime&, const PropNameID& name, const Value& value); // Get property names virtual std::vector getPropertyNames(Runtime& rt); }; ``` -------------------------------- ### Prepare and Evaluate JavaScript Code in Rust Source: https://github.com/ovr/kermio/blob/master/roadmap.md Optimizes the execution of JavaScript code by preparing it once and then evaluating it multiple times. This involves creating a `JSBuffer` from the code, preparing it into `PreparedJavaScript`, and then evaluating it. Requires a mutable JSRuntime and the prepared script. Returns the evaluation result or an error. ```rust pub struct JSBuffer { data: Vec, } pub struct PreparedJavaScript { inner: cxx::SharedPtr, } impl Runtime { pub fn prepare_javascript(&mut self, buffer: &JSBuffer, source_url: &str) -> Result; pub fn evaluate_prepared_javascript(&mut self, prepared: &PreparedJavaScript) -> Result; } ``` -------------------------------- ### Access Global Object and Runtime Info in Hermes JSI Source: https://github.com/ovr/kermio/blob/master/roadmap.md C++ functions within the JSI Runtime class to retrieve the global JavaScript object, get a description of the runtime, and check if the runtime is inspectable (debuggable). ```cpp virtual Object global() = 0; virtual std::string description() = 0; virtual bool isInspectable() = 0; ``` -------------------------------- ### Build Script for jsi-rs C++ Bindings Source: https://github.com/ovr/kermio/blob/master/crates/jsi-rs/CLAUDE.md The build.rs file configures the build process for jsi-rs, utilizing cxx_build to generate C++ binding code. It includes JSI headers from hermes-vendor and requires C++17 support. ```rust fn main() { cxx_build::bridge("src/lib.rs") .include("../hermes-engine/hermes-vendor/API/jsi/") .flag("-std=c++17") .compile("jsi-rs"); println!("cargo:rerun-if-changed=src/lib.rs"); println!("cargo:rerun-if-changed=../hermes-engine/hermes-vendor/API/jsi/"); } ``` -------------------------------- ### Hermes Runtime Creation (Rust) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Demonstrates how to create a new Hermes JavaScript runtime using the `hermes-engine` Rust crate. The `Runtime::new` function takes a `RuntimeConfig` object to customize the runtime's behavior and settings. ```rust use hermes_engine::Runtime; use hermes_engine::RuntimeConfig; // Assuming runtimeConfig is a valid RuntimeConfig object let runtime = Runtime::new(runtimeConfig); ``` -------------------------------- ### jsi-rs Crate - JSRuntime Source: https://github.com/ovr/kermio/blob/master/roadmap.md Provides a safe wrapper around the `facebook::jsi::Runtime` for managing JSI runtime instances. ```APIDOC ## JSRuntime (jsi-rs Crate) ### Description A safe Rust wrapper around the `facebook::jsi::Runtime`, ensuring proper pointer management. ### Usage - `JSRuntime`: Represents the JSI runtime. - Provides safe access to the underlying `facebook::jsi::Runtime`. ``` -------------------------------- ### Rust Hermes Unique ID Generation and Retrieval Source: https://github.com/ovr/kermio/blob/master/roadmap.md Provides functionality to get unique IDs for JavaScript objects and strings, and to retrieve JavaScript objects by their unique IDs from the runtime. This helps in tracking objects across the C++/Rust boundary. ```rust impl JSObject { pub fn get_unique_id(&self, runtime: &mut JSRuntime) -> u64; } impl JSString { pub fn get_unique_id(&self, runtime: &mut JSRuntime) -> u64; } impl Runtime { pub fn get_object_for_id(&mut self, id: u64) -> Option; } ``` -------------------------------- ### Apply Patches to Hermes Source Source: https://github.com/ovr/kermio/blob/master/crates/hermes-engine/DEVELOPMENT.md Applies pre-defined patches to the Hermes source code to optimize it for embedding. This script modifies the CMake configuration and excludes unnecessary components like test suites and Android tooling dependencies. ```bash ./apply-patches.sh ``` -------------------------------- ### JSBigInt Conversion (Rust) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Illustrates the conversion of Rust integer types (i64, u64) to JavaScript BigInts and vice versa using the `jsi-rs` crate. It also shows how to convert BigInts to strings with different radices. ```rust use jsi_rs::{JSRuntime, JSValue}; // Assuming runtime is a mutable JSRuntime reference // let mut runtime: JSRuntime = ...; // Create BigInt from i64 let big_int_i64 = JSValue::from_i64(&mut runtime, 1234567890123456789i64); // Create BigInt from u64 let big_int_u64 = JSValue::from_u64(&mut runtime, 9876543210987654321u64); // Convert BigInt to string (radix 10) if let Some(js_string) = big_int_i64.as_string(&mut runtime) { if let Some(rust_string) = js_string.value(&mut runtime) { println!("BigInt as string (radix 10): {}", rust_string); } } // Convert BigInt to string with custom radix (e.g., binary) if let Some(js_string_radix) = big_int_u64.as_string_opt(&mut runtime, 2) { if let Some(rust_string_radix) = js_string_radix.value(&mut runtime) { println!("BigInt as string (radix 2): {}", rust_string_radix); } } ``` -------------------------------- ### Hermes Runtime Helper Functions (C++) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Provides C++ helper functions for creating and managing Hermes JavaScript runtimes. This includes functions for creating a runtime with a given configuration, a non-throwing version, a thread-safe wrapper, a hardened configuration for untrusted code, and an accessor for the root API. ```cpp // Create Hermes runtime std::unique_ptr makeHermesRuntime( const ::hermes::vm::RuntimeConfig &runtimeConfig); std::unique_ptr makeHermesRuntimeNoThrow( const ::hermes::vm::RuntimeConfig &runtimeConfig) noexcept; // Thread-safe runtime wrapper std::unique_ptr makeThreadSafeHermesRuntime( const ::hermes::vm::RuntimeConfig &runtimeConfig); // Hardened config for untrusted code ::hermes::vm::RuntimeConfig hardenedHermesRuntimeConfig(); // Root API accessor jsi::ICast* makeHermesRootAPI(); ``` -------------------------------- ### PreparedJavaScript Class (C++) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Represents pre-compiled or optimized JavaScript code. This class is abstract and not directly exposed. ```cpp class PreparedJavaScript { virtual ~PreparedJavaScript() = 0; }; ``` -------------------------------- ### Create and Manipulate BigInt in Rust with Hermes Source: https://context7.com/ovr/kermio/llms.txt Demonstrates creating BigInt values from i64 and u64, converting them to strings with different bases, and extracting BigInts from evaluated JavaScript code using the Hermes Rust API. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; let mut jsi = runtime.jsi(); // Create BigInt from i64 let big_signed = jsi.create_bigint(-9007199254740993_i64); // Create BigInt from u64 let big_unsigned = jsi.create_bigint(18446744073709551615_u64); // Convert BigInt to string (base 10) let str_val = big_signed.to_string(&mut jsi)?; println!("BigInt value: {}", str_val); // Convert BigInt to string with custom radix let hex_str = big_unsigned.as_string_opt(&mut jsi, 16)?; println!("BigInt hex: {}", hex_str.value(&mut jsi)); // Extract BigInt from evaluated JavaScript let result = runtime.eval_with_result("BigInt('12345678901234567890')", None)?; let mut jsi = runtime.jsi(); if let Some(bigint) = result.as_bigint(&mut jsi) { let value = bigint.to_string(&mut jsi)?; println!("Evaluated BigInt: {}", value); } Ok(()) } ``` -------------------------------- ### Manage JavaScript Objects in C++ Source: https://github.com/ovr/kermio/blob/master/roadmap.md Enables the creation, comparison, and manipulation of JavaScript objects from C++. This includes setting and getting prototypes, accessing and modifying properties by various key types (string, String, PropNameID, Value), deleting properties, and performing type checks (isArray, isFunction, isArrayBuffer). It also supports conversion to specific C++ types like Array, ArrayBuffer, and Function. ```cpp class Object { // Create objects explicit Object(Runtime& runtime); // Create empty object static Object createFromHostObject(Runtime& runtime, std::shared_ptr ho); static Object create(Runtime& runtime, const Value& prototype); // Compare static bool strictEquals(Runtime& runtime, const Object& a, const Object& b); // Prototype manipulation void setPrototype(Runtime& runtime, const Value& prototype) const; Value getPrototype(Runtime& runtime) const; // Property access Value getProperty(Runtime& runtime, const char* name) const; Value getProperty(Runtime& runtime, const String& name) const; Value getProperty(Runtime& runtime, const PropNameID& name) const; Value getProperty(Runtime& runtime, const Value& name) const; bool hasProperty(Runtime& runtime, const char* name) const; bool hasProperty(Runtime& runtime, const String& name) const; bool hasProperty(Runtime& runtime, const PropNameID& name) const; bool hasProperty(Runtime& runtime, const Value& name) const; template void setProperty(Runtime& runtime, const char* name, T&& value) const; template void setProperty(Runtime& runtime, const String& name, T&& value) const; template void setProperty(Runtime& runtime, const PropNameID& name, T&& value) const; template void setProperty(Runtime& runtime, const Value& name, T&& value) const; void deleteProperty(Runtime& runtime, const char* name) const; void deleteProperty(Runtime& runtime, const String& name) const; void deleteProperty(Runtime& runtime, const PropNameID& name) const; void deleteProperty(Runtime& runtime, const Value& name) const; // Type checking bool isArray(Runtime& runtime) const; bool isArrayBuffer(Runtime& runtime) const; bool isFunction(Runtime& runtime) const; template bool isHostObject(Runtime& runtime) const; // Type conversions Array getArray(Runtime& runtime) const&; Array asArray(Runtime& runtime) const&; // Throws if not array ArrayBuffer getArrayBuffer(Runtime& runtime) const&; Function getFunction(Runtime& runtime) const&; Function asFunction(Runtime& runtime) const&; // Throws if not function // HostObject access template std::shared_ptr getHostObject(Runtime& runtime) const; template std::shared_ptr asHostObject(Runtime& runtime) const; // Throws // Native state template bool hasNativeState(Runtime& runtime) const; template std::shared_ptr getNativeState(Runtime& runtime) const; void setNativeState(Runtime& runtime, std::shared_ptr state) const; // Convenience methods Object getPropertyAsObject(Runtime& runtime, const char* name) const; Function getPropertyAsFunction(Runtime& runtime, const char* name) const; Array getPropertyNames(Runtime& runtime) const; // Memory pressure hint void setExternalMemoryPressure(Runtime& runtime, size_t amt) const; // instanceof check bool instanceOf(Runtime& rt, const Function& ctor) const; }; // Status: ✅ Exposed in jsi-rs as `JSObject::new()`, `get()`, `set()`, `has()`, `delete()`, `get_property_names()` ``` -------------------------------- ### Running jsi-rs Integration Tests Source: https://github.com/ovr/kermio/blob/master/crates/jsi-rs/CLAUDE.md Integration tests for jsi-rs are not run in isolation but within the hermes-engine crate, which provides a concrete JSI implementation. This command targets the specific test suite. ```bash cargo test -p hermes-engine --test jsi_rs ``` -------------------------------- ### JSFunction Invocation (Rust) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Demonstrates how to call JavaScript functions from Rust using the `jsi-rs` crate. This includes basic function calls, calls with an explicit `this` context, and calls as a constructor. ```rust use jsi_rs::{JSRuntime, JSValue, JSFunction, JSObject}; // Assuming runtime is a mutable JSRuntime reference and my_function is a JSFunction // let mut runtime: JSRuntime = ...; // let my_function: JSFunction = ...; // Prepare arguments for the function call let arg1 = JSValue::new_number(&mut runtime, 10.0); let arg2 = JSValue::new_number(&mut runtime, 20.0); let args = vec![arg1, arg2]; // Call the function match my_function.call(&mut runtime, &args) { Ok(result) => println!("Function call result: {:?}", result), Err(e) => eprintln!("Function call failed: {:?}", e), } // Example of calling with 'this' context (assuming 'this_obj' is a JSObject) // let this_obj = JSObject::new(&mut runtime); // my_function.call_with_this(&mut runtime, &this_obj, &args).expect("Call with this failed"); // Example of calling as a constructor // my_function.call_as_constructor(&mut runtime, &args).expect("Call as constructor failed"); ``` -------------------------------- ### JavaScript Compilation to Bytecode (Rust) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Illustrates compiling JavaScript source code into Hermes bytecode using the `hermes-engine` Rust crate. The `compile_to_bytecode` function takes the source code and a URL, returning the bytecode as a `Vec` or an error. ```rust use hermes_engine::Runtime; // Assuming runtime is an initialized HermesRuntime instance let source_code = "function add(a, b) { return a + b; }"; let url = ""; match runtime.compile_to_bytecode(source_code, url) { Ok(bytecode) => { println!("Compilation successful. Bytecode length: {}", bytecode.len()); // You can now save or execute this bytecode }, Err(e) => eprintln!("Compilation failed: {:?}", e), } ``` -------------------------------- ### JSI Runtime Class - Instrumentation Source: https://github.com/ovr/kermio/blob/master/roadmap.md API for accessing runtime instrumentation and metrics. ```APIDOC ## JSI Runtime Class - Instrumentation ### Description API for accessing runtime instrumentation and metrics. ### Method N/A (This is a C++ virtual method, not a direct API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Instrumentation** (jsi::Instrumentation&) - An interface for runtime instrumentation. #### Response Example ```cpp // Get instrumentation interface for metrics virtual Instrumentation& instrumentation(); ``` **Status:** Not exposed ``` -------------------------------- ### JSString Conversion (Rust) Source: https://github.com/ovr/kermio/blob/master/roadmap.md Demonstrates converting between Rust `String` and Hermes `JSString` using the `jsi-rs` crate. This includes creating a `JSString` from a Rust `String` and extracting a Rust `String` from a `JSString`. ```rust use jsi_rs::{JSRuntime, JSString, JSValue}; // Assuming runtime is a mutable JSRuntime reference // let mut runtime: JSRuntime = ...; // Create JSString from Rust String let rust_string = "Hello from Rust!".to_string(); let js_string = JSString::new(&mut runtime, &rust_string); // Convert JSString back to Rust String if let Some(extracted_string) = js_string.value(&mut runtime) { println!("Extracted string: {}", extracted_string); } ``` -------------------------------- ### Evaluate JavaScript Code with Rust Source: https://context7.com/ovr/kermio/llms.txt Shows how to evaluate JavaScript source code using the `hermes-engine` crate in Rust. It covers evaluating without capturing results, capturing typed results, evaluating complex expressions, and handling evaluation errors. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; // Evaluate without capturing result runtime.eval("const x = 42;", Some("init.js"))?; // Evaluate and capture result let result = runtime.eval_with_result("2 + 2", Some("calc.js"))?; assert!(result.is_number()); // Evaluate complex expressions let obj_result = runtime.eval_with_result("({name: 'test', value: 123})", None)?; assert!(obj_result.is_object()); // Handle evaluation errors match runtime.eval("throw new Error('Something went wrong')", None) { Ok(_) => println!("Success"), Err(e) => println!("JavaScript error: {}", e), } Ok(()) } ``` -------------------------------- ### hermes-engine Crate - Runtime Operations Source: https://github.com/ovr/kermio/blob/master/roadmap.md Provides high-level Rust bindings for interacting with the Hermes JavaScript runtime, including creation, evaluation, and bytecode handling. ```APIDOC ## Runtime Operations (hermes-engine Crate) ### Description High-level Rust bindings for interacting with the Hermes JavaScript runtime. Supports creating a runtime, evaluating JavaScript code, and handling bytecode. ### Methods - **Runtime::new(config)**: Create a new Hermes runtime instance with the specified configuration. - **Runtime::eval(source, url)**: Evaluate a JavaScript string and return the result. - **Runtime::eval_with_result(source, url)**: Evaluate a JavaScript string and return the result, handling potential errors. - **Runtime::eval_bytecode(bytecode)**: Execute pre-compiled JavaScript bytecode. - **Runtime::is_hermes_bytecode(data)**: Validate if the provided data is valid Hermes bytecode. - **Runtime::compile_to_bytecode(source, url)**: Compile JavaScript source code into bytecode. - **Runtime::jsi_runtime()**: Get a raw pointer to the underlying JSI runtime. - **Runtime::jsi() (unsafe feature)**: Get a wrapper around the JSI Runtime, marked as unsafe. ``` -------------------------------- ### Profiling API Source: https://github.com/ovr/kermio/blob/master/roadmap.md Enables performance profiling of JavaScript code execution within the Hermes runtime. ```APIDOC ## Profiling API ### Description APIs for enabling, disabling, and dumping profiler traces for performance analysis. ### Methods #### `enable_sampling_profiler(&mut self, freq_hz: f64)` Enables the sampling profiler with the specified frequency in Hz. #### `disable_sampling_profiler(&mut self)` Disables the sampling profiler. #### `dump_sampled_trace_to_file(&mut self, filename: &str) -> Result<(), String>` Dumps the sampled profiler trace to a file. #### `dump_sampled_trace_to_stream(&mut self, stream: &mut dyn std::io::Write) -> Result<(), String>` Dumps the sampled profiler trace to a given output stream. ``` -------------------------------- ### Create JavaScript Values from Rust using Hermes Source: https://context7.com/ovr/kermio/llms.txt Shows how to create JavaScript primitive values (undefined, null, boolean, number) directly from Rust without a runtime context. It also demonstrates creating JavaScript strings, objects, arrays, and BigInts that require a runtime context. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; // Create primitive values (no runtime needed) let undefined = Runtime::create_undefined(); let null_val = Runtime::create_null(); let bool_val = Runtime::create_bool(true); let num_val = Runtime::create_number(3.14159); // Create values requiring runtime context let js_string = runtime.create_string("Hello from Rust!"); let js_object = runtime.create_object(); let js_array = runtime.create_array(10); // Array with length 10 let empty_array = runtime.create_array_empty(); let prop_id = runtime.create_prop_name_id("myProperty"); let bigint_i64 = runtime.create_bigint(9007199254740993_i64); let bigint_u64 = runtime.create_bigint(18446744073709551615_u64); // Access values through JSI runtime let mut jsi = runtime.jsi(); let str_value = js_string.value(&mut jsi); println!("Created string: {}", str_value); Ok(()) } ``` -------------------------------- ### JSI Runtime Class - Global Object and Description Source: https://github.com/ovr/kermio/blob/master/roadmap.md APIs to access the global JavaScript object and runtime information. ```APIDOC ## JSI Runtime Class - Global Object and Description ### Description APIs to access the global JavaScript object and runtime information. ### Method N/A (These are C++ virtual methods, not direct API endpoints) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Object** (jsi::Object) - The global JavaScript object. - **std::string** - A description of the runtime. - **bool** - Indicates if the runtime is inspectable. #### Response Example ```cpp // Get the global object virtual Object global() = 0; // Get runtime description virtual std::string description() = 0; // Check if runtime is debuggable virtual bool isInspectable() = 0; ``` **Status:** Not exposed ``` -------------------------------- ### Call JavaScript Functions from Rust using Hermes Source: https://context7.com/ovr/kermio/llms.txt Shows how to retrieve and call JavaScript functions from Rust using the Hermes Engine. Supports regular calls, calls with explicit `this`, and constructor invocations. Requires the `hermes_engine` crate. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; // Define a function in JavaScript runtime.eval( r#"#, None, )?; // Get function reference and call it let func_val = runtime.eval_with_result("add", None)?; let mut jsi = runtime.jsi(); if let Some(add_fn) = func_val.as_function(&mut jsi) { let args = [ hermes_engine::jsi::JSValue::number(5.0), hermes_engine::jsi::JSValue::number(3.0), ]; let result = add_fn.call(&mut jsi, &args)?; assert!(result.is_number()); assert_eq!(result.as_number(), 8.0); } // Call with explicit 'this' object let obj = jsi.create_object(); let multiply_val = runtime.eval_with_result("multiply", None)?; let mut jsi = runtime.jsi(); if let Some(mult_fn) = multiply_val.as_function(&mut jsi) { let args = [ hermes_engine::jsi::JSValue::number(4.0), hermes_engine::jsi::JSValue::number(7.0), ]; let result = mult_fn.call_with_this(&mut jsi, &obj, &args)?; assert_eq!(result.as_number(), 28.0); } // Call as constructor (using 'new') let person_val = runtime.eval_with_result("Person", None)?; let mut jsi = runtime.jsi(); if let Some(person_ctor) = person_val.as_function(&mut jsi) { let name_arg = jsi.create_string("Alice"); // Note: Would need to convert JSString to JSValue for constructor args } Ok(()) } ``` -------------------------------- ### Create and Convert PropNameID in jsi-rs Source: https://github.com/ovr/kermio/blob/master/roadmap.md Rust functions for the jsi-rs crate to create and retrieve PropNameID values. Currently supports UTF-8 string creation and retrieval of the UTF-8 string representation. ```rust pub fn new(runtime: &Runtime, name: &str) -> JSPropNameID; pub fn value(runtime: &Runtime, name_id: &JSPropNameID) -> String; ``` -------------------------------- ### HostObject API Source: https://github.com/ovr/kermio/blob/master/roadmap.md Interface for exposing C++ objects to JavaScript in Kermio, including methods for property access and retrieval. ```APIDOC ## HostObject API ### Description An interface for exposing C++ objects to JavaScript. It defines methods for getting and setting properties, as well as retrieving property names. ### Method N/A (Interface Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Status ❌ Not exposed ``` -------------------------------- ### JSI Runtime Class - Microtask Queue Source: https://github.com/ovr/kermio/blob/master/roadmap.md APIs for managing the microtask queue in the JavaScript runtime. ```APIDOC ## JSI Runtime Class - Microtask Queue ### Description APIs for managing the microtask queue in the JavaScript runtime. ### Method N/A (These are C++ virtual methods, not direct API endpoints) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **callback** (jsi::Function) - The function to be queued as a microtask. - **maxMicrotasksHint** (int) - An optional hint for the maximum number of microtasks to drain. ### Request Example N/A ### Response #### Success Response (200) - **bool** - True if microtasks were drained, false otherwise. #### Response Example ```cpp // Queue a microtask virtual void queueMicrotask(const jsi::Function& callback) = 0; // Drain microtasks virtual bool drainMicrotasks(int maxMicrotasksHint = -1) = 0; ``` **Status:** Not exposed ``` -------------------------------- ### Create and Extract JavaScript Strings in Rust with Hermes Source: https://context7.com/ovr/kermio/llms.txt Shows how to create JavaScript strings from Rust string slices, extract their UTF-8 values back into Rust, and handle strings resulting from JavaScript evaluation. It also demonstrates correct handling of Unicode characters. ```rust use hermes_engine::{Runtime, RuntimeConfig}; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; let mut jsi = runtime.jsi(); // Create JavaScript string from Rust &str let js_str = jsi.create_string("Hello, JavaScript!"); // Extract UTF-8 value back to Rust String let rust_str = js_str.value(&mut jsi); assert_eq!(rust_str, "Hello, JavaScript!"); // Work with strings from JavaScript evaluation let result = runtime.eval_with_result("'prefix_' + 'suffix'", None)?; let mut jsi = runtime.jsi(); if let Some(str_val) = result.as_string(&mut jsi) { let concatenated = str_val.value(&mut jsi); assert_eq!(concatenated, "prefix_suffix"); } // Unicode strings work correctly let unicode = jsi.create_string("Emoji! 🚀 and 日本語"); let unicode_back = unicode.value(&mut jsi); assert_eq!(unicode_back, "Emoji! 🚀 and 日本語"); Ok(()) } ``` -------------------------------- ### Compile and Execute JavaScript Bytecode with Hermes Source: https://context7.com/ovr/kermio/llms.txt Compiles JavaScript code into Hermes bytecode, allowing for serialization, storage, and instant execution without parsing. This process can significantly improve startup performance. The bytecode can be converted to bytes and reconstructed from bytes. ```rust use hermes_engine::{Runtime, RuntimeConfig, CompiledBytecode}; fn main() -> hermes_engine::Result<()> { // Compile JavaScript to bytecode (no runtime needed) let bytecode = Runtime::compile_to_bytecode( r#" function greet(name) { return 'Hello, ' + name + '!'; } greet('World'); "#, Some("greet.js"), )?; // Get bytecode as bytes for storage/transmission let bytes = bytecode.as_bytes(); println!("Bytecode size: {} bytes", bytes.len()); // Reconstruct bytecode from bytes let bytecode_loaded = CompiledBytecode::from_bytes(bytes); // Execute bytecode let mut runtime = Runtime::new(RuntimeConfig::default())?; runtime.eval_bytecode(&bytecode_loaded)?; // Execute same bytecode multiple times runtime.eval_bytecode(&bytecode)?; runtime.eval_bytecode(&bytecode)?; Ok(()) } ``` -------------------------------- ### jsi-rs Crate - JSString Operations Source: https://github.com/ovr/kermio/blob/master/roadmap.md Handles the creation and extraction of JavaScript strings using JSI bindings. ```APIDOC ## JSString Operations (jsi-rs Crate) ### Description Enables the creation of JavaScript strings from UTF-8 data and extraction of their values in Rust. ### Methods - **`JSString::new(runtime, data)`**: Create a new JavaScript string from a UTF-8 encoded byte slice. - **`JSString::value(runtime)`**: Extract the string value as a Rust `String`. ``` -------------------------------- ### Create and Convert PropNameID in Hermes JSI Source: https://github.com/ovr/kermio/blob/master/roadmap.md Static factory methods for the C++ PropNameID class in JSI, allowing creation from ASCII, UTF-8, UTF-16 strings, and from String or Symbol types. Also includes methods for conversion to UTF-8 strings. ```cpp static PropNameID forAscii(Runtime& runtime, const char* str, size_t length); static PropNameID forAscii(Runtime& runtime, const char* str); static PropNameID forAscii(Runtime& runtime, const std::string& str); static PropNameID forUtf8(Runtime& runtime, const uint8_t* utf8, size_t length); static PropNameID forUtf8(Runtime& runtime, const std::string& utf8); static PropNameID forUtf16(Runtime& runtime, const char16_t* utf16, size_t length); static PropNameID forUtf16(Runtime& runtime, const std::u16string& str); static PropNameID forString(Runtime& runtime, const jsi::String& str); static PropNameID forSymbol(Runtime& runtime, const jsi::Symbol& sym); std::string utf8(Runtime& runtime) const; std::u16string utf16(Runtime& runtime) const; static bool compare(Runtime& runtime, const PropNameID& a, const PropNameID& b); ``` -------------------------------- ### Perform Array Operations in Rust using Hermes Source: https://context7.com/ovr/kermio/llms.txt Illustrates how to create and manipulate JavaScript arrays using the Hermes Engine in Rust. Supports indexed access, length queries, and bounds checking. Requires the `hermes_engine` crate. ```rust use hermes_engine::{Runtime, RuntimeConfig}; use hermes_engine::jsi::JSValue; fn main() -> hermes_engine::Result<()> { let mut runtime = Runtime::new(RuntimeConfig::default())?; let mut jsi = runtime.jsi(); // Create array with specific length let arr = jsi.create_array(5); assert_eq!(arr.len(&mut jsi), 5); // Set values at indices let val1 = JSValue::number(10.0); let val2 = JSValue::number(20.0); let val3 = JSValue::bool(true); arr.set(&mut jsi, 0, &val1)?; arr.set(&mut jsi, 1, &val2)?; arr.set(&mut jsi, 2, &val3)?; // Get values at indices let first = arr.get(&mut jsi, 0); assert!(first.is_number()); assert_eq!(first.as_number(), 10.0); // Out of bounds returns undefined let oob = arr.get(&mut jsi, 100); assert!(oob.is_undefined()); // Setting out of bounds returns error match arr.set(&mut jsi, 100, &val1) { Ok(_) => println!("Set succeeded"), Err(e) => println!("Error: {}", e), } // Check if empty let empty = jsi.create_array_empty(); assert!(empty.is_empty(&mut jsi)); Ok(()) } ``` -------------------------------- ### Array API Source: https://github.com/ovr/kermio/blob/master/roadmap.md Documentation for the Array type in Kermio, including creation, size retrieval, and element access. ```APIDOC ## Array API ### Description Represents a JavaScript array. Provides methods for creating arrays, getting their size, and accessing elements. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Status ✅ Exposed in jsi-rs as `JSArray::new()` (basic creation only) ``` -------------------------------- ### jsi-rs Crate - JSBigInt Operations Source: https://github.com/ovr/kermio/blob/master/roadmap.md Facilitates the creation and conversion of JavaScript BigInt values using JSI bindings. ```APIDOC ## JSBigInt Operations (jsi-rs Crate) ### Description Provides methods for creating and converting JavaScript BigInt values using JSI bindings. ### Methods - **`JSBigInt::from_i64(runtime, value)`**: Create a BigInt from a signed 64-bit integer. - **`JSBigInt::from_u64(runtime, value)`**: Create a BigInt from an unsigned 64-bit integer. - **`JSBigInt::as_string(runtime)`**: Convert the BigInt to a JavaScript string (base 10). - **`JSBigInt::as_string_opt(runtime, radix)`**: Convert the BigInt to a JavaScript string with a specified radix (2-36). - **`JSBigInt::to_string(runtime)`**: Convert the BigInt directly to a Rust `String` (base 10). ``` -------------------------------- ### Source Maps API Source: https://github.com/ovr/kermio/blob/master/roadmap.md Allows for evaluating JavaScript code with source maps, improving debugging and error reporting. ```APIDOC ## Source Maps API ### Description Evaluates JavaScript code along with its source map for enhanced debugging capabilities. ### Methods #### `evaluate_javascript_with_source_map(&mut self, source: &[u8], source_map: &[u8], source_url: &str) -> Result` Evaluates JavaScript code using provided source and source map data. ```