Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

jsep

EricSmekens10.8mMIT1.4.0TypeScript support: included

a tiny JavaScript expression parser

readme

jsep: A Tiny JavaScript Expression Parser

jsep is a simple expression parser written in JavaScript. It can parse JavaScript expressions but not operations. The difference between expressions and operations is akin to the difference between a cell in an Excel spreadsheet vs. a proper JavaScript program.

Why jsep?

I wanted a lightweight, tiny parser to be included in one of my other libraries. esprima and other parsers are great, but had more power than I need and were way too large to be included in a library that I wanted to keep relatively small.

jsep's output is almost identical to esprima's, which is in turn based on SpiderMonkey's.

Custom Build

While in the jsep project directory, run:

npm install
npm run default

The jsep built files will be in the build/ directory.

Usage

Client-side

<script type="module">
  import jsep from '/PATH/TO/jsep.min.js';
  const parsed = jsep('1 + 1');
</script>

<script src="/PATH/TO/jsep.iife.min.js"></script>
  ...
let parse_tree = jsep("1 + 1");

Node.JS

First, run npm install jsep. Then, in your source file:

// ESM:
import jsep from 'jsep';
const parse_tree = jsep('1 + 1');

// or:
import { Jsep } from 'jsep';
const parse_tree = Jsep.parse('1 + 1');


// CJS:
const jsep = require('jsep').default;
const parsed = jsep('1 + 1');

// or:
const { Jsep } = require('jsep');
const parse_tree = Jsep.parse('1 + 1');

Custom Operators

// Add a custom ^ binary operator with precedence 10
// (Note that higher number = higher precedence)
jsep.addBinaryOp("^", 10);

// Add exponentiation operator (right-to-left)
jsep.addBinaryOp('**', 11, true); // now included by default

// Add a custom @ unary operator
jsep.addUnaryOp('@');

// Remove a binary operator
jsep.removeBinaryOp(">>>");

// Remove a unary operator
jsep.removeUnaryOp("~");

Custom Identifiers

You can add or remove additional valid identifier chars. ('_' and '$' are already treated like this.)

// Add a custom @ identifier
jsep.addIdentifierChar("@");

// Removes a custom @ identifier
jsep.removeIdentifierChar('@');

Custom Literals

You can add or remove additional valid literals. By default, only true, false, and null are defined

// Add standard JS literals:
jsep.addLiteral('undefined', undefined);
jsep.addLiteral('Infinity', Infinity);
jsep.addLiteral('NaN', NaN);

// Remove "null" literal from default definition
jsep.removeLiteral('null');

Plugins

JSEP supports defining custom hooks for extending or modifying the expression parsing. Plugins are registered by calling jsep.plugins.register() with the plugin(s) as the argument(s).

JSEP-provided plugins:

| | | |-----------------------------------|-------------------------------------------------------------------------------------------| | ternary | Built-in by default, adds support for ternary a ? b : c expressions | | arrow | Adds arrow-function support: v => !!v | | assignment | Adds assignment and update expression support: a = 2, a++ | | comment | Adds support for ignoring comments: a /* ignore this */ > 1 // ignore this too | | new | Adds 'new' keyword support: new Date() | | numbers | Adds hex, octal, and binary number support, ignore _ char | | object | Adds object expression support: { a: 1, b: { c }} | | regex | Adds support for regular expression literals: /[a-z]{2}/ig | | spread | Adds support for the spread operator, fn(...[1, ...a]). Works with object plugin, too | | template | Adds template literal support: `hi ${name}` | | | |

How to add plugins:

Plugins have a name property so that they can only be registered once. Any subsequent registrations will have no effect. Add a plugin by registering it with JSEP:

import jsep from 'jsep';
import ternary from '@jsep-plugin/ternary';
import object from '@jsep-plugin/object';
jsep.plugins.register(object);
jsep.plugins.register(ternary, object);

List plugins:

