embark/lib/pipeline/pipeline.js

358 lines
12 KiB
JavaScript
Raw Normal View History

const fs = require('../core/fs.js');
const async = require('async');
const utils = require('../utils/utils.js');
2017-12-12 17:20:57 +00:00
const webpack = require("webpack");
const constants = require('../constants');
2016-08-21 16:02:02 +00:00
2018-01-17 00:17:52 +00:00
require("babel-preset-react");
require("babel-preset-es2015");
require("babel-preset-es2016");
require("babel-preset-es2017");
let pipeline;
2017-03-30 11:12:39 +00:00
class Pipeline {
2017-03-30 11:12:39 +00:00
constructor(options) {
this.buildDir = options.buildDir;
this.contractsFiles = options.contractsFiles;
this.assetFiles = options.assetFiles;
2017-12-12 17:20:57 +00:00
this.events = options.events;
this.pipelinePlugins = options.pipelinePlugins;
this.pluginImports = options.pluginImports;
this.interceptLogs();
}
interceptLogs() {
const context = {};
context.console = console;
context.console.log = this.log;
context.console.warn = this.log;
context.console.info = this.log;
context.console.debug = this.log;
context.console.trace = this.log;
context.console.dir = this.log;
}
log() {
process.send({result: constants.pipeline.log, message: arguments});
2017-03-30 11:12:39 +00:00
}
build(abi, contractsJSON, path, callback) {
2017-03-30 11:12:39 +00:00
let self = this;
this.buildContracts(contractsJSON);
2017-12-12 21:10:12 +00:00
self.buildWeb3JS(function() {
let importsList = {};
importsList["Embark/EmbarkJS"] = fs.dappPath(".embark", 'embark.js');
importsList["Embark/web3"] = fs.dappPath(".embark", 'web3_instance.js');
self.pluginImports.forEach(function (importObject) {
let [importName, importLocation] = importObject;
importsList[importName] = importLocation;
});
for (let contractName in contractsJSON) {
let contractCode = self.buildContractJS(contractName);
let filePath = fs.dappPath(".embark", contractName + '.js');
fs.writeFileSync(filePath, contractCode);
importsList["Embark/contracts/" + contractName] = filePath;
}
2017-12-12 17:20:57 +00:00
// limit:1 due to issues when downloading required files such as web3.js
2018-02-28 23:14:41 +00:00
async.eachOfLimit(self.assetFiles, 1, function (files, targetFile, cb) {
// limit:1 due to issues when downloading required files such as web3.js
async.mapLimit(files, 1,
function(file, fileCb) {
self.log("reading " + file.filename);
2017-12-12 17:20:57 +00:00
2018-02-28 23:14:41 +00:00
if (file.filename.indexOf('.js') >= 0) {
2018-02-22 19:56:55 +00:00
2018-01-12 19:21:36 +00:00
let realCwd;
2017-12-12 17:20:57 +00:00
async.waterfall([
2018-01-12 19:21:36 +00:00
2017-12-12 17:20:57 +00:00
function findImports(next) {
2018-02-23 19:04:08 +00:00
self.webpackRun(file.filename, {}, false, importsList, false, next);
2018-01-17 00:17:52 +00:00
},
function changeCwd(next) {
realCwd = utils.pwd();
2018-01-17 00:17:52 +00:00
process.chdir(fs.embarkPath(''));
next();
},
2018-02-23 19:04:08 +00:00
//function findImportsPhase2(next) {
// console.log("====> findImports_2");
// self.webpackRun(file.filename, {
// externals: function(context, request, callback) {
// if (request === utils.joinPath(fs.dappPath(), file.filename)) {
// callback();
// } else {
// //if (request.indexOf('Embark/contracts/') === 0) {
// // let contractName = request.split('/')[2];
// // let contractCode = self.buildContractJS(contractName);
// // let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
// // fs.writeFileSync(filePath, contractCode);
// // importsList[request] = filePath;
// //}
// callback(null, "amd " + Math.random());
// }
// }
// }, true, importsList, next);
//},
2018-01-12 19:21:36 +00:00
2017-12-12 17:20:57 +00:00
function runWebpack(next) {
2018-02-23 19:04:08 +00:00
self.webpackRun(file.filename, {}, true, importsList, true, next);
2018-01-12 19:21:36 +00:00
},
function changeCwdBack(next) {
process.chdir(realCwd);
next();
2017-12-12 17:20:57 +00:00
}
2018-02-23 19:04:08 +00:00
], function(err, _result) {
if (err) {
process.chdir(realCwd);
self.log(err);
2018-02-23 19:04:08 +00:00
return fileCb(err);
}
if (!fs.existsSync('./.embark/' + file.filename)) {
self.log("couldn't find file: " + file.filename);
return fileCb("couldn't find file: " + file.filename);
}
2017-12-12 17:20:57 +00:00
let fileContent = fs.readFileSync('./.embark/' + file.filename).toString();
2018-02-28 23:09:10 +00:00
self.runPlugins(file, fileContent, fileCb);
2017-12-12 17:20:57 +00:00
});
2018-02-28 23:14:41 +00:00
} else {
file.content(function(fileContent) {
self.runPlugins(file, fileContent, fileCb);
});
2017-12-12 17:20:57 +00:00
}
2018-02-28 23:14:41 +00:00
},
function (err, contentFiles) {
if (err) {
self.log('errors found while generating ' + targetFile);
2018-02-28 23:14:41 +00:00
}
let dir = targetFile.split('/').slice(0, -1).join('/');
self.log("creating dir " + self.buildDir + dir);
2018-02-28 23:14:41 +00:00
fs.mkdirpSync(self.buildDir + dir);
2017-12-12 17:20:57 +00:00
2018-02-28 23:14:41 +00:00
// if it's a directory
if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) {
let targetDir = targetFile;
2017-01-29 05:58:06 +00:00
2018-02-28 23:14:41 +00:00
if (targetDir.slice(-1) !== '/') {
targetDir = targetDir + '/';
2017-12-12 17:20:57 +00:00
}
2018-02-28 23:14:41 +00:00
contentFiles.map(function (file) {
let filename = file.filename.replace(file.basedir + '/', '');
self.log("writing file " + (self.buildDir + targetDir + filename).bold.dim);
2018-02-28 23:14:41 +00:00
fs.copySync(file.path, self.buildDir + targetDir + filename, {overwrite: true});
});
} else {
let content = contentFiles.map(function (file) {
if (file === undefined) {
return "";
}
return file.content;
}).join("\n");
self.log("writing file " + (self.buildDir + targetFile).bold.dim);
2018-02-28 23:14:41 +00:00
fs.writeFileSync(self.buildDir + targetFile, content);
}
cb();
2017-12-12 17:20:57 +00:00
}
2018-02-28 23:14:41 +00:00
);
},
function (_err, _results) {
callback();
});
2017-12-12 17:20:57 +00:00
});
}
2018-02-28 23:09:10 +00:00
runPlugins(file, fileContent, fileCb) {
const self = this;
if (self.pipelinePlugins.length <= 0) {
2018-02-28 23:09:10 +00:00
return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
}
async.eachSeries(self.pipelinePlugins,
2018-02-28 23:09:10 +00:00
function(plugin, pluginCB) {
if (file.options && file.options.skipPipeline) {
return pluginCB();
}
fileContent = plugin.runPipeline({targetFile: file.filename, source: fileContent});
file.modified = true;
pluginCB();
},
function (err) {
if (err) {
self.log(err.message);
2018-02-28 23:09:10 +00:00
}
return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, basedir: file.basedir, modified: true});
}
);
}
2018-02-23 19:04:08 +00:00
webpackRun(filename, options, includeModules, importsList, detectErrors, callback) {
let defaultOptions = {
2018-04-02 19:30:16 +00:00
entry: fs.dappPath(filename),
output: {
libraryTarget: 'umd',
2018-04-02 19:30:16 +00:00
path: fs.dappPath('.embark'),
filename: filename
},
resolve: {
alias: importsList,
modules: [
fs.embarkPath('node_modules'),
2018-04-02 19:30:16 +00:00
fs.dappPath('node_modules')
]
},
externals: function(context, request, callback) {
callback();
}
};
let webpackOptions = utils.recursiveMerge(defaultOptions, options);
if (includeModules) {
webpackOptions.module = {
rules: [
{
test: /\.css$/,
use: [{loader: "style-loader"}, {loader: "css-loader"}]
},
{
test: /\.scss$/,
use: [{loader: "style-loader"}, {loader: "css-loader"}]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.js$/,
loader: "babel-loader",
exclude: /(node_modules|bower_components)/,
options: {
2018-02-23 23:24:46 +00:00
presets: ['babel-preset-es2016', 'babel-preset-es2017', 'babel-preset-react'].map(require.resolve),
plugins: ["babel-plugin-webpack-aliases"].map(require.resolve),
compact: false
}
}
]
};
}
webpack(webpackOptions).run((_err, _stats) => {
2018-02-23 19:04:08 +00:00
if (!detectErrors) {
return callback();
}
if (_stats.hasErrors()) {
return callback(_stats.toJson().errors.join("\n"));
}
callback();
});
}
2017-04-04 10:37:50 +00:00
buildContracts(contractsJSON) {
2018-04-02 19:30:16 +00:00
fs.mkdirpSync(fs.dappPath(this.buildDir, 'contracts'));
2017-04-04 10:37:50 +00:00
for (let className in contractsJSON) {
let contract = contractsJSON[className];
2018-04-02 19:30:16 +00:00
fs.writeJSONSync(fs.dappPath(this.buildDir, 'contracts', className + ".json"), contract, {spaces: 2});
2017-04-04 10:37:50 +00:00
}
2016-08-21 16:02:02 +00:00
}
buildContractJS(contractName) {
2018-04-02 19:30:16 +00:00
let contractJSON = fs.readFileSync(fs.dappPath(this.buildDir, 'contracts', contractName + '.json')).toString();
let contractCode = "";
2017-12-12 18:51:14 +00:00
contractCode += "import web3 from 'Embark/web3';\n";
2017-12-12 17:20:57 +00:00
contractCode += "import EmbarkJS from 'Embark/EmbarkJS';\n";
contractCode += "let " + contractName + "JSONConfig = " + contractJSON + ";\n";
contractCode += "let " + contractName + " = new EmbarkJS.Contract(" + contractName + "JSONConfig);\n";
2017-12-12 17:20:57 +00:00
contractCode += "\n__embarkContext.execWhenReady(function() {\n";
contractCode += "\n" + contractName + ".setProvider(web3.currentProvider);\n";
contractCode += "\n});\n";
contractCode += "export default " + contractName + ";\n";
return contractCode;
}
2017-12-12 19:45:20 +00:00
buildWeb3JS(cb) {
2018-01-10 15:43:25 +00:00
const self = this;
let code = "";
async.waterfall([
function getWeb3Location(next) {
self.events.request("version:get:web3", function(web3Version) {
if (web3Version === "1.0.0-beta") {
return next(null, utils.joinPath(fs.embarkPath("js/web3-1.0.min.js")));
} else {
self.events.request("version:getPackageLocation", "web3", web3Version, function(err, location) {
2018-04-02 19:06:56 +00:00
return next(null, fs.dappPath(location));
2018-01-10 15:43:25 +00:00
});
}
});
},
function getImports(web3Location, next) {
2018-04-09 20:14:07 +00:00
web3Location = web3Location.replace(/\\/g, '/'); // Import paths must always have forward slashes
2018-01-10 15:43:25 +00:00
code += "\nimport Web3 from '" + web3Location + "';\n";
code += "\n if (typeof web3 !== 'undefined') {";
code += "\n } else {";
code += "\n var web3 = new Web3();\n";
code += "\n }";
self.events.request('provider-code', function(providerCode) {
code += providerCode;
code += "\nglobal.__embarkContext = __mainContext.__loadManagerInstance;\n";
code += "\nwindow.web3 = web3;\n";
code += "\nexport default web3;\n";
next();
});
},
function writeFile(next) {
2018-04-02 19:30:16 +00:00
fs.mkdirpSync(fs.dappPath(".embark"));
fs.writeFileSync(fs.dappPath(".embark", 'web3_instance.js'), code);
2018-01-10 15:43:25 +00:00
next();
}
], function(_err, _result) {
2017-12-12 19:45:20 +00:00
cb();
});
}
2017-03-30 11:12:39 +00:00
}
2016-08-21 16:02:02 +00:00
process.on('message', (msg) => {
if (msg.action === constants.pipeline.init) {
pipeline = new Pipeline(msg.options);
return process.send({result: constants.pipeline.initiated});
}
if (msg.action === constants.pipeline.build) {
return pipeline.build(msg.abi, msg.contractsJSON, msg.path, (err, result) => {
process.send({result: constants.pipeline.built, error: err, data: result});
});
}
});
process.on('exit', () => {
process.exit(0);
});