| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | const vm = require('vm'); |
| 4 | const path = require('path'); |
| 5 | const Module = require('module'); |
| 6 | |
| 7 | // Enhance `require` to search CWD first, then globally |
| 8 | function customRequire(moduleName) { |
| 9 | try { |
| 10 | // Try resolving from CWD's node_modules using Node's require.resolve |
| 11 | const cwdPath = require.resolve(moduleName, { paths: [path.join(process.cwd(), 'node_modules')] }); |
| 12 | // console.log("resolved path:", cwdPath); |
| 13 | return require(cwdPath); |
| 14 | } catch (cwdErr) { |
| 15 | try { |
| 16 | // Try resolving as a global module |
| 17 | return require(moduleName); |
| 18 | } catch (globalErr) { |
| 19 | console.error(`Cannot find module: ${moduleName}`); |
| 20 | throw globalErr; |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | // Create the VM context |
| 26 | const context = vm.createContext({ |
| 27 | ...global, |
| 28 | require: customRequire, // Use the custom require |
| 29 | __filename: path.join(process.cwd(), 'eval.js'), |
| 30 | __dirname: process.cwd(), |
| 31 | module: { exports: {} }, |
| 32 | exports: module.exports, |
| 33 | console: console, |
| 34 | process: process, |
| 35 | Buffer: Buffer, |
| 36 | setTimeout: setTimeout, |
| 37 | setInterval: setInterval, |
| 38 | setImmediate: setImmediate, |
| 39 | clearTimeout: clearTimeout, |
| 40 | clearInterval: clearInterval, |
| 41 | clearImmediate: clearImmediate, |
| 42 | }); |
| 43 | |
| 44 | // Retrieve the code from the command-line argument |
| 45 | const code = process.argv[2]; |
| 46 | |
| 47 | const wrappedCode = ` |
| 48 | (async function() { |
| 49 | try { |
| 50 | const __result__ = await eval(${JSON.stringify(code)}); |
| 51 | if (__result__ !== undefined) console.log('Out[1]:', __result__); |
| 52 | } catch (error) { |
| 53 | console.error(error); |
| 54 | } |
| 55 | })(); |
| 56 | `; |
| 57 | |
| 58 | vm.runInContext(wrappedCode, context, { |
| 59 | filename: 'eval.js', |
| 60 | lineOffset: -2, |
| 61 | columnOffset: 0, |
| 62 | }).catch(console.error); |