-
Notifications
You must be signed in to change notification settings - Fork 698
/
build.js
1594 lines (1418 loc) · 68 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
/**
* @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
/*jslint plusplus: true, nomen: true, regexp: true */
/*global define, require, requirejs */
define(function (require) {
'use strict';
var build, buildBaseConfig,
lang = require('lang'),
prim = require('prim'),
logger = require('logger'),
file = require('env!env/file'),
parse = require('parse'),
optimize = require('optimize'),
pragma = require('pragma'),
transform = require('transform'),
load = require('env!env/load'),
requirePatch = require('requirePatch'),
quit = require('env!env/quit'),
commonJs = require('commonJs'),
hasProp = lang.hasProp,
getOwn = lang.getOwn,
falseProp = lang.falseProp,
endsWithSemiColonRegExp = /;\s*$/;
prim.nextTick = function (fn) {
fn();
};
//Now map require to the outermost requirejs, now that we have
//local dependencies for this module. The rest of the require use is
//manipulating the requirejs loader.
require = requirejs;
//Caching function for performance. Attached to
//require so it can be reused in requirePatch.js. _cachedRawText
//set up by requirePatch.js
require._cacheReadAsync = function (path, encoding) {
var d;
if (lang.hasProp(require._cachedRawText, path)) {
d = prim();
d.resolve(require._cachedRawText[path]);
return d.promise;
} else {
return file.readFileAsync(path, encoding).then(function (text) {
require._cachedRawText[path] = text;
return text;
});
}
};
buildBaseConfig = {
appDir: "",
pragmas: {},
paths: {},
optimize: "uglify",
optimizeCss: "standard.keepLines",
inlineText: true,
isBuild: true,
optimizeAllPluginResources: false,
findNestedDependencies: false,
preserveLicenseComments: true,
//By default, all files/directories are copied, unless
//they match this regexp, by default just excludes .folders
dirExclusionRegExp: file.dirExclusionRegExp,
_buildPathToModuleIndex: {}
};
/**
* Some JS may not be valid if concatenated with other JS, in particular
* the style of omitting semicolons and rely on ASI. Add a semicolon in
* those cases.
*/
function addSemiColon(text) {
if (endsWithSemiColonRegExp.test(text)) {
return text;
} else {
return text + ";";
}
}
function endsWithSlash(dirName) {
if (dirName.charAt(dirName.length - 1) !== "/") {
dirName += "/";
}
return dirName;
}
//Method used by plugin writeFile calls, defined up here to avoid
//jslint warning about "making a function in a loop".
function makeWriteFile(namespace, layer) {
function writeFile(name, contents) {
logger.trace('Saving plugin-optimized file: ' + name);
file.saveUtf8File(name, contents);
}
writeFile.asModule = function (moduleName, fileName, contents) {
writeFile(fileName,
build.toTransport(namespace, moduleName, fileName, contents, layer));
};
return writeFile;
}
/**
* Main API entry point into the build. The args argument can either be
* an array of arguments (like the onese passed on a command-line),
* or it can be a JavaScript object that has the format of a build profile
* file.
*
* If it is an object, then in addition to the normal properties allowed in
* a build profile file, the object should contain one other property:
*
* The object could also contain a "buildFile" property, which is a string
* that is the file path to a build profile that contains the rest
* of the build profile directives.
*
* This function does not return a status, it should throw an error if
* there is a problem completing the build.
*/
build = function (args) {
var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
i, j, errorMod,
stackRegExp = /( {4}at[^\n]+)\n/,
standardIndent = ' ';
return prim().start(function () {
if (!args || lang.isArray(args)) {
if (!args || args.length < 1) {
logger.error("build.js buildProfile.js\n" +
"where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
return undefined;
}
//Next args can include a build file path as well as other build args.
//build file path comes first. If it does not contain an = then it is
//a build file path. Otherwise, just all build args.
if (args[0].indexOf("=") === -1) {
buildFile = args[0];
args.splice(0, 1);
}
//Remaining args are options to the build
cmdConfig = build.convertArrayToObject(args);
cmdConfig.buildFile = buildFile;
} else {
cmdConfig = args;
}
return build._run(cmdConfig);
}).then(null, function (e) {
errorMsg = e.toString();
errorTree = e.moduleTree;
stackMatch = stackRegExp.exec(errorMsg);
if (stackMatch) {
errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
}
//If a module tree that shows what module triggered the error,
//print it out.
if (errorTree && errorTree.length > 0) {
errorMsg += '\nIn module tree:\n';
for (i = errorTree.length - 1; i > -1; i--) {
errorMod = errorTree[i];
if (errorMod) {
for (j = errorTree.length - i; j > -1; j--) {
errorMsg += standardIndent;
}
errorMsg += errorMod + '\n';
}
}
logger.error(errorMsg);
}
errorStack = e.stack;
if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
errorMsg += '\n' + errorStack;
} else {
if (!stackMatch && errorStack) {
//Just trim out the first "at" in the stack.
stackMatch = stackRegExp.exec(errorStack);
if (stackMatch) {
errorMsg += '\n' + stackMatch[0] || '';
}
}
}
if (logger.level > logger.ERROR) {
throw new Error(errorMsg);
} else {
logger.error(errorMsg);
quit(1);
}
});
};
build._run = function (cmdConfig) {
var buildPaths, fileName, fileNames,
paths, i,
baseConfig, config,
modules, builtModule, srcPath, buildContext,
destPath, moduleMap, parentModuleMap, context,
resources, resource, plugin, fileContents,
pluginProcessed = {},
buildFileContents = "",
pluginCollector = {};
return prim().start(function () {
var prop, moduleName;
//Can now run the patches to require.js to allow it to be used for
//build generation. Do it here instead of at the top of the module
//because we want normal require behavior to load the build tool
//then want to switch to build mode.
requirePatch();
config = build.createConfig(cmdConfig);
paths = config.paths;
if (config.logLevel) {
logger.logLevel(config.logLevel);
}
//Remove the previous build dir, in case it contains source transforms,
//like the ones done with onBuildRead and onBuildWrite.
if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
file.deleteFile(config.dir);
}
if (!config.out && !config.cssIn) {
//This is not just a one-off file build but a full build profile, with
//lots of files to process.
//First copy all the baseUrl content
file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
//Adjust baseUrl if config.appDir is in play, and set up build output paths.
buildPaths = {};
if (config.appDir) {
//All the paths should be inside the appDir, so just adjust
//the paths to use the dirBaseUrl
for (prop in paths) {
if (hasProp(paths, prop)) {
buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
}
}
} else {
//If no appDir, then make sure to copy the other paths to this directory.
for (prop in paths) {
if (hasProp(paths, prop)) {
//Set up build path for each path prefix, but only do so
//if the path falls out of the current baseUrl
if (paths[prop].indexOf(config.baseUrl) === 0) {
buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
} else {
buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop.replace(/\./g, "/");
//Make sure source path is fully formed with baseUrl,
//if it is a relative URL.
srcPath = paths[prop];
if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
srcPath = config.baseUrl + srcPath;
}
destPath = config.dirBaseUrl + buildPaths[prop];
//Skip empty: paths
if (srcPath !== 'empty:') {
//If the srcPath is a directory, copy the whole directory.
if (file.exists(srcPath) && file.isDirectory(srcPath)) {
//Copy files to build area. Copy all files (the /\w/ regexp)
file.copyDir(srcPath, destPath, /\w/, true);
} else {
//Try a .js extension
srcPath += '.js';
destPath += '.js';
file.copyFile(srcPath, destPath);
}
}
}
}
}
}
}
//Figure out source file location for each module layer. Do this by seeding require
//with source area configuration. This is needed so that later the module layers
//can be manually copied over to the source area, since the build may be
//require multiple times and the above copyDir call only copies newer files.
require({
baseUrl: config.baseUrl,
paths: paths,
packagePaths: config.packagePaths,
packages: config.packages
});
buildContext = require.s.contexts._;
modules = config.modules;
if (modules) {
modules.forEach(function (module) {
if (module.name) {
module._sourcePath = buildContext.nameToUrl(module.name);
//If the module does not exist, and this is not a "new" module layer,
//as indicated by a true "create" property on the module, and
//it is not a plugin-loaded resource, then throw an error.
if (!file.exists(module._sourcePath) && !module.create &&
module.name.indexOf('!') === -1) {
throw new Error("ERROR: module path does not exist: " +
module._sourcePath + " for module named: " + module.name +
". Path is relative to: " + file.absPath('.'));
}
}
});
}
if (config.out) {
//Just set up the _buildPath for the module layer.
require(config);
if (!config.cssIn) {
config.modules[0]._buildPath = typeof config.out === 'function' ?
'FUNCTION' : config.out;
}
} else if (!config.cssIn) {
//Now set up the config for require to use the build area, and calculate the
//build file locations. Pass along any config info too.
baseConfig = {
baseUrl: config.dirBaseUrl,
paths: buildPaths
};
lang.mixin(baseConfig, config);
require(baseConfig);
if (modules) {
modules.forEach(function (module) {
if (module.name) {
module._buildPath = buildContext.nameToUrl(module.name, null);
if (!module.create) {
file.copyFile(module._sourcePath, module._buildPath);
}
}
});
}
}
//Run CSS optimizations before doing JS module tracing, to allow
//things like text loader plugins loading CSS to get the optimized
//CSS.
if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
buildFileContents += optimize.css(config.dir, config);
}
}).then(function () {
var actions = [];
if (modules) {
actions = modules.map(function (module, i) {
return function () {
//Save off buildPath to module index in a hash for quicker
//lookup later.
config._buildPathToModuleIndex[module._buildPath] = i;
//Call require to calculate dependencies.
return build.traceDependencies(module, config)
.then(function (layer) {
module.layer = layer;
});
};
});
return prim.serial(actions);
}
}).then(function () {
var actions;
if (modules) {
//Now build up shadow layers for anything that should be excluded.
//Do this after tracing dependencies for each module, in case one
//of those modules end up being one of the excluded values.
actions = modules.map(function (module) {
return function () {
var actions;
if (module.exclude) {
module.excludeLayers = [];
return prim.serial(module.exclude.map(function (exclude, i) {
return function () {
//See if it is already in the list of modules.
//If not trace dependencies for it.
var found = build.findBuildModule(exclude, modules);
if (found) {
module.excludeLayers[i] = found;
} else {
return build.traceDependencies({name: exclude}, config)
.then(function (layer) {
module.excludeLayers[i] = { layer: layer };
});
}
};
}));
}
};
});
return prim.serial(actions);
}
}).then(function () {
if (modules) {
return prim.serial(modules.map(function (module) {
return function () {
if (module.exclude) {
//module.exclude is an array of module names. For each one,
//get the nested dependencies for it via a matching entry
//in the module.excludeLayers array.
module.exclude.forEach(function (excludeModule, i) {
var excludeLayer = module.excludeLayers[i].layer, map = excludeLayer.buildPathMap, prop;
for (prop in map) {
if (hasProp(map, prop)) {
build.removeModulePath(prop, map[prop], module.layer);
}
}
});
}
if (module.excludeShallow) {
//module.excludeShallow is an array of module names.
//shallow exclusions are just that module itself, and not
//its nested dependencies.
module.excludeShallow.forEach(function (excludeShallowModule) {
var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
if (path) {
build.removeModulePath(excludeShallowModule, path, module.layer);
}
});
}
//Flatten them and collect the build output for each module.
return build.flattenModule(module, module.layer, config).then(function (builtModule) {
//Save it to a temp file for now, in case there are other layers that
//contain optimized content that should not be included in later
//layer optimizations. See issue #56.
if (module._buildPath === 'FUNCTION') {
module._buildText = builtModule.text;
} else {
file.saveUtf8File(module._buildPath + '-temp', builtModule.text);
}
buildFileContents += builtModule.buildText;
});
};
}));
}
}).then(function () {
var moduleName;
if (modules) {
//Now move the build layers to their final position.
modules.forEach(function (module) {
var finalPath = module._buildPath;
if (finalPath !== 'FUNCTION') {
if (file.exists(finalPath)) {
file.deleteFile(finalPath);
}
file.renameFile(finalPath + '-temp', finalPath);
//And finally, if removeCombined is specified, remove
//any of the files that were used in this layer.
//Be sure not to remove other build layers.
if (config.removeCombined) {
module.layer.buildFilePaths.forEach(function (path) {
if (file.exists(path) && !modules.some(function (mod) {
return mod._buildPath === path;
})) {
file.deleteFile(path);
}
});
}
}
});
}
//If removeCombined in play, remove any empty directories that
//may now exist because of its use
if (config.removeCombined && !config.out && config.dir) {
file.deleteEmptyDirs(config.dir);
}
//Do other optimizations.
if (config.out && !config.cssIn) {
//Just need to worry about one JS file.
fileName = config.modules[0]._buildPath;
if (fileName === 'FUNCTION') {
config.modules[0]._buildText = optimize.js(fileName,
config.modules[0]._buildText,
null,
config);
} else {
optimize.jsFile(fileName, null, fileName, config);
}
} else if (!config.cssIn) {
//Normal optimizations across modules.
//JS optimizations.
fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
fileNames.forEach(function (fileName, i) {
var cfg, override, moduleIndex;
//Generate the module name from the config.dir root.
moduleName = fileName.replace(config.dir, '');
//Get rid of the extension
moduleName = moduleName.substring(0, moduleName.length - 3);
//If there is an override for a specific layer build module,
//and this file is that module, mix in the override for use
//by optimize.jsFile.
moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
//Normalize, since getOwn could have returned undefined
moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
//Try to avoid extra work if the other files do not need to
//be read. Build layers should be processed at the very
//least for optimization.
if (moduleIndex > -1 || !config.skipDirOptimize ||
config.normalizeDirDefines === "all" ||
config.cjsTranslate) {
//Convert the file to transport format, but without a name
//inserted (by passing null for moduleName) since the files are
//standalone, one module per file.
fileContents = file.readFile(fileName);
//For builds, if wanting cjs translation, do it now, so that
//the individual modules can be loaded cross domain via
//plain script tags.
if (config.cjsTranslate) {
fileContents = commonJs.convert(fileName, fileContents);
}
//Only do transport normalization if this is not a build
//layer (since it was already normalized) and if
//normalizeDirDefines indicated all should be done.
if (moduleIndex === -1 && config.normalizeDirDefines === "all") {
fileContents = build.toTransport(config.namespace,
null,
fileName,
fileContents);
}
override = moduleIndex > -1 ?
config.modules[moduleIndex].override : null;
if (override) {
cfg = build.createOverrideConfig(config, override);
} else {
cfg = config;
}
if (moduleIndex > -1 || !config.skipDirOptimize) {
optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
}
}
});
//Normalize all the plugin resources.
context = require.s.contexts._;
for (moduleName in pluginCollector) {
if (hasProp(pluginCollector, moduleName)) {
parentModuleMap = context.makeModuleMap(moduleName);
resources = pluginCollector[moduleName];
for (i = 0; i < resources.length; i++) {
resource = resources[i];
moduleMap = context.makeModuleMap(resource, parentModuleMap);
if (falseProp(context.plugins, moduleMap.prefix)) {
//Set the value in context.plugins so it
//will be evaluated as a full plugin.
context.plugins[moduleMap.prefix] = true;
//Do not bother if the plugin is not available.
if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
continue;
}
//Rely on the require in the build environment
//to be synchronous
context.require([moduleMap.prefix]);
//Now that the plugin is loaded, redo the moduleMap
//since the plugin will need to normalize part of the path.
moduleMap = context.makeModuleMap(resource, parentModuleMap);
}
//Only bother with plugin resources that can be handled
//processed by the plugin, via support of the writeFile
//method.
if (falseProp(pluginProcessed, moduleMap.id)) {
//Only do the work if the plugin was really loaded.
//Using an internal access because the file may
//not really be loaded.
plugin = getOwn(context.defined, moduleMap.prefix);
if (plugin && plugin.writeFile) {
plugin.writeFile(
moduleMap.prefix,
moduleMap.name,
require,
makeWriteFile(
config.namespace
),
context.config
);
}
pluginProcessed[moduleMap.id] = true;
}
}
}
}
//console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
//All module layers are done, write out the build.txt file.
file.saveUtf8File(config.dir + "build.txt", buildFileContents);
}
//If just have one CSS file to optimize, do that here.
if (config.cssIn) {
buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
}
if (typeof config.out === 'function') {
config.out(config.modules[0]._buildText);
}
//Print out what was built into which layers.
if (buildFileContents) {
logger.info(buildFileContents);
return buildFileContents;
}
return '';
});
};
/**
* Converts command line args like "paths.foo=../some/path"
* result.paths = { foo: '../some/path' } where prop = paths,
* name = paths.foo and value = ../some/path, so it assumes the
* name=value splitting has already happened.
*/
function stringDotToObj(result, name, value) {
var parts = name.split('.'),
prop = parts[0];
parts.forEach(function (prop, i) {
if (i === parts.length - 1) {
result[prop] = value;
} else {
if (falseProp(result, prop)) {
result[prop] = {};
}
result = result[prop];
}
});
}
build.objProps = {
paths: true,
wrap: true,
pragmas: true,
pragmasOnSave: true,
has: true,
hasOnSave: true,
uglify: true,
closure: true,
map: true
};
build.hasDotPropMatch = function (prop) {
var dotProp,
index = prop.indexOf('.');
if (index !== -1) {
dotProp = prop.substring(0, index);
return hasProp(build.objProps, dotProp);
}
return false;
};
/**
* Converts an array that has String members of "name=value"
* into an object, where the properties on the object are the names in the array.
* Also converts the strings "true" and "false" to booleans for the values.
* member name/value pairs, and converts some comma-separated lists into
* arrays.
* @param {Array} ary
*/
build.convertArrayToObject = function (ary) {
var result = {}, i, separatorIndex, prop, value,
needArray = {
"include": true,
"exclude": true,
"excludeShallow": true,
"insertRequire": true
};
for (i = 0; i < ary.length; i++) {
separatorIndex = ary[i].indexOf("=");
if (separatorIndex === -1) {
throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
}
value = ary[i].substring(separatorIndex + 1, ary[i].length);
if (value === "true") {
value = true;
} else if (value === "false") {
value = false;
}
prop = ary[i].substring(0, separatorIndex);
//Convert to array if necessary
if (getOwn(needArray, prop)) {
value = value.split(",");
}
if (build.hasDotPropMatch(prop)) {
stringDotToObj(result, prop, value);
} else {
result[prop] = value;
}
}
return result; //Object
};
build.makeAbsPath = function (path, absFilePath) {
if (!absFilePath) {
return path;
}
//Add abspath if necessary. If path starts with a slash or has a colon,
//then already is an abolute path.
if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
path = absFilePath +
(absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
path;
path = file.normalize(path);
}
return path.replace(lang.backSlashRegExp, '/');
};
build.makeAbsObject = function (props, obj, absFilePath) {
var i, prop;
if (obj) {
for (i = 0; i < props.length; i++) {
prop = props[i];
if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
}
}
}
};
/**
* For any path in a possible config, make it absolute relative
* to the absFilePath passed in.
*/
build.makeAbsConfig = function (config, absFilePath) {
var props, prop, i;
props = ["appDir", "dir", "baseUrl"];
for (i = 0; i < props.length; i++) {
prop = props[i];
if (getOwn(config, prop)) {
//Add abspath if necessary, make sure these paths end in
//slashes
if (prop === "baseUrl") {
config.originalBaseUrl = config.baseUrl;
if (config.appDir) {
//If baseUrl with an appDir, the baseUrl is relative to
//the appDir, *not* the absFilePath. appDir and dir are
//made absolute before baseUrl, so this will work.
config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
} else {
//The dir output baseUrl is same as regular baseUrl, both
//relative to the absFilePath.
config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
}
} else {
config[prop] = build.makeAbsPath(config[prop], absFilePath);
}
config[prop] = endsWithSlash(config[prop]);
}
}
build.makeAbsObject(["out", "cssIn"], config, absFilePath);
build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
};
build.nestedMix = {
paths: true,
has: true,
hasOnSave: true,
pragmas: true,
pragmasOnSave: true
};
/**
* Mixes additional source config into target config, and merges some
* nested config, like paths, correctly.
*/
function mixConfig(target, source) {
var prop, value;
for (prop in source) {
if (hasProp(source, prop)) {
//If the value of the property is a plain object, then
//allow a one-level-deep mixing of it.
value = source[prop];
if (typeof value === 'object' && value &&
!lang.isArray(value) && !lang.isFunction(value) &&
!lang.isRegExp(value)) {
target[prop] = lang.mixin({}, target[prop], value, true);
} else {
target[prop] = value;
}
}
}
}
/**
* Converts a wrap.startFile or endFile to be start/end as a string.
* the startFile/endFile values can be arrays.
*/
function flattenWrapFile(wrap, keyName, absFilePath) {
var keyFileName = keyName + 'File';
if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
wrap[keyName] = '';
if (typeof wrap[keyFileName] === 'string') {
wrap[keyFileName] = [wrap[keyFileName]];
}
wrap[keyFileName].forEach(function (fileName) {
wrap[keyName] += (wrap[keyName] ? '\n' : '') +
file.readFile(build.makeAbsPath(fileName, absFilePath));
});
} else if (wrap[keyName] === null || wrap[keyName] === undefined) {
//Allow missing one, just set to empty string.
wrap[keyName] = '';
} else if (typeof wrap[keyName] !== 'string') {
throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
}
}
/**
* Creates a config object for an optimization build.
* It will also read the build profile if it is available, to create
* the configuration.
*
* @param {Object} cfg config options that take priority
* over defaults and ones in the build file. These options could
* be from a command line, for instance.
*
* @param {Object} the created config object.
*/
build.createConfig = function (cfg) {
/*jslint evil: true */
var config = {}, buildFileContents, buildFileConfig, mainConfig,
mainConfigFile, mainConfigPath, prop, buildFile, absFilePath;
//Make sure all paths are relative to current directory.
absFilePath = file.absPath('.');
build.makeAbsConfig(cfg, absFilePath);
build.makeAbsConfig(buildBaseConfig, absFilePath);
lang.mixin(config, buildBaseConfig);
lang.mixin(config, cfg, true);
if (config.buildFile) {
//A build file exists, load it to get more config.
buildFile = file.absPath(config.buildFile);
//Find the build file, and make sure it exists, if this is a build
//that has a build profile, and not just command line args with an in=path
if (!file.exists(buildFile)) {
throw new Error("ERROR: build file does not exist: " + buildFile);
}
absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
//Load build file options.
buildFileContents = file.readFile(buildFile);
try {
buildFileConfig = eval("(" + buildFileContents + ")");
build.makeAbsConfig(buildFileConfig, absFilePath);
//Mix in the config now so that items in mainConfigFile can
//be resolved relative to them if necessary, like if appDir
//is set here, but the baseUrl is in mainConfigFile. Will
//re-mix in the same build config later after mainConfigFile
//is processed, since build config should take priority.
mixConfig(config, buildFileConfig);
} catch (e) {
throw new Error("Build file " + buildFile + " is malformed: " + e);
}
}
mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
if (mainConfigFile) {
mainConfigFile = build.makeAbsPath(mainConfigFile, absFilePath);
if (!file.exists(mainConfigFile)) {
throw new Error(mainConfigFile + ' does not exist.');
}
try {
mainConfig = parse.findConfig(file.readFile(mainConfigFile)).config;
} catch (configError) {
throw new Error('The config in mainConfigFile ' +
mainConfigFile +
' cannot be used because it cannot be evaluated' +
' correctly while running in the optimizer. Try only' +
' using a config that is also valid JSON, or do not use' +
' mainConfigFile and instead copy the config values needed' +
' into a build file or command line arguments given to the optimizer.');
}
if (mainConfig) {
mainConfigPath = mainConfigFile.substring(0, mainConfigFile.lastIndexOf('/'));
//Add in some existing config, like appDir, since they can be
//used inside the mainConfigFile -- paths and baseUrl are
//relative to them.
if (config.appDir && !mainConfig.appDir) {
mainConfig.appDir = config.appDir;
}
//If no baseUrl, then use the directory holding the main config.
if (!mainConfig.baseUrl) {
mainConfig.baseUrl = mainConfigPath;
}
build.makeAbsConfig(mainConfig, mainConfigPath);
mixConfig(config, mainConfig);
}
}
//Mix in build file config, but only after mainConfig has been mixed in.
if (buildFileConfig) {
mixConfig(config, buildFileConfig);
}
//Re-apply the override config values. Command line
//args should take precedence over build file values.
mixConfig(config, cfg);
//Fix paths to full paths so that they can be adjusted consistently
//lately to be in the output area.
lang.eachProp(config.paths, function (value, prop) {
if (lang.isArray(value)) {
throw new Error('paths fallback not supported in optimizer. ' +
'Please provide a build config path override ' +
'for ' + prop);
}
config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
});
//Set final output dir
if (hasProp(config, "baseUrl")) {
if (config.appDir) {
config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
} else {
config.dirBaseUrl = config.dir || config.baseUrl;
}
//Make sure dirBaseUrl ends in a slash, since it is
//concatenated with other strings.
config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
}
//Check for errors in config
if (config.main) {
throw new Error('"main" passed as an option, but the ' +
'supported option is called "name".');
}
if (!config.name && !config.modules && !config.include && !config.cssIn) {
throw new Error('Missing either a "name", "include" or "modules" ' +
'option');
}
if (config.cssIn) {
if (config.dir || config.appDir) {
throw new Error('cssIn is only for the output of single file ' +
'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
}
if (!config.out) {
throw new Error('"out" option missing.');