Registry / web-framework / ts-evaluator

ts-evaluator

JSON →
library2.0.0jsnpmunverified

ts-evaluator is an advanced interpreter for TypeScript that enables the evaluation of arbitrary AST (Abstract Syntax Tree) Nodes, specifically Expressions, ExpressionStatements, or Declarations, within a given TypeScript AST. Unlike tools such as `ts-node` that execute full TypeScript programs, this library focuses on partial evaluation based on a node's lexical environment. The current stable version is 2.0.0. Release cadence appears to be driven by significant TypeScript and JSDOM version updates, typically with several minor and patch releases in between. Its key differentiators include the ability to evaluate specific nodes, support for browser, Node.js, and pure ECMAScript environments, and configurable policy options for sandboxing and restricting operations like I/O or network access. This makes it a valuable tool for linters, language services, partial evaluators, and frameworks requiring deep AST introspection and computation.

npm install ts-evaluator
INSTALL
IMPORT
SIG · TS-EVALUATOR
T
ts-evaluator
web-frameworkjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

evaluate
import { evaluate } from 'ts-evaluator'
const { evaluate } = require('ts-evaluator')
Since v1.0.1, ts-evaluator is an ESM-first package. While it provides a CJS fallback, ESM imports are preferred. The 'evaluate' function is the primary entry point for evaluating an AST Node.
createEvaluationContext
import { createEvaluationContext } from 'ts-evaluator'
Used to configure the evaluation environment, policies, and provide initial state or module overrides.
createSourceFile
import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'
While not directly from `ts-evaluator`, `createSourceFile` from `typescript` is essential for parsing code into an AST before evaluation. Developers often forget to import necessary `typescript` API functions.

This quickstart demonstrates how to parse a TypeScript code string into an AST, locate a specific node (a binary expression in this case), and then use `ts-evaluator` to evaluate that node within a configured context, including a TypeChecker and policy restrictions.

import { evaluate, createEvaluationContext } from 'ts-evaluator'; import ts, { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'; const code = ` const a = 10; const b = 'hello'; function greet(name: string) { return 'Hello, ' + name + '!'; } const result = greet(b); const obj = { x: a, y: result }; obj.x + 5; `; // Create a SourceFile from the code const sourceFile = createSourceFile('example.ts', code, ScriptTarget.ES2016, true); // Find the node to evaluate, e.g., 'obj.x + 5' const nodeToEvaluate = sourceFile.forEachChild(node => { if (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && node.left.name.text === 'x') { return node; } return undefined; }); if (!nodeToEvaluate) { console.error('Could not find the node to evaluate.'); } else { // Create an evaluation context, optionally passing a TypeScript TypeChecker and policy options const context = createEvaluationContext({ typeChecker: ts.createProgram([sourceFile.fileName], { target: ScriptTarget.ES2016 }).getTypeChecker(), // Example policy: disallow I/O operations policy: { disableIO: true, disableNetwork: true }, // Initial lexical environment variables (if any) lexicalEnvironment: new Map() }); // Evaluate the node const evaluationResult = evaluate(nodeToEvaluate, context); if (evaluationResult.success) { console.log(`Evaluation successful! Value: ${evaluationResult.value}`); // Expected output: Evaluation successful! Value: 15 } else { console.error(`Evaluation failed: ${evaluationResult.reason}`); } }
Debug
Known issues
breakingVersion 2.0.0 introduces a breaking change, requiring Node.js v18.20.0 or newer. Ensure your environment meets this minimum requirement before upgrading.
fix
Upgrade your Node.js runtime to version 18.20.0 or higher. For example, using nvm: `nvm install 18.20.0 && nvm use 18.20.0`.
affects: >=2.0.0
breakingStarting from v1.0.1, `ts-evaluator` transitioned to an ESM-first package. While it provides a CommonJS fallback, applications primarily using CommonJS might need to adjust import statements or package configurations.
fix
Prefer `import ... from 'ts-evaluator'` over `require()` statements. For CommonJS projects, ensure proper interoperability or consider migrating to ESM if possible. If using TypeScript, ensure your `tsconfig.json` has `"module": "Node16"` or `"module": "ESNext"` and `"moduleResolution": "Bundler"` or `"Node16"`.
affects: >=1.0.1
gotcha`ts-evaluator` is a peer dependency on `typescript` and `jsdom`. While this allows flexibility, ensure you have compatible versions of these packages installed in your project, as their APIs are heavily relied upon.
fix
Manually install `typescript` and `jsdom` in your project with versions compatible with `ts-evaluator`'s peer dependency range (e.g., `npm install typescript@5 jsdom@22`). Check the `package.json` for specific ranges.
affects: >=1.0.0
gotchaEvaluating certain complex expressions or nodes without a `typeChecker` can lead to less robust or incorrect evaluations. While `typeChecker` is optional, its absence can limit the evaluator's accuracy.
fix
Always provide a `typeChecker` created from a TypeScript program when initializing the evaluation context, especially for code involving type-dependent operations, interfaces, or generics. `createEvaluationContext({ typeChecker: program.getTypeChecker() })`.
affects: >=1.0.2
gotcha`ts-evaluator` is designed for evaluating individual AST nodes, not for running entire TypeScript programs or scripts like a REPL. Attempting to pass full programs or statement sequences for evaluation will not yield the expected results.
fix
Identify the specific `ts.Node` (Expression, ExpressionStatement, or Declaration) you intend to evaluate. If you need to execute full programs, consider tools like `ts-node`.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Evaluation failed: Cannot evaluate node '...' because the Host cannot resolve its' ModuleSpecifier '...'
The evaluator failed to resolve an imported module, likely due to a missing or misconfigured `ModuleOverrides` option in the evaluation context.
fix
Provide `ModuleOverrides` in `createEvaluationContext` to map module specifiers to their resolved values or mock implementations. Example: `createEvaluationContext({ moduleOverrides: new Map([['my-module', { foo: 123 }]]) })`.
TypeError: Cannot read properties of undefined (reading 'kind')
This often happens when `evaluate` is called with a `ts.Node` that is `undefined` or `null`, meaning the AST node was not correctly found or provided.
fix
Ensure the `ts.Node` passed to `evaluate()` is a valid and existing node from the parsed `SourceFile`. Add null/undefined checks before calling `evaluate`.
SyntaxError: Cannot use import statement outside a module
Running `ts-evaluator` (or code using it) in a CommonJS environment without proper configuration or when trying to `require` the ESM-first package.
fix
Ensure your project is configured for ES Modules (`"type": "module"` in `package.json`, `.mjs` files), or that your bundler correctly handles ESM to CJS transpilation. Prefer `import` syntax.
TypeError: Node.js version 16 or newer is required to run this package. You are currently running vXX.YY.Z.
Using an outdated Node.js version that does not meet the minimum requirement for `ts-evaluator` (v18.20.0 for v2.0.0, v14.19.0 for v1.x).
fix
Update your Node.js environment to the version specified in the `engines` field of the `ts-evaluator` package. Use `nvm` or your preferred Node.js version manager.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies
jsdomrequiredRequired for simulating a DOM environment when evaluating code that relies on browser APIs. Peer dependency.
typescriptrequiredThe core dependency providing the TypeScript compiler API for parsing and type checking ASTs. Peer dependency.
Agent activity
2 hits · last 30 days
node
2
Resources