1var path = require('path') 2var fs = require('fs') 3const crypto = require("crypto") 4var existsSync = fs.existsSync || path.existsSync 5 6var nodePaths = process.env.NODE_PATH ? process.env.NODE_PATH.split(':') : [] 7var cwd = process.cwd() 8nodePaths.push(cwd) 9 10function resolvePath(searchPath, pathBase) { 11 if (searchPath[0] === '.') { 12 // relative path, e.g. require("./foo") 13 return findModuleMain(path.resolve(pathBase, searchPath)) 14 } 15 16 // npm-style path, e.g. require("npm"). 17 // Climb parent directories in search for "node_modules" 18 var modulePath = findModuleMain(path.resolve(pathBase, 'node_modules', searchPath)) 19 if (modulePath) { 20 return modulePath 21 } 22 23 return '' 24} 25 26function resolveRequire(rawPath, currentPath) { 27 var resolvedPath = resolvePath(rawPath, path.dirname(currentPath)) 28 29 if (!resolvedPath && rawPath[0] !== '.' && rawPath[0] !== '/') { 30 for (var i = 0; i < nodePaths.length; i++) { 31 resolvedPath = findModuleMain(path.resolve(nodePaths[i], rawPath)) 32 /* istanbul ignore if */ 33 if (resolvedPath) { 34 break 35 } 36 } 37 } 38 39 return resolvedPath 40} 41 42function findModuleMain(absModulePath) { 43 var foundPath = '' 44 function attempt(aPath) { 45 if (foundPath) { 46 return 47 } 48 if (existsSync(aPath)) { 49 foundPath = aPath 50 } 51 } 52 if (path.extname(absModulePath) === '.js') { 53 absModulePath = absModulePath.replace(/\..+/, '') 54 } 55 56 attempt(absModulePath + '.js') 57 try { 58 var pkg = JSON.parse(fs.readFileSync(absModulePath + '/package.json').toString()) 59 attempt(path.resolve(absModulePath, pkg.main + '.js')) 60 attempt(path.resolve(absModulePath, pkg.main)) 61 } catch (e) {} 62 attempt(absModulePath + '/index.js') 63 64 return foundPath 65} 66 67var REQUIRE_REGEXP = /require\s*\(['"]([\w\/\.-]*)['"]\)/g // do not contain `@weex-module` and `@weex-component` 68 69function parseAndReplaceRequire(code, curPath) { 70 curPath = curPath || '.' 71 var requires = {} 72 var log = [] 73 code = code.replace(REQUIRE_REGEXP, function ($0, $1) { 74 var subModulePath 75 76 subModulePath = resolveRequire(path.resolve(cwd, curPath, $1), '.') 77 if (!subModulePath) { 78 subModulePath = resolveRequire($1, '.') 79 } 80 81 if (!subModulePath) { 82 log.push({reason: 'ERROR: Cannot find required module "' + $1 + '"'}) 83 return $0 84 } 85 else { 86 const hash = crypto.createHash('sha256') 87 hash.update(subModulePath.toString()) 88 var md5Path = hash.digest('hex') 89 requires[md5Path] = subModulePath 90 return 'browserifyRequire("' + md5Path + '")' 91 } 92 }) 93 return { 94 code: code, 95 requires: requires, 96 log: log 97 } 98} 99 100exports.parseAndReplaceRequire = parseAndReplaceRequire 101