UNPKG

1.7 kBJavaScriptView Raw
1var keys = require("lodash/keys");
2var through = require("through2");
3var assign = require("lodash/assign");
4
5module.exports = function() {
6 return through.obj(function(data, enc, next) {
7 loadNodeBuilder(data)
8 .then(function(newGraph) {
9 next(null, assign(data, { graph: newGraph }));
10 })
11 .catch(next);
12 });
13};
14
15/**
16 * Replaces a node source with its builder module
17 * @param {Object} data - The stream's data object
18 * @return {Promise.<graph>}
19 */
20function loadNodeBuilder(data) {
21 return new Promise(function(resolve, reject) {
22 var graph = data.graph;
23 var loader = data.loader;
24
25 var promises = keys(graph).map(function(nodeName) {
26 var node = graph[nodeName];
27
28 // pluginBuilder | extensionBuilder is a module identifier that
29 // should be loaded to replace the node's source during the build
30 var nodeBuilder =
31 node.value && (node.value.pluginBuilder || node.value.extensionBuilder);
32
33 // nothing to do in this case, return right away
34 if (!nodeBuilder) return;
35
36 return loader
37 .normalize(nodeBuilder)
38 .then(locate)
39 .then(_fetch)
40 .then(makeReplace(node));
41 });
42
43 function locate(name) {
44 return Promise.all([name, loader.locate({ name: name, metadata: {} })]);
45 }
46
47 // [ name, address ]
48 function _fetch(data) {
49 return Promise.all([
50 data[1],
51 loader.fetch({ name: data[0], address: data[1], metadata: {} })
52 ]);
53 }
54
55 function makeReplace(node) {
56 // [ address, load ]
57 return function replace(data) {
58 node.load = assign(node.load, {
59 address: data[0],
60 source: data[1],
61 metadata: {}
62 });
63 };
64 }
65
66 Promise.all(promises)
67 .then(function() {
68 resolve(graph);
69 })
70 .catch(reject);
71 });
72}