包详细信息

esniff

medikoo28.8mISC2.0.1

Low footprint ECMAScript source code parser

sniff, analyze, ast, parse

自述文件

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)

  • code - Code to parse
  • executor - A function to be executed immediately by the constructor, It receives an emitter parameter.

emitter emits following events:

  • trigger:<char> - When char is a code character approached in code, that is not a whitespaces, is not in a middle of identificator, is not part of a comment, string, template string or regular expression.

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

  • skipCodePart(codePart) - Skips forward through input codePart assuming parser index points start of given part. Returns true if given codePart was found and index and skipped
  • skipIdentifier - Skips approached identifier (can be function name or property name), returns { name, start, end } meta object
  • skipWhitespace - Skips any whitespace and comments founds at current parsing index
  • collectScope - If at current index ( character is found, it registers given paranthesis scope for registrations (it's content will be returned as one of the results after finished parsing)
  • stop - Stops parsing process
  • index - Returns currently parsed index
  • previousToken - Previous non-whitespace character
  • scopeDepth - Current scope depth
  • shouldCollectComments - Whether data about code comments should be collected in the result
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:

  • asProperty (default: false), on true will allow x.name() when we search for name calls
  • asPlain (default: true), on true it allows plain calls e.g. name() when we search for name. Should be set to false if we're strictly about method calls.

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

  • esniff assumes code that you pass is syntactically correct, it won't inform you about any syntax errors and may produce unexpected and nonsense results when such code is used.
  • There's single case of syntactically correct code, which will make esniff produce incorrect results, it's division made directly on object literal (e.g. x = { foo: 'bar' } / 14, esniff in that case will assume that / starts regular expression). Still there's not known use case where such code may make any sense, and many popular JS source code parsers share very same vulnerability.

Tests

$ npm test

Security contact information

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

更新日志

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

2.0.1 (2024-02-21)

Bug Fixes

  • Fix release of operator char trigger event (1309a18)

2.0.0 (2024-02-19)

⚠ BREAKING CHANGES

  • Main esniff interface changed from code, trigger, callback to code, executor where executor function is provided with emitter that provides access to internal parsing process
  • Property and variable names resolution now respects ES2015+ language rules instead of ES5
  • Utilties were moved:
    • ensure-string-literal.js -> utils/ensure-string-literal.js
    • is-string-literal.js -> utils/is-string-literal.js
    • is-var-name-valid.js -> utils/is-variable-name.js

Features

  • Replace parser with state machine based event driven variant (0d9bf17)
  • Support ES2015 template strings syntax (4016496)
  • Upgrade variable and property name patterns to ES2015+ (7f2f4ab)

Maintenance Improvements

  • Move basic utils into utils directory (afc6ddf)
  • Refactor stripComments to rely on main parser (6d2dd7f)
  • Rely on type package instead of es5-ext (2a79744)

1.1.3 (2024-01-04)

Maintenance Improvements

  • Improve isVarNameValid internals (82138c2)

1.1.2 (2024-01-04)

Maintenance Improvements

1.1.1 (2024-01-04)

Bug Fixes

  • Ensure to detect Windows EOL (\r\n) as single EOL (72a17fe)
  • Fix column indexing in move function (3c0a6cb)

Maintenance Improvements

  • Declare support for Node.js v0.10+ (1eba1d6)
  • ESLint suggested improvements (d7c65ef)
  • Extract regular expression patterns into modules (1b12cbe)
  • Fix reference links in source code comments (4787424)
  • Replace xlint configuration with eslint (f434553)
  • Switch LICENSE from MIT to ISC (cc33510)

Changelog for previous versions

See CHANGES file