Plugins are stored in an object, keyed by their name. They can be retrieved through jsep.plugins.registered.

Writing Your Own Plugin:

Plugins are objects with two properties: name and init. Here's a simple plugin example:

const plugin = {
  name: 'the plugin',
  init(jsep) {
    jsep.addIdentifierChar('@');
    jsep.hooks.add('gobble-expression', function myPlugin(env) {
      if (this.char === '@') {
        this.index += 1;
        env.node = {
          type: 'MyCustom@Detector',
        };
      }
    });
  },
};

This example would treat the @ character as a custom expression, returning a node of type MyCustom@Detector.

Hooks

Most plugins will make use of hooks to modify the parsing behavior of jsep. All hooks are bound to the jsep instance, are called with a single argument, and return void. The this context provides access to the internal parsing methods of jsep to allow reuse as needed. Some hook types will pass an object that allows reading/writing the node property as needed.

Hook Types
  • before-all: called just before starting all expression parsing.
  • after-all: called after parsing all. Read/Write arg.node as required.
  • gobble-expression: called just before attempting to parse an expression. Set arg.node as required.
  • after-expression: called just after parsing an expression. Read/Write arg.node as required.
  • gobble-token: called just before attempting to parse a token. Set arg.node as required.
  • after-token: called just after parsing a token. Read/Write arg.node as required.
  • gobble-spaces: called when gobbling whitespace.
The this context of Hooks
export interface HookScope {
    index: number;
    readonly expr: string;
    readonly char: string; // current character of the expression
    readonly code: number; // current character code of the expression
    gobbleSpaces: () => void;
    gobbleExpressions: (untilICode?: number) => Expression[];
    gobbleExpression: () => Expression;
    gobbleBinaryOp: () => PossibleExpression;
    gobbleBinaryExpression: () => PossibleExpression;
    gobbleToken: () => PossibleExpression;
    gobbleTokenProperty: (node: Expression) => Expression;
    gobbleNumericLiteral: () => PossibleExpression;
    gobbleStringLiteral: () => PossibleExpression;
    gobbleIdentifier: () => PossibleExpression;
    gobbleArguments: (untilICode: number) => PossibleExpression;
    gobbleGroup: () => Expression;
    gobbleArray: () => PossibleExpression;
    throwError: (msg: string) => never;
}

License

jsep is under the MIT license. See LICENSE file.

Thanks

Some parts of the latest version of jsep were adapted from the esprima parser.

changelog

1.4.0 (2024-11-05)

Bug Fixes

  • add license file to build output (f6678fb), closes #267

Features

  • add nullish coallescing (??) and exponentiation (**) binary_ops (7321a7b), closes #268

1.3.9 (2024-07-12)

Bug Fixes

  • add types add/remove/removeAll functions (b4a5b1a), closes #238
  • add types for SequenceExpressions (d0cf015), closes #261
  • detect unexpected ] in expression "[1,2][]" (70b8ea6), closes #256
  • do not access prototype (037d1db), closes #239
  • throwError return type (e0df539), closes #252
  • update Array elements typing (097ae12)

1.3.8 (2022-12-06)

Bug Fixes

  • support TypeScript's Node16 resolution (0c2cb45)

1.3.7 (2022-09-18)

Bug Fixes

  • add "types" export (505a81a)
  • export default IPlugin from all plugins (cd38da5), closes #231

1.3.6 (2022-04-27)

Bug Fixes

  • update release on package.json change (c1ceb54)

1.3.4 (2022-03-22)

Bug Fixes

  • embed correct version into builds (9e90f3d), closes #216

1.3.3 (2022-03-22)

Bug Fixes

  • add version to plugin for testing (1a148c7)

1.3.2 (2022-03-22)

Bug Fixes

  • pass next version into build script (8270873)
  • update commitPaths (3a1cc14)

1.3.1 (2022-03-22)

Bug Fixes

1.3.0 (2022-02-28)

Bug Fixes

  • types for optional member expression now in generic baseType (79fb0dc), closes #200

