forked from jlord/workshopper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module-use-tracker.js
84 lines (73 loc) · 2.15 KB
/
module-use-tracker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const fs = require('fs')
var data = { calls: [] }
, on = true
function writeData (outfile) {
try {
fs.writeFileSync(outfile, JSON.stringify(data))
} catch(e) {
console.error('Internal error!', e)
}
}
function track (mod, outfile, fn, args, stack) {
on = false
var _args = Array.prototype.map.call(args, function (a) {
if (typeof a == 'function')
return '<Function>'
if (Buffer.isBuffer(a))
return '<Buffer>'
return a
})
data.calls.push({ module: mod, fn: fn, args: _args, stack: stack })
data.required = Object.keys(require.cache)
writeData(outfile)
on = true
}
function trackMethods (name, obj, trackFile) {
Object.keys(obj).forEach(function (fn) {
var err, stack
if (typeof obj[fn] == 'function') {
obj['__' + fn] = obj[fn]
obj[fn] = function replacement () {
try {
err = new Error
Error._prepareStackTrace = Error.prepareStackTrace
Error.prepareStackTrace = function (err, stack) { return stack }
Error.captureStackTrace(err, replacement)
stack = err.stack.map(function (c) {
return {
type : c.getTypeName()
, fn : c.getFunctionName()
, method : c.getMethodName()
, file : c.getFileName()
, line : c.getLineNumber()
, col : c.getColumnNumber()
, global : c.isToplevel()
, native : c.isNative()
, ctor : c.isConstructor()
}
})
Error.prepareStackTrace = Error._prepareStackTrace
} catch (e) {}
if (on) {
track(name, trackFile, fn, arguments, stack)
}
return obj['__' + fn].apply(this, arguments)
}
}
})
}
function init () {
var outfile = process.argv[3]
, modules = process.argv[4].split(',')
data.argv = process.argv
data.cwd = process.cwd()
data.modules = modules
writeData(outfile)
modules.forEach(function (mod) {
var m = require(mod)
trackMethods(mod, m, outfile)
})
}
module.exports.trackMethods = trackMethods
module.exports.init = init
module.exports.args = 2