{"id":14981853,"url":"https://github.com/jonschlinkert/eval-estree-expression","last_synced_at":"2025-04-04T14:04:57.014Z","repository":{"id":46781968,"uuid":"403506850","full_name":"jonschlinkert/eval-estree-expression","owner":"jonschlinkert","description":"Safely evaluate JavaScript (estree) expressions, sync and async.","archived":false,"fork":false,"pushed_at":"2025-02-07T06:01:31.000Z","size":158,"stargazers_count":55,"open_issues_count":0,"forks_count":4,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-03-28T13:08:45.897Z","etag":null,"topics":["ast","babel","babeljs","clause","context","escodegen","esprima","estree","eval","evaluate","evaluate-expressions","evaluation","evaluator","expression","expression-evaluator","parse","parser","when","where"],"latest_commit_sha":null,"homepage":"https://github.com/jonschlinkert","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jonschlinkert.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/funding.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"jonschlinkert"}},"created_at":"2021-09-06T06:15:00.000Z","updated_at":"2025-03-16T09:24:06.000Z","dependencies_parsed_at":"2024-09-07T18:01:20.075Z","dependency_job_id":"e9ce8cf4-0915-49e7-af29-c9204ddec908","html_url":"https://github.com/jonschlinkert/eval-estree-expression","commit_stats":{"total_commits":31,"total_committers":4,"mean_commits":7.75,"dds":0.3870967741935484,"last_synced_commit":"edf42e2a82e3a2f4179f25103ddd54c4935365dd"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Feval-estree-expression","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Feval-estree-expression/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Feval-estree-expression/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonschlinkert%2Feval-estree-expression/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jonschlinkert","download_url":"https://codeload.github.com/jonschlinkert/eval-estree-expression/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247190246,"owners_count":20898702,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ast","babel","babeljs","clause","context","escodegen","esprima","estree","eval","evaluate","evaluate-expressions","evaluation","evaluator","expression","expression-evaluator","parse","parser","when","where"],"created_at":"2024-09-24T14:04:23.519Z","updated_at":"2025-04-04T14:04:56.997Z","avatar_url":"https://github.com/jonschlinkert.png","language":"JavaScript","readme":"# eval-estree-expression [![NPM version](https://img.shields.io/npm/v/eval-estree-expression.svg?style=flat)](https://www.npmjs.com/package/eval-estree-expression) [![NPM monthly downloads](https://img.shields.io/npm/dm/eval-estree-expression.svg?style=flat)](https://npmjs.org/package/eval-estree-expression) [![NPM total downloads](https://img.shields.io/npm/dt/eval-estree-expression.svg?style=flat)](https://npmjs.org/package/eval-estree-expression)\n\n\u003e Safely evaluate JavaScript (estree) expressions, sync and async.\n\nPlease consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.\n\n- [Install](#install)\n- [Usage](#usage)\n  * [Usage with Babel](#usage-with-babel)\n  * [Usage with Esprima](#usage-with-esprima)\n- [API](#api)\n  * [.evaluate](#evaluate)\n  * [.evaluate.sync](#evaluatesync)\n  * [.variables](#variables)\n- [Options](#options)\n  * [booleanLogicalOperators](#booleanlogicaloperators)\n  * [functions](#functions)\n  * [Top-Level await](#top-level-await)\n  * [generate](#generate)\n  * [regexOperator](#regexoperator)\n  * [strict](#strict)\n  * [withMembers](#withmembers)\n- [Examples](#examples)\n  * [Operators](#operators)\n- [About](#about)\n\n_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_\n\n## Install\n\nInstall with [npm](https://www.npmjs.com/):\n\n```sh\n$ npm install --save eval-estree-expression\n```\n\n## Usage\n\nRequires [Node.js](https://nodejs.org/en/download/) version 14 or greater.\n\nEvaluates an [estree](https://github.com/estree/estree) expression from [@babel/parser][], [esprima](http://esprima.org), [acorn](https://github.com/acornjs/acorn), or any other library that parses and returns a valid `estree` expression.\n\n```js\nconst { evaluate } = require('eval-estree-expression');\n// or\nimport { evaluate } from 'eval-estree-expression';\n\nevaluate.sync(expressionTree[, context]); // sync\nevaluate(expressionTree[, context]).then(console.log); // async\n```\n\nSee the [unit tests](./test) for hundreds of additional usage examples.\n\n**Params**\n\nThe `evaluate` function takes the following arguments:\n\n* `expressionTree` **{object}** - a valid [estree](https://github.com/estree/estree) expression AST.\n* `context` **{object}** - a data object with values to replace variables in expressions\n\n### Usage with Babel\n\nMost of the examples in this document assume the following setup code is used:\n\n```js\nconst { evaluate } = require('eval-estree-expression');\nconst { parseExpression } = require('@babel/parser');\n\n// parse your JavaScript expression\nconst ast = parseExpression('1 + 2');\n\n// evaluate synchronously\nconsole.log(evaluate.sync(ast)); //=\u003e 3\n\n// or asynchronously\nconsole.log(await evaluate(ast)); //=\u003e 3\n```\n\n### Usage with Esprima\n\n[Esprima][esprimar] doesn't have a \"parseExpression\" method like @babel/parser, so you'll need to return the expression from the AST, like so:\n\n```js\nconst { parse } = require('esprima');\nconst { evaluate } = require('eval-estree-expression');\nconst ast = parse('[1, 2, 3].map(n =\u003e n * x);').body[0].expression;\n\n// evaluate synchronously\nconsole.log(evaluate.sync(ast)); // =\u003e [2, 4, 6]\n\n// or asynchronously\nconsole.log(await evaluate(ast)); // =\u003e [2, 4, 6]\n```\n\n## API\n\n### .evaluate\n\nEvaluate expressions asynchronously.\n\n```js\nconsole.log(await evaluate(parse('1 + 2'))); //=\u003e 3\nconsole.log(await evaluate(parse('5 * 2'))); //=\u003e 10\nconsole.log(await evaluate(parse('1 \u003e 2'))); //=\u003e false\nconsole.log(await evaluate(parse('1 \u003c 2'))); //=\u003e true\n\n// with context object\nconsole.log(await evaluate(parse('page.title === \"home\"'), { page: { title: 'home' } })); //=\u003e true\n```\n\n### .evaluate.sync\n\nEvaluate expressions synchronously.\n\n```js\nconsole.log(evaluate.sync(parse('1 + 2'))); //=\u003e 3\nconsole.log(evaluate.sync(parse('5 * 2'))); //=\u003e 10\nconsole.log(evaluate.sync(parse('1 \u003e 2'))); //=\u003e false\nconsole.log(evaluate.sync(parse('1 \u003c 2'))); //=\u003e true\n\n// with context object\nconsole.log(evaluate.sync(parse('page.title === \"home\"'), { page: { title: 'home' } })); //=\u003e true\n```\n\n### .variables\n\nGet an array of variables from an expression:\n\n```js\nconst { parseExpression } = require('@babel/parser');\nconst { variables } = require('eval-estree-expression');\n\nconsole.log(variables(parseExpression('x * (y * 3) + z.y.x'))); //=\u003e ['x', 'y', 'z']\nconsole.log(variables(parseExpression('(a || b) ? c + d : e * f'))); //=\u003e ['a', 'b', 'c', 'd', 'e', 'f']\n\n```\n\n## Options\n\n### booleanLogicalOperators\n\nType: `boolean`\nDefault: `undefined`\n\nForce logical operators to return a boolean result.\n\n```js\nconsole.log(await evaluate(parse('a \u0026\u0026 b'), { a: undefined, b: true })); //=\u003e undefined\nconsole.log(await evaluate(parse('a \u0026\u0026 b'), { a: undefined, b: false })); //=\u003e undefined\nconsole.log(await evaluate(parse('a || b'), { a: false, b: null })); //=\u003e null\nconsole.log(await evaluate(parse('a || b'), { a: false, b: undefined })); //=\u003e undefined\n\n//\n// With booleanLogicalOperators enabled\n//\n\nconst options = {\n  booleanLogicalOperators: true\n};\n\nconsole.log(await evaluate(parse('a || b'), { a: false, b: null }, options)); //=\u003e false\nconsole.log(await evaluate(parse('a \u0026\u0026 b'), { a: undefined, b: true }, options)); //=\u003e false\nconsole.log(await evaluate(parse('a \u0026\u0026 b'), { a: undefined, b: false }, options)); //=\u003e false\nconsole.log(await evaluate(parse('a || b'), { a: false, b: undefined }, options)); //=\u003e false\n```\n\n### functions\n\nType: `boolean`\nDefault: `false`\n\nAllow function calls to be evaluated. This is unsafe, please enable this option at your own risk.\n\n**Example**\n\n```js\nconst { parse } = require('esprima');\nconst { generate } = require('escodegen');\nconst { evaluate } = require('eval-estree-expression');\n\nconst options = {\n  functions: true\n};\n\n// works with native methods\nconsole.log(evaluate.sync(parse('/([a-z]+)/.exec(\" foo \")'), { x: 2 }, options));\n//=\u003e [ 'foo', 'foo', index: 1, input: ' foo ', groups: undefined ]\n\n// and functions defined on the context\nconsole.log(evaluate.sync('a.upper(\"b\")', { a: { upper: v =\u003e v.toUpperCase() } }, options));\n//=\u003e 'B'\n```\n\nHowever, this does NOT support function expressions or function statements.\nTo enable function statements and expressions (not just function calls) to be evaluated, you must also use the [generate](#generate) option.\n\n### Top-Level await\n\nTo use top-level `await` with, you need to:\n\n1. Enable `functions`\n2. Enable `allowAwaitOutsideFunction`. This option is passed directly to the babel parser.\n\n```ts\nconst { evaluate } = require('eval-estree-expression');\nconst { parseExpression } = require('@babel/parser');\n\nconst opts = { functions: true, allowAwaitOutsideFunction: true };\n\nconst e = (input, ctx, options) =\u003e {\n  return evaluate(parseExpression(input, options), ctx, options);\n};\n\nconst run = async () =\u003e {\n  console.log(await e('await 1', {}, opts)); //=\u003e 1\n  console.log(await e('Promise.resolve(1)', { Promise }, opts)); //=\u003e 1\n  console.log(await e('await Promise.resolve(1)', { Promise }, opts)); //=\u003e 1\n};\n\nrun();\n```\n\n### generate\n\nType: `boolean`\nDefault: `undefined`\n\nEnable support for function statements and expressions by enabling the [functions](#functions) option AND by passing the `.generate()` function from the [escodegen](http://github.com/estools/escodegen) library.\n\n**Example**\n\n```js\nconst escodegen = require('escodegen');\nconst { parse } = require('esprima');\nconst { evaluate } = require('eval-estree-expression');\n\nconst options = {\n  functions: true,\n  generate: escodegen.generate\n};\n\nconsole.log(await evaluate(parse('[1, 2, 3].map(n =\u003e n * x);'), { x: 2 }, options)); // =\u003e [2, 4, 6]\n```\n\n### regexOperator\n\nType: `boolean`\nDefault: `true`\n\nEnable the `=~` regex operator to support testing values without using functions (example `name =~ /^a.*c$/`).\n\n**Why is this needed?**\n\nIn expressions, if you wish to test a value using a regular expression, you have two options:\n\n1. Enable function support so that you can use methods like `.test()` and `.match()`, or\n2. Use this option, which uses a special syntax to match against regular expressions _without evaluating any functions_.\n\nIn other words, instead of having to do this:\n\n```js\nconsole.log(evaluate.sync(parse('/^ab+c$/ig.test(\"abbbbbc\")'), {}, { functions: true }));\n```\n\nYou can do this:\n\n```js\nconsole.log(evaluate.sync(parse('name =~ /^a.*c$/'), { name: 'abc' }));\nconsole.log(evaluate.sync(parse('name =~ regex'), { name: 'abc', regex: /^a.*c$/ }));\n```\n\n### strict\n\nType: `boolean`\nDefault: `false`\n\nThrow an error when variables are undefined.\n\n### withMembers\n\nType: `boolean`\nDefault: `undefined`\n\nUsed with the [variables](#variables) method to return nested variables (e.g., variables with dot notation, like `foo.bar.baz`).\n\n## Examples\n\n### Operators\n\nSupports all JavaScript operators with the exception of assignment operators (`=`, `+=`, etc):\n\n```js\n// Arithmetic operators\nevaluate('a + b');\nevaluate('a - b');\nevaluate('a / b');\nevaluate('a * b');\nevaluate('a % b');\nevaluate('a ** b');\n\n// Relational operators\nevaluate('a instanceof b');\nevaluate('a \u003c b');\nevaluate('a \u003e b');\nevaluate('a \u003c= b');\nevaluate('a \u003e= b');\n\n// Equality operators\nevaluate('a !== b');\nevaluate('a === b');\nevaluate('a != b');\nevaluate('a == b');\n\n// Bitwise shift operators\nevaluate('a \u003c\u003c b');\nevaluate('a \u003e\u003e b');\nevaluate('a \u003e\u003e\u003e b');\n\n// Binary bitwise operators\nevaluate('a \u0026 b');\nevaluate('a | b');\nevaluate('a ^ b');\n\n// Binary logical operators\nevaluate('a \u0026\u0026 b'); // Logical AND.\nevaluate('a || b'); // Logical OR.\nevaluate('a ?? b'); // Nullish Coalescing Operator.\n```\n\n## About\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eContributing\u003c/strong\u003e\u003c/summary\u003e\n\nPull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eRunning Tests\u003c/strong\u003e\u003c/summary\u003e\n\nRunning and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:\n\n```sh\n$ npm install \u0026\u0026 npm test\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eBuilding docs\u003c/strong\u003e\u003c/summary\u003e\n\n_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_\n\nTo generate the readme, run the following command:\n\n```sh\n$ npm install -g verbose/verb#dev verb-generate-readme \u0026\u0026 verb\n```\n\n\u003c/details\u003e\n\n### Related projects\n\nYou might also be interested in these projects:\n\n[whence](https://www.npmjs.com/package/whence): Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful… [more](https://github.com/jonschlinkert/whence) | [homepage](https://github.com/jonschlinkert/whence \"Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful for evaluating expressions in config files, prompts, key bindings, completions, templates, and many other user cases.\")\n\n### Contributors\n\n| **Commits** | **Contributor** |  \n| --- | --- |  \n| 42 | [jonschlinkert](https://github.com/jonschlinkert) |  \n| 1  | [6utt3rfly](https://github.com/6utt3rfly) |  \n| 1  | [freshgum-bubbles](https://github.com/freshgum-bubbles) |  \n\n### Author\n\n**Jon Schlinkert**\n\n* [GitHub Profile](https://github.com/jonschlinkert)\n* [Twitter Profile](https://twitter.com/jonschlinkert)\n* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)\n\n### License\n\nCopyright © 2025, [Jon Schlinkert](https://github.com/jonschlinkert).\nReleased under the [MIT License](LICENSE).\n\n***\n\n_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on February 06, 2025._","funding_links":["https://github.com/sponsors/jonschlinkert"],"categories":["Packages"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonschlinkert%2Feval-estree-expression","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjonschlinkert%2Feval-estree-expression","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonschlinkert%2Feval-estree-expression/lists"}