{"id":12173,"library":"ts-evaluator","title":"TypeScript AST Evaluator","description":"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.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/wessberg/ts-evaluator","tags":["javascript","typescript","ts","interpreter","evaluate","evaluator","ast"],"install":[{"cmd":"npm install ts-evaluator","lang":"bash","label":"npm"},{"cmd":"yarn add ts-evaluator","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-evaluator","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for simulating a DOM environment when evaluating code that relies on browser APIs. Peer dependency.","package":"jsdom","optional":false},{"reason":"The core dependency providing the TypeScript compiler API for parsing and type checking ASTs. Peer dependency.","package":"typescript","optional":false}],"imports":[{"note":"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.","wrong":"const { evaluate } = require('ts-evaluator')","symbol":"evaluate","correct":"import { evaluate } from 'ts-evaluator'"},{"note":"Used to configure the evaluation environment, policies, and provide initial state or module overrides.","symbol":"createEvaluationContext","correct":"import { createEvaluationContext } from 'ts-evaluator'"},{"note":"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.","symbol":"createSourceFile","correct":"import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'"}],"quickstart":{"code":"import { evaluate, createEvaluationContext } from 'ts-evaluator';\nimport ts, { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript';\n\nconst code = `\n  const a = 10;\n  const b = 'hello';\n  function greet(name: string) { return 'Hello, ' + name + '!'; }\n  const result = greet(b);\n  const obj = { x: a, y: result };\n  obj.x + 5;\n`;\n\n// Create a SourceFile from the code\nconst sourceFile = createSourceFile('example.ts', code, ScriptTarget.ES2016, true);\n\n// Find the node to evaluate, e.g., 'obj.x + 5'\nconst nodeToEvaluate = sourceFile.forEachChild(node => {\n  if (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && node.left.name.text === 'x') {\n    return node;\n  }\n  return undefined;\n});\n\nif (!nodeToEvaluate) {\n  console.error('Could not find the node to evaluate.');\n} else {\n  // Create an evaluation context, optionally passing a TypeScript TypeChecker and policy options\n  const context = createEvaluationContext({\n    typeChecker: ts.createProgram([sourceFile.fileName], { target: ScriptTarget.ES2016 }).getTypeChecker(),\n    // Example policy: disallow I/O operations\n    policy: {\n      disableIO: true,\n      disableNetwork: true\n    },\n    // Initial lexical environment variables (if any)\n    lexicalEnvironment: new Map()\n  });\n\n  // Evaluate the node\n  const evaluationResult = evaluate(nodeToEvaluate, context);\n\n  if (evaluationResult.success) {\n    console.log(`Evaluation successful! Value: ${evaluationResult.value}`);\n    // Expected output: Evaluation successful! Value: 15\n  } else {\n    console.error(`Evaluation failed: ${evaluationResult.reason}`);\n  }\n}\n","lang":"typescript","description":"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."},"warnings":[{"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`.","message":"Version 2.0.0 introduces a breaking change, requiring Node.js v18.20.0 or newer. Ensure your environment meets this minimum requirement before upgrading.","severity":"breaking","affected_versions":">=2.0.0"},{"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\"`.","message":"Starting 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.","severity":"breaking","affected_versions":">=1.0.1"},{"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.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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() })`.","message":"Evaluating 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.","severity":"gotcha","affected_versions":">=1.0.2"},{"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`.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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 }]]) })`.","cause":"The evaluator failed to resolve an imported module, likely due to a missing or misconfigured `ModuleOverrides` option in the evaluation context.","error":"Error: Evaluation failed: Cannot evaluate node '...' because the Host cannot resolve its' ModuleSpecifier '...'"},{"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`.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'kind')"},{"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.","cause":"Running `ts-evaluator` (or code using it) in a CommonJS environment without proper configuration or when trying to `require` the ESM-first package.","error":"SyntaxError: Cannot use import statement outside a module"},{"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.","cause":"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).","error":"TypeError: Node.js version 16 or newer is required to run this package. You are currently running vXX.YY.Z."}],"ecosystem":"npm"}