Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit edd6774

Browse files
committed
code refactoring, resolve paths with join
1 parent 5548e10 commit edd6774

File tree

8 files changed

+43
-65
lines changed

8 files changed

+43
-65
lines changed

lib/__get__.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
'use strict';
12
/**
23
* This function will be stringified and then injected into every rewired module.
34
* Then you can leak private variables by calling myModule.__get__("myPrivateVar");

lib/addImportsAsVars.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
const importRegex = /^import\s+(?:\s?(.+)\}?\s+from\s+)?[\'"]([^"\']+)["\']/;
1+
'use strict';
2+
3+
const importRegex = /^import\s+(?:\s?(.+)\}?\s+from\s+)?[\'"]([^"\']+)["\']/m;
24
const namedRegex = /^{.+}$/;
35

46
let imports = {};
@@ -11,7 +13,8 @@ function detectImports(src) {
1113
let vars = null;
1214
let path = null;
1315
let importType = 'default';
14-
if (match) {
16+
17+
if (match && match[1]) {
1518
vars = match[1];
1619
// named export
1720
if (vars.match(namedRegex)) {
@@ -39,9 +42,9 @@ function detectImports(src) {
3942
const { path, importType } = imports[key];
4043
// eval(`var ${key};`);
4144
if (importType === 'named') {
42-
output += `global.${key} = require('${path}').${key};\n`;
45+
output += `global.${key} = require('${path}').${key};` + '\n';
4346
} else {
44-
output += `global.${key} = require('${path}');\n`;
47+
output += `global.${key} = require('${path}').default;` + '\n';
4548
}
4649

4750
} catch(e) {}

lib/fileExists.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
var fs = require('fs');
1+
'use strict';
2+
3+
const { accessSync, F_OK} = require('fs');
24

35
function fileExists(path) {
46
try {
5-
fs.accessSync(path, fs.F_OK);
7+
accessSync(path, F_OK);
68
} catch (e) {
79
if (e) {
810
console.log(e);

lib/getDefinePropertySrc.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ function getDefinePropertySrc(src) {
66

77
const getMethods = src => ({
88
'__get__': __get__.toString(),
9-
'__text__': '`' + src.toString() + "`",
9+
// '__text__': src.toString(),
1010
});
1111

1212
const methods = getMethods(src);
@@ -15,10 +15,8 @@ function getDefinePropertySrc(src) {
1515
if (typeof(module.exports) === 'function' ||
1616
(typeof(module.exports) === 'object' && module.exports !== null && Object.isExtensible(module.exports))) {
1717
${Object.keys(methods).reduce((preValue, value) => {
18-
return preValue += `Object.defineProperty(module.exports, '${value}', {enumerable: false, value: ${methods[value]}, writable: true});`;
19-
}, '')
20-
}
21-
}`;
18+
return preValue += `Object.defineProperty(module.exports, '` + value + `', {enumerable: false, value: ` + methods[value] + `, writable: true});`;
19+
}, '')}}`;
2220
}
2321

2422
module.exports = getDefinePropertySrc;

lib/getImportGlobalsSrc.js

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
'use strict';
12
/**
23
* Declares all globals with a var and assigns the global object. Thus you're able to
34
* override globals without changing the global object itself.
@@ -7,20 +8,14 @@
78
*
89
* @return {String}
910
*/
11+
const ignore = ['global', 'root', 'process', 'Buffer', 'clearImmediate', 'clearInterval', 'setTimeout', 'module', 'exports', 'require'];
12+
1013
function getImportGlobalsSrc(ignore) {
1114
var key,
1215
value,
1316
src = '',
1417
globalObj = typeof global === 'undefined' ? window : global;
1518

16-
ignore = ignore || [];
17-
// global itself can't be overridden because it's the only reference to our real global objects
18-
ignore.push('global');
19-
// ignore 'module', 'exports' and 'require' on the global scope, because otherwise our code would
20-
// shadow the module-internal variables
21-
// @see https://github.com/jhnns/rewire-webpack/pull/6
22-
ignore.push('module', 'exports', 'require');
23-
2419
for (key in globalObj) { /* jshint forin: false */
2520
if (ignore.indexOf(key) !== -1) {
2621
continue;
@@ -29,8 +24,8 @@ function getImportGlobalsSrc(ignore) {
2924

3025
// key may be an invalid variable name (e.g. 'a-b')
3126
try {
32-
eval(`var ${key};`);
33-
src += `var ${key} = global.${key};`;
27+
// eval('var ' + key);
28+
src += `var ${key} = global.${key}`;
3429
} catch(e) {}
3530
}
3631

lib/index.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
'use strict';
12
var rewireModule = require('./rewire.js');
23
var fileExists = require('./fileExists');
34

@@ -9,19 +10,21 @@ var fileExists = require('./fileExists');
910
* @return {*} the rewired module
1011
*/
1112
function rewire(filename) {
12-
// is not a package path
13-
if (!filename.match(/^[a-zA-Z]/)) {
14-
// if the file doesn't exist yet,
15-
// create a __get__ mock to prevent tests breaking
13+
// is not a node_module path
14+
if (!filename.match(/^[a-zA-Z\_]/)) {
1615
if (!fileExists(filename)) {
16+
// create a __get__ mock to prevent tests breaking
17+
// when file does not exist
1718
return {
1819
__get__: () => {},
1920
__text__: undefined,
2021
};
2122
}
23+
// proceed with rewiring
24+
return rewireModule(module.parent, filename);
2225
}
23-
// proceed with rewiring
24-
return rewireModule(module.parent, filename);
26+
// is a node_module path, use normal require
27+
return require(filename);
2528
}
2629

2730
module.exports = rewire;

lib/rewire.js

Lines changed: 11 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
var Module = require('module'),
2-
fs = require('fs'),
3-
getImportGlobalsSrc = require('./getImportGlobalsSrc.js'),
4-
getDefinePropertySrc = require('./getDefinePropertySrc.js'),
5-
moduleEnv = require('./moduleEnv.js'),
6-
addImportsAsVars = require('./addImportsAsVars');
1+
'use strict';
2+
const Module = require('module');
3+
const { readFileSync, join } = require('fs');
4+
const getImportGlobalsSrc = require('./getImportGlobalsSrc'),
5+
const getDefinePropertySrc = require('./getDefinePropertySrc'),
6+
const moduleEnv = require('./moduleEnv'),
7+
const addImportsAsVars = require('./addImportsAsVars');
78

89
/**
910
* Does actual rewiring the module. For further documentation @see index.js
@@ -20,36 +21,18 @@ function internalRewire(parentModulePath, targetPath) {
2021
}
2122

2223
// Resolve full filename relative to the parent module
23-
targetPath = Module._resolveFilename(targetPath, parentModulePath);
24-
25-
// Special support for older node versions that returned an array on Module._resolveFilename
26-
// @see https://github.com/joyent/node/blob/865b077819a9271a29f982faaef99dc635b57fbc/lib/module.js#L319
27-
// TODO Remove this switch on the next major release
28-
/* istanbul ignore next because it will be removed soon */
29-
if (Array.isArray(targetPath)) {
30-
targetPath = targetPath[1];
31-
}
24+
targetPath = join(targetPath, parentModulePath);
3225

33-
// Check if the module uses the strict mode.
34-
// If so we must ensure that "use strict"; stays at the beginning of the module.
35-
src = fs.readFileSync(targetPath, 'utf8');
26+
src = readFileSync(targetPath, 'utf8');
3627

37-
// Create testModule as it would be created by require()
28+
// create testModule as it would be created by require()
3829
targetModule = new Module(targetPath, parentModulePath);
3930

40-
// We prepend a list of all globals declared with var so they can be overridden (without changing original globals)
31+
// prepend a list of all globals declared with var so they can be overridden (without changing original globals)
4132
prelude = getImportGlobalsSrc();
42-
43-
// Wrap module src inside IIFE so that function declarations do not clash with global variables
44-
// @see https://github.com/jhnns/rewire/issues/56
4533
prelude += '(function () { ';
46-
47-
// We append our special setter and getter.
4834
appendix = '\n' + getDefinePropertySrc(src);
49-
5035
appendix += '\n' + addImportsAsVars(src);
51-
52-
// End of IIFE
5336
appendix += '})();';
5437

5538
moduleEnv.inject(prelude, appendix);

package.json

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,11 @@
11
{
22
"name": "rewire-coderoad",
3-
"version": "3.1.1",
4-
"description": "CodeRoad implementation to override 'require' in order to monkey-patch test globals",
3+
"version": "3.1.2",
4+
"description": "CodeRoad implementation to override 'require' in order to test globals",
55
"keywords": [
6+
"coderoad",
67
"dependency",
78
"injection",
8-
"mock",
9-
"shim",
10-
"module",
11-
"unit",
12-
"test",
13-
"leak",
14-
"inspect",
15-
"fake",
169
"require"
1710
],
1811
"author": {

0 commit comments

Comments
 (0)