/
index.js
517 lines (460 loc) · 15.1 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
"use strict";
const Charset = require("./charset");
const ScopeTracker = require("./scope-tracker");
const isLabelIdentifier = require("./is-label-identifier");
const bfsTraverseCreator = require("./bfs-traverse");
const fixupVarScoping = require("./fixup-var-scoping");
const {
markEvalScopes,
isMarked: isEvalScopesMarked,
hasEval
} = require("babel-helper-mark-eval-scopes");
const newIssueUrl = "https://github.com/babel/minify/issues/new";
module.exports = babel => {
const { types: t, traverse } = babel;
const bfsTraverse = bfsTraverseCreator(babel);
const hop = Object.prototype.hasOwnProperty;
class Mangler {
constructor(
charset,
program,
{
exclude = {},
keepFnName = false,
keepClassName = false,
eval: _eval = false,
topLevel = false
} = {}
) {
this.charset = charset;
this.program = program;
// user passed options
this.exclude = toObject(exclude);
this.keepFnName = keepFnName;
this.keepClassName = keepClassName;
this.topLevel = topLevel;
this.eval = _eval;
// tracking
this.visitedScopes = new Set();
this.scopeTracker = new ScopeTracker();
this.renamedNodes = new Set();
}
/**
* Run the mangler
*/
run() {
this.crawlScope();
this.collect();
this.fixup();
this.charset.sort();
this.mangle();
}
/**
* Tells if a variable name is excluded
* @param {String} name
*/
isExcluded(name) {
return hop.call(this.exclude, name) && this.exclude[name];
}
/**
* Clears traverse cache and recrawls the AST
*
* to recompute the bindings, references, other scope information
* and paths because the other transformations in the same pipeline
* (other plugins and presets) changes the AST and does NOT update
* the scope objects
*/
crawlScope() {
(traverse.clearCache || traverse.cache.clear)();
this.program.scope.crawl();
}
/**
* Re-crawling comes with a side-effect that let->var conversion
* reverts the update of the binding information (block to fn scope).
* This function takes care of it by updating it again.
*
* TODO: This is unnecessary work and needs to be fixed in babel.
* https://github.com/babel/babel/issues/4818
*
* When this is removed, remember to remove fixup's dependency in
* ScopeTracker
*/
fixup() {
fixupVarScoping(this);
}
/**
* A single pass through the AST to collect info for
*
* 1. Scope Tracker
* 2. Unsafe Scopes (direct eval scopes)
* 3. Charset considerations for better gzip compression
*
* Traversed in the same fashion(BFS) the mangling is done
*/
collect() {
const mangler = this;
const { scopeTracker } = mangler;
scopeTracker.addScope(this.program.scope);
/**
* Same usage as in DCE, whichever runs first
*/
if (!isEvalScopesMarked(mangler.program)) {
markEvalScopes(mangler.program);
}
/**
* The visitors to be used in traversal.
*
* Note: BFS traversal supports only the `enter` handlers, `exit`
* handlers are simply dropped without Errors
*
* Collects items defined in the ScopeTracker
*/
const collectVisitor = {
Scopable({ scope }) {
scopeTracker.addScope(scope);
// Collect bindings defined in the scope
Object.keys(scope.bindings).forEach(name => {
scopeTracker.addBinding(scope.bindings[name]);
});
},
/**
* This is necessary because, in Babel, the scope.references
* does NOT contain the references in that scope. Only the program
* scope (top most level) contains all the references.
*
* We collect the references in a fashion where all the scopes between
* and including the referenced scope and scope where it is declared
* is considered as scope referencing that identifier
*/
ReferencedIdentifier(path) {
if (isLabelIdentifier(path)) {
return;
}
const {
scope,
node: { name }
} = path;
const binding = scope.getBinding(name);
if (!binding) {
// Do not collect globals as they are already available via
// babel's API
if (scope.hasGlobal(name)) {
return;
}
// This should NOT happen ultimately. Panic if this code block is
// reached
throw new Error(
`Binding not found for ReferencedIdentifier "${name}" ` +
`present in "${path.parentPath.type}". ` +
`Please report this at ${newIssueUrl}`
);
} else {
// Add it to our scope tracker if everything is fine
scopeTracker.addReference(scope, binding, name);
}
}
};
/**
* These visitors are for collecting the Characters used in the program
* to measure the frequency and generate variable names for mangling so
* as to improve the gzip compression - as gzip likes repetition
*/
if (this.charset.shouldConsider) {
collectVisitor.Identifier = function Identifer(path) {
const { node } = path;
// We don't mangle properties, so we collect them as they contribute
// to the frequency of characters
if (
path.parentPath.isMemberExpression({ property: node }) ||
path.parentPath.isObjectProperty({ key: node })
) {
mangler.charset.consider(node.name);
}
};
collectVisitor.Literal = function Literal({ node }) {
mangler.charset.consider(String(node.value));
};
}
// Traverse the AST
bfsTraverse(mangler.program, collectVisitor);
}
/**
* Tells if a binding is exported as a NamedExport - so as to NOT mangle
*
* Babel treats NamedExports as a binding referenced by this NamedExport decl
* @param {Binding} binding
*/
isExportedWithName(binding) {
// short circuit
if (!this.topLevel) {
return false;
}
const refs = binding.referencePaths;
for (const ref of refs) {
if (ref.isExportNamedDeclaration()) {
return true;
}
}
// default
return false;
}
/**
* Mangle the scope
* @param {Scope} scope
*/
mangleScope(scope) {
const mangler = this;
const { scopeTracker } = mangler;
// Unsafe Scope
if (!mangler.eval && hasEval(scope)) {
return;
}
// Already visited
// This is because for a function, in Babel, the function and
// the function body's BlockStatement has the same scope, and will
// be visited twice by the Scopable handler, and we want to mangle
// it only once
if (mangler.visitedScopes.has(scope)) {
return;
}
mangler.visitedScopes.add(scope);
// Helpers to generate names
let i = 0;
function getNext() {
return mangler.charset.getIdentifier(i++);
}
function resetNext() {
i = 0;
}
const bindings = scopeTracker.bindings.get(scope);
const names = [...bindings.keys()];
/**
* 1. Iterate through the list of BindingIdentifiers
* 2. Rename each of them in-place
* 3. Update the scope tree.
*/
for (let i = 0; i < names.length; i++) {
const oldName = names[i];
const binding = bindings.get(oldName);
// Names which should NOT be mangled
if (
// arguments - for non-strict mode
oldName === "arguments" ||
// labels
binding.path.isLabeledStatement() ||
// ClassDeclaration has binding in two scopes
// 1. The scope in which it is declared
// 2. The class's own scope
(binding.path.isClassDeclaration() && binding.path === scope.path) ||
// excluded
mangler.isExcluded(oldName) ||
// function names
(mangler.keepFnName ? isFunction(binding.path) : false) ||
// class names
(mangler.keepClassName ? isClass(binding.path) : false) ||
// named export
mangler.isExportedWithName(binding)
) {
continue;
}
let next;
do {
next = getNext();
} while (
!t.isValidIdentifier(next) ||
scopeTracker.hasBinding(scope, next) ||
scope.hasGlobal(next) ||
scopeTracker.hasReference(scope, next) ||
!scopeTracker.canUseInReferencedScopes(binding, next)
);
// Reset so variables which are removed can be reused
resetNext();
// Once we detected a valid `next` Identifier which could be used,
// call the renamer
mangler.rename(scope, binding, oldName, next);
}
}
/**
* The mangle function that traverses through all the Scopes in a BFS
* fashion - calls mangleScope
*/
mangle() {
const mangler = this;
bfsTraverse(this.program, {
Scopable(path) {
if (!path.isProgram() || mangler.topLevel)
mangler.mangleScope(path.scope);
}
});
}
/**
* Given a NodePath, collects all the Identifiers which are BindingIdentifiers
* and replaces them with the new name
*
* For example,
* var a = 1, { b } = c; // a and b are BindingIdentifiers
*
* @param {NodePath} path
* @param {String} oldName
* @param {String} newName
* @param {Function} predicate
*/
renameBindingIds(path, oldName, newName, predicate = () => true) {
const bindingIds = path.getBindingIdentifierPaths(true, false);
for (const name in bindingIds) {
if (name !== oldName) continue;
for (const idPath of bindingIds[name]) {
if (predicate(idPath)) {
idPath.node.name = newName;
// babel-7 don't requeue
// idPath.replaceWith(t.identifier(newName));
this.renamedNodes.add(idPath.node);
}
}
}
}
/**
* The Renamer:
* Renames the following for one Binding in a Scope
*
* 1. Binding in that Scope
* 2. All the Binding's constant violations
* 3. All its References
* 4. Updates mangler.scopeTracker
* 5. Updates Babel's Scope tracking
*
* @param {Scope} scope
* @param {Binding} binding
* @param {String} oldName
* @param {String} newName
*/
rename(scope, binding, oldName, newName) {
const mangler = this;
const { scopeTracker } = mangler;
// rename at the declaration level
this.renameBindingIds(
binding.path,
oldName,
newName,
idPath => idPath.node === binding.identifier
);
// update mangler's ScopeTracker
scopeTracker.renameBinding(scope, oldName, newName);
// update all constant violations
const violations = binding.constantViolations;
for (let i = 0; i < violations.length; i++) {
if (violations[i].isLabeledStatement()) continue;
this.renameBindingIds(violations[i], oldName, newName);
scopeTracker.updateReference(
violations[i].scope,
binding,
oldName,
newName
);
}
// update all referenced places
const refs = binding.referencePaths;
for (let i = 0; i < refs.length; i++) {
const path = refs[i];
const { node } = path;
if (!path.isIdentifier()) {
// Ideally, this should not happen
// it happens in these places now -
// case 1: Export Statements
// This is a bug in babel
// https://github.com/babel/babel/pull/3629
// case 2: Replacements in other plugins
// eg: https://github.com/babel/minify/issues/122
// replacement in dce from `x` to `!x` gives referencePath as `!x`
path.traverse({
ReferencedIdentifier(refPath) {
if (refPath.node.name !== oldName) {
return;
}
const actualBinding = refPath.scope.getBinding(oldName);
if (actualBinding !== binding) {
return;
}
refPath.node.name = newName;
// babel-7 don't requeue
// refPath.replaceWith(t.identifier(newName));
mangler.renamedNodes.add(refPath.node);
scopeTracker.updateReference(
refPath.scope,
binding,
oldName,
newName
);
}
});
} else if (!isLabelIdentifier(path)) {
if (path.node.name === oldName) {
path.node.name = newName;
// babel-7 don't requeue
// path.replaceWith(t.identifier(newName));
mangler.renamedNodes.add(path.node);
scopeTracker.updateReference(path.scope, binding, oldName, newName);
} else if (mangler.renamedNodes.has(path.node)) {
// already renamed,
// just update the references
scopeTracker.updateReference(path.scope, binding, oldName, newName);
} else {
throw new Error(
`Unexpected Rename Error: ` +
`Trying to replace "${
node.name
}": from "${oldName}" to "${newName}". ` +
`Please report it at ${newIssueUrl}`
);
}
}
// else label identifier - silently ignore
}
// update babel's internal tracking
binding.identifier.name = newName;
// update babel's internal scope tracking
const { bindings } = scope;
bindings[newName] = binding;
delete bindings[oldName];
}
}
return {
name: "minify-mangle-names",
visitor: {
/**
* Mangler is run as a single pass. It's the same pattern as used in DCE
*/
Program: {
exit(path) {
// If the source code is small then we're going to assume that the user
// is running on this on single files before bundling. Therefore we
// need to achieve as much determinisim and we will not do any frequency
// sorting on the character set. Currently the number is pretty arbitrary.
const shouldConsiderSource = path.getSource().length > 70000;
const charset = new Charset(shouldConsiderSource);
const mangler = new Mangler(charset, path, this.opts);
mangler.run();
}
}
}
};
};
// convert value to object
function toObject(value) {
if (!Array.isArray(value)) {
return value;
}
const map = {};
for (let i = 0; i < value.length; i++) {
map[value[i]] = true;
}
return map;
}
// for keepFnName
function isFunction(path) {
return path.isFunctionExpression() || path.isFunctionDeclaration();
}
// for keepClassName
function isClass(path) {
return path.isClassExpression() || path.isClassDeclaration();
}