forked from calvinmetcalf/derequire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (73 loc) · 2.12 KB
/
index.js
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
'use strict';
var { Parser } = require('acorn');
var stage3Plugin = require('acorn-stage3');
var acorn = Parser.extend(stage3Plugin);
var escope = require('escope');
var requireRegexp = /\brequire\b/;
function write(arr, str, offset) {
for (var i = 0, l = str.length; i < l; i++) {
arr[offset + i] = str[i];
}
}
function rename(code, tokenTo, tokenFrom) {
var tokens;
if (!Array.isArray(tokenTo)) {
tokens = [{
from: tokenFrom || 'require',
to: tokenTo || '_dereq_'
}];
} else {
tokens = tokenTo;
}
tokens.forEach(function(token) {
if (token.to.length !== token.from.length) {
throw new Error('"' + token.to + '" and "' + token.from + '" must be the same length');
}
});
if (tokens.length === 1 &&
tokens[0].from === 'require' &&
!requireRegexp.test(code)) {
return code;
}
var ast;
try {
ast = acorn.parse(code, {
ecmaVersion: 11,
ranges: true,
allowReturnOutsideFunction: true
});
} catch(err) {
// this should probably log something and/or exit violently
return code;
}
//
// heavily inspired by https://github.com/estools/esshorten
//
code = String(code).split('');
var manager = escope.analyze(ast, {optimistic: true, ecmaVersion: 8});
for (var i = 0, iz = manager.scopes.length; i < iz; i++) {
var scope = manager.scopes[i];
for (var j = 0, jz = scope.variables.length; j < jz; j++) {
var variable = scope.variables[j];
if (variable.tainted || variable.identifiers.length === 0) {
continue;
}
for (var k = 0, kz = tokens.length; k < kz; k++) {
var token = tokens[k];
if (variable.name !== token.from) {
continue;
}
for (var l = 0, lz = variable.identifiers.length; l < lz; l++) {
var def = variable.identifiers[l];
write(code, token.to, def.range[0]);
}
for (var m = 0, mz = variable.references.length; m < mz; m++) {
var ref = variable.references[m];
write(code, token.to, ref.identifier.range[0]);
}
}
}
}
return code.join('');
}
module.exports = rename;