Modify JavaScript strings by applying mutation functions to each scope node in the AST

Usage no npm install needed!

<script type="module">
  import strongTraceScopetracer from '';



Modify scoped segments of JavaScript. Provide a mutating function and a filter test, and it will apply the mutator to scope blocks found in JavaScript strings.


var ScopeTracer = require("strong-trace-scopetracer")

var input = "// some javascript!\n\
function foo() {\n\
  // In a function\n\
  var abc = 'ABC'\n\
  setTimeout(function () {\n\
  }, 10)\n\

function mutate(content) {
  // We're putting things in single quotes, escape single quotes
  var name = this.fnName.replace(/'/g, "\\'")
  if (this.body.length === 0) {
    return []
  return [{insertion: "console.log('entering " + name + "');", pos: this.body[0].range[0]}]

function nodeTest() {
  // Only functions, not outer enclosing scope.
  return this.path.length > 0

var tracer = ScopeTracer(mutate, nodeTest)

var output = tracer.transform(input)


  // some javascript!
  function foo() {
    // In a function
    console.log('entering foo');var abc = 'ABC'
    setTimeout(function () {
      console.log('entering foo>setTimeout() fn argument');console.log(abc)
    }, 10)


  entering foo
  entering foo>setTimeout() fn argument


var scopetracer = require("scopetracer")(mutate[, nodeTest])

Creates a tracer object that can be used to transform javascript strings.

mutate(content[, extra[, ...]])

The mutate function is called with the context of this being the scopenodes node defining this scope.

This is usually a function, though will also include the outer Program enclosing scope.

It is an Esprima AST node with a couple of additions added by scopenodes.

To mutate the content, return an array of objects defining the insertions or replacements to make.

Insertions are always safe, but it is up to you to make sure that replacements (using remove) do overlap other insertions or replacements.

    insertion: "string to insert",
    pos: 200, // Position to insert, relative to the Esprima "range" e.g. this.range[0]
    remove: 0, // optional, how many characters to remove from content prior to inserting
    pri: 0, // optional: insertion priority in case of a `pos` tie. Lower pri inserts before higher pri.
    // ... return as many mutations as you like

nodeTest(content[, extra[, ...]])

The test function is called with the same context as mutate.

It is simply expected to return true if mutate should be run or false if mutate is to be skipped for this node.

The default nodeTest if not defined is function nodeTest() { return true; } i.e. always call mutate.

scopetracer.transform(content[, extra[, ...]])

Extract scope nodes, then transform them according to mutate and nodeTest.

Any extra arguments will be added as arguments to mutate and nodeTest.

Similar Projects