This repository was archived by the owner on Oct 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathbuilder.js
More file actions
458 lines (374 loc) · 13.9 KB
/
builder.js
File metadata and controls
458 lines (374 loc) · 13.9 KB
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
var Promise = require('rsvp').Promise;
var System = require('systemjs');
var asp = require('rsvp').denodeify;
var fs = require('fs');
var path = require('path');
var extend = require('./utils').extend;
var attachCompilers = require('./compile').attachCompilers;
var compileTree = require('./compile').compileTree;
var compileLoad = require('./compile').compileLoad;
var writeOutputs = require('./output').writeOutputs;
var traceExpression = require('./arithmetic').traceExpression;
var Trace = require('./trace');
var getCanonicalName = require('./utils').getCanonicalName;
var profile = require('./profile');
require('rsvp').on('error', function(reason) {
throw new Error('Unhandled promise rejection.\n' + reason && reason.stack || reason || '' + '\n');
});
function Builder(baseURL, cfg) {
if (typeof baseURL == 'object') {
cfg = baseURL;
baseURL = null;
}
this.loader = null;
this.reset();
if (baseURL)
this.config({ baseURL: baseURL });
// config passed to constructor will
// be saved for future .reset() calls
if (typeof cfg == 'object')
this.config(cfg, true, !!baseURL);
else if (typeof cfg == 'string')
this.loadConfigSync(cfg, true, !!baseURL);
}
Builder.prototype.reset = function(baseLoader) {
baseLoader = baseLoader || this.loader || System;
var loader = this.loader = new baseLoader.constructor();
var pluginLoader = loader.pluginLoader = new baseLoader.constructor();
loader.constructor = pluginLoader.constructor = baseLoader.constructor;
loader.baseURL = pluginLoader.baseURL = baseLoader.baseURL;
loader.normalize = pluginLoader.normalize = baseLoader.normalize;
loader.normalizeSync = pluginLoader.normalizeSync = baseLoader.normalizeSync;
// store original hooks for next reset
loader.originalHooks = baseLoader.originalHooks || {
locate: baseLoader.locate,
fetch: baseLoader.fetch,
translate: baseLoader.translate,
instantiate: baseLoader.instantiate
};
loader.locate = pluginLoader.locate = loader.originalHooks.locate;
loader.fetch = pluginLoader.fetch = loader.originalHooks.fetch;
loader.translate = pluginLoader.translate = loader.originalHooks.translate;
loader.instantiate = pluginLoader.instantiate = loader.originalHooks.instantiate;
loaderConfig = loader.config;
loader.config = function(cfg) {
loaderConfig.call(loader, cfg);
loader.pluginLoader.config(cfg);
};
loader.builder = true;
this.getCanonicalName = getCanonicalName.bind(null, this.loader);
this.loader.getCanonicalName = this.getCanonicalName;
attachCompilers(loader);
global.System = loader;
// this allows us to normalize package conditionals into package conditionals
// package environment normalization handling for fallbacks,
// which dont resolve in the loader itself unlike other conditionals which
// have this condition inlined under loader.builder in conditionals.js
var loaderNormalize = loader.normalize;
loader.normalize = function(name, parentName, parentAddress) {
var pkgConditional;
var pkgConditionalIndex = name.indexOf('#:');
if (pkgConditionalIndex != -1) {
pkgConditional = name.substr(pkgConditionalIndex);
name = name.substr(0, pkgConditionalIndex) + '/';
}
return loaderNormalize.call(this, name, parentName, parentAddress)
.then(function(normalized) {
if (pkgConditional)
normalized = normalized.substr(0, normalized.length - 1) + pkgConditional;
return normalized;
});
};
var loaderNormalizeSync = loader.normalizeSync;
loader.normalizeSync = function(name, parentName, parentAddress) {
var pkgConditional;
var pkgConditionalIndex = name.indexOf('#:');
if (pkgConditionalIndex != -1) {
pkgConditional = name.substr(pkgConditionalIndex);
name = name.substr(0, pkgConditionalIndex) + '/';
}
var normalized = loaderNormalizeSync.call(this, name, parentName, parentAddress);
if (pkgConditional)
normalized = normalized.substr(0, normalized.length - 1) + pkgConditional;
return normalized;
};
// add a local fetch cache to the loader
// useful for plugin duplications of hooks
var fetchCache = {};
var loaderFetch = loader.fetch;
loader.fetch = pluginLoader.fetch = function(load) {
if (fetchCache[load.name])
return fetchCache[load.name];
return Promise.resolve(loaderFetch.call(this, load)).then(function(source) {
fetchCache[load.name] = source;
return source;
});
};
if (this.resetConfig)
executeConfigFile.call(this, false, true, this.resetConfig);
// clear the cache
this.setCache({});
};
Builder.prototype.setCache = function(cacheObj) {
this.cache = {
compile: cacheObj.compile || { encodings: {}, loads: {} },
trace: cacheObj.trace || {}
};
this.tracer = new Trace(this.loader, this.cache.trace);
};
Builder.prototype.getCache = function() {
return this.cache;
};
function executeConfigFile(saveForReset, ignoreBaseURL, source) {
if (saveForReset)
this.resetConfig = source;
var builder = this;
var curSystem = global.System;
var configSystem = global.System = {
config: function(cfg) {
builder.config(cfg, ignoreBaseURL);
}
};
// jshint evil:true
new Function(source.toString()).call(global);
global.System = curSystem;
}
Builder.prototype.loadConfig = function(configFile, saveForReset, ignoreBaseURL) {
return asp(fs.readFile)(configFile)
.then(executeConfigFile.bind(this, saveForReset, ignoreBaseURL))
};
Builder.prototype.loadConfigSync = function(configFile, saveForReset, ignoreBaseURL) {
var source = fs.readFileSync(configFile);
executeConfigFile.call(this, saveForReset, ignoreBaseURL, source);
};
// note ignore argument is part of API
Builder.prototype.config = function(config, ignoreBaseURL) {
var cfg = {};
for (var p in config) {
if (ignoreBaseURL && p == 'baseURL' || p == 'bundles' || p == 'depCache')
continue;
cfg[p] = config[p];
}
this.loader.config(cfg);
};
/*
* Builder Operations
*/
function processTraceOpts(options, defaults) {
var opts = {
// conditional tracing options
browser: undefined,
node: undefined,
traceAllConditionals: true,
conditions: {},
traceConditionsOnly: false
};
extend(opts, defaults)
extend(opts, options);
// conditional tracing defaults
if (typeof opts.browser == 'boolean' || typeof opts.node == 'boolean') {
// browser true/false -> node is opposite
if (typeof opts.browser == 'boolean' && typeof opts.node != 'boolean')
opts.node = !opts.browser;
// node true/false -> browser is opposite
else if (typeof opts.node == 'boolean' && typeof opts.browser != 'boolean')
opts.browser = !opts.node;
// browser, node -> browser, ~browser, node, ~node
// !browser, node -> ~browser, node
// browser, !node -> browser, ~node
// !browser, !node -> ~browser, ~node
opts.conditions['@system-env|browser'] = opts.browser;
opts.conditions['~@system-env|browser'] = opts.browser === true ? opts.node : !opts.browser;
opts.conditions['@system-env|node'] = opts.node;
opts.conditions['~@system-env|node'] = opts.node === true ? opts.browser : !opts.node;
}
return opts;
}
Builder.prototype.trace = function(expression, opts) {
if (opts && opts.config)
this.config(opts.config);
return traceExpression(this, expression, processTraceOpts(opts));
};
function processCompileOpts(options, defaults) {
// NB deprecate these warnings
// all of the below features were undocumented and experimental, so deprecation needn't be long
options = options || {};
if ('sfxFormat' in options) {
console.warn('SystemJS Builder "sfxFormat" is deprecated and has been renamed to "format".');
options.format = options.sfxFormat;
}
if ('sfxEncoding' in options) {
console.warn('SystemJS Builder "sfxEncoding" is deprecated and has been renamed to "encodeNames".');
options.encodeNames = sfxEncoding;
}
if ('sfxGlobals' in options) {
console.warn('SystemJS Builder "sfxGlobals" is deprecated and has been renamed to "globalDeps".');
options.globalDeps = options.sfxGlobals;
}
if ('sfxGlobalName' in options) {
console.warn('SystemJS Builder "sfxGlobalName" is deprecated and has been renamed to "globalName".');
options.globalName = options.sfxGlobalName;
}
var opts = {
normalize: true,
anonymous: false,
systemGlobal: 'System',
// whether to inline package configurations into bundles
buildConfig: false,
static: false,
encodeNames: undefined,
sourceMaps: false,
lowResSourceMaps: false,
// static build options
// it may make sense to split this out into build options
// at a later point as static build and bundle compile diverge further
runtime: false,
format: 'global',
globalDeps: {},
globalName: null,
// conditionalResolutions: {},
// can add a special object here that matches condition predicates to direct module names to use for sfx
// this shouldn't strictly be a compile option,
// but the cjs compiler needs it to do NODE_ENV optimization
minify: false
};
extend(opts, defaults);
extend(opts, options);
if (opts.static) {
if (opts.encodeNames !== false)
opts.encodeNames = true;
// include runtime by default if needed
if (opts.runtime !== false)
opts.runtime = true;
// static builds have a System closure with a dummy name
opts.systemGlobal = '$__System';
}
return opts;
}
Builder.prototype.compile = function(moduleName, outFile, opts) {
if (outFile && typeof outFile == 'object') {
opts = outFile;
outFile = undefined;
}
if (opts && opts.config)
this.config(opts.config);
var self = this;
return Promise.resolve(self.loader.normalize(moduleName))
.then(function(moduleName) {
return self.tracer.getLoadRecord(getCanonicalName(self.loader, moduleName));
})
.then(function(load) {
return compileLoad(self.loader, load, processCompileOpts(opts, { normalize: false, anonymous: true }), self.cache.compile);
})
.then(function(output) {
return writeOutputs([output], self.loader.baseURL, processOutputOpts(opts, { outFile: outFile }));
});
};
function processOutputOpts(options, defaults) {
var opts = {
outFile: undefined,
minify: false,
mangle: true,
globalDefs: undefined,
sourceMaps: false,
sourceMapContents: undefined
};
extend(opts, defaults);
extend(opts, options);
// source maps 'inline' handling
if (opts.sourceMapContents === undefined)
opts.sourceMapContents = opts.sourceMaps == 'inline';
return opts;
}
// bundle
Builder.prototype.bundle = function(expressionOrTree, outFile, opts) {
if (outFile && typeof outFile === 'object') {
opts = outFile;
outFile = undefined;
}
var self = this;
if (opts && opts.config)
this.config(opts.config);
var outputOpts = processOutputOpts(opts, { outFile: outFile });
return Promise.resolve()
.then(function() {
if (typeof expressionOrTree != 'string')
return expressionOrTree;
return traceExpression(self, expressionOrTree, processTraceOpts(opts));
})
.then(function(tree) {
return compileTree(self.loader, tree, processCompileOpts(opts), outputOpts, self.cache.compile)
.then(function(compiled) {
return writeOutputs(compiled.outputs, self.loader.baseURL, outputOpts)
.then(function(output) {
output.modules = Object.keys(tree).filter(function(moduleName) {
return tree[moduleName] && !tree[moduleName].conditional;
});
output.entryPoints = compiled.entryPoints;
return output;
});
});
});
};
// build into an optimized static module
Builder.prototype.buildStatic = function(expressionOrTree, outFile, opts) {
if (outFile && typeof outFile === 'object') {
opts = outFile;
outFile = undefined;
}
var self = this;
if (opts && opts.config)
this.config(opts.config);
var outputOpts = processOutputOpts(opts, { outFile: outFile });
var traceOpts = processTraceOpts(opts);
var compileOpts = processCompileOpts(opts, { static: true });
return Promise.resolve()
.then(function() {
if (typeof expressionOrTree != 'string')
return expressionOrTree;
return traceExpression(self, expressionOrTree, traceOpts);
})
.then(function(tree) {
// inline conditionals of the trace
var inlinedTree = self.tracer.inlineConditions(tree, traceOpts.conditions);
return compileTree(self.loader, inlinedTree, compileOpts, outputOpts, self.cache.compile)
.then(function(compiled) {
return writeOutputs(compiled.outputs, self.loader.baseURL, outputOpts);
})
.then(function(output) {
output.modules = Object.keys(tree).filter(function(moduleName) {
return tree[moduleName];
});
return output;
});
});
};
Builder.prototype.build = function() {
console.warn('builder.build is deprecated. Using builder.bundle instead.');
return this.bundle.apply(this, arguments);
};
Builder.prototype.buildSFX = function() {
console.warn('builder.buildSFX is deprecated. Using builder.buildStatic instead.');
return this.buildStatic.apply(this, arguments);
};
Builder.prototype.buildTree = function() {
console.warn('builder.buildTree is deprecated. Using builder.bundle instead, which takes both a tree object or expression string.');
return this.bundle.apply(this, arguments);
};
// given a tree, creates a depCache for it
Builder.prototype.getDepCache = function(tree) {
var depCache = {};
Object.keys(tree).forEach(function(moduleName) {
var load = tree[moduleName];
if (load && load.deps.length)
depCache[moduleName] = load.deps.map(function(dep) {
return load.depMap[dep];
});
});
return depCache;
};
// expose useful tree statics on the builder instance for ease-of-use
Builder.prototype.intersectTrees = require('./arithmetic').intersectTrees;
Builder.prototype.addTrees = require('./arithmetic').addTrees;
Builder.prototype.subtractTrees = require('./arithmetic').subtractTrees;
module.exports = Builder;