| 1 |
"use strict"; |
| 2 |
|
| 3 |
var last = require("es5-ext/array/#/last") |
| 4 |
, esprima = require("esprima") |
| 5 |
, isArray = Array.isArray |
| 6 |
, keys = Object.keys |
| 7 |
, walker |
| 8 |
, eolRe |
| 9 |
, fnName |
| 10 |
, objName |
| 11 |
, asProperty; |
| 12 |
|
| 13 |
eolRe = /(?:\r\n|[\n\r\u2028\u2029])/; |
| 14 |
|
| 15 |
walker = function (ast) { |
| 16 |
var dep, lines, object; |
| 17 |
if (!ast || typeof ast !== "object") return; |
| 18 |
if (isArray(ast)) { |
| 19 |
ast.forEach(walker, this); |
| 20 |
return; |
| 21 |
} |
| 22 |
keys(ast).forEach(function (key) { if (key !== "range") walker.call(this, ast[key]); }, this); |
| 23 |
if (ast.type !== "CallExpression") return; |
| 24 |
if (objName) { |
| 25 |
if (ast.callee.type !== "MemberExpression") return; |
| 26 |
object = ast.callee.object; |
| 27 |
if (object.type === "MemberExpression") { |
| 28 |
if (!asProperty) return; |
| 29 |
if (object.property.name !== objName) return; |
| 30 |
} else if (object.name !== objName) { |
| 31 |
return; |
| 32 |
} |
| 33 |
if (ast.callee.property.name !== fnName) return; |
| 34 |
if (this.code[ast.range[0]] === "(") return; |
| 35 |
dep = { type: "scope", point: this.code.indexOf("(", ast.range[0]) + 2 }; |
| 36 |
dep.raw = this.code.slice(dep.point - 1, ast.range[1] - 1); |
| 37 |
lines = this.code.slice(ast.range[0], dep.point).split(eolRe); |
| 38 |
dep.line = ast.loc.start.line + lines.length - 1; |
| 39 |
dep.column = |
| 40 |
lines.length > 1 ? last.call(lines).length : ast.loc.start.column + lines[0].length; |
| 41 |
this.deps.push(dep); |
| 42 |
} else if ( |
| 43 |
ast.type === "CallExpression" && |
| 44 |
ast.callee.type === "Identifier" && |
| 45 |
ast.callee.name === fnName && |
| 46 |
this.code[ast.range[0]] !== "(" |
| 47 |
) { |
| 48 |
dep = { type: "scope", point: this.code.indexOf("(", ast.range[0]) + 2 }; |
| 49 |
dep.raw = this.code.slice(dep.point - 1, ast.range[1] - 1); |
| 50 |
lines = this.code.slice(ast.range[0], dep.point).split(eolRe); |
| 51 |
dep.line = ast.loc.start.line + lines.length - 1; |
| 52 |
dep.column = |
| 53 |
lines.length > 1 ? last.call(lines).length : ast.loc.start.column + lines[0].length; |
| 54 |
this.deps.push(dep); |
| 55 |
} |
| 56 |
}; |
| 57 |
|
| 58 |
module.exports = function (code, name, method, options) { |
| 59 |
var ctx = { code: code, deps: [] }; |
| 60 |
options = Object(options); |
| 61 |
if (method) { |
| 62 |
fnName = method; |
| 63 |
objName = name; |
| 64 |
} else { |
| 65 |
fnName = name; |
| 66 |
} |
| 67 |
asProperty = options.asProperty; |
| 68 |
walker.call(ctx, esprima.parse(code, { range: true, loc: true })); |
| 69 |
return ctx.deps; |
| 70 |
}; |