Features

  • assignment right-to-left and precedence with ternary (e5652eb), closes #189
  • simplify ternary since to stop handling ':' binary operator (4196623)

1.3.0-beta.1 (2021-12-13)

Bug Fixes

  • types for optional member expression now in generic baseType (79fb0dc), closes #200

Features

  • assignment right-to-left and precedence with ternary (e5652eb), closes #189
  • simplify ternary since to stop handling ':' binary operator (4196623)

1.2.0 (2021-10-31)

Features

  • add right-associative support for binary operators (2da8834), closes #195

1.1.2 (2021-10-17)

Bug Fixes

  • add missing optional property to types (e2f758e), closes #185

1.1.1 (2021-10-13)

Bug Fixes

  • literal 'raw' value now matches input string (432c514), closes #192

1.1.0 (2021-10-03)

Features

  • add optional chaining support (?.) (56d1e3d)

1.0.3 (2021-09-02)

Bug Fixes

1.0.2 - 2021-08-26

Republish to include types.

1.0.1 - 2021-08-24

Fixed support for CommonJS modules. This is only a republish.

1.0.0 - 2021-08-22

Rewrote to ESM, added a plugin system, and fixed numerous grammar issues. For most standard use-cases, this release should not be a breaking change, as every effort was made to maintain compatibility.

Breaking Changes

  • renamed build folder to dist (#130). The package file structure is now:
    ├── CHANGELOG.md
    ├── LICENSE
    ├── README.md
    ├── package.json
    ├── dist
    │   ├── jsep.js
    │   ├── jsep.min.js
    │   ├── cjs
    │   │   ├── jsep.cjs.js
    │   │   ├── jsep.cjs.min.js
    │   ├── iife
    │   │   ├── jsep.iife.js
    │   │   ├── jsep.iife.min.js
  • Removed LogicalExpression and treat it as a BinaryExpression (#100)
  • Call arguments must be either all comma-separated or all space-separated, but not mixed
  • unary expressions with no argument now throw missing unaryOp argument
  • binary expressions now require the left-hand side to exist
  • conditional (ternary) expressions with no condition now throw unexpected "?"
  • . now throws unexpected .
  • ()() now throws unexpected "("
  • a.this, a.true, a.false, a.null now match esprima and treat the property as an identifier instead of a literal or ThisExpression

Added

  • Added a plugin system, including plugins for
    • arrow expressions (() => ...)
    • assigment and update expressions (a = 2, a++)
    • async/await (await a.find(async (v1, v2) => await v1(v2)))
    • comments (/* .. */ and // ...)
    • new expressions (new Date())
    • object expressions ({a: 1, b})
    • regex support (/123/ig)
    • spread operator (fn(...a), [1, ...b], {...c})
    • template expressions (`hi ${name}`, msg`hig ${name}`)

Updated

  • (1, 2) now returns a SequenceExpression instead of throwing an Unclosed ( error
  • moved the ConditionExpression (ternary) into a plugin, but it is still included by default

0.4.0 - 2021-03-21

Added

  • You can add or remove additional valid identifier chars.
  • Support for gobble properties from array/strings. e.g. ([1].length)

Updated

  • Updated several dependancies for audit fixes.

0.3.5 - 2018-08-23

Updated

  • Development dependencies update for audit fixes.

0.3.4 - 2018-03-29

Fixed

  • Fixed identifiers as custom ops (#68,#83)

0.3.3 - 2017-12-16

Notice

  • No functional changes, only updated support for typescript definitions.
  • There may be a few known issues, check the issue page for details.

    Changed

  • Updated typings.
  • Updated grunt-uglify for 0.03 kB smaller jsep.min.js! :)

0.3.2 - 2017-08-31

Notice

First version that was using a CHANGELOG.md.

Added

  • Typings
  • Functions to remove all binary/unary/etc. ops.

Fixed

  • Supports multiline expressions.