-
Notifications
You must be signed in to change notification settings - Fork 37
/
amdclean.js
1685 lines (1677 loc) · 69.5 KB
/
amdclean.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! amdclean - v2.7.0 - 2015-12-05
* http://gregfranko.com/amdclean
* Copyright (c) 2015 Greg Franko */
/*The MIT License (MIT)
Copyright (c) 2014 Greg Franko
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
;(function(esprima, estraverse, escodegen, _, sourcemapToAst) {
// defaultOptions.js
// =================
// AMDclean default options
var defaultOptions, errorMsgs, defaultValues, utils, convertToIIFE, convertToIIFEDeclaration, normalizeModuleName, convertToFunctionExpression, convertToObjectDeclaration, createAst, convertDefinesAndRequires, traverseAndUpdateAst, getNormalizedModuleName, findAndStoreAllModuleIds, generateCode, clean;
defaultOptions = {
// The source code you would like to be 'cleaned'
'code': '',
// Provide a source map for the code you'd like to 'clean'
// Output will change from plain code to a hash: {code: ..., map: ...}
// Where code is 'cleaned' code and map is the new source map
'sourceMap': null,
// The relative file path of the file to be cleaned. Use this option if you are not using the code option.
// Hint: Use the __dirname trick
'filePath': '',
// The modules that you would like to set as window properties
// An array of strings (module names)
'globalModules': [],
// All esprima API options are supported: http://esprima.org/doc/
'esprima': {
'comment': true,
'loc': true,
'range': true,
'tokens': true
},
// All escodegen API options are supported: https://github.com/Constellation/escodegen/wiki/API
'escodegen': {
'comment': true,
'format': {
'indent': {
'style': ' ',
'adjustMultilineComment': true
}
}
},
// If there is a comment (that contains the following text) on the same line or one line above a specific module, the module will not be removed
'commentCleanName': 'amdclean',
// The ids of all of the modules that you would not like to be 'cleaned'
'ignoreModules': [],
// Determines which modules will be removed from the cleaned code
'removeModules': [],
// Determines if all of the require() method calls will be removed
'removeAllRequires': false,
// Determines if all of the 'use strict' statements will be removed
'removeUseStricts': true,
// Determines if conditional AMD checks are transformed
// e.g. if(typeof define == 'function') {} -> if(true) {}
'transformAMDChecks': true,
// Determines if a named or anonymous AMD module will be created inside of your conditional AMD check
// Note: This is only applicable to JavaScript libraries, do not change this for web apps
// If set to true: e.g. define('example', [], function() {}) -> define([], function() {})
'createAnonymousAMDModule': false,
// Allows you to pass an expression that will override shimmed modules return values
// e.g. { 'backbone': 'window.Backbone' }
'shimOverrides': {},
// Determines how to prefix a module name with when a non-JavaScript compatible character is found
// 'standard' or 'camelCase'
// 'standard' example: 'utils/example' -> 'utils_example'
// 'camelCase' example: 'utils/example' -> 'utilsExample'
'prefixMode': 'standard',
// A function hook that allows you add your own custom logic to how each module name is prefixed/normalized
'prefixTransform': function (postNormalizedModuleName, preNormalizedModuleName) {
return postNormalizedModuleName;
},
// Wrap any build bundle in a start and end text specified by wrap
// This should only be used when using the onModuleBundleComplete RequireJS Optimizer build hook
// If it is used with the onBuildWrite RequireJS Optimizer build hook, each module will get wrapped
'wrap': {
'start': ';(function() {\n',
'end': '\n}());'
},
// Determines if certain aggressive file size optimization techniques will be used to transform the soure code
'aggressiveOptimizations': false,
// Configuration info for modules
// Note: Further info can be found here - http://requirejs.org/docs/api.html#config-moduleconfig
'config': {}
};
errorMsgs = {
// The user has not supplied the cliean method with any code
'emptyCode': 'There is no code to generate the AST with',
// An AST has not been correctly returned by Esprima
'emptyAst': function (methodName) {
return 'An AST is not being passed to the ' + methodName + '() method';
},
// A parameter is not an object literal (which is expected)
'invalidObject': function (methodName) {
return 'An object is not being passed as the first parameter to the ' + methodName + '() method';
},
// Third-party dependencies have not been included on the page
'lodash': 'Make sure you have included lodash (https://github.com/lodash/lodash).',
'esprima': 'Make sure you have included esprima (https://github.com/ariya/esprima).',
'estraverse': 'Make sure you have included estraverse (https://github.com/Constellation/estraverse).',
'escodegen': 'Make sure you have included escodegen (https://github.com/Constellation/escodegen).',
'sourcemapToAst': 'Make sure you have included sourcemapToAst (https://github.com/tarruda/sourcemap-to-ast).'
};
defaultValues = {
// dependencyBlacklist
// -------------------
// Variable names that are not allowed as dependencies to functions
'dependencyBlacklist': {
'require': 'remove',
'exports': true,
'module': 'remove'
},
// defaultLOC
// ----------
// Default line of code property
'defaultLOC': {
'start': {
'line': 0,
'column': 0
}
},
// defaultRange
// ------------
// Default range property
'defaultRange': [
0,
0
]
};
utils = function () {
var Utils = {
// isDefine
// --------
// Returns if the current AST node is a define() method call
'isDefine': function (node) {
var expression = node.expression || {}, callee = expression.callee;
return _.isObject(node) && node.type === 'ExpressionStatement' && expression && expression.type === 'CallExpression' && callee.type === 'Identifier' && callee.name === 'define';
},
// isRequire
// ---------
// Returns if the current AST node is a require() method call
'isRequire': function (node) {
var expression = node.expression || {}, callee = expression.callee;
return node && node.type === 'ExpressionStatement' && expression && expression.type === 'CallExpression' && callee.type === 'Identifier' && callee.name === 'require';
},
// isModuleExports
// ---------------
// Is a module.exports member expression
'isModuleExports': function (node) {
if (!node) {
return false;
}
return node.type === 'AssignmentExpression' && node.left && node.left.type === 'MemberExpression' && node.left.object && node.left.object.type === 'Identifier' && node.left.object.name === 'module' && node.left.property && node.left.property.type === 'Identifier' && node.left.property.name === 'exports';
},
// isRequireExpression
// -------------------
// Returns if the current AST node is a require() call expression
// e.g. var example = require('someModule');
'isRequireExpression': function (node) {
return node && node.type === 'CallExpression' && node.callee && node.callee.name === 'require';
},
// isObjectExpression
// ------------------
// Returns if the current AST node is an object literal
'isObjectExpression': function (expression) {
return expression && expression && expression.type === 'ObjectExpression';
},
// isFunctionExpression
// --------------------
// Returns if the current AST node is a function
'isFunctionExpression': function (expression) {
return expression && expression && expression.type === 'FunctionExpression';
},
// isFunctionCallExpression
// ------------------------
// Returns if the current AST node is a function call expression
'isFunctionCallExpression': function (expression) {
return expression && expression && expression.type === 'CallExpression' && expression.callee && expression.callee.type === 'FunctionExpression';
},
// isUseStrict
// -----------
// Returns if the current AST node is a 'use strict' expression
// e.g. 'use strict'
'isUseStrict': function (expression) {
return expression && expression && expression.value === 'use strict' && expression.type === 'Literal';
},
// isIfStatement
// -------------
// Returns if the current AST node is an if statement
// e.g. if(true) {}
'isIfStatement': function (node) {
return node && node.type === 'IfStatement' && node.test;
},
// isAMDConditional
// ----------------
// Returns if the current AST node is an if statement AMD check
// e.g. if(typeof define === 'function') {}
'isAMDConditional': function (node) {
if (!Utils.isIfStatement(node)) {
return false;
}
var matchObject = {
'left': {
'operator': 'typeof',
'argument': {
'type': 'Identifier',
'name': 'define'
}
},
'right': {
'type': 'Literal',
'value': 'function'
}
}, reversedMatchObject = {
'left': matchObject.right,
'right': matchObject.left
};
try {
return _.find(node.test, matchObject) || _.find([node.test], matchObject) || _.find(node.test, reversedMatchObject) || _.find([node.test], reversedMatchObject) || _.find(node.test.left || {}, matchObject) || _.find([node.test.left || {}], matchObject) || _.find(node.test.left || {}, reversedMatchObject) || _.find([node.test.left || {}], reversedMatchObject);
} catch (e) {
return false;
}
},
// returnExpressionIdentifier
// --------------------------
// Returns a single identifier
// e.g. module
'returnExpressionIdentifier': function (name) {
return {
'type': 'ExpressionStatement',
'expression': {
'type': 'Identifier',
'name': name,
'range': defaultValues.defaultRange,
'loc': defaultValues.defaultLOC
},
'range': defaultValues.defaultRange,
'loc': defaultValues.defaultLOC
};
},
// readFile
// --------
// Synchronous file reading for node
'readFile': function (path) {
if (typeof exports !== 'undefined') {
var fs = require('fs');
return fs.readFileSync(path, 'utf8');
} else {
return '';
}
},
// isRelativeFilePath
// ------------------
// Returns a boolean that determines if the file path provided is a relative file path
// e.g. ../exampleModule -> true
'isRelativeFilePath': function (path) {
var segments = path.split('/');
return segments.length !== -1 && (segments[0] === '.' || segments[0] === '..');
},
// convertToCamelCase
// ------------------
// Converts a delimited string to camel case
// e.g. some_str -> someStr
convertToCamelCase: function (input, delimiter) {
delimiter = delimiter || '_';
return input.replace(new RegExp(delimiter + '(.)', 'g'), function (match, group1) {
return group1.toUpperCase();
});
},
// prefixReservedWords
// -------------------
// Converts a reserved word in JavaScript with an underscore
// e.g. class -> _class
'prefixReservedWords': function (name) {
var reservedWord = false;
try {
if (name.length) {
eval('var ' + name + ' = 1;');
}
} catch (e) {
reservedWord = true;
}
if (reservedWord === true) {
return '_' + name;
} else {
return name;
}
},
// normalizeDependencyName
// -----------------------
// Returns a normalized dependency name that handles relative file paths
'normalizeDependencyName': function (moduleId, dep) {
if (!moduleId || !dep) {
return dep;
}
var pluginName = function () {
if (!dep || dep.indexOf('!') === -1) {
return '';
}
var split = dep.split('!');
dep = split[1];
return split[0] + '!';
}(), normalizePath = function (path) {
var segments = path.split('/'), normalizedSegments;
normalizedSegments = _.reduce(segments, function (memo, segment) {
switch (segment) {
case '.':
break;
case '..':
memo.pop();
break;
default:
memo.push(segment);
}
return memo;
}, []);
return normalizedSegments.join('/');
}, baseName = function (path) {
var segments = path.split('/');
segments.pop();
return segments.join('/');
};
if (!Utils.isRelativeFilePath(dep)) {
return pluginName + dep;
}
return pluginName + normalizePath([
baseName(moduleId),
dep
].join('/'));
}
};
return Utils;
}();
convertToIIFE = function convertToIIFE(obj) {
var callbackFuncParams = obj.callbackFuncParams, callbackFunc = obj.callbackFunc, dependencyNames = obj.dependencyNames, node = obj.node, range = node.range || defaultValues.defaultRange, loc = node.loc || defaultValues.defaultLOC;
return {
'type': 'ExpressionStatement',
'expression': {
'type': 'CallExpression',
'callee': {
'type': 'FunctionExpression',
'id': null,
'params': callbackFuncParams,
'defaults': [],
'body': callbackFunc.body,
'rest': callbackFunc.rest,
'generator': callbackFunc.generator,
'expression': callbackFunc.expression,
'range': range,
'loc': loc
},
'arguments': dependencyNames,
'range': range,
'loc': loc
},
'range': range,
'loc': loc
};
};
convertToIIFEDeclaration = function convertToIIFEDeclaration(obj) {
var amdclean = this, options = amdclean.options, moduleId = obj.moduleId, moduleName = obj.moduleName, hasModuleParam = obj.hasModuleParam, hasExportsParam = obj.hasExportsParam, callbackFuncParams = obj.callbackFuncParams, isOptimized = obj.isOptimized, callback = obj.callbackFunc, node = obj.node, name = callback.name, type = callback.type, range = node.range || defaultValues.defaultRange, loc = node.loc || defaultValues.defaultLOC, callbackFunc = function () {
var cbFunc = obj.callbackFunc;
if (type === 'Identifier' && name !== 'undefined') {
cbFunc = {
'type': 'FunctionExpression',
'id': null,
'params': [],
'defaults': [],
'body': {
'type': 'BlockStatement',
'body': [{
'type': 'ReturnStatement',
'argument': {
'type': 'ConditionalExpression',
'test': {
'type': 'BinaryExpression',
'operator': '===',
'left': {
'type': 'UnaryExpression',
'operator': 'typeof',
'argument': {
'type': 'Identifier',
'name': name,
'range': range,
'loc': loc
},
'prefix': true,
'range': range,
'loc': loc
},
'right': {
'type': 'Literal',
'value': 'function',
'raw': '\'function\'',
'range': range,
'loc': loc
},
'range': range,
'loc': loc
},
'consequent': {
'type': 'CallExpression',
'callee': {
'type': 'Identifier',
'name': name,
'range': range,
'loc': loc
},
'arguments': callbackFuncParams,
'range': range,
'loc': loc
},
'alternate': {
'type': 'Identifier',
'name': name,
'range': range,
'loc': loc
},
'range': range,
'loc': loc
},
'range': range,
'loc': loc
}],
'range': range,
'loc': loc
},
'rest': null,
'generator': false,
'expression': false,
'range': range,
'loc': loc
};
}
return cbFunc;
}(), dependencyNames = function () {
var depNames = obj.dependencyNames, objExpression = {
'type': 'ObjectExpression',
'properties': [],
'range': range,
'loc': loc
}, configMemberExpression = {
'type': 'MemberExpression',
'computed': true,
'object': {
'type': 'Identifier',
'name': 'modules'
},
'property': {
'type': 'Literal',
'value': moduleId
}
}, moduleDepIndex;
if (options.config && options.config[moduleId]) {
if (hasExportsParam && hasModuleParam) {
return [
objExpression,
objExpression,
configMemberExpression
];
} else if (hasModuleParam) {
moduleDepIndex = _.findIndex(depNames, function (currentDep) {
return currentDep.name === '{}';
});
depNames[moduleDepIndex] = configMemberExpression;
}
}
return depNames;
}(), cb = function () {
if (callbackFunc.type === 'Literal' || callbackFunc.type === 'Identifier' && callbackFunc.name === 'undefined' || isOptimized === true) {
return callbackFunc;
} else {
return {
'type': 'CallExpression',
'callee': {
'type': 'FunctionExpression',
'id': {
'type': 'Identifier',
'name': '',
'range': range,
'loc': loc
},
'params': callbackFuncParams,
'defaults': [],
'body': callbackFunc.body,
'rest': callbackFunc.rest,
'generator': callbackFunc.generator,
'expression': callbackFunc.expression,
'range': range,
'loc': loc
},
'arguments': dependencyNames,
'range': range,
'loc': loc
};
}
}(), updatedNode = {
'type': 'ExpressionStatement',
'expression': {
'type': 'AssignmentExpression',
'operator': '=',
'left': {
'type': 'Identifier',
'name': options.IIFEVariableNameTransform ? options.IIFEVariableNameTransform(moduleName, moduleId) : moduleName,
'range': range,
'loc': loc
},
'right': cb,
'range': range,
'loc': loc
},
'range': range,
'loc': loc
};
estraverse.replace(callbackFunc, {
'enter': function (node) {
if (utils.isModuleExports(node)) {
return {
'type': 'AssignmentExpression',
'operator': '=',
'left': {
'type': 'Identifier',
'name': 'exports'
},
'right': node.right
};
} else {
return node;
}
}
});
return updatedNode;
};
normalizeModuleName = function normalizeModuleName(name, moduleId) {
var amdclean = this, options = amdclean.options, prefixMode = options.prefixMode, prefixTransform = options.prefixTransform, dependencyBlacklist = defaultValues.dependencyBlacklist, prefixTransformValue, preNormalized, postNormalized;
name = name || '';
if (name === '{}') {
if (dependencyBlacklist[name] === 'remove') {
return '';
} else {
return name;
}
}
preNormalized = utils.prefixReservedWords(name.replace(/\./g, '').replace(/[^A-Za-z0-9_$]/g, '_').replace(/^_+/, ''));
postNormalized = prefixMode === 'camelCase' ? utils.convertToCamelCase(preNormalized) : preNormalized;
if (_.isFunction(prefixTransform)) {
prefixTransformValue = prefixTransform(postNormalized, name);
if (_.isString(prefixTransformValue) && prefixTransformValue.length) {
return prefixTransformValue;
}
}
return postNormalized;
};
convertToFunctionExpression = function convertToFunctionExpression(obj) {
var amdclean = this, options = amdclean.options, ignoreModules = options.ignoreModules, node = obj.node, isDefine = obj.isDefine, isRequire = obj.isRequire, isOptimized = false, moduleName = obj.moduleName, moduleId = obj.moduleId, dependencies = obj.dependencies, depLength = dependencies.length, aggressiveOptimizations = options.aggressiveOptimizations, exportsExpressions = [], moduleExportsExpressions = [], defaultRange = defaultValues.defaultRange, defaultLOC = defaultValues.defaultLOC, range = obj.range || defaultRange, loc = obj.loc || defaultLOC, shouldOptimize = obj.shouldOptimize, dependencyBlacklist = defaultValues.dependencyBlacklist, hasNonMatchingParameter = false, callbackFunc = function () {
var callbackFunc = obj.moduleReturnValue, body, returnStatements, firstReturnStatement, returnStatementArg;
// If the module callback function is not empty
if (callbackFunc && callbackFunc.type === 'FunctionExpression' && callbackFunc.body && _.isArray(callbackFunc.body.body) && callbackFunc.body.body.length) {
// Filter 'use strict' statements
body = _.filter(callbackFunc.body.body, function (node) {
if (options.removeUseStricts === true) {
return !utils.isUseStrict(node.expression);
} else {
return node;
}
});
callbackFunc.body.body = body;
// Returns an array of all return statements
returnStatements = _.where(body, { 'type': 'ReturnStatement' });
exportsExpressions = _.where(body, {
'left': {
'type': 'Identifier',
'name': 'exports'
}
});
moduleExportsExpressions = _.where(body, {
'left': {
'type': 'MemberExpression',
'object': {
'type': 'Identifier',
'name': 'module'
},
'property': {
'type': 'Identifier',
'name': 'exports'
}
}
});
// If there is a return statement
if (returnStatements.length) {
firstReturnStatement = returnStatements[0];
returnStatementArg = firstReturnStatement.argument;
hasNonMatchingParameter = function () {
var nonMatchingParameter = false;
_.each(callbackFunc.params, function (currentParam) {
var currentParamName = currentParam.name;
if (!amdclean.storedModules[currentParamName] && !dependencyBlacklist[currentParamName]) {
nonMatchingParameter = true;
}
});
return nonMatchingParameter;
}();
// If something other than a function expression is getting returned
// and there is more than one AST child node in the factory function
// return early
if (hasNonMatchingParameter || !shouldOptimize || !utils.isFunctionExpression(firstReturnStatement) && body.length > 1 || returnStatementArg && returnStatementArg.type === 'Identifier') {
return callbackFunc;
} else {
// Optimize the AMD module by setting the callback function to the return statement argument
callbackFunc = returnStatementArg;
isOptimized = true;
if (callbackFunc.params) {
depLength = callbackFunc.params.length;
}
}
}
} else if (callbackFunc && callbackFunc.type === 'FunctionExpression' && callbackFunc.body && _.isArray(callbackFunc.body.body) && callbackFunc.body.body.length === 0) {
callbackFunc = {
'type': 'Identifier',
'name': 'undefined',
'range': range,
'loc': loc
};
depLength = 0;
}
return callbackFunc;
}(), hasReturnStatement = function () {
var returns = [];
if (callbackFunc && callbackFunc.body && _.isArray(callbackFunc.body.body)) {
returns = _.where(callbackFunc.body.body, { 'type': 'ReturnStatement' });
if (returns.length) {
return true;
}
}
return false;
}(), originalCallbackFuncParams, hasExportsParam = function () {
var cbParams = callbackFunc.params || [];
return _.where(cbParams, { 'name': 'exports' }).length;
}(), hasModuleParam = function () {
var cbParams = callbackFunc.params || [];
return _.where(cbParams, { 'name': 'module' }).length;
}(), normalizeDependencyNames = {}, dependencyNames = function () {
var deps = [], currentName;
_.each(dependencies, function (currentDependency) {
currentName = normalizeModuleName.call(amdclean, utils.normalizeDependencyName(moduleId, currentDependency), moduleId);
normalizeDependencyNames[currentName] = true;
deps.push({
'type': 'Identifier',
'name': currentName,
'range': defaultRange,
'loc': defaultLOC
});
});
return deps;
}(),
// Makes sure the new name is not an existing callback function dependency and/or existing local variable
findNewParamName = function findNewParamName(name) {
name = '_' + name + '_';
var containsLocalVariable = function () {
var containsVariable = false;
if (normalizeDependencyNames[name]) {
containsVariable = true;
} else {
estraverse.traverse(callbackFunc, {
'enter': function (node) {
if (node.type === 'VariableDeclarator' && node.id && node.id.type === 'Identifier' && node.id.name === name) {
containsVariable = true;
}
}
});
}
return containsVariable;
}();
// If there is not a local variable declaration with the passed name, return the name and surround it with underscores
// Else if there is already a local variable declaration with the passed name, recursively add more underscores surrounding it
if (!containsLocalVariable) {
return name;
} else {
return findNewParamName(name);
}
}, matchingRequireExpressionNames = function () {
var matchingNames = [];
if (hasExportsParam) {
estraverse.traverse(callbackFunc, {
'enter': function (node) {
var variableName, expressionName;
if (node.type === 'VariableDeclarator' && utils.isRequireExpression(node.init)) {
// If both variable name and expression names are there
if (node.id && node.id.name && node.init && node.init['arguments'] && node.init['arguments'][0] && node.init['arguments'][0].value) {
variableName = node.id.name;
expressionName = normalizeModuleName.call(amdclean, utils.normalizeDependencyName(moduleId, node.init['arguments'][0].value, moduleId));
if (!_.contains(ignoreModules, expressionName) && variableName === expressionName) {
matchingNames.push({
'originalName': expressionName,
'newName': findNewParamName(expressionName),
'range': node.range || defaultRange,
'loc': node.loc || defaultLOC
});
}
}
}
}
});
}
return matchingNames;
}(), matchingRequireExpressionParams = function () {
var params = [];
_.each(matchingRequireExpressionNames, function (currentParam) {
params.push({
'type': 'Identifier',
'name': currentParam.newName ? currentParam.newName : currentParam,
'range': currentParam.range,
'loc': currentParam.loc
});
});
return params;
}(), callbackFuncParams = function () {
var deps = [], currentName, cbParams = _.union(callbackFunc.params && callbackFunc.params.length ? callbackFunc.params : !shouldOptimize && dependencyNames && dependencyNames.length ? dependencyNames : [], matchingRequireExpressionParams), mappedParameter = {},
// For calculating cbParams we'll optimize by removing not referenced names in the callback parameters.
// If the callback body contains a reference to 'arguments' then we cannot perform this optimization.
// but at the same time if only inner functions body contains arguments WE DO optimize.
// What we do is find inner function declarations and then remove their text from the callback body. Then we look for 'arguments' references
innerFunctions = [], lookForArgumentsCode;
if (callbackFunc.body) {
estraverse.traverse(callbackFunc.body, {
enter: function (node, parent) {
if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration')
innerFunctions.push(node);
}
});
if (innerFunctions.length) {
for (var i = callbackFunc.body.range[0]; i < callbackFunc.body.range[1]; i++) {
_.each(innerFunctions, function (innerFunction) {
if (i < innerFunction.range[0] || i >= innerFunction.range[1]) {
lookForArgumentsCode += amdclean.options.code[i];
}
});
}
} else {
lookForArgumentsCode = amdclean.options.code.substring(callbackFunc.body.range[0], callbackFunc.body.range[1]);
}
if (/[^\w0-9_]arguments[^\w0-9_]/.test(lookForArgumentsCode)) {
cbParams = cbParams.concat(dependencyNames.slice(cbParams.length));
}
}
_.each(cbParams, function (currentParam, iterator) {
if (currentParam) {
currentName = currentParam.name;
} else {
currentName = dependencyNames[iterator].name;
}
if (!shouldOptimize && currentName !== '{}') {
deps.push({
'type': 'Identifier',
'name': currentName,
'range': defaultRange,
'loc': defaultLOC
});
} else if (currentName !== '{}' && (!hasExportsParam || defaultValues.dependencyBlacklist[currentName] !== 'remove')) {
deps.push({
'type': 'Identifier',
'name': currentName,
'range': defaultRange,
'loc': defaultLOC
});
// If a callback parameter is not the exact name of a stored module and there is a dependency that matches the current callback parameter
if (!isOptimized && aggressiveOptimizations === true && !amdclean.storedModules[currentName] && dependencyNames[iterator]) {
// If the current dependency has not been stored
if (!amdclean.callbackParameterMap[dependencyNames[iterator].name]) {
amdclean.callbackParameterMap[dependencyNames[iterator].name] = [{
'name': currentName,
'count': 1
}];
} else {
mappedParameter = _.where(amdclean.callbackParameterMap[dependencyNames[iterator].name], { 'name': currentName });
if (mappedParameter.length) {
mappedParameter = mappedParameter[0];
mappedParameter.count += 1;
} else {
amdclean.callbackParameterMap[dependencyNames[iterator].name].push({
'name': currentName,
'count': 1
});
}
}
}
}
});
originalCallbackFuncParams = deps;
// Only return callback function parameters that do not directly match the name of existing stored modules
return _.filter(deps || [], function (currentParam) {
return aggressiveOptimizations === true && shouldOptimize ? !amdclean.storedModules[currentParam.name] : true;
});
}(), isCommonJS = !hasReturnStatement && hasExportsParam, hasExportsAssignment = exportsExpressions.length || moduleExportsExpressions.length, dependencyNameLength, callbackFuncParamsLength;
// Only return dependency names that do not directly match the name of existing stored modules
dependencyNames = _.filter(dependencyNames || [], function (currentDep, iterator) {
var mappedCallbackParameter = originalCallbackFuncParams[iterator], currentDepName = currentDep.name;
// If the matching callback parameter matches the name of a stored module, then do not return it
// Else if the matching callback parameter does not match the name of a stored module, return the dependency
return aggressiveOptimizations === true && shouldOptimize ? !mappedCallbackParameter || amdclean.storedModules[mappedCallbackParameter.name] && mappedCallbackParameter.name === currentDepName ? !amdclean.storedModules[currentDepName] : !amdclean.storedModules[mappedCallbackParameter.name] : true;
});
dependencyNames = _.map(dependencyNames || [], function (currentDep, iterator) {
if (dependencyBlacklist[currentDep.name]) {
currentDep.name = '{}';
}
return currentDep;
});
dependencyNameLength = dependencyNames.length;
callbackFuncParamsLength = callbackFuncParams.length;
// If the module dependencies passed into the current module are greater than the used callback function parameters, do not pass the dependencies
if (dependencyNameLength > callbackFuncParamsLength) {
dependencyNames.splice(callbackFuncParamsLength, dependencyNameLength - callbackFuncParamsLength);
}
// If it is a CommonJS module and there is an exports assignment, make sure to return the exports object
if (isCommonJS && hasExportsAssignment) {
callbackFunc.body.body.push({
'type': 'ReturnStatement',
'argument': {
'type': 'Identifier',
'name': 'exports',
'range': defaultRange,
'loc': defaultLOC
},
'range': defaultRange,
'loc': defaultLOC
});
}
// Makes sure to update all the local variable require expressions to any updated names
estraverse.replace(callbackFunc, {
'enter': function (node) {
var normalizedModuleName, newName;
if (utils.isRequireExpression(node)) {
if (node['arguments'] && node['arguments'][0] && node['arguments'][0].value) {
normalizedModuleName = normalizeModuleName.call(amdclean, utils.normalizeDependencyName(moduleId, node['arguments'][0].value, moduleId));
if (_.contains(ignoreModules, normalizedModuleName)) {
return node;
}
if (_.where(matchingRequireExpressionNames, { 'originalName': normalizedModuleName }).length) {
newName = _.where(matchingRequireExpressionNames, { 'originalName': normalizedModuleName })[0].newName;
}
return {
'type': 'Identifier',
'name': newName ? newName : normalizedModuleName,
'range': node.range || defaultRange,
'loc': node.loc || defaultLOC
};
} else {
return node;
}
}
}
});
if (isDefine) {
return convertToIIFEDeclaration.call(amdclean, {
'moduleId': moduleId,
'moduleName': moduleName,
'dependencyNames': dependencyNames,
'callbackFuncParams': callbackFuncParams,
'hasModuleParam': hasModuleParam,
'hasExportsParam': hasExportsParam,
'callbackFunc': callbackFunc,
'isOptimized': isOptimized,
'node': node
});
} else if (isRequire) {
return convertToIIFE.call(amdclean, {
'dependencyNames': dependencyNames,
'callbackFuncParams': callbackFuncParams,
'callbackFunc': callbackFunc,
'node': node
});
}
};
convertToObjectDeclaration = function (obj, type) {
var node = obj.node, defaultRange = defaultValues.defaultRange, defaultLOC = defaultValues.defaultLOC, range = node.range || defaultRange, loc = node.loc || defaultLOC, moduleName = obj.moduleName, moduleReturnValue = function () {
var modReturnValue, callee, params, returnStatement, nestedReturnStatement, internalFunctionExpression;
if (type === 'functionCallExpression') {
modReturnValue = obj.moduleReturnValue;
callee = modReturnValue.callee;
params = callee.params;
if (params && params.length && _.isArray(params) && _.where(params, { 'name': 'global' })) {
if (_.isObject(callee.body) && _.isArray(callee.body.body)) {
returnStatement = _.where(callee.body.body, { 'type': 'ReturnStatement' })[0];
if (_.isObject(returnStatement) && _.isObject(returnStatement.argument) && returnStatement.argument.type === 'FunctionExpression') {
internalFunctionExpression = returnStatement.argument;
if (_.isObject(internalFunctionExpression.body) && _.isArray(internalFunctionExpression.body.body)) {
nestedReturnStatement = _.where(internalFunctionExpression.body.body, { 'type': 'ReturnStatement' })[0];
if (_.isObject(nestedReturnStatement.argument) && _.isObject(nestedReturnStatement.argument.right) && _.isObject(nestedReturnStatement.argument.right.property)) {
if (nestedReturnStatement.argument.right.property.name) {
modReturnValue = {
'type': 'MemberExpression',
'computed': false,
'object': {
'type': 'Identifier',
'name': 'window',
'range': range,
'loc': loc
},
'property': {
'type': 'Identifier',
'name': nestedReturnStatement.argument.right.property.name,
'range': range,
'loc': loc
},
'range': range,
'loc': loc
};
}
}
}
}
}
}
}
modReturnValue = modReturnValue || obj.moduleReturnValue;
return modReturnValue;
}(), updatedNode = {
'type': 'ExpressionStatement',
'expression': {
'type': 'AssignmentExpression',
'operator': '=',
'left': {
'type': 'Identifier',
'name': moduleName,
'range': range,
'loc': loc
},
'right': moduleReturnValue,
'range': range,
'loc': loc
},
'range': range,
'loc': loc
};
return updatedNode;
};
createAst = function createAst(providedCode) {
var amdclean = this, options = amdclean.options, filePath = options.filePath, code = providedCode || options.code || (filePath ? utils.readFile(filePath) : ''), esprimaOptions = options.esprima, escodegenOptions = options.escodegen;
if (!code) {
throw new Error(errorMsgs.emptyCode);
} else {
if (!_.isPlainObject(esprima) || !_.isFunction(esprima.parse)) {
throw new Error(errorMsgs.esprima);
}
var ast = esprima.parse(code, esprimaOptions);
if (options.sourceMap)
sourcemapToAst(ast, options.sourceMap);
// Check if both the esprima and escodegen comment options are set to true
if (esprimaOptions.comment === true && escodegenOptions.comment === true) {
try {
// Needed to keep source code comments when generating the code with escodegen
ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
} catch (e) {
}
}
return ast;
}
};
convertDefinesAndRequires = function convertDefinesAndRequires(node, parent) {
var amdclean = this, options = amdclean.options, moduleName, args, dependencies, moduleReturnValue, moduleId, params, isDefine = utils.isDefine(node), isRequire = utils.isRequire(node), startLineNumber, callbackFuncArg = false, type = '', shouldBeIgnored, moduleToBeIgnored, parentHasFunctionExpressionArgument, defaultRange = defaultValues.defaultRange, defaultLOC = defaultValues.defaultLOC, range = node.range || defaultRange, loc = node.loc || defaultLOC, dependencyBlacklist = defaultValues.dependencyBlacklist, shouldOptimize;
startLineNumber = isDefine || isRequire ? node.expression.loc.start.line : node && node.loc && node.loc.start ? node.loc.start.line : null;
shouldBeIgnored = amdclean.matchingCommentLineNumbers[startLineNumber] || amdclean.matchingCommentLineNumbers[startLineNumber - 1];
// If it is an AMD conditional statement
// e.g. if(typeof define === 'function') {}
if (utils.isAMDConditional(node)) {
estraverse.traverse(node, {
'enter': function (node) {
var normalizedModuleName;
if (utils.isDefine(node)) {
if (node.expression && node.expression.arguments && node.expression.arguments.length) {
// Add the module name to the ignore list
if (node.expression.arguments[0].type === 'Literal' && node.expression.arguments[0].value) {
normalizedModuleName = normalizeModuleName.call(amdclean, node.expression.arguments[0].value);
if (options.transformAMDChecks !== true) {
amdclean.conditionalModulesToIgnore[normalizedModuleName] = true;
} else {
amdclean.conditionalModulesToNotOptimize[normalizedModuleName] = true;
}
if (options.createAnonymousAMDModule === true) {
amdclean.storedModules[normalizedModuleName] = false;