tronbox
Version:
TronBox - Simple development framework for Tron
1 lines • 9.83 kB
JavaScript
;var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t["return"]||t["return"]()}finally{if(u)throw o}}}}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}var fs=require("fs");var path=require("path");var chalk=require("chalk");var tsort=require("tsort");var parser=require("@solidity-parser/parser");var Config=require("../Config");var Resolver=require("../Resolver");var packageJson=require("../../../package.json");var IMPORT_SOLIDITY_REGEX=/^\s*import(\s+)[\s\S]*?;\s*$/gm;function unique(array){return(0,_toConsumableArray2["default"])(new Set(array))}function resolve(_x){return _resolve.apply(this,arguments)}function _resolve(){_resolve=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(importPath){var config,resolver,filePath,fileContents;return _regenerator["default"].wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:config=Config.detect({});resolver=new Resolver(config);_context.prev=2;if(!(importPath==="tronbox/console.sol")){_context.next=7;break}filePath=path.resolve(__dirname,"../../../console.sol");fileContents=fs.readFileSync(filePath).toString();return _context.abrupt("return",{fileContents:fileContents,filePath:filePath});case 7:_context.next=9;return new Promise(function(resolve,reject){resolver.resolve(importPath,function(err,fileContents,filePath){if(err){reject(err)}else{resolve({fileContents:fileContents,filePath:filePath})}})});case 9:return _context.abrupt("return",_context.sent);case 12:_context.prev=12;_context.t0=_context["catch"](2);throw new Error("File "+importPath+" doesn't exist or is not a readable file.");case 15:case"end":return _context.stop()}},_callee,null,[[2,12]])}));return _resolve.apply(this,arguments)}function getDirPath(filePath){var index1=filePath.lastIndexOf(path.sep);var index2=filePath.lastIndexOf("/");return filePath.substring(0,Math.max(index1,index2))}function getDependencies(filePath,fileContents){try{var ast=parser.parse(fileContents);var imports=[];parser.visit(ast,{ImportDirective:function ImportDirective(node){imports.push(getNormalizedDependencyPath(node.path,filePath))}});return imports}catch(error){throw new Error("Could not parse "+filePath+" for extracting its imports: "+error)}}function getNormalizedDependencyPath(dependency,filePath){if(dependency.startsWith("./")||dependency.startsWith("../")){dependency=path.join(getDirPath(filePath),dependency);dependency=path.normalize(dependency)}return dependency.replace(/\\/g,"/")}function dependenciesDfs(_x2,_x3,_x4){return _dependenciesDfs.apply(this,arguments)}function _dependenciesDfs(){_dependenciesDfs=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(graph,visitedFiles,filePath){var resolved,dependencies,_iterator,_step,dependency;return _regenerator["default"].wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:visitedFiles.push(filePath);_context2.next=3;return resolve(filePath);case 3:resolved=_context2.sent;dependencies=getDependencies(resolved.filePath,resolved.fileContents);_iterator=_createForOfIteratorHelper(dependencies);_context2.prev=6;_iterator.s();case 8:if((_step=_iterator.n()).done){_context2.next=16;break}dependency=_step.value;graph.add(dependency,filePath);if(visitedFiles.includes(dependency)){_context2.next=14;break}_context2.next=14;return dependenciesDfs(graph,visitedFiles,dependency);case 14:_context2.next=8;break;case 16:_context2.next=21;break;case 18:_context2.prev=18;_context2.t0=_context2["catch"](6);_iterator.e(_context2.t0);case 21:_context2.prev=21;_iterator.f();return _context2.finish(21);case 24:case"end":return _context2.stop()}},_callee2,null,[[6,18,21,24]])}));return _dependenciesDfs.apply(this,arguments)}function getSortedFilePaths(_x5,_x6){return _getSortedFilePaths.apply(this,arguments)}function _getSortedFilePaths(){_getSortedFilePaths=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(entryPoints,projectRoot){var graph,visitedFiles,_iterator2,_step2,entryPoint,topologicalSortedFiles,message,withEntries,files;return _regenerator["default"].wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:graph=tsort();visitedFiles=[];_iterator2=_createForOfIteratorHelper(entryPoints);_context3.prev=3;_iterator2.s();case 5:if((_step2=_iterator2.n()).done){_context3.next=11;break}entryPoint=_step2.value;_context3.next=9;return dependenciesDfs(graph,visitedFiles,entryPoint);case 9:_context3.next=5;break;case 11:_context3.next=16;break;case 13:_context3.prev=13;_context3.t0=_context3["catch"](3);_iterator2.e(_context3.t0);case 16:_context3.prev=16;_iterator2.f();return _context3.finish(16);case 19:_context3.prev=19;topologicalSortedFiles=graph.sort();_context3.next=28;break;case 23:_context3.prev=23;_context3.t1=_context3["catch"](19);if(!_context3.t1.toString().includes("Error: There is a cycle in the graph.")){_context3.next=28;break}message="There is a cycle in the dependency"+" graph, can't compute topological ordering. Files:\n\t"+visitedFiles.join("\n\t");throw new Error(message);case 28:withEntries=topologicalSortedFiles.concat(entryPoints).map(function(f){var fileName=fileNameToGlobalName(f,projectRoot);if(fileName.substring(0,14)==="node_modules\\@"){return fileName.substring(13)}else{return fileName}});files=unique(withEntries);return _context3.abrupt("return",files);case 31:case"end":return _context3.stop()}},_callee3,null,[[3,13,16,19],[19,23]])}));return _getSortedFilePaths.apply(this,arguments)}function fileContentWithoutImports(_x7){return _fileContentWithoutImports.apply(this,arguments)}function _fileContentWithoutImports(){_fileContentWithoutImports=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(filePath){var resolved,output;return _regenerator["default"].wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=2;return resolve(filePath);case 2:resolved=_context4.sent;output=resolved.fileContents.replace(IMPORT_SOLIDITY_REGEX,"");return _context4.abrupt("return",output.trim()+"\n");case 5:case"end":return _context4.stop()}},_callee4)}));return _fileContentWithoutImports.apply(this,arguments)}function fileNameToGlobalName(fileName,projectRoot){var globalName=getFilePathsFromProjectRoot([fileName],projectRoot)[0];if(globalName.indexOf("node_modules/")!==-1){globalName=globalName.substr(globalName.indexOf("node_modules/")+"node_modules/".length)}return globalName}function printContactenation(_x8,_x9){return _printContactenation.apply(this,arguments)}function _printContactenation(){_printContactenation=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(files,log){var parts;return _regenerator["default"].wrap(function _callee6$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.next=2;return Promise.all(files.map(function(){var _ref=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5(file){return _regenerator["default"].wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.t0="// File: "+file+"\n\n";_context5.next=3;return fileContentWithoutImports(file);case 3:_context5.t1=_context5.sent;return _context5.abrupt("return",_context5.t0+_context5.t1);case 5:case"end":return _context5.stop()}},_callee5)}));return function(_x10){return _ref.apply(this,arguments)}}()));case 2:parts=_context6.sent;log(parts.join("\n"));case 4:case"end":return _context6.stop()}},_callee6)}));return _printContactenation.apply(this,arguments)}function getFilePathsFromProjectRoot(filePaths,projectRoot){return filePaths.map(function(f){return path.relative(projectRoot,path.resolve(f))})}var Flatten={run:function run(filePaths,callback){var projectRoot=process.cwd();var filePathsFromProjectRoot=getFilePathsFromProjectRoot(filePaths,projectRoot);var res="// Sources flattened with tronbox v".concat(packageJson.version," ").concat(packageJson.homepage,"\n\n");getSortedFilePaths(filePathsFromProjectRoot,projectRoot).then(function(sortedFiles){printContactenation(sortedFiles,function(str){return res+=str}).then(function(){process.stdout.write(res);callback()})["catch"](function(e){console.error(chalk.red(chalk.bold("ERROR:"),e.message?e.message:e));callback()})})["catch"](function(e){console.error(chalk.red(chalk.bold("ERROR:"),e.message?e.message:e));callback()})}};module.exports=Flatten;