-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
Copy pathbuild.js
executable file
·1677 lines (1495 loc) · 58.7 KB
/
build.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
#!/usr/bin/env node
;(function() {
'use strict';
/** Load modules */
var fs = require('fs'),
path = require('path'),
vm = require('vm'),
minify = require(path.join(__dirname, 'build', 'minify')),
_ = require(path.join(__dirname, 'lodash'));
/** The current working directory */
var cwd = process.cwd();
/** Used for array method references */
var arrayRef = [];
/** Shortcut used to push arrays of values to an array */
var push = arrayRef.push;
/** Shortcut used to convert array-like objects to arrays */
var slice = arrayRef.slice;
/** Shortcut to the `stdout` object */
var stdout = process.stdout;
/** Used to associate aliases with their real names */
var aliasToRealMap = {
'all': 'every',
'any': 'some',
'collect': 'map',
'detect': 'find',
'drop': 'rest',
'each': 'forEach',
'foldl': 'reduce',
'foldr': 'reduceRight',
'head': 'first',
'include': 'contains',
'inject': 'reduce',
'methods': 'functions',
'select': 'filter',
'tail': 'rest',
'take': 'first',
'unique': 'uniq'
};
/** Used to associate real names with their aliases */
var realToAliasMap = {
'contains': ['include'],
'every': ['all'],
'filter': ['select'],
'find': ['detect'],
'first': ['head', 'take'],
'forEach': ['each'],
'functions': ['methods'],
'map': ['collect'],
'reduce': ['foldl', 'inject'],
'reduceRight': ['foldr'],
'rest': ['drop', 'tail'],
'some': ['any'],
'uniq': ['unique']
};
/** Used to track function dependencies */
var dependencyMap = {
'after': [],
'bind': ['isFunction'],
'bindAll': ['bind', 'functions'],
'chain': ['mixin'],
'clone': ['extend', 'forEach', 'forOwn', 'isArguments', 'isPlainObject'],
'compact': [],
'compose': [],
'contains': ['indexOf', 'some'],
'countBy': ['forEach'],
'debounce': [],
'defaults': ['isArguments'],
'defer': [],
'delay': [],
'difference': ['indexOf'],
'escape': [],
'every': ['forEach'],
'extend': ['isArguments'],
'filter': ['forEach'],
'find': ['some'],
'first': [],
'flatten': ['isArray'],
'forEach': ['identity'],
'forIn': ['identity', 'isArguments'],
'forOwn': ['identity', 'isArguments'],
'functions': ['forIn', 'isFunction'],
'groupBy': ['forEach'],
'has': [],
'identity': [],
'indexOf': ['sortedIndex'],
'initial': [],
'intersection': ['filter', 'indexOf'],
'invert': ['forOwn'],
'invoke': ['forEach'],
'isArguments': [],
'isArray': [],
'isBoolean': [],
'isDate': [],
'isElement': [],
'isEmpty': ['forOwn', 'isArguments', 'isFunction'],
'isEqual': ['isArguments', 'isFunction'],
'isFinite': [],
'isFunction': [],
'isNaN': [],
'isNull': [],
'isNumber': [],
'isObject': [],
'isPlainObject': ['forIn', 'isArguments', 'isFunction'],
'isRegExp': [],
'isString': [],
'isUndefined': [],
'keys': ['forOwn', 'isArguments'],
'last': [],
'lastIndexOf': [],
'lateBind': ['isFunction'],
'map': ['forEach', 'isArray'],
'max': ['forEach'],
'memoize': [],
'merge': ['forOwn', 'isArray', 'isPlainObject'],
'min': ['forEach'],
'mixin': ['forEach', 'functions'],
'noConflict': [],
'object': [],
'omit': ['forIn', 'indexOf'],
'once': [],
'pairs': ['forOwn'],
'partial': ['isFunction'],
'pick': ['forIn'],
'pluck': ['forEach'],
'random': [],
'range': [],
'reduce': ['forEach'],
'reduceRight': ['forEach', 'keys'],
'reject': ['filter'],
'rest': [],
'result': ['isFunction'],
'shuffle': ['forEach'],
'size': ['keys'],
'some': ['forEach'],
'sortBy': ['forEach'],
'sortedIndex': ['identity'],
'tap': ['mixin'],
'template': ['escape'],
'throttle': [],
'times': [],
'toArray': ['values'],
'unescape': [],
'union': ['indexOf'],
'uniq': ['identity', 'indexOf'],
'uniqueId': [],
'value': ['mixin'],
'values': ['forOwn'],
'where': ['filter', 'forIn'],
'without': ['indexOf'],
'wrap': [],
'zip': ['max', 'pluck']
};
/** Used to inline `iteratorTemplate` */
var iteratorOptions = [
'args',
'arrayLoop',
'bottom',
'firstArg',
'hasDontEnumBug',
'isKeysFast',
'objectLoop',
'noArgsEnum',
'noCharByIndex',
'shadowed',
'top',
'useHas',
'useStrict'
];
/** List of all Lo-Dash methods */
var allMethods = _.keys(dependencyMap);
/** List Backbone's Lo-Dash dependencies */
var backboneDependencies = [
'bind',
'bindAll',
'clone',
'contains',
'escape',
'every',
'extend',
'filter',
'find',
'first',
'forEach',
'groupBy',
'has',
'indexOf',
'initial',
'invoke',
'isArray',
'isEmpty',
'isEqual',
'isFunction',
'isObject',
'isRegExp',
'keys',
'last',
'lastIndexOf',
'lateBind',
'map',
'max',
'min',
'mixin',
'reduce',
'reduceRight',
'reject',
'rest',
'result',
'shuffle',
'size',
'some',
'sortBy',
'sortedIndex',
'toArray',
'uniqueId',
'without'
];
/** List of methods used by Underscore */
var underscoreMethods = _.without.apply(_, [allMethods].concat([
'forIn',
'forOwn',
'isPlainObject',
'lateBind',
'merge',
'partial'
]));
/** List of ways to export the `lodash` function */
var exportsAll = [
'amd',
'commonjs',
'global',
'node'
];
/*--------------------------------------------------------------------------*/
/**
* Compiles template files matched by the given file path `pattern` into a
* single source, extending `_.templates` with precompiled templates named after
* each template file's basename.
*
* @private
* @param {String} [pattern='<cwd>/*.jst'] The file path pattern.
* @param {Object} [options=_.templateSettings] The options object.
* @returns {String} Returns the compiled source.
*/
function buildTemplate(pattern, options) {
pattern || (pattern = path.join(cwd, '*.jst'));
options || (options = _.templateSettings);
var directory = path.dirname(pattern);
var moduleName = 'lodash';
var source = [
';(function(window) {',
" var freeExports = typeof exports == 'object' && exports &&",
" (typeof global == 'object' && global && global == global.global && (window = global), exports);",
'',
' var templates = {},',
' _ = window._;',
''
];
// convert to a regexp
pattern = RegExp(
path.basename(pattern)
.replace(/[.+?^=!:${}()|[\]\/\\]/g, '\\$&')
.replace(/\*/g, '.*?') + '$'
);
fs.readdirSync(directory).forEach(function(filename) {
var filePath = path.join(directory, filename);
if (pattern.test(filename)) {
var text = fs.readFileSync(filePath, 'utf8'),
precompiled = getFunctionSource(_.template(text, null, options)),
prop = filename.replace(/\..*$/, '');
source.push(" templates['" + prop.replace(/'/g, "\\'") + "'] = " + precompiled + ';', '');
}
});
source.push(
" if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {",
" define(['" + moduleName + "'], function(lodash) {",
' lodash.templates = lodash.extend(lodash.templates || {}, templates);',
' });',
" } else if (freeExports) {",
" if (typeof module == 'object' && module && module.exports == freeExports) {",
' (module.exports = templates).templates = templates;',
' } else {',
' freeExports.templates = templates;',
' }',
' } else if (_) {',
' _.templates = _.extend(_.templates || {}, templates);',
' }',
'}(this));'
);
return source.join('\n');
}
/**
* Removes unnecessary comments, whitespace, and pseudo private properties.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the modified source.
*/
function cleanupSource(source) {
return source
// remove pseudo private properties
.replace(/(?:(?:\s*\/\/.*)*\s*lodash\._[^=]+=.+\n)+/g, '\n')
// remove lines with just whitespace and semicolons
.replace(/^ *;\n/gm, '')
// consolidate consecutive horizontal rule comment separators
.replace(/(?:\s*\/\*-+\*\/\s*){2,}/g, function(separators) {
return separators.match(/^\s*/)[0] + separators.slice(separators.lastIndexOf('/*'));
});
}
/**
* Writes the help message to standard output.
*
* @private
*/
function displayHelp() {
console.log([
'',
' Commands:',
'',
' lodash backbone Build with only methods required by Backbone',
' lodash csp Build supporting default Content Security Policy restrictions',
' lodash legacy Build tailored for older browsers without ES5 support',
' lodash mobile Build with IE < 9 bug fixes & method compilation removed',
' lodash strict Build with `_.bindAll`, `_.defaults`, & `_.extend` in strict mode',
' lodash underscore Build tailored for projects already using Underscore',
' lodash include=... Comma separated method/category names to include in the build',
' lodash minus=... Comma separated method/category names to remove from those included in the build',
' lodash plus=... Comma separated method/category names to add to those included in the build',
' lodash category=... Comma separated categories of methods to include in the build (case-insensitive)',
' (i.e. “arrays”, “chaining”, “collections”, “functions”, “objects”, and “utilities”)',
' lodash exports=... Comma separated names of ways to export the `lodash` function',
' (i.e. “amd”, “commonjs”, “global”, “node”, and “none”)',
' lodash iife=... Code to replace the immediately-invoked function expression that wraps Lo-Dash',
' (e.g. `lodash iife="!function(window,undefined){%output%}(this)"`)',
'',
' lodash template=... File path pattern used to match template files to precompile',
' (e.g. `lodash template=./*.jst`)',
' lodash settings=... Template settings used when precompiling templates',
' (e.g. `lodash settings="{interpolate:/\\\\{\\\\{([\\\\s\\\\S]+?)\\\\}\\\\}/g}"`)',
'',
' All arguments, except `legacy` with `csp` or `mobile`, may be combined.',
' Unless specified by `-o` or `--output`, all files created are saved to the current working directory.',
'',
' Options:',
'',
' -c, --stdout Write output to standard output',
' -d, --debug Write only the debug output',
' -h, --help Display help information',
' -m, --minify Write only the minified output',
' -o, --output Write output to a given path/filename',
' -s, --silent Skip status updates normally logged to the console',
' -V, --version Output current version of Lo-Dash',
''
].join('\n'));
}
/**
* Gets the aliases associated with a given function name.
*
* @private
* @param {String} methodName The name of the method to get aliases for.
* @returns {Array} Returns an array of aliases.
*/
function getAliases(methodName) {
return realToAliasMap[methodName] || [];
}
/**
* Gets the Lo-Dash method assignments snippet from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the method assignments snippet.
*/
function getMethodAssignments(source) {
return (source.match(/lodash\.VERSION *= *[\s\S]+?\/\*-+\*\/\n/) || [''])[0];
}
/**
* Gets an array of depenants for a method by a given name.
*
* @private
* @param {String} methodName The name of the method to query.
* @returns {Array} Returns an array of method dependants.
*/
function getDependants(methodName) {
// iterate over the `dependencyMap`, adding the names of methods that
// have `methodName` as a dependency
return _.reduce(dependencyMap, function(result, dependencies, otherName) {
if (_.contains(dependencies, methodName)) {
result.push(otherName);
}
return result;
}, []);
}
/**
* Gets an array of dependencies for a given method name. If passed an array
* of dependencies it will return an array containing the given dependencies
* plus any additional detected sub-dependencies.
*
* @private
* @param {Array|String} methodName A single method name or array of
* dependencies to query.
* @returns {Array} Returns an array of method dependencies.
*/
function getDependencies(methodName) {
var dependencies = Array.isArray(methodName) ? methodName : dependencyMap[methodName];
if (!dependencies) {
return [];
}
// recursively accumulate the dependencies of the `methodName` function, and
// the dependencies of its dependencies, and so on.
return _.uniq(dependencies.reduce(function(result, otherName) {
result.push.apply(result, getDependencies(otherName).concat(otherName));
return result;
}, []));
}
/**
* Gets the formatted source of the given function.
*
* @private
* @param {Function} func The function to process.
* @returns {String} Returns the formatted source.
*/
function getFunctionSource(func) {
var source = func.source || (func + '');
// format leading whitespace
return source.replace(/\n(?:.*)/g, function(match, index) {
match = match.slice(1);
return (
match == '}' && source.indexOf('}', index + 2) == -1 ? '\n ' : '\n '
) + match;
});
}
/**
* Gets the `_.isArguments` fallback from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the `isArguments` fallback.
*/
function getIsArgumentsFallback(source) {
return (source.match(/(?:\s*\/\/.*)*\n( +)if *\(noArgsClass\)[\s\S]+?};\n\1}/) || [''])[0];
}
/**
* Gets the `_.isFunction` fallback from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the `isFunction` fallback.
*/
function getIsFunctionFallback(source) {
return (source.match(/(?:\s*\/\/.*)*\n( +)if *\(isFunction\(\/x\/[\s\S]+?};\n\1}/) || [''])[0];
}
/**
* Gets the names of methods in `source` belonging to the given `category`.
*
* @private
* @param {String} source The source to inspect.
* @param {String} category The category to filter by.
* @returns {Array} Returns a new array of method names belonging to the given category.
*/
function getMethodsByCategory(source, category) {
return allMethods.filter(function(methodName) {
return category && RegExp('@category ' + category + '\\b').test(matchFunction(source, methodName));
});
}
/**
* Gets the real name, not alias, of a given method name.
*
* @private
* @param {String} methodName The name of the method to resolve.
* @returns {String} Returns the real method name.
*/
function getRealName(methodName) {
return aliasToRealMap[methodName] || methodName;
}
/**
* Determines if all functions of the given names have been removed from `source`.
*
* @private
* @param {String} source The source to inspect.
* @param {String} [funcName1, funcName2, ...] The names of functions to check.
* @returns {Boolean} Returns `true` if all functions have been removed, else `false`.
*/
function isRemoved(source) {
return slice.call(arguments, 1).every(function(funcName) {
return !matchFunction(source, funcName);
});
}
/**
* Searches `source` for a `funcName` function declaration, expression, or
* assignment and returns the matched snippet.
*
* @private
* @param {String} source The source to inspect.
* @param {String} funcName The name of the function to match.
* @returns {String} Returns the matched function snippet.
*/
function matchFunction(source, funcName) {
var result = source.match(RegExp(
// match multi-line comment block (could be on a single line)
'(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/\\n)?' +
// begin non-capturing group
'(?:' +
// match a function declaration
'( +)function ' + funcName + '\\b[\\s\\S]+?\\n\\1}|' +
// match a variable declaration with `createIterator`
' +var ' + funcName + ' *=.*?createIterator\\((?:{|[a-zA-Z])[\\s\\S]+?\\);|' +
// match a variable declaration with function expression
'( +)var ' + funcName + ' *=.*?function[\\s\\S]+?\\n\\2};' +
// end non-capturing group
')\\n'
));
return result ? result[0] : '';
}
/**
* Converts a comma separated options string into an array.
*
* @private
* @param {String} value The option to convert.
* @returns {Array} Returns the new converted array.
*/
function optionToArray(value) {
return value.match(/\w+=(.*)$/)[1].split(/, */);
}
/**
* Converts a comma separated options string into an array containing
* only real method names.
*
* @private
* @param {String} source The source to inspect.
* @param {String} value The option to convert.
* @returns {Array} Returns the new converted array.
*/
function optionToMethodsArray(source, value) {
var methodNames = optionToArray(value);
// convert categories to method names
methodNames.forEach(function(category) {
push.apply(methodNames, getMethodsByCategory(source, category));
});
// convert aliases to real method names
methodNames = methodNames.map(getRealName);
// remove nonexistent and duplicate method names
return _.uniq(_.intersection(allMethods, methodNames));
}
/**
* Removes the all references to `refName` from `createIterator` in `source`.
*
* @private
* @param {String} source The source to process.
* @param {String} refName The name of the reference to remove.
* @returns {String} Returns the modified source.
*/
function removeFromCreateIterator(source, refName) {
var snippet = matchFunction(source, 'createIterator');
if (snippet) {
// clip the snippet at the `factory` assignment
snippet = snippet.match(/Function\([\s\S]+$/)[0];
var modified = snippet.replace(RegExp('\\b' + refName + '\\b,? *', 'g'), '');
source = source.replace(snippet, modified);
}
return source;
}
/**
* Removes the `funcName` function declaration, expression, or assignment and
* associated code from `source`.
*
* @private
* @param {String} source The source to process.
* @param {String} funcName The name of the function to remove.
* @returns {String} Returns the source with the function removed.
*/
function removeFunction(source, funcName) {
var modified,
snippet = matchFunction(source, funcName);
// exit early if function is not found
if (!snippet) {
return source;
}
// remove function
source = source.replace(snippet, '');
// grab the method assignments snippet
snippet = getMethodAssignments(source);
// remove assignment and aliases
modified = getAliases(funcName).concat(funcName).reduce(function(result, otherName) {
return result.replace(RegExp('(?:\\n *//.*\\s*)* *lodash\\.' + otherName + ' *= *.+\\n'), '');
}, snippet);
// replace with the modified snippet
source = source.replace(snippet, modified);
return removeFromCreateIterator(source, funcName);
}
/**
* Removes the `_.isArguments` fallback from `source`.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the source with the `isArguments` fallback removed.
*/
function removeIsArgumentsFallback(source) {
return source.replace(getIsArgumentsFallback(source), '');
}
/**
* Removes the `_.isFunction` fallback from `source`.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the source with the `isFunction` fallback removed.
*/
function removeIsFunctionFallback(source) {
return source.replace(getIsFunctionFallback(source), '');
}
/**
* Removes the `Object.keys` object iteration optimization from `source`.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the modified source.
*/
function removeKeysOptimization(source) {
return removeVar(source, 'isKeysFast')
// remove optimized branch in `iteratorTemplate`
.replace(/(?: *\/\/.*\n)* *'( *)<% *if *\(isKeysFast[\s\S]+?'\1<% *} *else *\{ *%>.+\n([\s\S]+?) *'\1<% *} *%>.+/, "'\\n' +\n$2")
// remove data object property assignment in `createIterator`
.replace(/ *'isKeysFast':.+\n/, '');
}
/**
* Removes all `noArgsClass` references from `source`.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the modified source.
*/
function removeNoArgsClass(source) {
return removeVar(source, 'noArgsClass')
// remove `noArgsClass` from `_.clone` and `_.isEqual`
.replace(/ *\|\| *\(noArgsClass *&&[^)]+?\)\)/g, '')
// remove `noArgsClass` from `_.isEqual`
.replace(/if *\(noArgsClass[^}]+?}\n/, '\n');
}
/**
* Removes all `noNodeClass` references from `source`.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the modified source.
*/
function removeNoNodeClass(source) {
return source
// remove `noNodeClass` assignment
.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var noNodeClass[\s\S]+?catch[^}]+}\n/, '')
// remove `noNodeClass` from `isPlainObject`
.replace(/\(!noNodeClass *\|\|[\s\S]+?\)\) *&&/, '')
// remove `noNodeClass` from `_.isEqual`
.replace(/ *\|\| *\(noNodeClass *&&[\s\S]+?\)\)\)/, '');
}
/**
* Removes a given variable from `source`.
*
* @private
* @param {String} source The source to process.
* @param {String} varName The name of the variable to remove.
* @returns {String} Returns the source with the variable removed.
*/
function removeVar(source, varName) {
// simplify `cloneableClasses`
if (varName == 'cloneableClasses') {
source = source.replace(/(var cloneableClasses *=)[\s\S]+?(true;\n)/, '$1$2');
}
// simplify `hasObjectSpliceBug`
if (varName == 'hasObjectSpliceBug') {
source = source.replace(/(var hasObjectSpliceBug *=)[^;]+/, '$1false');
}
source = source.replace(RegExp(
// match multi-line comment block
'(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)?\\n' +
// match a variable declaration that's not part of a declaration list
'( +)var ' + varName + ' *= *(?:.+?(?:;|&&\\n[^;]+;)|(?:\\w+\\(|{)[\\s\\S]+?\\n\\1.+?;)\\n|' +
// match a variable in a declaration list
'\\n +' + varName + ' *=.+?,'
), '');
// remove a varaible at the start of a variable declaration list
source = source.replace(RegExp('(var +)' + varName + ' *=.+?,\\s+'), '$1');
// remove a variable at the end of a variable declaration list
source = source.replace(RegExp(',\\s*' + varName + ' *=.+?;'), ';');
// remove variable reference from `cloneableClasses` assignments
source = source.replace(RegExp('cloneableClasses\\[' + varName + '\\] *= *(?:false|true)?', 'g'), '');
return removeFromCreateIterator(source, varName);
}
/**
* Searches `source` for a `varName` variable declaration and replaces its
* assigned value with `varValue`.
*
* @private
* @param {String} source The source to inspect.
* @param {String} varName The name of the variable to replace.
* @returns {String} Returns the source with the variable replaced.
*/
function replaceVar(source, varName, varValue) {
// replace a variable that's not part of a declaration list
var result = source.replace(RegExp(
'(( +)var ' + varName + ' *= *)' +
'(?:.+?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\2.+?;)\\n'
), '$1' + varValue + ';\n');
if (source == result) {
// replace a varaible at the start or middle of a declaration list
result = source.replace(RegExp('((?:var|\\n) +' + varName + ' *=).+?,'), '$1 ' + varValue + ',');
}
if (source == result) {
// replace a variable at the end of a variable declaration list
result = source.replace(RegExp('(,\\s*' + varName + ' *=).+?;'), '$1 ' + varValue + ';');
}
return result;
}
/**
* Hard-codes the `useStrict` template option value for `iteratorTemplate`.
*
* @private
* @param {String} source The source to process.
* @param {Boolean} value The value to set.
* @returns {String} Returns the modified source.
*/
function setUseStrictOption(source, value) {
// inject "use strict"
if (value) {
source = source.replace(/^[\s\S]*?function[^{]+{/, "$&\n 'use strict';");
}
// replace `useStrict` branch in `value` with hard-coded option
return source.replace(/(?: *\/\/.*\n)*(\s*)' *<%.+?useStrict.+/, value ? "$1'\\'use strict\\';\\n' +" : '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a debug and/or minified build, executing the `callback` for each.
* The `callback` is invoked with two arguments; (filePath, outputSource).
*
* Note: For a list of commands see `displayHelp()` or run `lodash --help`.
*
* @param {Array} [options=[]] An array of commands.
* @param {Function} callback The function called per build.
*/
function build(options, callback) {
options || (options = []);
// the debug version of `source`
var debugSource;
// used to report invalid command-line arguments
var invalidArgs = _.reject(options.slice(options[0] == 'node' ? 2 : 0), function(value, index, options) {
if (/^(?:-o|--output)$/.test(options[index - 1]) ||
/^(?:category|exclude|exports|iife|include|minus|plus|settings|template)=.*$/.test(value)) {
return true;
}
return [
'backbone',
'csp',
'legacy',
'mobile',
'strict',
'underscore',
'-c', '--stdout',
'-d', '--debug',
'-h', '--help',
'-m', '--minify',
'-o', '--output',
'-s', '--silent',
'-V', '--version'
].indexOf(value) > -1;
});
// report invalid arguments
if (invalidArgs.length) {
console.log(
'\n' +
'Invalid argument' + (invalidArgs.length > 1 ? 's' : '') +
' passed: ' + invalidArgs.join(', ')
);
displayHelp();
return;
}
// display help message
if (_.find(options, function(arg) {
return /^(?:-h|--help)$/.test(arg);
})) {
displayHelp();
return;
}
// display `lodash.VERSION`
if (_.find(options, function(arg) {
return /^(?:-V|--version)$/.test(arg);
})) {
console.log(_.VERSION);
return;
}
/*------------------------------------------------------------------------*/
// backup `dependencyMap` to restore later
var dependencyBackup = _.clone(dependencyMap, true);
// used to specify a custom IIFE to wrap Lo-Dash
var iife = options.reduce(function(result, value) {
var match = value.match(/iife=(.*)/);
return match ? match[1] : result;
}, null);
// flag used to specify a Backbone build
var isBackbone = options.indexOf('backbone') > -1;
// flag used to specify a Content Security Policy build
var isCSP = options.indexOf('csp') > -1 || options.indexOf('CSP') > -1;
// flag used to specify only creating the debug build
var isDebug = options.indexOf('-d') > -1 || options.indexOf('--debug') > -1;
// flag used to specify a legacy build
var isLegacy = options.indexOf('legacy') > -1;
// flag used to specify an Underscore build
var isUnderscore = options.indexOf('underscore') > -1;
// flag used to specify only creating the minified build
var isMinify = !isDebug && options.indexOf('-m') > -1 || options.indexOf('--minify')> -1;
// flag used to specify a mobile build
var isMobile = !isLegacy && (isCSP || isUnderscore || options.indexOf('mobile') > -1);
// flag used to specify writing output to standard output
var isStdOut = options.indexOf('-c') > -1 || options.indexOf('--stdout') > -1;
// flag used to specify skipping status updates normally logged to the console
var isSilent = isStdOut || options.indexOf('-s') > -1 || options.indexOf('--silent') > -1;
// flag used to specify `_.bindAll`, `_.extend`, and `_.defaults` are
// constructed using the "use strict" directive
var isStrict = options.indexOf('strict') > -1;
// used to specify the ways to export the `lodash` function
var exportsOptions = options.reduce(function(result, value) {
return /exports/.test(value) ? optionToArray(value).sort() : result;
}, isUnderscore
? ['commonjs', 'global', 'node']
: exportsAll.slice()
);
// used to specify the output path for builds
var outputPath = options.reduce(function(result, value, index) {
if (/-o|--output/.test(value)) {
result = options[index + 1];
result = path.join(fs.realpathSync(path.dirname(result)), path.basename(result));
}
return result;
}, '');
// used to match external template files to precompile
var templatePattern = options.reduce(function(result, value) {
var match = value.match(/template=(.+)$/);
return match
? path.join(fs.realpathSync(path.dirname(match[1])), path.basename(match[1]))
: result;
}, '');
// used when precompiling template files
var templateSettings = options.reduce(function(result, value) {
var match = value.match(/settings=(.+)$/);
return match
? Function('return {' + match[1].replace(/^{|}$/g, '') + '}')()
: result;
}, _.clone(_.templateSettings));
// flag used to specify a template build
var isTemplate = !!templatePattern;
// the lodash.js source
var source = fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8');
// flag used to specify replacing Lo-Dash's `_.clone` with Underscore's
var useUnderscoreClone = isUnderscore;
// flags used to specify exposing Lo-Dash methods in an Underscore build
var exposeForIn = !isUnderscore,
exposeForOwn = !isUnderscore,
exposeIsPlainObject = !isUnderscore;
/*------------------------------------------------------------------------*/
// names of methods to include in the build
var buildMethods = !isTemplate && (function() {
var result;
var minusMethods = options.reduce(function(accumulator, value) {
return /exclude|minus/.test(value)
? _.union(accumulator, optionToMethodsArray(source, value))
: accumulator;
}, []);
var plusMethods = options.reduce(function(accumulator, value) {
return /plus/.test(value)
? _.union(accumulator, optionToMethodsArray(source, value))
: accumulator;
}, []);
// update dependencies
if (isUnderscore) {
dependencyMap.isEqual = ['isArray', 'isFunction'];
dependencyMap.isEmpty = ['isArray', 'isString'];
dependencyMap.pick = [];
dependencyMap.template = ['defaults', 'escape'];
if (useUnderscoreClone) {
dependencyMap.clone = ['extend', 'isArray'];
}
}
// add method names explicitly
options.some(function(value) {
return /include/.test(value) &&
(result = getDependencies(optionToMethodsArray(source, value)));
});
// include Lo-Dash's methods if explicitly requested
if (result) {
exposeForIn = result.indexOf('forIn') > -1;
exposeForOwn = result.indexOf('forOwn') > -1;
exposeIsPlainObject = result.indexOf('isPlainObject') > -1;
useUnderscoreClone = result.indexOf('clone') < 0;
}
// add method names required by Backbone and Underscore builds
if (isBackbone && !result) {
result = getDependencies(backboneDependencies);
}
if (isUnderscore && !result) {
result = getDependencies(underscoreMethods);
}
// add method names by category
options.some(function(value) {
if (!/category/.test(value)) {