Skip to content

Commit

Permalink
fix(runtime): support custom dep path in import()
Browse files Browse the repository at this point in the history
  • Loading branch information
maslow committed Nov 23, 2023
1 parent 6e37103 commit d23bacc
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions runtimes/nodejs/src/support/engine/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any> = new Map()

private static customRequire: any = null;
private static customRequire = createRequire(CUSTOM_DEPENDENCY_NODE_MODULES_PATH)

static get(functionName: string): any {
const moduleName = `@/${functionName}`
Expand Down Expand Up @@ -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)
}

/**
Expand All @@ -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)
}
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit d23bacc

Please sign in to comment.