From b7b5fae2c8bc322f5dd0acc822a8510983d3b6d4 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Tue, 12 Dec 2017 12:20:57 -0500 Subject: [PATCH] imports with shared web3 object --- js/embark.js | 16 +- lib/contracts/code_generator.js | 6 + .../code_templates/web3-connector.js.ejs | 6 +- lib/core/config.js | 275 +-------------- lib/core/engine.js | 1 + lib/pipeline/pipeline.js | 329 +++++++++++++++++- test_app/app/js/foo.js | 3 + test_app/app/js/new_index.js | 238 +++++++------ test_app/embark.json | 13 +- test_app/embark.old_config.json | 28 ++ 10 files changed, 508 insertions(+), 407 deletions(-) create mode 100644 test_app/embark.old_config.json diff --git a/js/embark.js b/js/embark.js index cd69dc8a0..914590ad3 100644 --- a/js/embark.js +++ b/js/embark.js @@ -1,11 +1,12 @@ var EmbarkJS = {}; EmbarkJS.isNewWeb3 = function() { - var _web3 = new Web3(); - if (typeof(_web3.version) === "string") { - return true; - } - return parseInt(_web3.version.api.split('.')[0], 10) >= 1; + return true; + //var _web3 = new Web3(); + //if (typeof(_web3.version) === "string") { + // return true; + //} + //return parseInt(_web3.version.api.split('.')[0], 10) >= 1; }; EmbarkJS.Contract = function(options) { @@ -16,7 +17,10 @@ EmbarkJS.Contract = function(options) { this.abi = options.abi; this.address = options.address; this.code = '0x' + options.code; - this.web3 = options.web3 || web3; + //this.web3 = options.web3 || web3; + this.web3 = options.web3 || window.web3; + console.log("set web3"); + console.log(this.web3); if (EmbarkJS.isNewWeb3()) { // TODO: diff --git a/lib/contracts/code_generator.js b/lib/contracts/code_generator.js index 3b73f4f68..64c38c0ee 100644 --- a/lib/contracts/code_generator.js +++ b/lib/contracts/code_generator.js @@ -27,6 +27,12 @@ class CodeGenerator { listenToCommands() { let self = this; + this.events.setCommandHandlerOnce('provider-code', function(cb) { + let providerCode = self.generateProvider(false); + + cb(providerCode); + }); + // deprecated events; to remove in embark 2.7.0 this.events.setCommandHandlerOnce('abi-vanila', function(cb) { let vanillaABI = self.generateABI({useEmbarkJS: false}); diff --git a/lib/contracts/code_templates/web3-connector.js.ejs b/lib/contracts/code_templates/web3-connector.js.ejs index ea97f0849..a8e2927d3 100644 --- a/lib/contracts/code_templates/web3-connector.js.ejs +++ b/lib/contracts/code_templates/web3-connector.js.ejs @@ -5,10 +5,12 @@ __reduce(<%- connectionList %>,function(prev, value, next) { } if (value === '$WEB3' && (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined')) { - web3 = new Web3(web3.currentProvider); + //web3 = new Web3(web3.currentProvider); + web3.setProvider(web3.currentProvider); } else if (value !== '$WEB3' && (typeof Web3 !== 'undefined' && ((typeof web3 === 'undefined') || (typeof web3 !== 'undefined' && (!web3.isConnected || (web3.isConnected && !web3.isConnected())))))) { - web3 = new Web3(new Web3.providers.HttpProvider(value)); + //web3 = new Web3(new Web3.providers.HttpProvider(value)); + web3.setProvider(new Web3.providers.HttpProvider(value)); } else if (value === '$WEB3') { return next(null, ''); } diff --git a/lib/core/config.js b/lib/core/config.js index f3b8d2621..53825ea46 100644 --- a/lib/core/config.js +++ b/lib/core/config.js @@ -2,10 +2,6 @@ var fs = require('./fs.js'); var File = require('./file.js'); var Plugins = require('./plugins.js'); var utils = require('../utils/utils.js'); -var Npm = require('../pipeline/npm.js'); -let async = require('async'); -let currentWeb3Version = require('../../package.json').dependencies.web3.replace("^",""); -const webpack = require("webpack"); var Config = function(options) { this.env = options.env; @@ -128,15 +124,6 @@ Config.prototype.loadStorageConfigFile = function() { } }; - //var configPlugins = this.plugins.getPluginsFor('storageConfig'); - //if (configPlugins.length > 0) { - // configPlugins.forEach(function(plugin) { - // plugin.contractsConfigs.forEach(function(pluginConfig) { - // configObject = utils.recursiveMerge(configObject, pluginConfig); - // }); - // }); - //} - var storageConfig; if (fs.existsSync(this.configDir + "storage.json")) { storageConfig = fs.readJSONSync(this.configDir + "storage.json"); @@ -171,15 +158,6 @@ Config.prototype.loadCommunicationConfigFile = function() { } }; - //var configPlugins = this.plugins.getPluginsFor('communicationConfig'); - //if (configPlugins.length > 0) { - // configPlugins.forEach(function(plugin) { - // plugin.contractsConfigs.forEach(function(pluginConfig) { - // configObject = utils.recursiveMerge(configObject, pluginConfig); - // }); - // }); - //} - var communicationConfig; if (fs.existsSync(this.configDir + "communication.json")) { @@ -228,11 +206,7 @@ Config.prototype.loadEmbarkConfigFile = function() { Config.prototype.loadPipelineConfigFile = function() { var assets = this.embarkConfig.app; for(var targetFile in assets) { - if (typeof(assets[targetFile]) === 'string' || (Array.isArray(assets[targetFile]) && (assets[targetFile].length === 1))) { - this.assetFiles[targetFile] = this.loadFile(assets[targetFile]); - } else { - this.assetFiles[targetFile] = this.loadFiles(assets[targetFile]); - } + this.assetFiles[targetFile] = this.loadFiles(assets[targetFile]); } }; @@ -250,246 +224,19 @@ Config.prototype.loadChainTrackerFile = function() { this.chainTracker = chainTracker; }; -Config.prototype.loadFile = function(files) { - var self = this; - var originalFiles = utils.filesMatchingPattern(files); - var readFiles = []; - - // get embark.js object first - originalFiles.filter(function(file) { - return (file[0] === '$' || file.indexOf('.') >= 0); - }).filter(function(file) { - if (file === 'embark.js') { - - if (self.blockchainConfig.enabled || self.communicationConfig.provider === 'whisper' || self.communicationConfig.available_providers.indexOf('whisper') >= 0) { - let web3Version = self.contractsConfig.versions["web3.js"]; - if (web3Version && web3Version != currentWeb3Version) { - //if (false) { - //readFiles.push(new File({filename: 'web3-' + web3Version + '.js', type: 'custom', resolver: function(callback) { - readFiles.push(new File({filename: 'web3.js', type: 'custom', resolver: function(callback) { - if (web3Version === "1.0.0-beta") { - return callback(fs.readFileSync(fs.embarkPath('js/web3-1.0.min.js')).toString()); - } else { - let npm = new Npm({logger: self.logger}); - npm.getPackageVersion('web3', web3Version, 'dist/web3.min.js', true, function(web3Content) { - callback(web3Content); - }); - } - }})); - } else { - readFiles.push(new File({filename: 'web3.js', type: 'embark_internal', path: "js/web3.js"})); - } - } - - if (self.storageConfig.enabled && (self.storageConfig.provider === 'ipfs' || self.storageConfig.available_providers.indexOf('ipfs') >= 0)) { - //until issues with the correct ipfs version to use are fixed - //readFiles.push(new File({filename: 'ipfs.js', type: 'embark_internal', path: "node_modules/ipfs-api/dist/index.min.js"})); - readFiles.push(new File({filename: 'ipfs.js', type: 'embark_internal', path: "js/ipfs.js"})); - } - - if (self.communicationConfig.enabled && (self.communicationConfig.provider === 'orbit' || self.communicationConfig.available_providers.indexOf('orbit') >= 0)) { - readFiles.push(new File({filename: 'orbit.js', type: 'embark_internal', path: "node_modules/orbit-db/dist/orbitdb.min.js"})); - } - - readFiles.push(new File({filename: 'embark.js', type: 'embark_internal', path: "js/build/embark.bundle.js"})); - } - if (file === '$EMBARK_JS') { - readFiles.push(new File({filename: '$EMBARK_JS', type: 'embark_internal', path: "js/build/embark.bundle.js"})); - } - //if (file === "web3.js") { - // readFiles.push(new File({filename: 'web3.js', type: 'embark_internal', path: "js/web3.js")); - //} - }); - - // get plugins - var filesFromPlugins = []; - - var filePlugins = self.plugins.getPluginsFor('pipelineFiles'); - - if (filePlugins.length > 0) { - filePlugins.forEach(function(plugin) { - try { - var fileObjects = plugin.runFilePipeline(); - for (var i=0; i < fileObjects.length; i++) { - var fileObject = fileObjects[i]; - filesFromPlugins.push(fileObject); - } - } - catch(err) { - self.logger.error(err.message); - } - }); - } - - filesFromPlugins.filter(function(file) { - if (utils.fileMatchesPattern(files, file.intendedPath)) { - readFiles.push(file); - } - }); - - // get user files - originalFiles.filter(function(file) { - return file.indexOf('.') >= 0; - }).filter(function(file) { - if (file === 'embark.js') { - return; - } else if (file.indexOf("web3-") === 0) { - return; - } else if (file.indexOf("web3") === 0) { - return; - } else if (file.indexOf("embark") >= 0) { - return; - //} else if (file === 'abi.js') { - // readFiles.push({filename: file, content: "", path: file}); - } else { - - if (file.indexOf('.js') >= 0) { - //if (file.indexOf('.js') >= 0) { - readFiles.push(new File({filename: file, type: "custom", path: file, resolver: function(fileCallback) { - console.log("---"); - console.log(fs.dappPath()); - console.log(file); - console.log("---"); - - let importsList = {}; - async.waterfall([ - function findImports(next) { - webpack({ - entry: utils.joinPath(fs.dappPath(), file), - output: { - libraryTarget: 'umd', - path: utils.joinPath(fs.dappPath(), '.embark'), - filename: file - }, - externals: function(context, request, callback) { - if (request === utils.joinPath(fs.dappPath(), file)) { - callback(); - } else { - if (request === "Embark/EmbarkJS") { - importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js"); - } else if (request === "Embark/test") { - importsList["Embark/test"] = fs.embarkPath("js/test.js"); - } - callback(null, "amd " + Math.random()); - } - }, - module: { - rules: [ - { - test: /\.css$/, - use: [ - { loader: "style-loader" }, - { loader: "css-loader" } - ] - } - ] - } - }).run((err, stats) => { - next(); - }); - }, - - function runWebpack(next) { - webpack({ - entry: utils.joinPath(fs.dappPath(), file), - output: { - libraryTarget: 'umd', - path: utils.joinPath(fs.dappPath(), '.embark'), - filename: file - }, - resolve: { - alias: importsList - }, - module: { - rules: [ - { - test: /\.css$/, - use: [ - { loader: "style-loader" }, - { loader: "css-loader" } - ] - } - ] - } - }).run((err, stats) => { - next(); - }); - - } - - ], function(err, _result) { - fileCallback(fs.readFileSync('./.embark/' + file).toString()); - }); - - }})); - - } else { - readFiles.push(new File({filename: file, type: "dapp_file", path: file})); - } - - } - - }); - - return readFiles; -}; - Config.prototype.loadFiles = function(files) { var self = this; var originalFiles = utils.filesMatchingPattern(files); var readFiles = []; - // get embark.js object first originalFiles.filter(function(file) { return (file[0] === '$' || file.indexOf('.') >= 0); }).filter(function(file) { - if (file === 'embark.js') { - - if (self.blockchainConfig.enabled || self.communicationConfig.provider === 'whisper' || self.communicationConfig.available_providers.indexOf('whisper') >= 0) { - let web3Version = self.contractsConfig.versions["web3.js"]; - if (web3Version && web3Version != currentWeb3Version) { - //if (false) { - //readFiles.push(new File({filename: 'web3-' + web3Version + '.js', type: 'custom', resolver: function(callback) { - readFiles.push(new File({filename: 'web3.js', type: 'custom', resolver: function(callback) { - if (web3Version === "1.0.0-beta") { - return callback(fs.readFileSync(fs.embarkPath('js/web3-1.0.min.js')).toString()); - } else { - let npm = new Npm({logger: self.logger}); - npm.getPackageVersion('web3', web3Version, 'dist/web3.min.js', true, function(web3Content) { - callback(web3Content); - }); - } - }})); - } else { - readFiles.push(new File({filename: 'web3.js', type: 'embark_internal', path: "js/web3.js"})); - } - } - - if (self.storageConfig.enabled && (self.storageConfig.provider === 'ipfs' || self.storageConfig.available_providers.indexOf('ipfs') >= 0)) { - //until issues with the correct ipfs version to use are fixed - //readFiles.push(new File({filename: 'ipfs.js', type: 'embark_internal', path: "node_modules/ipfs-api/dist/index.min.js"})); - readFiles.push(new File({filename: 'ipfs.js', type: 'embark_internal', path: "js/ipfs.js"})); - } - - if (self.communicationConfig.enabled && (self.communicationConfig.provider === 'orbit' || self.communicationConfig.available_providers.indexOf('orbit') >= 0)) { - readFiles.push(new File({filename: 'orbit.js', type: 'embark_internal', path: "node_modules/orbit-db/dist/orbitdb.min.js"})); - } - - readFiles.push(new File({filename: 'embark.js', type: 'embark_internal', path: "js/build/embark.bundle.js"})); - } - if (file === '$EMBARK_JS') { - readFiles.push(new File({filename: '$EMBARK_JS', type: 'embark_internal', path: "js/build/embark.bundle.js"})); - } - //if (file === "web3.js") { - // readFiles.push(new File({filename: 'web3.js', type: 'embark_internal', path: "js/web3.js")); - //} + readFiles.push(new File({filename: file, type: "dapp_file", path: file})); }); - // get plugins var filesFromPlugins = []; - var filePlugins = self.plugins.getPluginsFor('pipelineFiles'); - if (filePlugins.length > 0) { filePlugins.forEach(function(plugin) { try { @@ -504,30 +251,12 @@ Config.prototype.loadFiles = function(files) { } }); } - filesFromPlugins.filter(function(file) { if (utils.fileMatchesPattern(files, file.intendedPath)) { readFiles.push(file); } }); - // get user files - originalFiles.filter(function(file) { - return file.indexOf('.') >= 0; - }).filter(function(file) { - if (file === 'embark.js') { - return; - } else if (file.indexOf("web3-") === 0) { - return; - } else if (file.indexOf("web3") === 0) { - return; - //} else if (file === 'abi.js') { - // readFiles.push({filename: file, content: "", path: file}); - } else { - readFiles.push(new File({filename: file, type: "dapp_file", path: file})); - } - }); - return readFiles; }; diff --git a/lib/core/engine.js b/lib/core/engine.js index e1d249a21..a07de2334 100644 --- a/lib/core/engine.js +++ b/lib/core/engine.js @@ -77,6 +77,7 @@ class Engine { buildDir: this.config.buildDir, contractsFiles: this.config.contractsFiles, assetFiles: this.config.assetFiles, + events: this.events, logger: this.logger, plugins: this.plugins }); diff --git a/lib/pipeline/pipeline.js b/lib/pipeline/pipeline.js index cd1e4bc6b..b75685225 100644 --- a/lib/pipeline/pipeline.js +++ b/lib/pipeline/pipeline.js @@ -1,6 +1,11 @@ /*jshint esversion: 6, loopfunc: true */ let fs = require('../core/fs.js'); let async = require('async'); +var Plugins = require('../core/plugins.js'); +var utils = require('../utils/utils.js'); +var Npm = require('../pipeline/npm.js'); +let currentWeb3Version = require('../../package.json').dependencies.web3.replace("^",""); +const webpack = require("webpack"); class Pipeline { @@ -8,6 +13,7 @@ class Pipeline { this.buildDir = options.buildDir; this.contractsFiles = options.contractsFiles; this.assetFiles = options.assetFiles; + this.events = options.events; this.logger = options.logger; this.plugins = options.plugins; } @@ -19,7 +25,181 @@ class Pipeline { // limit:1 due to issues when downloading required files such as web3.js async.eachOfLimit(this.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.logger.trace("reading " + file.filename); + if (file.filename.indexOf('.js') >= 0) { + + console.log("---"); + console.log(fs.dappPath()); + console.log(file.filename); + console.log("---"); + + let importsList = {}; + async.waterfall([ + function findImports(next) { + webpack({ + entry: utils.joinPath(fs.dappPath(), file.filename), + output: { + libraryTarget: 'umd', + path: utils.joinPath(fs.dappPath(), '.embark'), + filename: file.filename + }, + externals: function(context, request, callback) { + if (request === utils.joinPath(fs.dappPath(), file.filename)) { + callback(); + } else { + console.log("request " + request); + if (request === "Embark/EmbarkJS") { + importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js"); + } else if (request === "Embark/test") { + importsList["Embark/test"] = fs.embarkPath("js/test.js"); + } 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; + } else if (request === "Embark/web3") { + console.log("--> web3"); + return self.events.request('provider-code', function(providerCode) { + let code = ""; + code += "\nimport Web3 from '" + utils.joinPath(fs.embarkPath("js/web3-1.0.min.js")) + "'\n"; + //code += "\nvar __mainContext = __mainContext || this;\n"; + + code += "\n if (typeof web3 !== 'undefined') {"; + //code += "\n__mainContext.web3 = web3;\n"; + code += "\n } else {"; + code += "\n var web3 = new Web3();\n"; + code += "\n }"; + + code += providerCode; + code += "\nglobal.__embarkContext = __mainContext.__loadManagerInstance;\n"; + code += "\nconsole.log('web3');\n"; + code += "\nconsole.log(web3);\n"; + //code += "\nwindow.web3 = __mainContext.web3;\n"; + code += "\nwindow.web3 = web3;\n"; + code += "\nexport default web3;\n"; + let filePath = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js'); + fs.writeFileSync(filePath, code); + importsList[request] = filePath; + callback(null, "amd " + Math.random()); + }); + } + callback(null, "amd " + Math.random()); + } + }, + module: { + rules: [ + { + test: /\.css$/, + use: [ + { loader: "style-loader" }, + { loader: "css-loader" } + ] + } + ] + } + }).run((err, stats) => { + next(); + }); + }, + + function runWebpack(next) { + webpack({ + entry: utils.joinPath(fs.dappPath(), file.filename), + output: { + libraryTarget: 'umd', + path: utils.joinPath(fs.dappPath(), '.embark'), + filename: file.filename + }, + resolve: { + alias: importsList + }, + externals: function(context, request, callback) { + if (request === "Embark/contracts/all") { + return callback(null, fs.readFileSync(utils.joinPath(fs.dappPath(), '.embark', 'embark.js'))); + } + callback(); + }, + module: { + rules: [ + { + test: /\.css$/, + use: [ + { loader: "style-loader" }, + { loader: "css-loader" } + ] + } + ] + } + }).run((err, stats) => { + next(); + }); + + } + + ], function(err, _result) { + let fileContent = fs.readFileSync('./.embark/' + file.filename).toString(); + fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true}); + }); + + } else { + file.content(function(fileContent) { + return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true}); + }); + } + + }, + function (err, contentFiles) { + let dir = targetFile.split('/').slice(0, -1).join('/'); + self.logger.trace("creating dir " + self.buildDir + dir); + fs.mkdirpSync(self.buildDir + dir); + + // if it's a directory + if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) { + let targetDir = targetFile; + + if (targetDir.slice(-1) !== '/') { + targetDir = targetDir + '/'; + } + + contentFiles.map(function (file) { + let filename = file.filename.replace('app/', ''); + filename = filename.replace(targetDir, ''); + self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim); + + fs.copySync(self.buildDir + targetDir + filename, file.path, {overwrite: true}); + }); + } else { + let content = contentFiles.map(function (file) { + if (file === undefined) { + return ""; + } + return file.content; + }).join("\n"); + + self.logger.info("writing file " + (self.buildDir + targetFile).bold.dim); + fs.writeFileSync(self.buildDir + targetFile, content); + } + cb(); + } + ); + }, + function (_err, _results) { + callback(); + }); + } + + build2(abi, contractsJSON, path, callback) { + let self = this; + + this.buildContracts(contractsJSON); + + // limit:1 due to issues when downloading required files such as web3.js + async.eachOfLimit(this.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) { @@ -37,9 +217,47 @@ class Pipeline { let contractName = file.filename.substr(1); return fileCb(null, {content: self.buildContractJS(contractName), filename: contractName + ".js", path: file.path, modified: true}); } else if (file.filename === 'embark.js') { + + //if (file === 'embark.js') { +// + // if (self.blockchainConfig.enabled || self.communicationConfig.provider === 'whisper' || self.communicationConfig.available_providers.indexOf('whisper') >= 0) { + // let web3Version = self.contractsConfig.versions["web3.js"]; + // if (web3Version && web3Version != currentWeb3Version) { + // //if (false) { + // //readFiles.push(new File({filename: 'web3-' + web3Version + '.js', type: 'custom', resolver: function(callback) { + // readFiles.push(new File({filename: 'web3.js', type: 'custom', resolver: function(callback) { + // if (web3Version === "1.0.0-beta") { + // return callback(fs.readFileSync(fs.embarkPath('js/web3-1.0.min.js')).toString()); + // } else { + // let npm = new Npm({logger: self.logger}); + // npm.getPackageVersion('web3', web3Version, 'dist/web3.min.js', true, function(web3Content) { + // callback(web3Content); + // }); + // } + // }})); + // } else { + // readFiles.push(new File({filename: 'web3.js', type: 'embark_internal', path: "js/web3.js"})); + // } + // } +// + // if (self.storageConfig.enabled && (self.storageConfig.provider === 'ipfs' || self.storageConfig.available_providers.indexOf('ipfs') >= 0)) { + // //until issues with the correct ipfs version to use are fixed + // //readFiles.push(new File({filename: 'ipfs.js', type: 'embark_internal', path: "node_modules/ipfs-api/dist/index.min.js"})); + // readFiles.push(new File({filename: 'ipfs.js', type: 'embark_internal', path: "js/ipfs.js"})); + // } +// + // if (self.communicationConfig.enabled && (self.communicationConfig.provider === 'orbit' || self.communicationConfig.available_providers.indexOf('orbit') >= 0)) { + // readFiles.push(new File({filename: 'orbit.js', type: 'embark_internal', path: "node_modules/orbit-db/dist/orbitdb.min.js"})); + // } +// + // readFiles.push(new File({filename: 'embark.js', type: 'embark_internal', path: "js/build/embark.bundle.js"})); + //} + return file.content(function(fileContent) { return fileCb(null, {content: fileContent + "\n" + abi, filename: file.filename, path: file.path, modified: true}); }); + + } else if (file.filename === 'abi.js') { return fileCb(null, {content: abi, filename: file.filename, path: file.path, modified: true}); } else if (['web3.js', 'ipfs.js', 'ipfs-api.js', 'orbit.js'].indexOf(file.filename) >= 0) { @@ -71,6 +289,98 @@ class Pipeline { return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true}); }); } + + //if (file.indexOf('.js') >= 0) { + ////if (file.indexOf('.js') >= 0) { + // readFiles.push(new File({filename: file, type: "custom", path: file, resolver: function(fileCallback) { + // console.log("---"); + // console.log(fs.dappPath()); + // console.log(file); + // console.log("---"); +// + // let importsList = {}; + // async.waterfall([ + // function findImports(next) { + // webpack({ + // entry: utils.joinPath(fs.dappPath(), file), + // output: { + // libraryTarget: 'umd', + // path: utils.joinPath(fs.dappPath(), '.embark'), + // filename: file + // }, + // externals: function(context, request, callback) { + // if (request === utils.joinPath(fs.dappPath(), file)) { + // callback(); + // } else { + // if (request === "Embark/EmbarkJS") { + // importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js"); + // } else if (request === "Embark/test") { + // importsList["Embark/test"] = fs.embarkPath("js/test.js"); + // } + // callback(null, "amd " + Math.random()); + // } + // }, + // module: { + // rules: [ + // { + // test: /\.css$/, + // use: [ + // { loader: "style-loader" }, + // { loader: "css-loader" } + // ] + // } + // ] + // } + // }).run((err, stats) => { + // next(); + // }); + // }, +// + // function runWebpack(next) { + // webpack({ + // entry: utils.joinPath(fs.dappPath(), file), + // output: { + // libraryTarget: 'umd', + // path: utils.joinPath(fs.dappPath(), '.embark'), + // filename: file + // }, + // resolve: { + // alias: importsList + // }, + // externals: function(context, request, callback) { + // if (request === "Embark/contracts/all") { + // return callback(null, fs.readFileSync(utils.joinPath(fs.dappPath(), '.embark', 'embark.js'))); + // } + // callback(); + // }, + // module: { + // rules: [ + // { + // test: /\.css$/, + // use: [ + // { loader: "style-loader" }, + // { loader: "css-loader" } + // ] + // } + // ] + // } + // }).run((err, stats) => { + // next(); + // }); +// + // } +// + // ], function(err, _result) { + // fileCallback(fs.readFileSync('./.embark/' + file).toString()); + // }); +// + // }})); +// + //} + + + + } }, function (err, contentFiles) { @@ -127,12 +437,25 @@ class Pipeline { //let EmbarkJSLib = fs.readFileSync(fs.embarkPath("js/embark.js")).toString(); let contractCode = ""; + contractCode += "import EmbarkJS from 'Embark/EmbarkJS';\n"; contractCode += "let " + contractName + "JSONConfig = " + contractJSON + ";\n"; + //contractCode += contractName + "JSONConfig.web3 = window.web3;\n"; //contractCode += EmbarkJSLib + "\n"; contractCode += "let " + contractName + " = new EmbarkJS.Contract(" + contractName + "JSONConfig);\n"; - contractCode += "if (typeof module !== 'undefined' && module.exports) {\n"; - contractCode += "module.exports = " + contractName + ";\n"; - contractCode += "}\n"; + //contractCode += "if (typeof module !== 'undefined' && module.exports) {\n"; + //contractCode += "module.exports = " + contractName + ";\n"; + //contractCode += "}\n"; + //contractCode += "window.contractWeb3 = web3;\n"; + + // on ready + // contractName.setProvider(web3.currentProvider + //ontractCode += "\n__embarkContext.__loadManagerInstance.execWhenReady(function() {\n"; + contractCode += "\n__embarkContext.execWhenReady(function() {\n"; + contractCode += "\nconsole.log('ready to set provider');\n"; + contractCode += "\n" + contractName + ".setProvider(web3.currentProvider);\n"; + contractCode += "\n});\n"; + + contractCode += "export default " + contractName + ";\n"; return contractCode; } diff --git a/test_app/app/js/foo.js b/test_app/app/js/foo.js index 0ab4b0c58..0b80d116a 100644 --- a/test_app/app/js/foo.js +++ b/test_app/app/js/foo.js @@ -1,3 +1,6 @@ +import web3 from 'Embark/web3'; +console.log("foo"); +console.log(web3); const FOO = "dude"; diff --git a/test_app/app/js/new_index.js b/test_app/app/js/new_index.js index 7ae34e164..e2b968d0c 100644 --- a/test_app/app/js/new_index.js +++ b/test_app/app/js/new_index.js @@ -1,15 +1,27 @@ /*globals $, SimpleStorage, document*/ import $ from './_vendor/jquery.min'; -//import EmbarkJS from 'Embark/EmbarkJS'; +import web3 from 'Embark/web3'; +console.log("new_index"); +console.log(web3); +//window.web3 = web3; +//console.log("finished importing web3"); import EmbarkJS from 'Embark/EmbarkJS'; +import SimpleStorage from 'Embark/contracts/SimpleStorage'; + +console.log("SimpleStorage") +console.log(SimpleStorage); + console.log(EmbarkJS); +window.SimpleStorage = SimpleStorage; import test3 from './foo'; import './foo.css'; -window.test_3 = test3; +console.log(test3); +////window.test_3 = test3; +//// var addToLog = function(id, txt) { $(id + " .logs").append("
" + txt); }; @@ -52,114 +64,114 @@ $(document).ready(function() { }); -// =========================== -// Storage (IPFS) example -// =========================== -$(document).ready(function() { - // automatic set if config/storage.json has "enabled": true and "provider": "ipfs" - //EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}); - - $("#storage .error").hide(); - EmbarkJS.Storage.ipfsConnection.ping() - .then(function(){ - $("#status-storage").addClass('status-online'); - $("#storage-controls").show(); - }) - .catch(function(err) { - if(err){ - console.log("IPFS Connection Error => " + err.message); - $("#storage .error").show(); - $("#status-storage").addClass('status-offline'); - $("#storage-controls").hide(); - } - }); - - $("#storage button.setIpfsText").click(function() { - var value = $("#storage input.ipfsText").val(); - EmbarkJS.Storage.saveText(value).then(function(hash) { - $("span.textHash").html(hash); - $("input.textHash").val(hash); - addToLog("#storage", "EmbarkJS.Storage.saveText('" + value + "').then(function(hash) { })"); - }) - .catch(function(err) { - if(err){ - console.log("IPFS saveText Error => " + err.message); - } - }); - }); - - $("#storage button.loadIpfsHash").click(function() { - var value = $("#storage input.textHash").val(); - EmbarkJS.Storage.get(value).then(function(content) { - $("span.ipfsText").html(content); - addToLog("#storage", "EmbarkJS.Storage.get('" + value + "').then(function(content) { })"); - }) - .catch(function(err) { - if(err){ - console.log("IPFS get Error => " + err.message); - } - }); - }); - - $("#storage button.uploadFile").click(function() { - var input = $("#storage input[type=file]"); - EmbarkJS.Storage.uploadFile(input).then(function(hash) { - $("span.fileIpfsHash").html(hash); - $("input.fileIpfsHash").val(hash); - addToLog("#storage", "EmbarkJS.Storage.uploadFile($('input[type=file]')).then(function(hash) { })"); - }) - .catch(function(err) { - if(err){ - console.log("IPFS uploadFile Error => " + err.message); - } - }); - }); - - $("#storage button.loadIpfsFile").click(function() { - var hash = $("#storage input.fileIpfsHash").val(); - var url = EmbarkJS.Storage.getUrl(hash); - var link = '' + url + ''; - $("span.ipfsFileUrl").html(link); - $(".ipfsImage").attr('src', url); - addToLog("#storage", "EmbarkJS.Storage.getUrl('" + hash + "')"); - }); - -}); - -// =========================== -// Communication (Whisper) example -// =========================== -$(document).ready(function() { - - $("#communication .error").hide(); - $("#communication .errorVersion").hide(); - if (EmbarkJS.Messages.providerName === 'whisper') { - EmbarkJS.Messages.getWhisperVersion(function(err, version) { - if (err) { - $("#communication .error").show(); - $("#communication-controls").hide(); - $("#status-communication").addClass('status-offline'); - } else { - EmbarkJS.Messages.setProvider('whisper'); - $("#status-communication").addClass('status-online'); - } - }); - } - - $("#communication button.listenToChannel").click(function() { - var channel = $("#communication .listen input.channel").val(); - $("#communication #subscribeList").append("
subscribed to " + channel + " now try sending a message"); - EmbarkJS.Messages.listenTo({topic: [channel]}).then(function(message) { - $("#communication #messagesList").append("
channel: " + channel + " message: " + message); - }); - addToLog("#communication", "EmbarkJS.Messages.listenTo({topic: ['" + channel + "']}).then(function(message) {})"); - }); - - $("#communication button.sendMessage").click(function() { - var channel = $("#communication .send input.channel").val(); - var message = $("#communication .send input.message").val(); - EmbarkJS.Messages.sendMessage({topic: channel, data: message}); - addToLog("#communication", "EmbarkJS.Messages.sendMessage({topic: '" + channel + "', data: '" + message + "'})"); - }); - -}); +////// =========================== +////// Storage (IPFS) example +////// =========================== +////$(document).ready(function() { +//// // automatic set if config/storage.json has "enabled": true and "provider": "ipfs" +//// //EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}); +//// +//// $("#storage .error").hide(); +//// EmbarkJS.Storage.ipfsConnection.ping() +//// .then(function(){ +//// $("#status-storage").addClass('status-online'); +//// $("#storage-controls").show(); +//// }) +//// .catch(function(err) { +//// if(err){ +//// console.log("IPFS Connection Error => " + err.message); +//// $("#storage .error").show(); +//// $("#status-storage").addClass('status-offline'); +//// $("#storage-controls").hide(); +//// } +//// }); +//// +//// $("#storage button.setIpfsText").click(function() { +//// var value = $("#storage input.ipfsText").val(); +//// EmbarkJS.Storage.saveText(value).then(function(hash) { +//// $("span.textHash").html(hash); +//// $("input.textHash").val(hash); +//// addToLog("#storage", "EmbarkJS.Storage.saveText('" + value + "').then(function(hash) { })"); +//// }) +//// .catch(function(err) { +//// if(err){ +//// console.log("IPFS saveText Error => " + err.message); +//// } +//// }); +//// }); +//// +//// $("#storage button.loadIpfsHash").click(function() { +//// var value = $("#storage input.textHash").val(); +//// EmbarkJS.Storage.get(value).then(function(content) { +//// $("span.ipfsText").html(content); +//// addToLog("#storage", "EmbarkJS.Storage.get('" + value + "').then(function(content) { })"); +//// }) +//// .catch(function(err) { +//// if(err){ +//// console.log("IPFS get Error => " + err.message); +//// } +//// }); +//// }); +//// +//// $("#storage button.uploadFile").click(function() { +//// var input = $("#storage input[type=file]"); +//// EmbarkJS.Storage.uploadFile(input).then(function(hash) { +//// $("span.fileIpfsHash").html(hash); +//// $("input.fileIpfsHash").val(hash); +//// addToLog("#storage", "EmbarkJS.Storage.uploadFile($('input[type=file]')).then(function(hash) { })"); +//// }) +//// .catch(function(err) { +//// if(err){ +//// console.log("IPFS uploadFile Error => " + err.message); +//// } +//// }); +//// }); +//// +//// $("#storage button.loadIpfsFile").click(function() { +//// var hash = $("#storage input.fileIpfsHash").val(); +//// var url = EmbarkJS.Storage.getUrl(hash); +//// var link = '' + url + ''; +//// $("span.ipfsFileUrl").html(link); +//// $(".ipfsImage").attr('src', url); +//// addToLog("#storage", "EmbarkJS.Storage.getUrl('" + hash + "')"); +//// }); +//// +////}); +//// +////// =========================== +////// Communication (Whisper) example +////// =========================== +////$(document).ready(function() { +//// +//// $("#communication .error").hide(); +//// $("#communication .errorVersion").hide(); +//// if (EmbarkJS.Messages.providerName === 'whisper') { +//// EmbarkJS.Messages.getWhisperVersion(function(err, version) { +//// if (err) { +//// $("#communication .error").show(); +//// $("#communication-controls").hide(); +//// $("#status-communication").addClass('status-offline'); +//// } else { +//// EmbarkJS.Messages.setProvider('whisper'); +//// $("#status-communication").addClass('status-online'); +//// } +//// }); +//// } +//// +//// $("#communication button.listenToChannel").click(function() { +//// var channel = $("#communication .listen input.channel").val(); +//// $("#communication #subscribeList").append("
subscribed to " + channel + " now try sending a message"); +//// EmbarkJS.Messages.listenTo({topic: [channel]}).then(function(message) { +//// $("#communication #messagesList").append("
channel: " + channel + " message: " + message); +//// }); +//// addToLog("#communication", "EmbarkJS.Messages.listenTo({topic: ['" + channel + "']}).then(function(message) {})"); +//// }); +//// +//// $("#communication button.sendMessage").click(function() { +//// var channel = $("#communication .send input.channel").val(); +//// var message = $("#communication .send input.message").val(); +//// EmbarkJS.Messages.sendMessage({topic: channel, data: message}); +//// addToLog("#communication", "EmbarkJS.Messages.sendMessage({topic: '" + channel + "', data: '" + message + "'})"); +//// }); +//// +////}); diff --git a/test_app/embark.json b/test_app/embark.json index 57b46ad28..6812e8990 100644 --- a/test_app/embark.json +++ b/test_app/embark.json @@ -4,20 +4,13 @@ "js/webpack_test.js": "app/js/index.js", "css/app.css": ["app/css/**"], "images/": ["app/images/**"], - "js/app.js": ["embark.js", "app/js/_vendor/jquery.min.js", "app/js/_vendor/bootstrap.min.js", "app/js/**", "!app/js/test.js", "!app/js/foo.js", "!app/js/foo.css", "!app/js/new_index.js"], + "js/app.js": ["app/js/_vendor/jquery.min.js", "app/js/_vendor/bootstrap.min.js", "app/js/**", "!app/js/test.js", "!app/js/foo.js", "!app/js/foo.css", "!app/js/new_index.js"], "js/new_app.js": ["app/js/new_index.js"], - "js/embark.js": ["embark.js"], - "js/abi.js": "abi.js", - "js/test.js": ["embark.js", "app/js/_vendor/jquery.min.js", "app/js/_vendor/async.min.js", "app/js/test.js"], - "js/mytoken.js": ["$MyToken", "app/js/token_test.js"], + "js/test.js": ["app/js/_vendor/jquery.min.js", "app/js/_vendor/async.min.js", "app/js/test.js"], "index.html": "app/index.html", "new_index.html": "app/new_index.html", "test.html": "app/test.html", - "test2.html": "app/test2.html", - "js/myweb3.js": "web3-0.18.js", - "js/web3.js": "web3.js", - "js/all_contracts.js": "$ALL_CONTRACTS", - "js/only_embark.js": "$EMBARK_JS" + "test2.html": "app/test2.html" }, "buildDir": "dist/", "config": "config/", diff --git a/test_app/embark.old_config.json b/test_app/embark.old_config.json new file mode 100644 index 000000000..57b46ad28 --- /dev/null +++ b/test_app/embark.old_config.json @@ -0,0 +1,28 @@ +{ + "contracts": ["app/contracts/**"], + "app": { + "js/webpack_test.js": "app/js/index.js", + "css/app.css": ["app/css/**"], + "images/": ["app/images/**"], + "js/app.js": ["embark.js", "app/js/_vendor/jquery.min.js", "app/js/_vendor/bootstrap.min.js", "app/js/**", "!app/js/test.js", "!app/js/foo.js", "!app/js/foo.css", "!app/js/new_index.js"], + "js/new_app.js": ["app/js/new_index.js"], + "js/embark.js": ["embark.js"], + "js/abi.js": "abi.js", + "js/test.js": ["embark.js", "app/js/_vendor/jquery.min.js", "app/js/_vendor/async.min.js", "app/js/test.js"], + "js/mytoken.js": ["$MyToken", "app/js/token_test.js"], + "index.html": "app/index.html", + "new_index.html": "app/new_index.html", + "test.html": "app/test.html", + "test2.html": "app/test2.html", + "js/myweb3.js": "web3-0.18.js", + "js/web3.js": "web3.js", + "js/all_contracts.js": "$ALL_CONTRACTS", + "js/only_embark.js": "$EMBARK_JS" + }, + "buildDir": "dist/", + "config": "config/", + "plugins": { + "embark-babel": {"files": ["**/*.js", "**/*.jsx", "!**/_vendor/*.js"]}, + "embark-service": {} + } +}