diff --git a/src/server.js b/src/server.js index 251b731..e95d65b 100644 --- a/src/server.js +++ b/src/server.js @@ -27,11 +27,11 @@ const globalVMContext = { let globalVariableContext = {}; /** - * Load all JSON files from global/ directory and make them available as global objects - * Pattern: global/filename.json -> globalVariableContext['filename'] + * Load all JSON files from globalVariables/ directory and make them available as global objects + * Pattern: globalVariables/filename.json -> globalVariableContext['filename'] */ function loadGlobalObjects() { - const globalDir = join(__dirname, "..", "global"); + const globalDir = join(__dirname, "globalVariables"); try { const files = readdirSync(globalDir).filter( @@ -68,6 +68,44 @@ function loadGlobalObjects() { } } +/** + * Load helpers module using vm.Script + * Pattern: helpers.js returns object with utility functions via IIFE + * + * @returns {Object} Helpers object with all utility functions + */ +function loadHelpers() { + const helpersPath = join(__dirname, "globalVariables", "helpers.js"); + + try { + const helpersCode = readFileSync(helpersPath, "utf-8"); + const helpersScript = new vm.Script(helpersCode, { filename: "helpers.js" }); + + // Create isolated context for helpers (needs crypto and console) + const helpersContext = vm.createContext({ + crypto, + console: logger, + }); + + // Execute helpers.js and get the returned object + const helpers = helpersScript.runInContext(helpersContext); + + logger.info("Loaded helpers module", { + functions: Object.keys(helpers).length, + exports: Object.keys(helpers), + }); + + return helpers; + } catch (error) { + logger.error("Failed to load helpers module", { + path: helpersPath, + error: error.message, + stack: error.stack, + }); + throw error; + } +} + /** * Load configuration from config/default.json * Merges with environment variables (ENV takes precedence) @@ -119,9 +157,12 @@ async function startServer() { // Load configuration into global.config global.config = loadConfig(); - // Load global objects from global/ directory (e.g., service account keys) + // Load global objects from globalVariables/ directory (e.g., service account keys) loadGlobalObjects(); + // Load helpers module via vm.Script + const helpers = loadHelpers(); + logger.info("Starting Proxy Script Server..."); logger.info( `Configuration loaded: ${JSON.stringify({ @@ -135,7 +176,7 @@ async function startServer() { validateConfig(global.config); logger.info("Configuration validated successfully"); - const proxyPath = join(__dirname, "proxy.js"); + const proxyPath = join(__dirname, "proxyScripts", "proxy.js"); const proxyCode = readFileSync(proxyPath, "utf-8"); const script = new vm.Script(proxyCode, { filename: "proxy.js" }); @@ -146,6 +187,7 @@ async function startServer() { const context = vm.createContext({ ...globalVMContext, ...globalVariableContext, + helpers, req, res, });