Welcome to mirror list, hosted at ThFree Co, Russian Federation.

rewire.js « lib - github.com/twbs/rewire.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6f1ac7d20907296c6b7649bb0cad9255b894f969 (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
55
56
57
58
59
60
61
62
63
64
65
66
"use strict"; // run code in ES5 strict mode

var Module = require("module"),
    nodeWrapper0 = Module.wrapper[0], // caching original wrapper
    nodeWrapper1 = Module.wrapper[1],
    getLeakingSrc = require("./getLeakingSrc.js"),
    getInjectionSrc = require("./getInjectionSrc.js");

function restoreOriginalWrappers() {
    Module.wrapper[1] = nodeWrapper1;
}

/**
 * Does actual rewiring the module. For further documentation @see index.js
 */
module.exports = function doRewire(parentModule, filename, mocks, injections, leaks, cache) {
    var testModule,
        nodeRequire,
        wrapperExtensions = "";

    function requireTrick(path) {
        restoreOriginalWrappers();  // we need to restore the wrappers now so we don't influence other modules

        if (mocks && mocks.hasOwnProperty(path)) {
            return mocks[path];
        } else {
            return nodeRequire.call(testModule, path);  // node's require only works when "this" points to the module
        }
    }

    // Checking params
    if (typeof filename !== "string") {
        throw new TypeError("Filename must be a string");
    }

    // Init vars
    filename = Module._resolveFilename(filename, parentModule);  // resolve full filename relative to the parent module
    testModule = new Module(filename, parentModule);
    nodeRequire = testModule.require;   // caching original node require

    // Prepare module for injection
    if (typeof injections === "object") {
        wrapperExtensions += getInjectionSrc(injections);
    } else if (typeof injections === "string") {
        wrapperExtensions += injections;
    }

    // Prepare module for leaking private vars
    if (Array.isArray(leaks)) {
        wrapperExtensions += getLeakingSrc(leaks);
    }
    Module.wrapper[1] = wrapperExtensions + nodeWrapper1;

    // Mocking module.require-function
    testModule.require = requireTrick;
    // Loading module
    testModule.load(testModule.id);

    if (cache) {
        require.cache[filename] = testModule;
    }

    restoreOriginalWrappers();  // this is only necessary if nothing has been required within the module

    return testModule.exports;
};