forked from aheckmann/gleak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (88 loc) · 1.75 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Gleak - detect global var leaks.
*/
/**
* Whitelisted globals.
*
* @api public
*/
exports.whitelist = [
setTimeout
, setInterval
, clearTimeout
, clearInterval
, console
, Buffer
, process
, global
];
/**
* Default format.
*/
exports.format = '\x1b[31mGleak!:\x1b[0m %s';
/**
* Detects global variable leaks.
*
* @api public
*/
exports.detect = function detect () {
var whitelist = exports.whitelist
, ret = []
Object.keys(global).forEach(function (key) {
var w = whitelist.length
, bad = true
while (w--) if (global[key] === whitelist[w]) {
bad = false;
break;
}
if (bad) ret.push(key);
});
return ret;
};
/**
* Prints all gleaks to stderr.
*/
exports.print = function print () {
exports.detect().forEach(function (leak) {
console.error(exports.format, leak);
});
}
/**
* Express middleware.
*/
exports.middleware = function gleakMiddleware (stream, format) {
if (!format) {
switch (typeof stream) {
case 'string':
format = stream;
stream = process.stderr;
break;
case 'undefined':
format = exports.format;
stream = process.stderr;
break;
default:
format = exports.format;
}
}
var known = [];
setTimeout(print, 1000);
function print () {
exports.detect().forEach(function (leak) {
if (~known.indexOf(leak)) return;
known.push(leak);
stream.write(format.replace(/%s/, leak) + '\n');
});
}
return function gleakMiddleware (req, res, next) {
if (res._gleak) return next();
res._gleak = true;
var send = res.send;
res.send = function () {
res.send = send;
res.send.apply(res, arguments);
print();
}
next();
}
}