### Example: Get Property Value Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md This example demonstrates how to retrieve a property value using `getSync` to get a reference to an object and then `get` to access a property on that object. ```javascript const obj = context.global.getSync('data', { reference: true }); const prop = await obj.get('x'); console.log(prop.typeof); // Type of data.x ``` -------------------------------- ### Use Snapshots for Common Setup Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Leverage snapshots to pre-compile and load common libraries or setup code into new isolates. This speeds up isolate initialization. ```javascript // Pre-compile standard library const snapshot = ivm.Isolate.createSnapshot([ { code: fs.readFileSync('lib/polyfills.js', 'utf8') }, { code: fs.readFileSync('lib/helpers.js', 'utf8') } ]); // All isolates start with libraries pre-loaded const isolate = new ivm.Isolate({ snapshot }); ``` -------------------------------- ### Minimal Isolated VM Example Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/README.md A basic example demonstrating the creation of an isolate and context, compiling and running a simple script, and logging the result. This is useful for understanding the fundamental workflow. ```javascript const ivm = require('isolated-vm'); const isolate = new ivm.Isolate({ memoryLimit: 128 }); const context = isolate.createContextSync(); const script = isolate.compileScriptSync('2 + 3'); const result = script.runSync(context); console.log(result); // 5 ``` -------------------------------- ### Callback Constructor Examples Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/07-callback.md Demonstrates how to create synchronous, asynchronous, and ignored callbacks using the ivm.Callback constructor with different options. ```javascript const ivm = require('isolated-vm'); // Synchronous callback (default) const syncCallback = new ivm.Callback((a, b) => { return a + b; }, { sync: true }); // Asynchronous callback const asyncCallback = new ivm.Callback((data) => { return Promise.resolve(processData(data)); }, { async: true }); // Fire-and-forget callback const ignoredCallback = new ivm.Callback((msg) => { console.log(msg); // Errors ignored }, { ignored: true }); ``` -------------------------------- ### Example: Set Property Value Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md This example shows how to set a property's value asynchronously. It first gets a reference to an object and then uses `set` to update a property. ```javascript const obj = context.global.getSync('data', { reference: true }); await obj.set('x', 42); ``` -------------------------------- ### Install isolated-vm on Red Hat Source: https://github.com/laverdet/isolated-vm/blob/main/README.md On Red Hat systems, use dnf to install isolated-vm. This command installs python3, make, gcc, gcc-c++, zlib-devel, brotli-devel, and openssl-devel. ```bash sudo dnf install python3 make gcc gcc-c++ zlib-devel brotli-devel openssl-devel ``` -------------------------------- ### Install isolated-vm on Ubuntu Source: https://github.com/laverdet/isolated-vm/blob/main/README.md To install isolated-vm on Ubuntu, ensure you have Python, g++, and build-essential installed. This is necessary for the native module compilation. ```bash sudo apt-get install python g++ build-essential ``` -------------------------------- ### Install isolated-vm on Arch Linux Source: https://github.com/laverdet/isolated-vm/blob/main/README.md For Arch Linux, install isolated-vm by running the command below. This installs make, gcc, and python, which are needed for the build process. ```bash sudo pacman -S make gcc python ``` -------------------------------- ### Using a Snapshot to Initialize Isolates Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Initialize multiple isolates from a pre-generated snapshot. This ensures all isolates start with the same pre-compiled heap, improving startup performance. ```javascript const snapshot = ivm.Isolate.createSnapshot([ { code: 'const CONST_DATA = { /* ... */ };' } ]); const isolate1 = new ivm.Isolate({ snapshot }); const isolate2 = new ivm.Isolate({ snapshot }); const isolate3 = new ivm.Isolate({ snapshot }); ``` -------------------------------- ### Create Isolate with Options Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/01-isolate.md Example of creating an Isolate with a specified memory limit and disabling the V8 inspector. ```javascript const ivm = require('isolated-vm'); // Create an isolate with 256MB memory limit const isolate = new ivm.Isolate({ memoryLimit: 256, inspector: false }); ``` -------------------------------- ### Build and Load Native Module Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Use `npm install` to build the native module with node-gyp. Then, load the compiled module into your application using `isolated-vm`'s `NativeModule`. ```bash # Build the module npm install # In your application const ivm = require('isolated-vm'); const nativeModule = new ivm.NativeModule(require.resolve('./build/Release/addon')); ``` -------------------------------- ### Run Simple Scripts Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/12-examples.md Shows how to compile and run simple JavaScript expressions within a given context. Includes examples for arithmetic and generating random numbers. ```javascript const script = isolate.compileScriptSync('2 + 3'); const result = script.runSync(context); console.log(result); // 5 const script2 = isolate.compileScriptSync('Math.random()'); const random = script2.runSync(context); console.log(random); // Random number between 0 and 1 ``` -------------------------------- ### Create Isolate and Context Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/12-examples.md Demonstrates the basic setup for creating an isolate with a memory limit and a context within that isolate. It also shows how to make the global object available to scripts. ```javascript const ivm = require('isolated-vm'); // Create an isolate with memory limit const isolate = new ivm.Isolate({ memoryLimit: 128 }); // Create a context within the isolate const context = isolate.createContextSync(); // Get reference to global object const global = context.global; // Make global available to scripts global.setSync('global', global.derefInto()); console.log('Ready to execute code'); ``` -------------------------------- ### Basic Synchronous Callback Setup Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/07-callback.md Define a synchronous callback function in Node.js and expose it to an isolate. The isolate can then call this function. ```javascript const ivm = require('isolated-vm'); const isolate = new ivm.Isolate(); const context = isolate.createContextSync(); const global = context.global; // Define a synchronous callback const logger = new ivm.Callback((message) => { console.log(`[Isolate]: ${message}`); return true; }); global.setSync('log', logger); // Isolated code can call it context.evalSync(` log('Hello from isolate'); log('This is safe'); `); ``` -------------------------------- ### startCpuProfiler Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/01-isolate.md Starts CPU profiling in this isolate with a specified title. This allows for performance analysis of the code running within the isolate. ```APIDOC ## startCpuProfiler(title) ### Description Starts CPU profiling in this isolate with the given title. ### Method `startCpuProfiler(title: string): void` ### Parameters #### Path Parameters - **title** (string) - Required - Profile name identifier ### Request Example ```javascript isolate.startCpuProfiler('myProfile'); // ... run code ... const profiles = await isolate.stopCpuProfiler('myProfile'); ``` ``` -------------------------------- ### Example: Delete Property Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md This example demonstrates how to delete a property asynchronously. It retrieves a reference to an object and then uses `delete` to remove a specified property. ```javascript const obj = context.global.getSync('data', { reference: true }); await obj.delete('tempField'); ``` -------------------------------- ### Example C++ Native Module Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md This C++ code demonstrates a simple native module that exports an 'add' function. Ensure your module exports the `InitForContext` symbol. ```c++ #include #include namespace addon { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; void Add(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); double a = args[0]->NumberValue(args[0]->GetIsolate()->GetCurrentContext()).FromMaybe(0.0); double b = args[1]->NumberValue(args[1]->GetIsolate()->GetCurrentContext()).FromMaybe(0.0); args.GetReturnValue().Set(a + b); } extern "C" void InitForContext( Local context, Local exports ) { Isolate* isolate = context->GetIsolate(); exports->Set( context, String::NewFromUtf8(isolate, "add", NewStringType::kNormal).ToLocalChecked(), Function::New(context, Add).ToLocalChecked() ).FromJust(); } } ``` -------------------------------- ### Isolate Memory Limit Examples Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Demonstrates creating Isolates with different memory limits based on workload requirements, from small scripts to large datasets. ```javascript // Small scripts, quick execution const smallIsolate = new ivm.Isolate({ memoryLimit: 32 }); ``` ```javascript // Typical workloads const normalIsolate = new ivm.Isolate({ memoryLimit: 128 }); ``` ```javascript // Large datasets, complex computation const largeIsolate = new ivm.Isolate({ memoryLimit: 512 }); ``` ```javascript // Minimum possible (8 MB) const tinyIsolate = new ivm.Isolate({ memoryLimit: 8 }); ``` -------------------------------- ### Install isolated-vm on Alpine Linux Source: https://github.com/laverdet/isolated-vm/blob/main/README.md For Alpine Linux users, install isolated-vm by running the following command. This ensures Python, make, and g++ are available for compilation. ```bash sudo apk add python3 make g++ ``` -------------------------------- ### Multiple Contexts with Same Native Module Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Demonstrates how a single native module can be instantiated and used independently across multiple isolated-vm contexts. Each context gets its own instance of the native module. ```javascript const nativeModule = new ivm.NativeModule(nativePath); // Create multiple contexts const context1 = isolate.createContextSync(); const context2 = isolate.createContextSync(); const context3 = isolate.createContextSync(); // Instantiate native module in each context const ref1 = nativeModule.createSync(context1); const ref2 = nativeModule.createSync(context2); const ref3 = nativeModule.createSync(context3); // Each context has its own instance context1.global.setSync('native', ref1.derefInto()); context2.global.setSync('native', ref2.derefInto()); context3.global.setSync('native', ref3.derefInto()); // Each can use the native module independently ``` -------------------------------- ### Install isolated-vm on Amazon Linux AMI Source: https://github.com/laverdet/isolated-vm/blob/main/README.md On Amazon Linux AMI, install isolated-vm using yum. This command installs gcc72 and gcc72-c++, which are required for building the native module. ```bash sudo yum install gcc72 gcc72-c++ ``` -------------------------------- ### Start CPU Profiler Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/01-isolate.md Begin CPU profiling for the isolate with a specified title. This is used in conjunction with stopCpuProfiler to analyze performance. ```javascript isolate.startCpuProfiler('myProfile'); // ... run code ... const profiles = await isolate.stopCpuProfiler('myProfile'); ``` -------------------------------- ### Template Rendering with Isolated VM Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/12-examples.md This example demonstrates how to use isolated-vm for template rendering. It exposes a 'render' utility function to the sandbox, which processes a template string with provided data. Useful for dynamic content generation. ```javascript function createTemplateRenderer() { const isolate = new ivm.Isolate(); const context = isolate.createContextSync(); const global = context.global; // Add rendering utilities global.setSync('render', new ivm.Callback((template, data) => { return template.replace(/{{\w+}}/g, (match, key) => { return data[key] || ''; }); })); return { render: (template, data) => { const code = `render(\"${template}\", ${JSON.stringify(data)})`; return context.evalSync(code); }, dispose: () => isolate.dispose() }; } // Usage const renderer = createTemplateRenderer(); const result = renderer.render( 'Hello {{name}}, you have {{count}} messages', { name: 'Alice', count: 5 } ); console.log(result); // "Hello Alice, you have 5 messages" renderer.dispose(); ``` -------------------------------- ### `getSync(property, options?)` Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Synchronous version of `get`. It allows for immediate retrieval of property values without the overhead of asynchronous operations. ```APIDOC ## `getSync(property, options?)` ### Description Synchronous version of `get`. It allows for immediate retrieval of property values without the overhead of asynchronous operations. ### Method `getSync` ### Parameters #### Path Parameters - **property** (string/number/symbol) - Yes - Property name to access #### Query Parameters - **options.accessors** (boolean) - No - If true, invoke getters and proxies (no timeout protection) - **options.copy** (boolean) - No - Deep copy the property value - **options.reference** (boolean) - No - Wrap property in Reference ### Response **Returns:** The property value (or Reference by default) ``` -------------------------------- ### ArrayBuffer Transfer Examples Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Demonstrates different methods for transferring ArrayBuffers using ExternalCopy, including default copying, transferring ownership out of the isolate, and using a transfer list. ```javascript // Create a large buffer const buffer = Buffer.alloc(10 * 1024 * 1024); // 10MB // Option 1: Copy (default) const copy1 = new ivm.ExternalCopy(buffer); // Memory is duplicated // Option 2: Transfer out const copy2 = new ivm.ExternalCopy(buffer, { transferOut: true }); // Ownership is transferred from this isolate // Option 3: With transferList const buf1 = new ArrayBuffer(1024); const buf2 = new ArrayBuffer(1024); const copy3 = new ivm.ExternalCopy( { buffers: [buf1, buf2] }, { transferList: [buf1, buf2] } ); // buf1 and buf2 ownership is transferred ``` -------------------------------- ### Error Handling with Native Modules Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Provides an example of how to handle potential errors during native module loading or instantiation. Includes a fallback mechanism to a JavaScript implementation if the native module fails to load. ```javascript const nativeModule = new ivm.NativeModule(nativePath); const context = isolate.createContextSync(); try { // Try to create native module const ref = nativeModule.createSync(context); context.global.setSync('native', ref.derefInto()); } catch (err) { console.error('Failed to load native module:', err.message); // Fallback to JavaScript implementation context.global.setSync('native', new ivm.Reference({ fallback: true, fallbackFunction: () => { /* ... */ } })); } ``` -------------------------------- ### Evaluate JavaScript String in Isolate Source: https://github.com/laverdet/isolated-vm/blob/main/ISSUE_TEMPLATE.md This snippet shows how to initialize an isolated-vm isolate and context, then evaluate a simple JavaScript string expression. Ensure 'isolated-vm' is installed. ```javascript import ivm from "isolated-vm"; const isolate = new ivm.Isolate(); const context = await isolate.createContext(); console.log(await context.eval('"hello world"')); ``` -------------------------------- ### Accessing Native Module Methods Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Shows how to get a reference to a native module's method within a context and then call it. This involves retrieving the method reference and then applying it with arguments. ```javascript const isolate = new ivm.Isolate(); const context = isolate.createContextSync(); const global = context.global; // Create and dereference native module const nativeModule = new ivm.NativeModule(nativePath); const ref = nativeModule.createSync(context); global.setSync('native', ref.derefInto()); // Get a method reference const methodRef = global.getSync('native'); const method = methodRef.getSync('someMethod', { reference: true }); // Call the method const result = method.applySync(null, [arg1, arg2]); ``` -------------------------------- ### `get(property, options?)` Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Asynchronously accesses a property on the referenced object, returning a reference to that value. It supports options for accessing getters/proxies, deep copying, and wrapping the result in a Reference. ```APIDOC ## `get(property, options?)` ### Description Asynchronously accesses a property on the referenced object, returning a reference to that value. It supports options for accessing getters/proxies, deep copying, and wrapping the result in a Reference. ### Method `get` ### Parameters #### Path Parameters - **property** (string/number/symbol) - Yes - Property name to access #### Query Parameters - **options.accessors** (boolean) - No - If true, invoke getters and proxies (no timeout protection) - **options.copy** (boolean) - No - Deep copy the property value - **options.reference** (boolean) - No - Wrap property in Reference ### Response **Returns:** Promise resolving to the property value (or Reference by default) **Throws:** Error if accessing a proxy or getter without `accessors: true` ### Request Example ```javascript const obj = context.global.getSync('data', { reference: true }); const prop = await obj.get('x'); console.log(prop.typeof); // Type of data.x ``` ``` -------------------------------- ### Initializing Isolates with Snapshot Data using ExternalCopy Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/05-externalcopy.md Demonstrates how to create an ExternalCopy of initialization data and use it with `copyInto` when creating an isolate with a snapshot. ```javascript // Create snapshot with initial data const snapshot = ivm.Isolate.createSnapshot([ { code: 'const DATA = require("initialData");' } ]); // Create external copy of initialization data const initialData = new ivm.ExternalCopy({ config: { timeout: 5000 }, version: '1.0.0' }); // Create isolates with snapshot const isolate = new ivm.Isolate({ snapshot }); const context = isolate.createContextSync(); context.global.setSync('initialData', initialData.copyInto()); ``` -------------------------------- ### Basic Native Module Instantiation Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Demonstrates the basic steps to load and instantiate a native Node.js module within an isolated-vm context. Ensure the native module is compiled with node-gyp first. ```javascript const ivm = require('isolated-vm'); const path = require('path'); // Compile native module with node-gyp first const nativePath = require.resolve('./build/Release/addon'); // Create isolate and context const isolate = new ivm.Isolate(); const context = isolate.createContextSync(); // Create native module const nativeModule = new ivm.NativeModule(nativePath); // Instantiate in context const moduleRef = isolate.createContextSync(); const ref = nativeModule.createSync(context); // Dereference into context context.global.setSync('native', ref.derefInto()); // Isolate code can use native functions context.evalSync('native.someFunction()'); ``` -------------------------------- ### Create an Isolate and Execute Code Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/00-index.md Demonstrates the basic steps to create a new isolate with a memory limit, compile and run a simple script synchronously, and log the result. ```javascript const ivm = require('isolated-vm'); // Create isolate with 128MB memory limit const isolate = new ivm.Isolate({ memoryLimit: 128 }); // Create context const context = isolate.createContextSync(); // Execute code const script = isolate.compileScriptSync('1 + 1'); const result = script.runSync(context); console.log(result); // 2 ``` -------------------------------- ### Synchronously Get Property Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Use `getSync` for a synchronous version of `get` to access properties. This method directly returns the property value. ```javascript getSync( property: Key, options?: Options ): ResultTypeSync ``` -------------------------------- ### Module.instantiate() Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/06-module.md Asynchronously instantiates this module and all its dependencies in the given context. This method can only be called once per module. ```APIDOC ## Module.instantiate(context, resolveCallback) ### Description Asynchronously instantiates this module and all its dependencies in the given context. Can only be called once per module. ### Method `instantiate( context: Context, resolveCallback: (specifier: string, referrer: Module) => Module | Promise ): Promise` ### Parameters #### Parameters - **context** (Context) - Required - The context in which to instantiate the module - **resolveCallback** (function) - Required - Callback to resolve import specifiers to Module objects #### Callback Parameters - `specifier` (string) - The import specifier (e.g., "./helper.js") - `referrer` (Module) - The module that is importing (useful for relative resolution) ### Returns Promise ### Example ```javascript const moduleMap = { './math.js': mathModule, './utils.js': utilsModule }; await mainModule.instantiate(context, (specifier, referrer) => { if (specifier in moduleMap) { return moduleMap[specifier]; } throw new Error(`Cannot resolve ${specifier}`); }); ``` ``` -------------------------------- ### Getting the Type of a Referenced Value Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Demonstrates how to use the `typeof` property to get the JavaScript type of the value a reference points to. This property is accessible from any isolate at any time. ```javascript const ref = context.global.getSync('someValue'); console.log(ref.typeof); // "number", "function", etc. ``` -------------------------------- ### Create and Evaluate Basic Isolate and Context Source: https://github.com/laverdet/isolated-vm/blob/main/README.md Demonstrates the creation of an isolate with a memory limit and a context. It shows how to expose global objects and functions from the host to the isolate, and how to evaluate a simple script. ```javascript const ivm = require('isolated-vm'); const isolate = new ivm.Isolate({ memoryLimit: 128 }); const context = isolate.createContextSync(); const jail = context.global; jail.setSync('global', jail.derefInto()); jail.setSync('log', function(...args) { console.log(...args); }); context.evalSync('log("hello world")'); ``` -------------------------------- ### Asynchronously Get Property Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Use `get` to asynchronously access a property on a referenced object. It returns a promise that resolves to the property's value or a Reference by default. Ensure `accessors: true` is used when invoking getters or proxies. ```javascript get( property: Key, options?: Options ): ResultTypeAsync ``` -------------------------------- ### Setting Up Global Functions in Isolated Context Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/02-context.md Illustrates how to make the global object itself available within the isolated context and add utility functions like 'log'. This allows the isolated code to interact with the host environment's global scope. ```javascript const ivm = require('isolated-vm'); const isolate = new ivm.Isolate({ memoryLimit: 128 }); const context = isolate.createContextSync(); const global = context.global; // Make global available as a reference global.setSync('global', global.derefInto()); // Add utility function global.setSync('log', function(...args) { console.log(...args); }); // Now code can use them context.evalSync('log("Hello from context")'); ``` -------------------------------- ### Module.instantiateSync() Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/06-module.md Synchronous version of `instantiate`. ```APIDOC ## Module.instantiateSync(context, resolveCallback) ### Description Synchronous version of `instantiate`. ### Method `instantiateSync( context: Context, resolveCallback: (specifier: string, referrer: Module) => Module ): void` ### Parameters #### Parameters - **context** (Context) - Required - The context in which to instantiate the module - **resolveCallback** (function) - Required - Callback to resolve import specifiers to Module objects ### Returns void ``` -------------------------------- ### Import Isolated VM Module Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/MANIFEST.md This is the standard way to import the isolated-vm module in Node.js. Ensure you have the module installed. ```javascript const ivm = require('isolated-vm') ``` -------------------------------- ### Reference.derefInto() Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Returns a serializable handle that, when passed to another isolate, causes that isolate to dereference the handle and get the actual value. ```APIDOC ## derefInto(options?) ### Description Returns an object that, when passed to another isolate, causes that isolate to dereference the handle and get the actual value. ### Parameters #### Parameters - **options.release** (boolean) - Optional - If true, automatically release after dereference. ### Returns Dereference - A serializable dereference handle. ``` -------------------------------- ### Execute Module with Dependencies Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/06-module.md Demonstrates compiling and instantiating multiple modules, where one module imports from another. This pattern is essential for building complex applications with modular code. ```javascript // Compile multiple modules const mathModule = isolate.compileModuleSync(` export const add = (a, b) => a + b; export const multiply = (a, b) => a * b; `); const mainModule = isolate.compileModuleSync(` import { add, multiply } from './math.js'; export const compute = (x, y) => { const sum = add(x, y); const product = multiply(x, y); return { sum, product }; }; `); // Create resolver const modules = { './math.js': mathModule }; const resolver = (specifier, referrer) => { if (specifier in modules) { return modules[specifier]; } throw new Error(`Cannot resolve: ${specifier}`); }; // Instantiate with dependencies await mainModule.instantiate(context, resolver); // Use the module const ns = mainModule.namespace; const compute = ns.getSync('compute', { reference: true }); const result = await compute.apply(null, [5, 3]); console.log(result); // { sum: 8, product: 15 } ``` -------------------------------- ### NativeModule.create Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Asynchronously instantiates the native module in the given context by calling the `InitForContext` symbol defined in the C++ module. This is the recommended way to load native modules. ```APIDOC ### Instance Methods #### `create(context)` Asynchronously instantiates the native module in the given context by calling the `InitForContext` symbol defined in the C++ module. ```javascript create(context: Context): Promise> ``` #### Parameters * **context** (Context) - Yes - The context to initialize the module in #### Returns Promise resolving to a `Reference` to the module instance. #### Throws Error if the native module doesn't export `InitForContext` symbol. #### Example ```javascript const nativeModule = new ivm.NativeModule(require.resolve('./build/Release/native')); const context = isolate.createContextSync(); const moduleRef = await nativeModule.create(context); // moduleRef is a Reference to the module instance ``` ``` -------------------------------- ### node-gyp Configuration for Native Module Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Configure your `binding.gyp` file to include the C++ source file and necessary headers for building the native module. ```json { "targets": [ { "target_name": "addon", "sources": [ "binding.cc" ], "include_dirs": [" a + b; `); const appModule = isolate.compileModuleSync(` import { PI, add } from './math.js'; export const calculateArea = (radius) => { return PI * radius * radius; }; export const compute = () => { return add(1, 2); }; `); // Create resolver const moduleMap = { './math.js': mathModule }; const resolver = (specifier, referrer) => { if (specifier in moduleMap) { return moduleMap[specifier]; } throw new Error(`Cannot resolve: ${specifier}`); }; // Instantiate await appModule.instantiate(context, resolver); // Use exports const ns = appModule.namespace; const calcArea = ns.getSync('calculateArea', { reference: true }); const area = await calcArea.apply(null, [5]); console.log(area); // 78.53975... ``` -------------------------------- ### Expose Basic Logging Function Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/12-examples.md Illustrates how to expose a host function (log) to an isolated context, allowing code running inside the isolate to log messages back to the host environment. ```javascript const global = context.global; // Create logging callback global.setSync('log', new ivm.Callback((msg) => { console.log(`[Isolate] ${msg}`); })); // Use in isolated code context.evalSync( 'log(\'Hello from isolated code\');\nlog(\'This works!\');' ); ``` -------------------------------- ### Context Creation Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/00-index.md Shows how to create a new context within an isolate, both synchronously and asynchronously. ```APIDOC ## isolate.createContext(options) ### Description Creates a new context asynchronously. ### Method ASYNC ### Endpoint N/A (Method on Isolate object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Optional - Configuration options for the context. ``` ```APIDOC ## isolate.createContextSync(options) ### Description Creates a new context synchronously. ### Method SYNC ### Endpoint N/A (Method on Isolate object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Optional - Configuration options for the context. ``` -------------------------------- ### Get Property Configuration Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Retrieve a property from a reference with various options controlling access and copying behavior. Use when fine-grained control over property retrieval is needed. ```javascript const prop = await ref.get('property', { accessors: false, copy: false, externalCopy: false, reference: false, promise: false }); ``` -------------------------------- ### Expose File I/O Functions Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/12-examples.md Demonstrates exposing host file system functions (readFile, writeFile) to an isolated context. This allows scripts within the isolate to read from and write to the host's file system. ```javascript const fs = require('fs'); const global = context.global; // Expose file read global.setSync('readFile', new ivm.Callback((path) => { return fs.readFileSync(path, 'utf8'); })); // Expose file write global.setSync('writeFile', new ivm.Callback((path, content) => { fs.writeFileSync(path, content, 'utf8'); return true; })); // Use in code context.evalSync( 'const config = readFile(\'/config.json\');\nwriteFile(\'/output.txt\', config);' ); ``` -------------------------------- ### Isolate Creation Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/00-index.md Demonstrates how to create a new V8 isolate with an optional memory limit. ```APIDOC ## new Isolate(options) ### Description Creates a new V8 isolate. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Optional - Configuration options for the isolate. - **memoryLimit** (number) - Optional - The maximum memory in MB the isolate can use. ``` -------------------------------- ### Deeply Nested Object Transfer Example Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/05-externalcopy.md Demonstrates transferring a complex object with nested arrays, objects, and Dates between isolates, verifying that the structure and types are preserved. ```javascript const complex = { users: [ { id: 1, name: 'Alice', created: new Date() }, { id: 2, name: 'Bob', created: new Date() } ], metadata: { version: '1.0', nested: { deep: { value: 'preserved' } } } }; const copy = new ivm.ExternalCopy(complex); const received = copy.copy(); // All structure and types are preserved console.log(received.users[0].created instanceof Date); // true console.log(received.metadata.nested.deep.value); // "preserved" ``` -------------------------------- ### Profile CPU Usage Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/00-index.md Starts and stops CPU profiling for an isolate, then logs the resulting profile data. This is essential for identifying performance bottlenecks in your isolated code. ```javascript isolate.startCpuProfiler('profile'); // ... run code ... const profiles = await isolate.stopCpuProfiler('profile'); console.log(JSON.stringify(profiles[0].profile)); ``` -------------------------------- ### Isolate Constructor with Options Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Initialize an Isolate with specific configuration options such as memory limit, inspector enablement, and snapshot. ```javascript const isolate = new ivm.Isolate({ memoryLimit: 128, inspector: false, snapshot: undefined, onCatastrophicError: undefined }); ``` -------------------------------- ### Run Script Options Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Configure script execution with timeout, release, and data copying/referencing options. Use `script.run` for async or `script.runSync` for sync operations. ```javascript const result = await script.run(context, { timeout: 5000, release: false, copy: false, externalCopy: false, reference: false, promise: false }); ``` -------------------------------- ### Callback Configuration Options Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Configure how callbacks are invoked. Use `sync` for immediate execution, `async` for promise-based execution, or `ignored` for fire-and-forget behavior. ```javascript const syncCallback = new ivm.Callback(fn, { sync: true }); const asyncCallback = new ivm.Callback(fn, { async: true }); const ignoredCallback = new ivm.Callback(fn, { ignored: true }); ``` -------------------------------- ### Expose Host Functions to an Isolate Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/00-index.md Illustrates how to expose a synchronous function from the host environment (e.g., `console.log`) to an isolate using `ivm.Callback`. The exposed function can then be called from within the isolated code. ```javascript const isolate = new ivm.Isolate(); const context = isolate.createContextSync(); const global = context.global; // Expose logging global.setSync('log', new ivm.Callback((msg) => { console.log(`[Code]: ${msg}`); })); // Use in isolate context.evalSync('log("Hello from isolate")'); ``` -------------------------------- ### Import and Create Isolate Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/01-isolate.md Import the isolated-vm library and create a new Isolate instance. Options can be provided to configure memory limits and inspector support. ```javascript const ivm = require('isolated-vm'); const isolate = new ivm.Isolate(options); ``` -------------------------------- ### Asynchronous Callback Setup Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/07-callback.md Define an asynchronous callback that performs work in the main Node.js environment and can be awaited by the isolate. Ensure to use the `{ promise: true }` option for `evalSync` when awaiting. ```javascript // Perform async work in the main isolate const fetchData = new ivm.Callback(async (id) => { const response = await fetch(`/api/data/${id}`); return response.json(); }, { async: true }); context.global.setSync('fetch', fetchData); // Isolate code can await it const result = context.evalSync(` (async () => { const data = await fetch(42); return data.name; })() `, { promise: true }); console.log(await result); ``` -------------------------------- ### ExternalCopy Initialization Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Create an ExternalCopy instance to manage data transfer between isolates. Configure options for transfer lists and releasing ownership. ```javascript const copy = new ivm.ExternalCopy(value, { transferList: undefined, transferOut: false }); ``` -------------------------------- ### Access and Modify Object Properties Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Demonstrates how to get, set, and delete properties of an object within an isolated context. Use 'copy: true' for primitive values and 'reference: true' for objects. ```javascript const obj = context.global.getSync('data', { reference: true }); // Get property const x = await obj.get('x', { copy: true }); // Set property await obj.set('y', 100); // Delete property await obj.delete('temp'); // Check type console.log(obj.typeof); // "object" ``` -------------------------------- ### Creating ExternalCopy instances Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/05-externalcopy.md Demonstrates how to create ExternalCopy instances for various data types like numbers, objects, and ArrayBuffers. The `transferOut` option can be used to transfer ownership of ArrayBuffers. ```javascript const ivm = require('isolated-vm'); // Copy a simple value const num = new ivm.ExternalCopy(42); // Copy an object const obj = new ivm.ExternalCopy({ x: 1, y: 2 }); // Copy an ArrayBuffer with transfer const buffer = new ArrayBuffer(1024); const copy = new ivm.ExternalCopy(buffer, { transferOut: true }); ``` -------------------------------- ### Dereferencing a Reference within the Owning Isolate Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Explains how to get the actual value pointed to by a reference, but only when executed within the same isolate that owns the reference. An optional release option can automatically call `release()` after dereferencing. ```javascript // Only usable from within the isolate that owns the value const value = ref.deref(); ``` -------------------------------- ### Asynchronously Create Native Module Instance Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Instantiate the native module in a given context asynchronously. This requires the native module to export an 'InitForContext' symbol. It returns a Promise that resolves to a Reference to the module instance. ```javascript const nativeModule = new ivm.NativeModule(require.resolve('./build/Release/native')); const context = isolate.createContextSync(); const moduleRef = await nativeModule.create(context); // moduleRef is a Reference to the module instance ``` -------------------------------- ### Script Compilation Options Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Demonstrates the basic usage of `isolate.compileScript` with common configuration options. ```javascript const script = await isolate.compileScript(code, { filename: 'file:///app.js', lineOffset: 0, columnOffset: 0, cachedData: undefined, produceCachedData: false }); ``` -------------------------------- ### Importing and Creating a Reference Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/04-reference.md Demonstrates how to import the Reference class and create a new reference to a JavaScript function. This reference can then be set within an isolated context. ```javascript const ref = new ivm.Reference(value, options); // or obtained from various API calls ``` ```javascript const ivm = require('isolated-vm'); const isolate = new ivm.Isolate(); const context = isolate.createContextSync(); // Create reference to a function const fn = new ivm.Reference(function add(a, b) { return a + b; }); // Set it in the isolated context context.global.setSync('add', fn); // Code in isolate can call it context.evalSync('add(2, 3)'); ``` -------------------------------- ### Module with import.meta and Custom Metadata Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/06-module.md Illustrates how to use `import.meta.url` within a module and how to provide custom metadata during compilation using the `meta` option. This is useful for module identification and configuration. ```javascript const code = ` console.log('Module URL:', import.meta.url); export const moduleInfo = import.meta; `; const module = isolate.compileModuleSync(code, { filename: 'file:///modules/app.js', meta: (importMeta) => { importMeta.url = 'file:///modules/app.js'; importMeta.version = '1.0.0'; } }); const global = context.global; global.setSync('console', new ivm.Reference(console)); await module.instantiate(context, (spec) => { throw new Error(`No dependencies: ${spec}`); }); const info = module.namespace.getSync('moduleInfo', { copy: true }); console.log(info); // { url: '...', version: '1.0.0' } ``` -------------------------------- ### Transferring Data Between Isolates using ExternalCopy Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/05-externalcopy.md Shows how to create an ExternalCopy in one isolate and then transfer it into another isolate's context using `copyInto`. ```javascript const ivm = require('isolated-vm'); const isolate1 = new ivm.Isolate(); const context1 = isolate1.createContextSync(); const isolate2 = new ivm.Isolate(); const context2 = isolate2.createContextSync(); // Create external copy in isolate1 const data = new ivm.ExternalCopy({ value: 42 }); // Copy into isolate2 context2.global.setSync('imported', data.copyInto()); // Isolate2 can use it const result = context2.evalSync('imported.value'); // 42 ``` -------------------------------- ### Preparing ExternalCopy for another isolate Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/05-externalcopy.md Demonstrates using `copyInto()` to create a handle that, when passed to another isolate, causes that isolate to copy the external data into its own heap. The `transferIn` option can be used to transfer ownership instead of copying. ```javascript const external = new ivm.ExternalCopy([1, 2, 3, 4, 5]); const copyHandle = external.copyInto(); // Pass to another isolate context.global.setSync('data', copyHandle); // The isolate gets a copy const result = context.evalSync('data.length'); // 5 ``` -------------------------------- ### Creating a Snapshot with Code and Filename Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/11-configuration.md Generate a snapshot from an array of code objects, each with optional filename. This pre-compiles scripts for faster isolate initialization. ```javascript const snapshot = ivm.Isolate.createSnapshot([ { code: 'const PI = 3.14159;', filename: 'file:///math.js' }, { code: 'const E = 2.71828;', filename: 'file:///math2.js' } ], 'warmup_code'); ``` -------------------------------- ### Create ExternalCopy with Isolate, Context, and Global Source: https://github.com/laverdet/isolated-vm/blob/main/README.md Demonstrates creating an `ExternalCopy` instance with nested transferable objects including isolate, context, and global references. This is useful for managing complex data structures that need to be shared or copied between isolates. ```javascript let isolate = new ivm.Isolate; let context = isolate.createContextSync(); let global = context.global; let data = new ExternalCopy({ isolate, context, global }); ``` -------------------------------- ### C++ Native Module InitForContext Signature Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md The `InitForContext` function is required for native modules. It receives the V8 context and exports object to populate. ```c++ extern "C" void InitForContext( v8::Local context, v8::Local exports ); ``` -------------------------------- ### Create Snapshot for Isolate Initialization Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/01-isolate.md Use Isolate.createSnapshot to generate a snapshot of compiled code and heap state. This snapshot can then be used to initialize a new Isolate for faster startup. ```javascript const snapshot = ivm.Isolate.createSnapshot([ { code: 'const helper = () => 42;', filename: 'file:///helper.js' } ]); // Use snapshot in new isolate const isolate = new ivm.Isolate({ snapshot }); ``` -------------------------------- ### Synchronously Create Native Module Instance Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Synchronously instantiate the native module in a given context. This method blocks the current thread until the module is initialized. ```javascript createSync(context: Context): Reference ``` -------------------------------- ### NativeModule.createSync Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Synchronous version of `create`. This method blocks the current thread until the native module is instantiated in the context. ```APIDOC #### `createSync(context)` Synchronous version of `create`. Blocks the current thread. ```javascript createSync(context: Context): Reference ``` #### Parameters * **context** (Context) - Yes - The context to initialize the module in #### Returns A `Reference` to the module instance. ``` -------------------------------- ### Import NativeModule Source: https://github.com/laverdet/isolated-vm/blob/main/_autodocs/08-nativemodule.md Import the NativeModule class from the isolated-vm library. ```javascript const nativeModule = new ivm.NativeModule(filename); ``` -------------------------------- ### Compiling a Module and Accessing Dependencies Source: https://github.com/laverdet/isolated-vm/blob/main/README.md Demonstrates how to compile a JavaScript module and retrieve its dependency specifiers. The code assumes an 'isolate' object is already available. ```javascript const code = `import something from './something';`; const module = await isolate.compileModule(code); const dependencySpecifiers = module.dependencySpecifiers; // dependencySpecifiers => ["./something"]; ```