### Install ShadowRealm API Polyfill Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Install the shadowrealm-api package using npm. ```bash npm i -S shadowrealm-api ``` -------------------------------- ### Install ShadowRealm polyfill Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Patches the global object to make ShadowRealm available without explicit imports. ```javascript // Polyfill usage - patches global object import 'shadowrealm-api/dist/polyfill'; // ShadowRealm is now available globally const realm = new ShadowRealm(); // Works with existing global checks if (typeof ShadowRealm !== 'undefined') { const sandbox = new ShadowRealm(); sandbox.evaluate('console.log("Running in sandbox")'); } ``` -------------------------------- ### Initialize ShadowRealm instances Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Demonstrates creating isolated realms and verifying their independent global scopes. ```javascript // Ponyfill usage - non-invasive import import ShadowRealm from 'shadowrealm-api'; // Create a new isolated realm const realm = new ShadowRealm(); // Each realm has its own isolated global scope const realm1 = new ShadowRealm(); const realm2 = new ShadowRealm(); // Variables in one realm don't affect others realm1.evaluate('globalThis.counter = 100'); realm2.evaluate('globalThis.counter = 200'); console.log(realm1.evaluate('globalThis.counter')); // 100 console.log(realm2.evaluate('globalThis.counter')); // 200 console.log(typeof globalThis.counter); // "undefined" - main realm unaffected ``` -------------------------------- ### Initialize ShadowRealm (Global Patch) Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Import the polyfill to patch the global object, then instantiate ShadowRealm. ```javascript import 'shadowrealm-api/dist/polyfill' const realm = new ShadowRealm(); ``` -------------------------------- ### Use ES Module Syntax in ShadowRealm Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Shows how to use dynamic imports and import.meta within a ShadowRealm, which are transformed for sandbox compatibility. ```javascript import ShadowRealm from 'shadowrealm-api'; const realm = new ShadowRealm(); // Dynamic import is supported (transformed to internal __import) const loadAndRun = realm.evaluate(` async () => { const module = await import('./my-module.js'); return module.processData(); } `); loadAndRun().then(result => { console.log('Module result:', result); }); // import.meta is available inside modules realm.importValue('./module-with-meta.js', 'getModuleUrl') .then(getUrl => { console.log('Module URL:', getUrl()); }); ``` -------------------------------- ### Polyfills for Compatibility Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Includes necessary polyfills for fetch and URL, along with the ShadowRealm polyfill, for broader browser compatibility. ```javascript import "fetch polyfill"; import "URL polyfill"; import "shadowrealm-api/dist/polyfill"; // Your codes ``` -------------------------------- ### Initialize ShadowRealm (Non-invasive) Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Instantiate the ShadowRealm class without modifying the global object. ```javascript import ShadowRealm from 'shadowrealm-api' const realm = new ShadowRealm(); ``` -------------------------------- ### ShadowRealm Constructor Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Creates a new isolated JavaScript execution environment with its own global object. ```APIDOC ## Constructor ShadowRealm() ### Description Creates a new isolated JavaScript execution environment (realm) with its own global object. Each instance maintains complete separation from the main realm. ### Request Example const realm = new ShadowRealm(); ``` -------------------------------- ### ShadowRealm Class API Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md The core interface for creating and interacting with a ShadowRealm sandbox. ```APIDOC ## ShadowRealm Class ### Description Represents a new isolated JavaScript realm. ### Constructor - **new ShadowRealm()** - Creates a new instance of a ShadowRealm. ### Methods - **evaluate(sourceText: string)** - Evaluates the provided source text within the realm. Returns a Primitive or Function. - **importValue(specifier: string, bindingName: string)** - Asynchronously imports a value from a module. Returns a Promise that resolves to a Primitive or Function. ### Request Example ```javascript const realm = new ShadowRealm(); const result = realm.evaluate('1 + 2'); ``` ``` -------------------------------- ### Exporting Variables Correctly Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Shows the correct way to export variables by declaring them first and then exporting them using a named export. ```javascript // ✅ const obj = {...}, fn = () => {...}; export { obj, fn }; ``` -------------------------------- ### Handle Errors in ShadowRealm Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Demonstrates how syntax, runtime, and type errors are handled and wrapped when evaluating code within a ShadowRealm instance. ```javascript import ShadowRealm from 'shadowrealm-api'; const realm = new ShadowRealm(); // Syntax errors are caught at evaluation time try { realm.evaluate('const x = ;'); // Invalid syntax } catch (error) { console.log(error instanceof SyntaxError); // true console.log(error.message); // Unexpected token ';' } // Runtime errors are wrapped in TypeError try { realm.evaluate(` throw new Error('Something went wrong inside'); `); } catch (error) { console.log(error instanceof TypeError); // true console.log(error.message); // "Cross-Realm Error: Error: Something went wrong inside" } // Type validation errors try { realm.evaluate(42); // Not a string } catch (error) { console.log(error.message); // "evaluate expects a string" } // Must be called on ShadowRealm instance try { const evaluate = ShadowRealm.prototype.evaluate; evaluate.call({}, '1 + 1'); } catch (error) { console.log(error.message); // "must be called on ShadowRealm object" } ``` -------------------------------- ### Valid ESM Import Statement Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Demonstrates the correct syntax for ESM import statements, avoiding redundant comments. ```javascript // ✅ import defaultExport from "module-name"; export default 'xxx'; ``` -------------------------------- ### Enable Debugging Output Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Set the `__debug` static property to true to print internal debugging information. ```javascript ShadowRealm.__debug = true; ``` -------------------------------- ### Perform Cross-Realm Function Communication Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Demonstrates passing functions between realms and maintaining realm context. Functions are automatically wrapped for safe execution across boundaries. ```javascript import ShadowRealm from 'shadowrealm-api'; const realm = new ShadowRealm(); // Pass functions between realms const outerAdd = (a, b) => a + b; const realmCalculator = realm.evaluate(` (externalAdd, x, y, multiplier) => { // Call the wrapped function from the outer realm const sum = externalAdd(x, y); return sum * multiplier; } `); // Function from outer realm is wrapped and callable inside const result = realmCalculator(outerAdd, 2, 3, 4); console.log(result); // 20 (2 + 3 = 5, 5 * 4 = 20) // Bidirectional function wrapping const createAdder = realm.evaluate(` (initial) => { let value = initial; return (increment) => { value += increment; return value; }; } `); const adder = createAdder(10); console.log(adder(5)); // 15 console.log(adder(3)); // 18 // Functions preserve their realm context realm.evaluate('globalThis.secret = "hidden"'); const getSecret = realm.evaluate('() => globalThis.secret'); console.log(getSecret()); // "hidden" console.log(typeof globalThis.secret); // "undefined" ``` -------------------------------- ### Debugging Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Enable debug mode to print internal transformation and evaluation information for troubleshooting. ```APIDOC ## Debugging ### Description Enable debug mode to print internal transformation and evaluation information for troubleshooting. ### Configuration - **ShadowRealm.__debug** (boolean) - Set to true to enable internal logging. ``` -------------------------------- ### Import ES Modules with importValue Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Asynchronously imports named or default exports from ES modules into a ShadowRealm. Returns a Promise resolving to the wrapped exported value. ```javascript import ShadowRealm from 'shadowrealm-api'; const realm = new ShadowRealm(); // Import a named export from a module // Assuming './math-utils.js' exports: export const add = (a, b) => a + b; realm.importValue('./math-utils.js', 'add') .then(add => { console.log(add(2, 3)); // 5 }) .catch(error => { console.error('Failed to import:', error); }); // Using async/await async function loadModule() { try { // Import default export const defaultFn = await realm.importValue('./plugin.js', 'default'); defaultFn(); // Import multiple named exports const helper1 = await realm.importValue('./utils.js', 'helper1'); const helper2 = await realm.importValue('./utils.js', 'helper2'); console.log(helper1()); console.log(helper2()); } catch (error) { // Handle module loading errors or missing exports if (error.message.includes('has no export named')) { console.error('Export not found in module'); } else { console.error('Module failed to load:', error); } } } loadModule(); ``` -------------------------------- ### Create Nested ShadowRealms Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Establishes hierarchical isolation by creating ShadowRealm instances within other realms. Each nested realm maintains its own independent global scope. ```javascript import ShadowRealm from 'shadowrealm-api'; // Set a value in the main realm globalThis.myValue = 'main'; const realm1 = new ShadowRealm(); realm1.evaluate('globalThis.myValue = "realm1"'); // Create a nested realm inside realm1 const realm2Evaluate = realm1.evaluate(` const realm2 = new ShadowRealm(); realm2.evaluate('globalThis.myValue = "realm2"'); // Return a function to evaluate code in realm2 (code) => realm2.evaluate(code) `); // All three realms maintain separate state console.log(globalThis.myValue); // "main" console.log(realm1.evaluate('globalThis.myValue')); // "realm1" console.log(realm2Evaluate('globalThis.myValue')); // "realm2" // Changes don't leak between realms realm1.evaluate('globalThis.myValue = "updated"'); console.log(globalThis.myValue); // "main" (unchanged) console.log(realm2Evaluate('globalThis.myValue')); // "realm2" (unchanged) ``` -------------------------------- ### Evaluate code in ShadowRealm Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Executes strings of code within the realm, returning primitives or wrapped functions. Note that returning plain objects will throw a TypeError. ```javascript import ShadowRealm from 'shadowrealm-api'; const realm = new ShadowRealm(); // Evaluate expressions and get primitive results const sum = realm.evaluate('1 + 1'); console.log(sum); // 2 const str = realm.evaluate('"Hello, " + "World!"'); console.log(str); // "Hello, World!" // Define and retrieve functions from the realm const getTimestamp = realm.evaluate(` () => Date.now() `); console.log(getTimestamp()); // 1699999999999 // Define variables and functions in the realm's global scope realm.evaluate(` globalThis.multiplier = 10; globalThis.multiply = (x) => x * globalThis.multiplier; `); const multiply = realm.evaluate('multiply'); console.log(multiply(5)); // 50 // Strict mode is enforced - this throws an error try { realm.evaluate('x = 10'); // ReferenceError: x is not defined } catch (e) { console.log('Strict mode prevents implicit globals'); } // Objects cannot be returned directly (only primitives and functions) try { realm.evaluate('({ key: "value" })'); // TypeError } catch (e) { console.log('Cannot return objects, only primitives or callables'); } ``` -------------------------------- ### Enable Debug Mode Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Activates internal logging to inspect code transformations and evaluation processes. Ensure debug mode is disabled in production environments. ```javascript import ShadowRealm from 'shadowrealm-api'; // Enable debug logging ShadowRealm.__debug = true; const realm = new ShadowRealm(); // Debug output will show transformed code realm.evaluate(` const x = 10; const square = (n) => n * n; square(x) `); // Console will show internal code transformations // Disable when done debugging ShadowRealm.__debug = false; ``` -------------------------------- ### Nested ShadowRealms Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt ShadowRealms can create nested ShadowRealm instances, enabling hierarchical isolation where each nested realm maintains its own separate global scope. ```APIDOC ## Nested ShadowRealms ### Description ShadowRealms can create nested ShadowRealm instances, enabling hierarchical isolation. Each nested realm maintains its own separate global scope. ``` -------------------------------- ### Cross-Realm Function Communication Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Functions passed between realms are automatically wrapped to enable safe execution. Arguments and return values are handled across boundaries, while objects are restricted to prevent leakage. ```APIDOC ## Cross-Realm Function Communication ### Description Functions returned from `evaluate()` are wrapped to enable safe cross-realm calls. Arguments and return values are automatically wrapped, with functions being callable across realms while objects throw TypeErrors. ### Request Example ```javascript const realm = new ShadowRealm(); const outerAdd = (a, b) => a + b; const realmCalculator = realm.evaluate(`(externalAdd, x, y, multiplier) => externalAdd(x, y) * multiplier`); const result = realmCalculator(outerAdd, 2, 3, 4); ``` ``` -------------------------------- ### importValue(specifier, bindingName) Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Asynchronously imports a specific named export from an ES module into the realm. ```APIDOC ## importValue(specifier, bindingName) ### Description Asynchronously imports a specific named export from an ES module into the realm. Returns a Promise that resolves to the wrapped exported value. ### Parameters - **specifier** (string) - Required - The module path to import. - **bindingName** (string) - Required - The name of the export to import. ### Response - **Promise** (object) - Resolves to the wrapped exported value. ``` -------------------------------- ### evaluate(sourceText) Source: https://context7.com/ambit-tsai/shadowrealm-api/llms.txt Evaluates a string of JavaScript code within the isolated realm and returns the result. ```APIDOC ## evaluate(sourceText) ### Description Evaluates a string of JavaScript code within the isolated realm. Returns primitive values directly, wraps functions for cross-realm communication, and throws TypeError for non-callable objects. ### Parameters #### Request Body - **sourceText** (string) - Required - The JavaScript code string to be evaluated within the realm. ### Response #### Success Response (200) - **result** (primitive/function) - The result of the evaluation. ### Request Example realm.evaluate('1 + 1'); ``` -------------------------------- ### ShadowRealm Class Definition Source: https://github.com/ambit-tsai/shadowrealm-api/blob/main/README.md Defines the TypeScript interface for the ShadowRealm class, including evaluate and importValue methods. ```typescript declare class ShadowRealm { constructor(); evaluate(sourceText: string): Primitive | Function; importValue(specifier: string, bindingName: string): Promise; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.