index.js
2.84 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _util() {
const data = require('util');
_util = function () {
return data;
};
return data;
}
function _v() {
const data = require('v8');
_v = function () {
return data;
};
return data;
}
function _vm() {
const data = require('vm');
_vm = function () {
return data;
};
return data;
}
function _jestGetType() {
const data = require('jest-get-type');
_jestGetType = function () {
return data;
};
return data;
}
function _prettyFormat() {
const data = _interopRequireDefault(require('pretty-format'));
_prettyFormat = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const tick = (0, _util().promisify)(setImmediate);
class _default {
constructor(value) {
_defineProperty(this, '_isReferenceBeingHeld', void 0);
if ((0, _jestGetType().isPrimitive)(value)) {
throw new TypeError(
[
'Primitives cannot leak memory.',
'You passed a ' +
typeof value +
': <' +
(0, _prettyFormat().default)(value) +
'>'
].join(' ')
);
}
let weak;
try {
// eslint-disable-next-line import/no-extraneous-dependencies
weak = require('weak-napi');
} catch (err) {
if (!err || err.code !== 'MODULE_NOT_FOUND') {
throw err;
}
throw new Error(
'The leaking detection mechanism requires the "weak-napi" package to be installed and work. ' +
'Please install it as a dependency on your main project'
);
}
weak(value, () => (this._isReferenceBeingHeld = false));
this._isReferenceBeingHeld = true; // Ensure value is not leaked by the closure created by the "weak" callback.
value = null;
}
async isLeaking() {
this._runGarbageCollector(); // wait some ticks to allow GC to run properly, see https://github.com/nodejs/node/issues/34636#issuecomment-669366235
for (let i = 0; i < 10; i++) {
await tick();
}
return this._isReferenceBeingHeld;
}
_runGarbageCollector() {
const isGarbageCollectorHidden = !global.gc; // GC is usually hidden, so we have to expose it before running.
(0, _v().setFlagsFromString)('--expose-gc');
(0, _vm().runInNewContext)('gc')(); // The GC was not initially exposed, so let's hide it again.
if (isGarbageCollectorHidden) {
(0, _v().setFlagsFromString)('--no-expose-gc');
}
}
}
exports.default = _default;