1 | 'use strict';
|
2 |
|
3 | function ProxyquireifyError(msg) {
|
4 | this.name = 'ProxyquireifyError';
|
5 | Error.captureStackTrace(this, ProxyquireifyError);
|
6 | this.message = msg || 'An error occurred inside proxyquireify.';
|
7 | }
|
8 |
|
9 | function validateArguments(request, stubs) {
|
10 | var msg = (function getMessage() {
|
11 | if (!request)
|
12 | return 'Missing argument: "request". Need it to resolve desired module.';
|
13 |
|
14 | if (!stubs)
|
15 | return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.';
|
16 |
|
17 | if (typeof request != 'string')
|
18 | return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.';
|
19 |
|
20 | if (typeof stubs != 'object')
|
21 | return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.';
|
22 | })();
|
23 |
|
24 | if (msg) throw new ProxyquireifyError(msg);
|
25 | }
|
26 |
|
27 | var stubs;
|
28 |
|
29 | function stub(stubs_) {
|
30 | stubs = stubs_;
|
31 | }
|
32 |
|
33 | function reset() {
|
34 | stubs = undefined;
|
35 | }
|
36 |
|
37 | function fillMissingKeys(mdl, original) {
|
38 | Object.keys(original).forEach(function (key) {
|
39 | if (!mdl[key]) mdl[key] = original[key];
|
40 | });
|
41 |
|
42 | return mdl;
|
43 | }
|
44 |
|
45 | var proxyquire = module.exports = function (require_) {
|
46 | if (typeof require_ != 'function')
|
47 | throw new ProxyquireifyError(
|
48 | 'It seems like you didn\'t initialize proxyquireify with the require in your test.\n'
|
49 | + 'Make sure to correct this, i.e.: "var proxyquire = require(\'proxyquireify\')(require);"'
|
50 | );
|
51 |
|
52 | reset();
|
53 |
|
54 | return function(request, stubs) {
|
55 |
|
56 | validateArguments(request, stubs);
|
57 |
|
58 |
|
59 |
|
60 | stub(stubs);
|
61 | var dep = require_(request);
|
62 | reset();
|
63 |
|
64 | return dep;
|
65 | };
|
66 | };
|
67 |
|
68 | proxyquire.proxy = function (require_) {
|
69 | return function (request) {
|
70 | function original() {
|
71 | return require_(request);
|
72 | }
|
73 |
|
74 | if (!stubs) return original();
|
75 |
|
76 | var stub = stubs[request];
|
77 |
|
78 | if (!stub) return original();
|
79 |
|
80 | var stubWideNoCallThru = !!stubs['@noCallThru'] && stub['@noCallThru'] !== false;
|
81 | var noCallThru = stubWideNoCallThru || !!stub['@noCallThru'];
|
82 | return noCallThru ? stub : fillMissingKeys(stub, original());
|
83 | };
|
84 | };
|
85 |
|
86 | if (require.cache) {
|
87 |
|
88 | var hackPrelude = './lib/hack-prelude';
|
89 | proxyquire.browserify = require(hackPrelude).browserify;
|
90 | }
|