diff --git a/runtimes/nodejs/src/support/engine/module.ts b/runtimes/nodejs/src/support/engine/module.ts index 332511caf7..f61fa6c148 100644 --- a/runtimes/nodejs/src/support/engine/module.ts +++ b/runtimes/nodejs/src/support/engine/module.ts @@ -3,14 +3,15 @@ import { FunctionCache, FunctionModuleGlobalContext } from '.' import Config from '../../config' import { Console } from '.' import * as vm from 'vm' -import * as fs from 'fs' +import { createRequire } from 'node:module' +const CUSTOM_DEPENDENCY_NODE_MODULES_PATH = `${Config.CUSTOM_DEPENDENCY_BASE_PATH}/node_modules/` export class FunctionModule { protected static cache: Map = new Map() - private static customRequire: any = null; + private static customRequire = createRequire(CUSTOM_DEPENDENCY_NODE_MODULES_PATH) static get(functionName: string): any { const moduleName = `@/${functionName}` @@ -46,18 +47,12 @@ export class FunctionModule { return mod } - // check custom dependency exists - const dependencyPath = `${Config.CUSTOM_DEPENDENCY_BASE_PATH}/node_modules/` - if (fs.existsSync(`${dependencyPath}/${name}`)) { - if (!FunctionModule.customRequire) { - FunctionModule.customRequire = require('module').createRequire( - dependencyPath, - ) - } + // load custom dependency from custom dependency path first + try { return FunctionModule.customRequire(name) + } catch (e) { + return require(name) } - - return require(name) } /** @@ -79,9 +74,11 @@ export class FunctionModule { filename: `FunctionModule.${functionName}`, displayErrors: true, contextCodeGeneration: { - strings: false, + strings: true, + wasm: true, }, } as any + const script = this.createScript(wrapped, {}) return script.runInNewContext(sandbox, options) } @@ -111,13 +108,17 @@ export class FunctionModule { ): vm.Script { const _options = { ...options, - importModuleDynamically: async ( specifier: string, _: vm.Script, _importAssertions: any, ) => { - return await import(specifier) + try { + const resolvedPath = FunctionModule.customRequire.resolve(specifier) + return await import(resolvedPath) + } catch (e) { + return await import(specifier) + } }, } as any