Home

Awesome

Build status Tests coverage npm version

esniff

Low footprint JavaScript source code parser

Low footprint, fast source code parser, which allows you to find all code fragment occurrences with respect to all syntax rules that cannot be handled with plain regular expression search.

It aims at use cases where we don't need full AST tree, but instead we're interested in finding usages of given function, property etc. in syntactically valid code.

Installation

npm

$ npm install esniff

Usage

Using main module you can configure sophisticated parser on your own. However, first, see preprared API utilities that may already address use cases you have.

esniff(code, executor)

emitter emits following events:

Emitter passes to listener the accessor object, which provides access to current parser state and allows to manipulate parsing process. accessor exposes following methods:

Example

Parse all require(..) calls:

var esniff = require("esniff");

var parseRequires = function (code) {
  return esniff(code, function (emitter) {
    emitter.on("trigger:r", function (accessor) {
      if (accessor.previousToken === ".") return;
      if (!accessor.skipCodePart("require")) return;
      accessor.skipWhitespace();
      accessor.collectScope();
    });
  });
};

console.log(parseRequires("var x = require('foo/bar')"));
[{ type: "scope", point: 17, column: 17, line: 1, raw: "'foo/bar'" }];

Predefined utils for common use cases

accessedProperties(objName) (esniff/accessed-properties)

Returns function which allows us to find all accessed property names on given object name

var findProperties = require("esniff/accessed-properties");
var findContextProperties = findProperties("this");

var result = findContextProperties(
  "var foo = \"0\"; this.bar = foo; this.someMethod(); otherFunction()"
);
console.log(result); // [ { name: 'bar', start: 20, end: 23 }, { name: 'someMethod', start: 36, end: 46 } ]

function(name[, options]) (esniff/function)

Returns function which allows us to find all occurrences of given function (or method) being invoked

Through options we can restrict cases which we're after:

Setting both asProperty and asPlain to false, will always produce empty result

var findRequires = require("esniff/function")("require");

findRequires("var x = require('foo/bar')");
// [{ point: 17, column: 17, line: 1, raw: '\'foo/bar\'' }]

resolveArguments(code[, limit]) (esniff/resolve-arguments)

Resolves expressions separated with commas, with additional limit you can specify after which number of arguments resolver should stop

var resolveArgs = require("esniff/resolve-arguments");

var result = resolveArgs("'raz', 'dwa', ['raz', 'dwa'], 'trzy'", 3);

console.log(result); // ['"raz"', ' "dwa"', ' [\'raz\', \'dwa\']']

Limitations

Tests

$ npm test

Security contact information

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.