### Install @rxflex/rom package Source: https://github.com/rxflex/rom/blob/main/bindings/gom-node/README.md Installs the @rxflex/rom package via npm to enable ROM runtime integration in Node.js projects. ```bash npm install @rxflex/rom ``` -------------------------------- ### Execute Bridge Protocol Commands via CLI Source: https://context7.com/rxflex/rom/llms.txt Provides examples of interacting with the ROM runtime bridge protocol using JSON payloads via standard input to execute snapshots, scripts, and probes. ```bash echo '{"command":"surface-snapshot"}' | cargo run -p rom-runtime --bin rom_bridge echo '{"command":"eval","script":"navigator.userAgent"}' | cargo run -p rom-runtime --bin rom_bridge echo '{ "command":"eval-async", "config": { "href": "https://myapp.com/", "user_agent": "Custom/1.0" }, "script": "(async () => location.href)()" }' | cargo run -p rom-runtime --bin rom_bridge ``` -------------------------------- ### Execute Asynchronous JavaScript Source: https://context7.com/rxflex/rom/llms.txt Provides examples for executing asynchronous JavaScript that returns Promises. This is required for Web APIs like fetch, crypto, or timers. ```rust use rom_runtime::{RomRuntime, RuntimeConfig}; let runtime = RomRuntime::new(RuntimeConfig::default()).unwrap(); // Execute async code with Promise resolution let result = runtime.eval_async_as_string(r#" (async () => { // Simulate async operation with crypto const data = new TextEncoder().encode("hello world"); const hash = await crypto.subtle.digest("SHA-256", data); const hashArray = Array.from(new Uint8Array(hash)); const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join(""); return { input: "hello world", algorithm: "SHA-256", hash: hashHex }; })() "#).unwrap(); ``` -------------------------------- ### Build rom-runtime Natively from Source Source: https://github.com/rxflex/rom/blob/main/bindings/gom-python/README.md Provides instructions for building the 'rom-runtime' native extension from source. This involves installing 'maturin' and then running the build command with the correct manifest path. ```bash python -m pip install maturin python -m maturin build --manifest-path bindings/gom-python/Cargo.toml --release ``` -------------------------------- ### Install rom-runtime Package Source: https://github.com/rxflex/rom/blob/main/bindings/gom-python/README.md Installs the 'rom-runtime' Python package using pip. This is the standard method for adding the library to your project. ```bash pip install rom-runtime ``` -------------------------------- ### Initialize ROM Runtime and Execute JavaScript Source: https://github.com/rxflex/rom/blob/main/README.md Demonstrates how to instantiate the RomRuntime and execute asynchronous JavaScript code within the environment using Node.js and Python bindings. ```javascript import { RomRuntime, hasNativeBinding } from "./bindings/gom-node/src/index.js"; const runtime = new RomRuntime({ href: "https://example.test/" }); const href = await runtime.evalAsync("(async () => location.href)()"); console.log("native binding:", hasNativeBinding()); console.log(href); ``` ```python import sys sys.path.insert(0, "bindings/gom-python/src") from rom import RomRuntime, has_native_binding runtime = RomRuntime({"href": "https://example.test/"}) print("native binding:", has_native_binding()) print(runtime.eval_async("(async () => location.href)()")) ``` -------------------------------- ### Initialize RomRuntime with Configuration Source: https://context7.com/rxflex/rom/llms.txt Demonstrates how to instantiate the RomRuntime using default or custom configurations. The configuration allows setting browser-specific properties like user agent, platform, and hardware characteristics. ```rust use rom_runtime::{RomRuntime, RuntimeConfig}; // Create runtime with default configuration let runtime = RomRuntime::new(RuntimeConfig::default()).unwrap(); // Create runtime with custom configuration let config = RuntimeConfig { href: "https://example.com/app".to_owned(), user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0".to_owned(), platform: "Win32".to_owned(), language: "en-US".to_owned(), languages: vec!["en-US".to_owned(), "en".to_owned()], hardware_concurrency: 8, device_memory: 8.0, webdriver: false, ..RuntimeConfig::default() }; let runtime = RomRuntime::new(config).unwrap(); // Verify browser globals are present let result: bool = runtime.eval(r#" window === self && document.defaultView === window && navigator.webdriver === false && location.href === "https://example.com/app" "#).unwrap(); assert!(result); ``` -------------------------------- ### Initialize and use RomRuntime Source: https://github.com/rxflex/rom/blob/main/bindings/gom-node/README.md Demonstrates how to instantiate the RomRuntime with a specific URL and execute asynchronous JavaScript code within the environment. It also checks for the presence of native bindings using the hasNativeBinding utility. ```javascript import { RomRuntime, hasNativeBinding } from "@rxflex/rom"; const runtime = new RomRuntime({ href: "https://example.test/" }); const href = await runtime.evalAsync("(async () => location.href)()"); console.log("native:", hasNativeBinding()); console.log(href); ``` -------------------------------- ### Build and Test ROM Project Source: https://github.com/rxflex/rom/blob/main/README.md Standard commands for building the Rust-based project and executing the test suite. ```bash cargo build cargo test ``` -------------------------------- ### Build native bindings Source: https://github.com/rxflex/rom/blob/main/bindings/gom-node/README.md Triggers the compilation process for native Node.js bindings to optimize performance for the ROM runtime. ```bash npm run build:native ``` -------------------------------- ### Run FingerprintJS Harness - Rust Source: https://context7.com/rxflex/rom/llms.txt Executes the vendored FingerprintJS library harness to validate browser compatibility against real-world fingerprinting probes. It returns detailed component analysis and visitor identification results. ```rust use rom_runtime::{RomRuntime, RuntimeConfig}; let runtime = RomRuntime::new(RuntimeConfig::default()).unwrap(); let report = runtime.run_fingerprintjs_harness().unwrap(); // Verify harness execution assert!(report.ok); assert_eq!(report.version.as_deref(), Some("5.1.0")); assert!(report.visitor_id.is_some()); assert!(report.confidence_score.is_some()); assert!(report.component_count > 0); // Compare against baseline snapshots let baseline = RomRuntime::default_fingerprintjs_harness_snapshot(); let diff = report.diff(&baseline); assert!(diff.is_empty(), "Unexpected differences: {:?}", diff); // Compare against Chromium reference (excluding identity) let chromium = RomRuntime::chromium_fingerprintjs_harness_snapshot(); let diff = report.diff(&chromium).without_identity(); assert!(diff.is_empty()); ``` -------------------------------- ### Basic Usage of RomRuntime in Python Source: https://github.com/rxflex/rom/blob/main/bindings/gom-python/README.md Demonstrates basic usage of the RomRuntime class in Python. It shows how to initialize the runtime, evaluate an asynchronous JavaScript expression, and check for the native binding availability. ```python from rom import RomRuntime, has_native_binding runtime = RomRuntime({"href": "https://example.test/"}) href = runtime.eval_async("(async () => location.href)()") print("native:", has_native_binding()) print(href) ``` -------------------------------- ### WebSocket API - Real-time Communication Source: https://context7.com/rxflex/rom/llms.txt Establishes real-time, bi-directional communication channels using WebSocket protocols. ```APIDOC ## WebSocket API - Real-time Communication ### Description Full WebSocket implementation with ws:/wss: protocols, text and binary frame support, Blob payloads, protocol negotiation, and proper close event handling. ### Method `WebSocket` constructor ### Endpoint `ws://:` or `wss://:` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A (Data is sent via `send` method) ### Request Example ```javascript // Basic WebSocket connection const socket = new WebSocket("wss://echo.websocket.org"); socket.onopen = () => { console.log("Connected, readyState:", socket.readyState); socket.send("Hello Server"); socket.send(new Uint8Array([1, 2, 3, 4])); }; socket.onmessage = async (event) => { if (typeof event.data === "string") { console.log("Text message:", event.data); } else if (event.data instanceof Blob) { console.log("Blob message:", await event.data.text()); } }; socket.onclose = (event) => { console.log("Closed:", event.code, event.reason, event.wasClean); }; socket.onerror = () => { console.log("Connection error"); }; // Negotiated protocol example const chatSocket = new WebSocket("wss://chat.example.com", ["chat", "superchat"]); console.log("Negotiated protocol:", chatSocket.protocol); ``` ### Response #### Success Response (200) Connection established. Events like `onopen`, `onmessage`, `onclose`, and `onerror` are triggered. #### Response Example ```javascript // onopen event example // readyState: 1 // onmessage event example (text) // Text message: Hello Client // onmessage event example (binary) // Binary message: Uint8Array(4) [ 1, 2, 3, 4 ] // onclose event example // Closed: 1000 "Normal Closure" true ``` ### Error Handling The `onerror` event handler is called when an error occurs. The `onclose` event handler is called when the connection is closed, providing details about the closure. ``` -------------------------------- ### Generate Browser Fingerprint Probe - Rust Source: https://context7.com/rxflex/rom/llms.txt Generates a comprehensive browser fingerprint probe for anti-detection research. It includes hardware characteristics, storage availability, media capabilities, and canvas fingerprinting data. ```rust use rom_runtime::{RomRuntime, RuntimeConfig}; let runtime = RomRuntime::new(RuntimeConfig::default()).unwrap(); let probe = runtime.fingerprint_probe().unwrap(); // Hardware fingerprint assert!(probe.hardware_concurrency.is_some()); assert!(probe.device_memory.is_some()); assert_eq!(probe.max_touch_points, 0); // Storage fingerprint assert!(probe.storage.local_storage); assert!(probe.storage.session_storage); // Media fingerprint assert!(probe.media.match_media); assert!(probe.media.audio_context); // Screen fingerprint assert!(probe.screen.width > 0); assert!(probe.screen.height > 0); assert!(probe.screen.color_depth > 0); // Canvas fingerprint assert!(probe.canvas.has_2d_context); assert!(probe.canvas.text_width.is_some()); ``` -------------------------------- ### Generate Browser Surface Snapshot - Rust Source: https://context7.com/rxflex/rom/llms.txt Generates a structured snapshot of the browser's runtime API surface. This is useful for compatibility testing and fingerprint analysis, providing details on globals, navigator properties, canvas support, and observers. ```rust use rom_runtime::{RomRuntime, RuntimeConfig}; let config = RuntimeConfig { user_agent: "Mozilla/5.0 Custom/1.0".to_owned(), ..RuntimeConfig::default() }; let runtime = RomRuntime::new(config.clone()).unwrap(); let snapshot = runtime.surface_snapshot().unwrap(); // Inspect global availability assert!(snapshot.globals.window); assert!(snapshot.globals.document); assert!(snapshot.globals.crypto); assert!(snapshot.globals.text_encoder); // Check navigator surface assert_eq!(snapshot.navigator.user_agent, config.user_agent); assert_eq!(snapshot.navigator.language, "en-US"); assert!(!snapshot.navigator.webdriver); // Verify canvas support assert!(snapshot.canvas.has_canvas); assert!(snapshot.canvas.has_2d_context); // Check observer support assert!(snapshot.observers.mutation_observer); assert!(snapshot.observers.resize_observer); assert!(snapshot.observers.intersection_observer); ``` -------------------------------- ### Execute Synchronous JavaScript Source: https://context7.com/rxflex/rom/llms.txt Shows how to run JavaScript synchronously within the ROM runtime. It covers retrieving typed Rust values using eval and obtaining JSON-serialized strings using eval_as_string. ```rust use rom_runtime::{RomRuntime, RuntimeConfig}; let runtime = RomRuntime::new(RuntimeConfig::default()).unwrap(); // Execute and get typed result let is_browser: bool = runtime.eval(r#" typeof window === "object" && typeof document === "object" "#).unwrap(); assert!(is_browser); // Execute and get JSON string result let result = runtime.eval_as_string(r#" (() => { const div = document.createElement("div"); div.id = "test"; div.className = "container"; document.body.appendChild(div); return { tagName: div.tagName, id: div.id, className: div.className, found: document.getElementById("test") === div }; })() "#).unwrap(); ``` -------------------------------- ### Manipulate DOM Elements with JavaScript Source: https://context7.com/rxflex/rom/llms.txt Demonstrates standard browser DOM operations including element creation, class manipulation, dataset access, query selection, event handling, and observing mutations. ```javascript const div = document.createElement("div"); div.id = "container"; div.className = "wrapper active"; div.setAttribute("data-value", "123"); document.body.appendChild(div); div.classList.add("new-class"); div.classList.remove("active"); div.classList.toggle("highlight"); div.dataset.userId = "456"; const found = document.querySelector("#container"); div.innerHTML = "Hello World"; const handler = (event) => { console.log("Event:", event.type, event.target.id); event.stopPropagation(); }; div.addEventListener("click", handler, { once: true, capture: false }); const observer = new MutationObserver((mutations) => { mutations.forEach(m => console.log("Mutation:", m.type, m.attributeName)); }); observer.observe(div, { attributes: true, childList: true, subtree: true }); ``` -------------------------------- ### Fetch API - HTTP Requests - JavaScript Source: https://context7.com/rxflex/rom/llms.txt Provides a full implementation of the Fetch API for making HTTP requests. Supports Request/Response objects, Headers, CORS handling, redirect modes, and various body consumption methods like JSON, text, FormData, and Blob. ```javascript // Basic fetch with JSON response const response = await fetch("https://api.example.com/data"); const data = await response.json(); // POST request with headers and JSON body const request = new Request("/api/items", { method: "POST", headers: new Headers({ "Content-Type": "application/json", "Authorization": "Bearer token123" }), body: JSON.stringify({ name: "item", value: 42 }) }); const result = await fetch(request); console.log(result.ok, result.status); // FormData upload with file const formData = new FormData(); formData.append("field", "value"); formData.append("file", new File(["content"], "data.txt", { type: "text/plain" })); await fetch("/upload", { method: "POST", body: formData }); // Abort controller for request cancellation const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); try { await fetch("/slow-endpoint", { signal: controller.signal }); } catch (error) { console.log("Request aborted:", error.message); } // Blob object URLs const blob = new Blob(["Hello World"], { type: "text/plain" }); const objectUrl = URL.createObjectURL(blob); const blobResponse = await fetch(objectUrl); const text = await blobResponse.text(); URL.revokeObjectURL(objectUrl); ``` -------------------------------- ### Parse and Manipulate URLs with JavaScript Source: https://context7.com/rxflex/rom/llms.txt Covers URL construction, modification of components, and management of query parameters using the URL and URLSearchParams APIs. ```javascript const url = new URL("/api/items?page=1", "https://example.com"); url.searchParams.append("limit", "20"); url.searchParams.set("page", "2"); url.hostname = "api.example.com"; const params = new URLSearchParams("a=1&b=2&a=3"); params.delete("b"); params.sort(); for (const [key, value] of params) { console.log(key, value); } ``` -------------------------------- ### Initialize and Retrieve Visitor ID via CDN Source: https://github.com/rxflex/rom/blob/main/fixtures/package/readme.md Demonstrates how to load the FingerprintJS agent using an asynchronous import from the CDN and retrieve a unique visitor identifier. This approach is suitable for quick integration but may be affected by ad blockers or privacy-focused browser settings. ```javascript // Initialize the agent at application startup. // If you're using an ad blocker or Brave/Firefox, this import will not work. // Please use the NPM package instead: https://t.ly/ORyXk const fpPromise = import('https://openfpcdn.io/fingerprintjs/v5') .then(FingerprintJS => FingerprintJS.load()) // Get the visitor identifier when you need it. fpPromise .then(fp => fp.get()) .then(result => { // This is the visitor identifier: const visitorId = result.visitorId console.log(visitorId) }) ``` -------------------------------- ### WebSocket API: Real-time Communication in JavaScript Source: https://context7.com/rxflex/rom/llms.txt Provides a full WebSocket implementation supporting ws/wss protocols, text and binary frames, Blob payloads, protocol negotiation, and proper close event handling. It utilizes the browser's built-in WebSocket API. ```javascript // Basic WebSocket connection const socket = new WebSocket("wss://echo.websocket.org"); socket.onopen = () => { console.log("Connected, readyState:", socket.readyState); socket.send("Hello Server"); socket.send(new Uint8Array([1, 2, 3, 4])); socket.send(new Blob(["blob data"])); }; socket.onmessage = async (event) => { if (typeof event.data === "string") { console.log("Text message:", event.data); } else if (event.data instanceof Blob) { console.log("Blob message:", await event.data.text()); } else { console.log("Binary message:", new Uint8Array(event.data)); } }; socket.onclose = (event) => { console.log("Closed:", event.code, event.reason, event.wasClean); }; socket.onerror = () => { console.log("Connection error"); }; // Binary type configuration socket.binaryType = "arraybuffer"; // or "blob" (default) // Protocol negotiation const chatSocket = new WebSocket("wss://chat.example.com", ["chat", "superchat"]); console.log("Negotiated protocol:", chatSocket.protocol); // Graceful close socket.close(1000, "Goodbye"); ``` -------------------------------- ### WebCrypto API - Cryptographic Operations Source: https://context7.com/rxflex/rom/llms.txt Implements subtle crypto operations including digest, HMAC, AES encryption/decryption, key wrapping, and key derivation. ```APIDOC ## WebCrypto API - Cryptographic Operations ### Description Complete SubtleCrypto implementation supporting digest, HMAC, AES-CTR/CBC/GCM encryption, AES-KW key wrapping, and PBKDF2/HKDF key derivation with browser-compliant validation. ### Method Various (e.g., `crypto.subtle.digest`, `crypto.subtle.sign`, `crypto.subtle.encrypt`, `crypto.subtle.deriveKey`, `crypto.subtle.importKey`) ### Endpoint N/A (Client-side API) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body Depends on the specific operation (e.g., data for hashing, key material for import, plaintext for encryption). ### Request Example ```javascript // SHA-256 digest const data = new TextEncoder().encode("message"); const hash = await crypto.subtle.digest("SHA-256", data); // AES-GCM encryption const aesKey = await crypto.subtle.generateKey( { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); const iv = crypto.getRandomValues(new Uint8Array(12)); const ciphertext = await crypto.subtle.encrypt( { name: "AES-GCM", iv, tagLength: 128 }, aesKey, new TextEncoder().encode("secret message") ); ``` ### Response #### Success Response (200) Depends on the operation. For `digest`, it returns an ArrayBuffer containing the hash. For encryption, it returns an ArrayBuffer with the ciphertext. #### Response Example ```javascript // Example response for digest // ArrayBuffer representing the SHA-256 hash // Example response for encrypt // ArrayBuffer representing the ciphertext ``` ### Error Handling Errors are typically thrown as exceptions (e.g., `OperationError`). ``` -------------------------------- ### Node.js Integration with ROM Runtime Source: https://context7.com/rxflex/rom/llms.txt Integrates the ROM runtime into a Node.js application, providing asynchronous API access. It supports checking for native binding availability, synchronous and asynchronous JavaScript evaluation, JSON parsing, and compatibility inspection with FingerprintJS. ```javascript import { RomRuntime, hasNativeBinding } from "./bindings/gom-node/src/index.js"; // Check binding type console.log("Using native binding:", hasNativeBinding()); // Create runtime with configuration const runtime = new RomRuntime({ href: "https://myapp.example.com/", user_agent: "Mozilla/5.0 MyApp/1.0", platform: "MacIntel", language: "en-US" }); // Synchronous evaluation const userAgent = await runtime.eval("navigator.userAgent"); console.log("User Agent:", userAgent); // Async evaluation const result = await runtime.evalAsync( `(async () => { const hash = await crypto.subtle.digest( "SHA-256", new TextEncoder().encode("test") ); return Array.from(new Uint8Array(hash)) .map(b => b.toString(16).padStart(2, "0")).join(""); })()` ); // Parse JSON results const data = await runtime.evalJson("({ a: 1, b: 2 })"); console.log(data); // { a: 1, b: 2 } // Compatibility inspection const snapshot = await runtime.surfaceSnapshot(); const probe = await runtime.fingerprintProbe(); const harness = await runtime.runFingerprintJsHarness(); console.log("FingerprintJS version:", await runtime.fingerprintJsVersion()); ``` -------------------------------- ### Interact with ROM via CLI Bridge Source: https://github.com/rxflex/rom/blob/main/README.md Directly interface with the rom_bridge binary to perform operations like surface snapshots using JSON input. ```bash echo "{\"command\":\"surface-snapshot\"}" | cargo run -p rom-runtime --bin rom_bridge ``` -------------------------------- ### Python Integration with ROM Runtime Source: https://context7.com/rxflex/rom/llms.txt Integrates the ROM runtime into a Python application, offering flexibility with native extension or CLI bridge modes. It supports checking for native binding availability, synchronous and asynchronous JavaScript evaluation, JSON parsing, and compatibility testing with FingerprintJS. ```python import sys sys.path.insert(0, "bindings/gom-python/src") from rom import RomRuntime, create_runtime, has_native_binding # Check binding availability print("Native binding available:", has_native_binding()) # Create runtime with configuration runtime = RomRuntime({ "href": "https://myapp.example.com/", "user_agent": "Mozilla/5.0 MyApp/1.0", "platform": "Linux x86_64", "hardware_concurrency": 4, "device_memory": 8.0 }) # Synchronous evaluation user_agent = runtime.eval("navigator.userAgent") print("User Agent:", user_agent) # Async evaluation hash_result = runtime.eval_async(""" (async () => { const data = new TextEncoder().encode("test"); const hash = await crypto.subtle.digest("SHA-256", data); return Array.from(new Uint8Array(hash)) .map(b => b.toString(16).padStart(2, "0")).join(""); })() """) print("SHA-256:", hash_result) # Parse JSON results data = runtime.eval_json("({ items: [1, 2, 3], count: 3 })") print("Parsed:", data) # Compatibility testing snapshot = runtime.surface_snapshot() probe = runtime.fingerprint_probe() harness = runtime.run_fingerprintjs_harness() version = runtime.fingerprintjs_version() print(f"FingerprintJS {version}: visitor_id={harness['visitor_id']}") print(f"Components: {harness['component_count']}, Errors: {harness['error_component_count']}") ``` -------------------------------- ### WebCrypto API: Cryptographic Operations in JavaScript Source: https://context7.com/rxflex/rom/llms.txt Implements various cryptographic operations using the WebCrypto API, including random value generation, SHA-256 digests, HMAC signing/verification, AES-GCM encryption/decryption, PBKDF2 key derivation, and JWK import/export. It relies on the browser's built-in crypto module. ```javascript const randomBytes = new Uint8Array(32); crypto.getRandomValues(randomBytes); const uuid = crypto.randomUUID(); // SHA-256 digest const data = new TextEncoder().encode("message"); const hash = await crypto.subtle.digest("SHA-256", data); const hashHex = Array.from(new Uint8Array(hash)) .map(b => b.toString(16).padStart(2, "0")).join(""); // HMAC sign and verify const hmacKey = await crypto.subtle.importKey( "raw", new TextEncoder().encode("secret-key"), { name: "HMAC", hash: "SHA-256" }, true, ["sign", "verify"] ); const signature = await crypto.subtle.sign("HMAC", hmacKey, data); const isValid = await crypto.subtle.verify("HMAC", hmacKey, signature, data); // AES-GCM encryption/decryption const aesKey = await crypto.subtle.generateKey( { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); const iv = crypto.getRandomValues(new Uint8Array(12)); const ciphertext = await crypto.subtle.encrypt( { name: "AES-GCM", iv, tagLength: 128 }, aesKey, new TextEncoder().encode("secret message") ); const plaintext = await crypto.subtle.decrypt( { name: "AES-GCM", iv, tagLength: 128 }, aesKey, ciphertext ); // PBKDF2 key derivation const baseKey = await crypto.subtle.importKey( "raw", new TextEncoder().encode("password"), "PBKDF2", false, ["deriveBits", "deriveKey"] ); const derivedKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: new Uint8Array(16), iterations: 100000, hash: "SHA-256" }, baseKey, { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); // JWK import/export const jwk = await crypto.subtle.exportKey("jwk", aesKey); const importedKey = await crypto.subtle.importKey( "jwk", jwk, { name: "AES-GCM" }, true, ["encrypt", "decrypt"] ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.