{"id":12105,"library":"sval","title":"Sval JavaScript Interpreter","description":"Sval is a JavaScript interpreter written entirely in JavaScript, leveraging the Acorn parser to support modern ECMAScript features while maintaining compatibility with ES5 environments. As of version 0.6.12, it provides robust capabilities for executing JavaScript code in either an isolated sandbox or an invasive mode, depending on user requirements. This flexibility makes it particularly useful for environments where native `eval`, `setTimeout`, or `new Function` might be disabled or restricted due to security policies. The package is actively maintained, with frequent updates addressing bug fixes and dependency bumps, ensuring ongoing support for new JavaScript syntax and improved stability. Key differentiators include its ability to run cutting-edge ES features on older runtimes and its explicit support for both script and module source types, alongside TypeScript type definitions for enhanced developer experience.","status":"active","version":"0.6.12","language":"javascript","source_language":"en","source_url":"https://github.com/Siubaak/sval","tags":["javascript","sval","js","eval","interpreter","typescript"],"install":[{"cmd":"npm install sval","lang":"bash","label":"npm"},{"cmd":"yarn add sval","lang":"bash","label":"yarn"},{"cmd":"pnpm add sval","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Sval internally uses Acorn for JavaScript parsing. While not a peer dependency, understanding its role is crucial for advanced use cases like custom parsers.","package":"acorn","optional":false}],"imports":[{"note":"Sval is a default export for ES Modules. Attempting to use a named import will result in a runtime error.","wrong":"import { Sval } from 'sval'","symbol":"Sval","correct":"import Sval from 'sval'"},{"note":"For CommonJS environments, the module's default export is directly assigned when requiring the package.","wrong":"const { Sval } = require('sval')","symbol":"Sval (CommonJS)","correct":"const Sval = require('sval')"},{"note":"TypeScript users can import the `SvalOptions` interface for type-safe configuration of the interpreter.","symbol":"SvalOptions (Type)","correct":"import type { SvalOptions } from 'sval'"}],"quickstart":{"code":"import Sval from 'sval';\n\nconst interpreter = new Sval({\n  ecmaVer: 'latest', // Support latest ECMAScript features\n  sourceType: 'script', // Treat code as a standard script\n  sandBox: true, // Run code in an isolated environment (recommended)\n});\n\n// Import host-environment variables or modules into the interpreter's scope\ninterpreter.import({\n  log: console.log,\n  greet: (name: string) => `Hello, ${name} from interpreter!`,\n});\n\ntry {\n  // Execute JavaScript code as a string\n  interpreter.run(`\n    const message = greet('Sval User');\n    log(message);\n    \n    const sum = (a, b) => a + b;\n    log('2 + 3 =', sum(2, 3));\n\n    // Accessing built-in globals like Math\n    log('Math.PI =', Math.PI);\n  `);\n} catch (error) {\n  console.error('Interpreter Error:', error);\n}\n","lang":"typescript","description":"Demonstrates how to create a `Sval` interpreter instance, configure it with options, import host functions and variables, and execute a JavaScript string in a sandboxed environment."},"warnings":[{"fix":"If your code relies on `this` referring to the global object at the top level of a module, it will break. Refactor your module code to avoid top-level `this` or explicitly import global objects (e.g., `interpreter.import('globalThis', globalThis)`). For scripts requiring classic global `this` behavior, ensure `sourceType` is set to `'script'`.","message":"In `sval` versions 0.6.10 and later, the behavior of `sourceType: 'module'` was updated to strictly align with ECMAScript module semantics. This includes treating the top-level `this` as `undefined` and enforcing strict mode by default for module contexts.","severity":"breaking","affected_versions":">=0.6.10"},{"fix":"Always explicitly set `sandBox: true` unless you have absolute trust in the executed code and specifically require direct global scope interaction. When `sandBox: true`, explicitly import any host objects (like `console` or `window`) that the interpreted code needs to access via `interpreter.import()`.","message":"The `sandBox` option, which defaults to `true`, is crucial for security. When `sandBox: false` (invasive mode), the interpreted code can directly interact with and mutate the host environment's global scope, posing a significant security risk if executing untrusted code.","severity":"gotcha","affected_versions":">=0.6.0"},{"fix":"Be mindful of your `sourceType`. For simple variable injection into a script, `sourceType: 'script'` with `interpreter.import({ varName: value })` is appropriate. For true ES module behavior with `import`/`export` statements inside the interpreted code, use `sourceType: 'module'`.","message":"The `import` method's behavior is context-dependent based on the `sourceType`. When `sourceType: 'script'`, `import` makes provided values available as global variables within the script's scope. However, for `sourceType: 'module'`, `import` is intended to pre-populate the module's internal import map, behaving closer to how ES modules resolve dependencies.","severity":"gotcha","affected_versions":">=0.6.0"},{"fix":"Never execute untrusted, unsanitized user-generated code with `sval` in invasive mode (`sandBox: false`). Even in sandboxed mode, be cautious about the host objects you expose via `interpreter.import()`, as access to powerful APIs can still compromise security. Always validate and sanitize inputs thoroughly.","message":"While `sval` is often used as a safer alternative to `eval` for executing dynamic code, it still executes arbitrary JavaScript. Without proper sandboxing (`sandBox: true`) and input validation, it can still be exploited if fed malicious code.","severity":"gotcha","affected_versions":">=0.6.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use `interpreter.import('variable_name', hostVariable)` or `interpreter.import({ variable_name: hostVariable })` to make the host variable accessible within the interpreter's context.","cause":"The interpreted code is attempting to access a variable or function that exists in the host environment but has not been explicitly imported into the `sval` interpreter's scope.","error":"ReferenceError: [variable_name] is not defined"},{"fix":"Initialize the `Sval` interpreter with `new Sval({ sourceType: 'module', ... })` to enable ES module parsing and execution.","cause":"The interpreted JavaScript code contains ES module syntax (e.g., `import` statements, `export` statements) but the `Sval` instance was initialized with the default `sourceType: 'script'`.","error":"SyntaxError: 'import' and 'export' may only appear with 'sourceType: \"module\"'"},{"fix":"When using `sourceType: 'module'`, top-level `this` is `undefined`. Explicitly import global objects like `console` or `Math` into the interpreter's scope: `interpreter.import('console', console);`.","cause":"This often occurs when trying to access `console.log` (or other host globals) within a module-type script (`sourceType: 'module'`) or when `this` is `undefined` at the top level, and `console` was not explicitly imported.","error":"TypeError: Cannot read properties of undefined (reading 'log')"},{"fix":"Ensure `ecmaVer` is set to `'latest'` or a specific year that supports the syntax in your code (e.g., `ecmaVer: '2024'`). Double-check the interpreted code for any actual syntax errors.","cause":"The `ecmaVer` option is set to an older ECMAScript version that does not support the syntax used in the interpreted code, or there's a general syntax error.","error":"Error: [Parser Error] (e.g., 'Unexpected token', 'Unexpected keyword')"}],"ecosystem":"npm"}