blob: 3ac20424f08b76c95b0b29b540cd5d4d478a1b0d (
plain)
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
|
var Module = require("module"),
fs = require("fs"),
getImportGlobalsSrc = require("./getImportGlobalsSrc.js"),
getDefinePropertySrc = require("./getDefinePropertySrc.js"),
detectStrictMode = require("./detectStrictMode.js"),
moduleEnv = require("./moduleEnv.js");
/**
* Does actual rewiring the module. For further documentation @see index.js
*/
function internalRewire(parentModulePath, targetPath) {
var targetModule,
prelude,
appendix,
src;
// Checking params
if (typeof targetPath !== "string") {
throw new TypeError("Filename must be a string");
}
// Resolve full filename relative to the parent module
targetPath = Module._resolveFilename(targetPath, parentModulePath);
// Create testModule as it would be created by require()
targetModule = new Module(targetPath, parentModulePath);
// We prepend a list of all globals declared with var so they can be overridden (without changing original globals)
prelude = getImportGlobalsSrc();
// Wrap module src inside IIFE so that function declarations do not clash with global variables
// @see https://github.com/jhnns/rewire/issues/56
prelude += "(function () { ";
// We append our special setter and getter.
appendix = "\n" + getDefinePropertySrc();
// End of IIFE
appendix += "})();";
// Check if the module uses the strict mode.
// If so we must ensure that "use strict"; stays at the beginning of the module.
src = fs.readFileSync(targetPath, "utf8");
if (detectStrictMode(src) === true) {
prelude = ' "use strict"; ' + prelude;
}
moduleEnv.inject(prelude, appendix);
moduleEnv.load(targetModule);
return targetModule.exports;
}
module.exports = internalRewire;
|