diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2022-09-20 02:18:09 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2022-09-20 02:18:09 +0300 |
commit | 6ed4ec3e0b1340f96b7c043ef51d1b33bbe85fde (patch) | |
tree | dc4d20fe6064752c0bd323187252c77e0a89144b /config/helpers | |
parent | 9868dae7fc0655bd7ce4a6887d4e6d487690eeed (diff) |
Add latest changes from gitlab-org/gitlab@15-4-stable-eev15.4.0-rc42
Diffstat (limited to 'config/helpers')
-rw-r--r-- | config/helpers/evaluate_module_from_source.js | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/config/helpers/evaluate_module_from_source.js b/config/helpers/evaluate_module_from_source.js new file mode 100644 index 00000000000..b55bbb82b63 --- /dev/null +++ b/config/helpers/evaluate_module_from_source.js @@ -0,0 +1,37 @@ +const vm = require('vm'); + +/** + * This function uses Node's `vm` modules to evaluate the `module.exports` of a given source string + * + * Example: + * + * ```javascript + * const { exports: moduleExports } = evaluateModuleFromSource("const foo = 7;\n module.exports.bar = 10 + foo;"); + * + * assert(moduleExports.bar === 17); + * ``` + * + * @param {String} source to be evaluated using Node's `vm` modules + * @param {{ require: Function }} options used in the context during evaluation of the Node module + * @returns {{ exports: any }} exports added to the script's `module.exports` context + */ +const evaluateModuleFromSource = (source, { require } = {}) => { + const context = { + module: { + exports: {}, + }, + require, + }; + + try { + const script = new vm.Script(source); + script.runInNewContext(context); + } catch (e) { + console.error(e); + throw e; + } + + return context.module; +}; + +module.exports = { evaluateModuleFromSource }; |