From 0ac27dee56ef42ee85345ff5e9664c24b8aa1354 Mon Sep 17 00:00:00 2001 From: Divy Mohan Rai Date: Sat, 15 Apr 2023 12:33:45 +0530 Subject: [PATCH] feature(async-script): adding support for using async pre-request scripts --- .../bruno-electron/src/ipc/network/index.js | 2 +- .../bruno-js/src/runtime/script-runtime.js | 27 +++++++++++++++---- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/bruno-electron/src/ipc/network/index.js b/packages/bruno-electron/src/ipc/network/index.js index f8d6cec3c..2468aa972 100644 --- a/packages/bruno-electron/src/ipc/network/index.js +++ b/packages/bruno-electron/src/ipc/network/index.js @@ -113,7 +113,7 @@ const registerNetworkIpc = (mainWindow, watcher, lastOpenedCollections) => { const requestScript = get(request, 'script.req'); if(requestScript && requestScript.length) { const scriptRuntime = new ScriptRuntime(); - const result = scriptRuntime.runRequestScript(requestScript, request, envVars, collectionVariables, collectionPath); + const result = await scriptRuntime.runRequestScript(requestScript, request, envVars, collectionVariables, collectionPath); mainWindow.webContents.send('main:script-environment-update', { envVariables: result.envVariables, diff --git a/packages/bruno-js/src/runtime/script-runtime.js b/packages/bruno-js/src/runtime/script-runtime.js index 39ce6b1ba..ceef3e240 100644 --- a/packages/bruno-js/src/runtime/script-runtime.js +++ b/packages/bruno-js/src/runtime/script-runtime.js @@ -1,5 +1,12 @@ const { NodeVM } = require('vm2'); const path = require('path'); +const http = require('http'); +const https = require('https'); +const stream = require('stream'); +const util = require('util'); +const zlib = require('zlib'); +const url = require('url'); +const punycode = require('punycode'); const Bru = require('../bru'); const BrunoRequest = require('../bruno-request'); const BrunoResponse = require('../bruno-response'); @@ -11,16 +18,16 @@ const lodash = require('lodash'); const moment = require('moment'); const uuid = require('uuid'); const nanoid = require('nanoid'); +const axios = require('axios'); const CryptoJS = require('crypto-js'); class ScriptRuntime { constructor() { } - runRequestScript(script, request, envVariables, collectionVariables, collectionPath) { + async runRequestScript(script, request, envVariables, collectionVariables, collectionPath){ const bru = new Bru(envVariables, collectionVariables); const req = new BrunoRequest(request); - const context = { bru, req @@ -32,19 +39,29 @@ class ScriptRuntime { external: true, root: [collectionPath], mock: { + // node libs + path, + stream, + util, + url, + http, + https, + punycode, + zlib, + // 3rd party libs atob, btoa, lodash, moment, uuid, nanoid, + axios, 'crypto-js': CryptoJS } } }); - - vm.run(script, path.join(collectionPath, 'vm.js')); - + const asyncVM = vm.run(`module.exports = async () => { ${script} }`, path.join(collectionPath, 'vm.js')); + await asyncVM(); return { request, envVariables,