forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
executable file
·3846 lines (3510 loc) · 136 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 Node.js modules */
var vm = require('vm');
/** Load other modules */
var _ = require('./lodash.js'),
minify = require('./build/minify.js'),
util = require('./build/util.js');
/** Module shortcuts */
var fs = util.fs,
path = util.path;
/** The current working directory */
var cwd = process.cwd();
/** Used for array and object method references */
var arrayRef = Array.prototype,
objectRef = Object.prototype;
/** Native method shortcuts */
var hasOwnProperty = objectRef.hasOwnProperty,
push = arrayRef.push,
slice = arrayRef.slice;
/** Used to create regexes that may detect multi-line comment blocks */
var multilineComment = '(?:\\n */\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)?\\n';
/** Used to detect the Node.js executable in command-line arguments */
var reNode = RegExp('(?:^|' + path.sepEscaped + ')node(?:\\.exe)?$');
/** 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',
'extend': 'assign',
'findWhere': 'find',
'foldl': 'reduce',
'foldr': 'reduceRight',
'head': 'first',
'include': 'contains',
'inject': 'reduce',
'methods': 'functions',
'object': 'zipObject',
'select': 'filter',
'tail': 'rest',
'take': 'first',
'unique': 'uniq'
};
/** Used to associate real names with their aliases */
var realToAliasMap = {
'assign': ['extend'],
'contains': ['include'],
'every': ['all'],
'filter': ['select'],
'find': ['detect', 'findWhere'],
'first': ['head', 'take'],
'forEach': ['each'],
'functions': ['methods'],
'map': ['collect'],
'reduce': ['foldl', 'inject'],
'reduceRight': ['foldr'],
'rest': ['drop', 'tail'],
'some': ['any'],
'uniq': ['unique'],
'zipObject': ['object']
};
/** Used to track function dependencies */
var dependencyMap = {
'after': [],
'assign': ['createIterator'],
'at': ['isString'],
'bind': ['createBound'],
'bindAll': ['bind', 'functions'],
'bindKey': ['createBound'],
'clone': ['assign', 'forEach', 'forOwn', 'getArray', 'isArray', 'isObject', 'isNode', 'releaseArray', 'slice'],
'cloneDeep': ['clone'],
'compact': [],
'compose': [],
'contains': ['basicEach', 'getIndexOf', 'isString'],
'countBy': ['createCallback', 'forEach'],
'createCallback': ['identity', 'isEqual', 'keys'],
'debounce': ['isObject'],
'defaults': ['createIterator'],
'defer': ['bind'],
'delay': [],
'difference': ['cacheIndexOf', 'createCache', 'getIndexOf', 'releaseObject'],
'escape': ['escapeHtmlChar'],
'every': ['basicEach', 'createCallback', 'isArray'],
'filter': ['basicEach', 'createCallback', 'isArray'],
'find': ['basicEach', 'createCallback', 'isArray'],
'findIndex': ['createCallback'],
'findKey': ['createCallback', 'forOwn'],
'first': ['slice'],
'flatten': ['isArray', 'overloadWrapper'],
'forEach': ['basicEach', 'createCallback', 'isArray'],
'forIn': ['createIterator'],
'forOwn': ['createIterator'],
'functions': ['forIn', 'isFunction'],
'groupBy': ['createCallback', 'forEach'],
'has': [],
'identity': [],
'indexOf': ['basicIndexOf', 'sortedIndex'],
'initial': ['slice'],
'intersection': ['cacheIndexOf', 'createCache', 'getArray', 'getIndexOf', 'releaseArray', 'releaseObject'],
'invert': ['keys'],
'invoke': ['forEach'],
'isArguments': [],
'isArray': [],
'isBoolean': [],
'isDate': [],
'isElement': [],
'isEmpty': ['forOwn', 'isArguments', 'isFunction'],
'isEqual': ['forIn', 'getArray', 'isArguments', 'isFunction', 'isNode', 'releaseArray'],
'isFinite': [],
'isFunction': [],
'isNaN': ['isNumber'],
'isNull': [],
'isNumber': [],
'isObject': [],
'isPlainObject': ['isArguments', 'shimIsPlainObject'],
'isRegExp': [],
'isString': [],
'isUndefined': [],
'keys': ['isArguments', 'isObject', 'shimKeys'],
'last': ['slice'],
'lastIndexOf': [],
'map': ['basicEach', 'createCallback', 'isArray'],
'max': ['basicEach', 'charAtCallback', 'createCallback', 'isArray', 'isString'],
'memoize': [],
'merge': ['forEach', 'forOwn', 'getArray', 'isArray', 'isObject', 'isPlainObject', 'releaseArray'],
'min': ['basicEach', 'charAtCallback', 'createCallback', 'isArray', 'isString'],
'mixin': ['forEach', 'functions'],
'noConflict': [],
'omit': ['forIn', 'getIndexOf'],
'once': [],
'pairs': ['keys'],
'parseInt': ['isString'],
'partial': ['createBound'],
'partialRight': ['createBound'],
'pick': ['forIn', 'isObject'],
'pluck': ['map'],
'random': [],
'range': [],
'reduce': ['basicEach', 'createCallback', 'isArray'],
'reduceRight': ['createCallback', 'forEach', 'isString', 'keys'],
'reject': ['createCallback', 'filter'],
'rest': ['slice'],
'result': ['isFunction'],
'runInContext': ['defaults', 'pick'],
'shuffle': ['forEach'],
'size': ['keys'],
'some': ['basicEach', 'createCallback', 'isArray'],
'sortBy': ['compareAscending', 'createCallback', 'forEach', 'getObject', 'releaseObject'],
'sortedIndex': ['createCallback', 'identity'],
'tap': ['value'],
'template': ['defaults', 'escape', 'escapeStringChar', 'keys', 'values'],
'throttle': ['debounce', 'getObject', 'isObject', 'releaseObject'],
'times': ['createCallback'],
'toArray': ['isString', 'slice', 'values'],
'transform': ['createCallback', 'createObject', 'forOwn', 'isArray'],
'unescape': ['unescapeHtmlChar'],
'union': ['isArray', 'uniq'],
'uniq': ['cacheIndexOf', 'createCache', 'getArray', 'getIndexOf', 'overloadWrapper', 'releaseArray', 'releaseObject'],
'uniqueId': [],
'unzip': ['max', 'pluck'],
'value': ['basicEach', 'forOwn', 'isArray', 'lodashWrapper'],
'values': ['keys'],
'where': ['filter'],
'without': ['difference'],
'wrap': [],
'zip': ['unzip'],
'zipObject': [],
// private methods
'basicEach': ['createIterator'],
'basicIndexOf': [],
'cacheIndexOf': ['basicIndexOf'],
'cachePush': [],
'charAtCallback': [],
'compareAscending': [],
'createBound': ['createObject', 'isFunction', 'isObject'],
'createCache': ['cachePush', 'getObject', 'releaseObject'],
'createIterator': ['getObject', 'isArguments', 'isArray', 'isString', 'iteratorTemplate', 'keys', 'releaseObject'],
'createObject': [ 'isObject', 'noop'],
'escapeHtmlChar': [],
'escapeStringChar': [],
'getArray': [],
'getIndexOf': ['basicIndexOf', 'indexOf'],
'getObject': [],
'iteratorTemplate': [],
'isNode': [],
'lodashWrapper': ['wrapperToString', 'wrapperValueOf'],
'noop': [],
'overloadWrapper': ['createCallback'],
'releaseArray': [],
'releaseObject': [],
'shimIsPlainObject': ['forIn', 'isArguments', 'isFunction', 'isNode'],
'shimKeys': ['createIterator'],
'slice': [],
'unescapeHtmlChar': [],
'wrapperToString': [],
'wrapperValueOf': [],
// method used by the `backbone` and `underscore` builds
'chain': ['value'],
'findWhere': ['where']
};
/** Used to track property dependencies */
var propDependencyMap = {
'at': ['support'],
'bind': ['support'],
'bindKey': ['indicatorObject'],
'clone': ['support'],
'createCallback': ['indicatorObject'],
'createIterator': ['objectTypes', 'support'],
'isArguments': ['support'],
'isEmpty': ['support'],
'isEqual': ['indicatorObject', 'support'],
'isObject': ['objectTypes'],
'isPlainObject': ['support'],
'isRegExp': ['objectTypes'],
'iteratorTemplate': ['support'],
'keys': ['support'],
'merge': ['indicatorObject'],
'partialRight': ['indicatorObject'],
'reduceRight': ['support'],
'shimIsPlainObject': ['support'],
'template': ['templateSettings'],
'toArray': ['support']
};
/** Used to inline `iteratorTemplate` */
var iteratorOptions = [
'args',
'array',
'bottom',
'firstArg',
'init',
'loop',
'shadowedProps',
'support',
'top',
'useHas',
'useKeys'
];
/** List of all methods */
var allMethods = _.keys(dependencyMap);
/** List of Backbone's Lo-Dash dependencies */
var backboneDependencies = [
'bind',
'bindAll',
'chain',
'clone',
'contains',
'countBy',
'defaults',
'escape',
'every',
'extend',
'filter',
'find',
'first',
'forEach',
'groupBy',
'has',
'indexOf',
'initial',
'invert',
'invoke',
'isArray',
'isEmpty',
'isEqual',
'isFunction',
'isObject',
'isRegExp',
'isString',
'keys',
'last',
'lastIndexOf',
'map',
'max',
'min',
'mixin',
'omit',
'once',
'pairs',
'pick',
'reduce',
'reduceRight',
'reject',
'rest',
'result',
'shuffle',
'size',
'some',
'sortBy',
'sortedIndex',
'toArray',
'uniqueId',
'value',
'values',
'without'
];
/** List of Lo-Dash only methods */
var lodashOnlyMethods = [
'at',
'bindKey',
'cloneDeep',
'createCallback',
'findIndex',
'findKey',
'forIn',
'forOwn',
'isPlainObject',
'merge',
'parseInt',
'partialRight',
'runInContext',
'transform',
'unzip'
];
/** List of ways to export the `lodash` function */
var exportsAll = [
'amd',
'commonjs',
'global',
'node'
];
/** List of method categories */
var methodCategories = [
'Arrays',
'Chaining',
'Collections',
'Functions',
'Objects',
'Utilities'
];
/** List of private methods */
var privateMethods = [
'basicEach',
'basicIndex',
'cacheIndexOf',
'cachePush',
'charAtCallback',
'compareAscending',
'createBound',
'createCache',
'createIterator',
'escapeHtmlChar',
'escapeStringChar',
'getArray',
'getObject',
'isNode',
'iteratorTemplate',
'lodashWrapper',
'overloadWrapper',
'releaseArray',
'releaseObject',
'shimIsPlainObject',
'shimKeys',
'slice',
'unescapeHtmlChar'
];
/** List of Lo-Dash methods */
var lodashMethods = _.without.apply(_, [allMethods, 'findWhere'].concat(privateMethods));
/** List of Underscore methods */
var underscoreMethods = _.without.apply(_, [allMethods].concat(lodashOnlyMethods, privateMethods));
/*--------------------------------------------------------------------------*/
/**
* Adds support for Underscore style chaining to the `source`.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the modified source.
*/
function addChainMethods(source) {
// add `_.chain`
source = source.replace(matchFunction(source, 'tap'), function(match) {
var indent = getIndent(match);
return match && (indent + [
'',
'/**',
' * Creates a `lodash` object that wraps the given `value`.',
' *',
' * @static',
' * @memberOf _',
' * @category Chaining',
' * @param {Mixed} value The value to wrap.',
' * @returns {Object} Returns the wrapper object.',
' * @example',
' *',
' * var stooges = [',
" * { 'name': 'moe', 'age': 40 },",
" * { 'name': 'larry', 'age': 50 },",
" * { 'name': 'curly', 'age': 60 }",
' * ];',
' *',
' * var youngest = _.chain(stooges)',
' * .sortBy(function(stooge) { return stooge.age; })',
" * .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })",
' * .first();',
" * // => 'moe is 40'",
' */',
'function chain(value) {',
' value = new lodashWrapper(value);',
' value.__chain__ = true;',
' return value;',
'}',
'',
match
].join('\n' + indent));
});
// add `wrapperChain`
source = source.replace(matchFunction(source, 'wrapperToString'), function(match) {
var indent = getIndent(match);
return match && (indent + [
'',
'/**',
' * Enables method chaining on the wrapper object.',
' *',
' * @name chain',
' * @memberOf _',
' * @category Chaining',
' * @returns {Mixed} Returns the wrapper object.',
' * @example',
' *',
' * var sum = _([1, 2, 3])',
' * .chain()',
' * .reduce(function(sum, num) { return sum + num; })',
' * .value()',
' * // => 6`',
' */',
'function wrapperChain() {',
' this.__chain__ = true;',
' return this;',
'}',
'',
match
].join('\n' + indent));
});
// remove `lodash.prototype.toString` and `lodash.prototype.valueOf` assignments
source = source.replace(/^ *lodash\.prototype\.(?:toString|valueOf) *=.+\n/gm, '');
// remove `lodash.prototype` batch method assignments
source = source.replace(/(?:\s*\/\/.*)*\n( *)forOwn\(lodash, *function\(func, *methodName\)[\s\S]+?\n\1}.+/g, '');
// replace `_.mixin`
source = replaceFunction(source, 'mixin', [
'function mixin(object) {',
' forEach(functions(object), function(methodName) {',
' var func = lodash[methodName] = object[methodName];',
'',
' lodash.prototype[methodName] = function() {',
' var args = [this.__wrapped__];',
' push.apply(args, arguments);',
'',
' var result = func.apply(lodash, args);',
' if (this.__chain__) {',
' result = new lodashWrapper(result);',
' result.__chain__ = true;',
' }',
' return result;',
' };',
' });',
'}'
].join('\n'));
// replace wrapper `Array` method assignments
source = source.replace(/^(?:(?: *\/\/.*\n)*(?: *if *\(.+\n)?( *)(basicEach|forEach)\(\['[\s\S]+?\n\1}\);(?:\n *})?\n+)+/m, function(match, indent, funcName) {
return indent + [
'// add `Array` mutator functions to the wrapper',
funcName + "(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {",
' var func = arrayRef[methodName];',
' lodash.prototype[methodName] = function() {',
' var value = this.__wrapped__;',
' func.apply(value, arguments);',
'',
' // avoid array-like object bugs with `Array#shift` and `Array#splice`',
' // in Firefox < 10 and IE < 9',
' if (!support.spliceObjects && value.length === 0) {',
' delete value[0];',
' }',
' return this;',
' };',
'});',
'',
'// add `Array` accessor functions to the wrapper',
funcName + "(['concat', 'join', 'slice'], function(methodName) {",
' var func = arrayRef[methodName];',
' lodash.prototype[methodName] = function() {',
' var value = this.__wrapped__,',
' result = func.apply(value, arguments);',
'',
' if (this.__chain__) {',
' result = new lodashWrapper(result);',
' result.__chain__ = true;',
' }',
' return result;',
' };',
'});',
''
].join('\n' + indent);
});
// replace `_.chain` assignment
source = source.replace(getMethodAssignments(source), function(match) {
return match.replace(/^( *lodash\.chain *= *)[\s\S]+?(?=;\n)/m, '$1chain')
});
// move `mixin(lodash)` to after the method assignments
source = source.replace(/(?:\s*\/\/.*)*\n( *)mixin\(lodash\).+/, '');
source = source.replace(getMethodAssignments(source), function(match) {
var indent = /^ *(?=lodash\.)/m.exec(match)[0];
return match + [
'',
'// add functions to `lodash.prototype`',
'mixin(lodash);',
''
].join('\n' + indent);
});
// move the `lodash.prototype.chain` assignment to after `mixin(lodash)`
source = source
.replace(/^ *lodash\.prototype\.chain *=[\s\S]+?;\n/m, '')
.replace(/^( *)lodash\.prototype\.value *=/m, '$1lodash.prototype.chain = wrapperChain;\n$&');
return source;
}
/**
* Adds build `commands` to the copyright/license header of the `source`.
*
* @private
* @param {String} source The source to process.
* @param {Array} [commands=[]] An array of commands.
* @returns {String} Returns the modified source.
*/
function addCommandsToHeader(source, commands) {
return source.replace(/(\/\**\n)( \*)( *@license[\s*]+)( *Lo-Dash [\w.-]+)(.*)/, function() {
// remove `node path/to/build.js` from `commands`
if (reNode.test(commands[0])) {
commands.splice(0, 2);
}
// add quotes to commands with spaces or equals signs
commands = _.map(commands, function(command) {
var separator = command.match(/[= ]/);
if (separator) {
separator = separator[0];
var pair = command.split(separator);
command = pair[0] + separator + '"' + pair[1] + '"';
}
// escape newlines, carriage returns, multi-line comment end tokens
command = command
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\*\//g, '*\\/');
return command;
});
// add build commands to copyright/license header
var parts = slice.call(arguments, 1);
return (
parts[0] +
parts[1] +
parts[2] + parts[3] + ' (Custom Build)' + parts[4] + '\n' +
parts[1] + ' Build: `lodash ' + commands.join(' ') + '`'
);
});
}
/**
* 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 The options object.
* @returns {String} Returns the compiled source.
*/
function buildTemplate(pattern, options) {
pattern || (pattern = path.join(cwd, '*.jst'));
var directory = path.dirname(pattern);
var source = [
';(function(window) {',
' var undefined;',
'',
' var objectTypes = {',
" 'function': true,",
" 'object': true",
' };',
'',
" var freeExports = objectTypes[typeof exports] && typeof require == 'function' && exports;",
'',
" var freeModule = objectTypes[typeof module] && module && module.exports == freeExports && module;",
'',
" var freeGlobal = objectTypes[typeof global] && global;",
' if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {',
' window = freeGlobal;',
' }',
'',
' 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 = cleanupCompiled(getFunctionSource(_.template(text, null, options))),
prop = filename.replace(/\..*$/, '');
source.push(" templates['" + prop.replace(/['\n\r\t]/g, '\\$&') + "'] = " + precompiled + ';', '');
}
});
source.push(
" if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {",
" define(['" + options.moduleId + "'], function(lodash) {",
' _ = lodash;',
' lodash.templates = lodash.extend(lodash.templates || {}, templates);',
' });',
" } else if (freeExports && !freeExports.nodeType) {",
" _ = require('" + options.moduleId + "');",
" if (freeModule) {",
' (freeModule.exports = templates).templates = templates;',
' } else {',
' freeExports.templates = templates;',
' }',
' } else if (_) {',
' _.templates = _.extend(_.templates || {}, templates);',
' }',
'}(this));'
);
return source.join('\n');
}
/**
* Capitalizes a given string.
*
* @private
* @param {String} string The string to capitalize.
* @returns {String} Returns the capitalized string.
*/
function capitalize(string) {
return string[0].toUpperCase() + string.slice(1);
}
/**
* Removes unnecessary semicolons and whitespace from compiled code.
*
* @private
* @param {String} source The source to process.
* @returns {String} Returns the modified source.
*/
function cleanupCompiled(source) {
return source
.replace(/\b(function) *(\()/g, '$1$2')
.replace(/([{}]) *;/g, '$1');
}
/**
* 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) {
source = removePseudoPrivates(source);
return source
// consolidate consecutive horizontal rule comment separators
.replace(/(?:\s*\/\*-+\*\/\s*){2,}/g, function(separators) {
return separators.match(/^\s*/)[0] + separators.slice(separators.lastIndexOf('/*'));
})
// remove unneeded single line comments
.replace(/(\{\s*)?(\n *\/\/.*)(\s*\})/g, function(match, prelude, comment, postlude) {
return (!prelude && postlude) ? postlude : match;
})
// remove unneeded horizontal rule comment separators
.replace(/(\{\n)\s*\/\*-+\*\/\n|^ *\/\*-+\*\/\n(\s*\})/gm, '$1$2')
// remove extraneous whitespace
.replace(/^ *\n/gm, '\n')
// remove lines with just whitespace and semicolons
.replace(/^ *;\n/gm, '')
// consolidate multiple newlines
.replace(/\n{3,}/g, '\n\n');
}
/**
* The default callback used for `build` invocations.
*
* @private
* @param {Object} data The data for the given build.
* gzip - The gzipped output of the built source
* outputPath - The path where the built source is to be written
* source - The built source output
* sourceMap - The source map output
*/
function defaultBuildCallback(data) {
var outputPath = data.outputPath,
sourceMap = data.sourceMap;
if (outputPath) {
fs.writeFileSync(outputPath, data.source, 'utf8');
if (sourceMap) {
fs.writeFileSync(path.join(path.dirname(outputPath), path.basename(outputPath, '.js') + '.map'), sourceMap, 'utf8');
}
}
}
/**
* Writes the help message to standard output.
*
* @private
*/
function displayHelp() {
console.log([
'',
' Commands:',
'',
' lodash backbone Build with only methods required by Backbone',
' lodash legacy Build tailored for older environments without ES5 support',
' lodash mobile Build without method compilation and most bug fixes for old browsers',
' lodash modern Build tailored for newer environments with ES5 support',
' lodash strict Build with `_.assign`, `_.bindAll`, & `_.defaults` 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){%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}"`)',
' lodash moduleId=... The AMD module ID of Lo-Dash, which defaults to “lodash”, used by precompiled templates',
'',
' All arguments, except `backbone`, `legacy`, `mobile`, `modern`, and `underscore`, 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 non-minified development output',
' -h, --help Display help information',
' -m, --minify Write only the minified production output',
' -o, --output Write output to a given path/filename',
' -p, --source-map Generate a source map for the minified output, using an optional source map URL',
' -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) {
var aliases = hasOwnProperty.call(realToAliasMap, methodName) && realToAliasMap[methodName];
return _.filter(aliases, function(methodName) {
return !hasOwnProperty.call(dependencyMap, methodName);
});
}
/**
* Gets the category of the given method name.
*
* @private
* @param {String} source The source to inspect.
* @param {String} methodName The method name.
* @returns {String} Returns the method name's category.
*/
function getCategory(source, methodName) {
var result = /@category +(\w+)/.exec(matchFunction(source, methodName));
if (result) {
return result[1];
}
// check for the `_.chain` alias
return methodName == 'chain' ? 'Chaining' : '';
}
/**
* Gets an array of category dependencies for a given category.
*
* @private
* @param {String} source The source to inspect.
* @param {String} category The category.
* @returns {Array} Returns an array of cetegory dependants.
*/
function getCategoryDependencies(source, category) {
var methods = _.uniq(getMethodsByCategory(source, category).reduce(function(result, methodName) {
push.apply(result, getDependencies(methodName));
return result;
}, []));
var categories = _.uniq(methods.map(function(methodName) {
return getCategory(source, methodName);
}));
return categories.filter(function(other) {
return other != category;
});
}
/**
* Gets the `createObject` fork from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the `createObject` fork.
*/
function getCreateObjectFork(source) {
var result = source.match(/(?:\s*\/\/.*)*\n( *)if *\((?:!nativeCreate)[\s\S]+?\n *};\n\1}/);
return result ? result[0] : '';
}
/**
* Gets the `_.defer` fork from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the `_.defer` fork.
*/
function getDeferFork(source) {
var result = source.match(/(?:\s*\/\/.*)*\n( *)if *\(isV8 *&& *freeModule[\s\S]+?\n\1}/);
return result ? result[0] : '';
}
/**
* Gets an array of depenants for the given method name(s).
*
* @private
* @param {String} methodName A method name or array of method names.
* @param {Boolean} [isShallow=false] A flag to indicate getting only the immediate dependants.
* @param- {Array} [stackA=[]] Internally used track queried methods.
* @returns {Array} Returns an array of method dependants.
*/
function getDependants(methodName, isShallow, stack) {
var methodNames = _.isArray(methodName) ? methodName : [methodName];
stack || (stack = []);
// iterate over the `dependencyMap`, adding names of methods
// that have the `methodName` as a dependency
return _.uniq(_.reduce(dependencyMap, function(result, dependencies, otherName) {
if (!_.contains(stack, otherName) && _.some(methodNames, function(methodName) {
return _.contains(dependencies, methodName);
})) {
stack.push(otherName);
result.push(otherName);
if (isShallow) {
result.push.apply(result, getDependants(otherName, isShallow, stack));
}
}
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 method name or array of dependencies to query.
* @param {Boolean} [isShallow=false] A flag to indicate getting only the immediate dependencies.
* @param- {Array} [stackA=[]] Internally used track queried methods.
* @returns {Array} Returns an array of method dependencies.
*/
function getDependencies(methodName, isShallow, stack) {
var dependencies = _.isArray(methodName)
? methodName
: (hasOwnProperty.call(dependencyMap, methodName) && dependencyMap[methodName]);
if (!dependencies || !dependencies.length) {
return [];
}
if (isShallow) {
return dependencies.slice();
}
stack || (stack = []);
// recursively accumulate the dependencies of the `methodName` function, and
// the dependencies of its dependencies, and so on
return _.uniq(dependencies.reduce(function(result, otherName) {
if (!_.contains(stack, otherName)) {
stack.push(otherName);
result.push.apply(result, getDependencies(otherName, isShallow, stack).concat(otherName));
}
return result;
}, []));
}
/**
* Gets the formatted source of the given function.
*
* @private
* @param {Function} func The function to process.
* @param {String} indent The function indent.
* @returns {String} Returns the formatted source.
*/
function getFunctionSource(func, indent) {
var source = func.source || (func + '');
if (indent == null) {
indent = ' ';
}
// format leading whitespace
return source.replace(/\n(?:.*)/g, function(match, index) {
match = match.slice(1);
return (
'\n' + indent +
(match == '}' && !_.contains(source, '}', index + 2) ? '' : ' ')
) + match;
});
}
/**
* Gets the indent of the given function.
*
* @private
* @param {Function} func The function to process.
* @returns {String} Returns the indent.
*/
function getIndent(func) {
return /^ *(?=\S)/m.exec(func.source || func)[0];
}
/**
* Gets the `_.isArguments` fork from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the `isArguments` fork.
*/
function getIsArgumentsFork(source) {
var result = source.match(/(?:\s*\/\/.*)*\n( *)if *\((?:!support\.argsClass|!isArguments)[\s\S]+?\n *};\n\1}/);
return result ? result[0] : '';
}
/**
* Gets the `_.isArray` fork from `source`.
*
* @private
* @param {String} source The source to inspect.
* @returns {String} Returns the `isArray` fork.
*/
function getIsArrayFork(source) {
return matchFunction(source, 'isArray')
.replace(/^[\s\S]+?=\s*nativeIsArray\b/, '')
.replace(/[;\s]+$/, '');
}