From e41aa66092f2cc15009aa4870d74cd6ce8d2f010 Mon Sep 17 00:00:00 2001 From: Miroslav Shubernetskiy Date: Fri, 7 Apr 2023 09:01:43 -0400 Subject: [PATCH] adding support for .cjs file extensions for user function Within ES modules (type is module inside package.json), if you try to either: ``` require('file') require('file.js') ``` it does not allow that as imports should be used within ES modules. The only way to use require() is to explicitly require `.cjs` file which explicitly insidicates that path is a CommonJS file, not ESM: ``` require('file.cjs') ``` This change allows to require .cjs files when a user function is being searched. I would imagine eventually this library would need to fully support ES modules as per https://github.com/aws/aws-lambda-nodejs-runtime-interface-client/issues/44 however this diff will allow people to use lambdas within ES modules if they have .cjs lambda files. --- src/utils/UserFunction.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/utils/UserFunction.ts b/src/utils/UserFunction.ts index cf39e07d..d924d5db 100644 --- a/src/utils/UserFunction.ts +++ b/src/utils/UserFunction.ts @@ -58,13 +58,18 @@ function _resolveHandler(object: any, nestedProperty: string): any { } /** - * Verify that the provided path can be loaded as a file per: + * Try to get path to a file path if it can loaded as a file per: * https://nodejs.org/dist/latest-v10.x/docs/api/modules.html#modules_all_together * @param string - the fully resolved file path to the module - * @return bool + * @return string */ -function _canLoadAsFile(modulePath: string): boolean { - return fs.existsSync(modulePath) || fs.existsSync(modulePath + ".js"); +function _getLoadAsFilePath(modulePath: string): string { + const paths = [modulePath + ".cjs", modulePath + ".js", modulePath]; + for (const path of paths) { + if (fs.existsSync(path)) { + return path; + } + } } /** @@ -74,8 +79,9 @@ function _canLoadAsFile(modulePath: string): boolean { */ function _tryRequire(appRoot: string, moduleRoot: string, module: string): any { const lambdaStylePath = path.resolve(appRoot, moduleRoot, module); - if (_canLoadAsFile(lambdaStylePath)) { - return require(lambdaStylePath); + const filePath = _getLoadAsFilePath(lambdaStylePath); + if (filePath) { + return require(filePath); } else { // Why not just require(module)? // Because require() is relative to __dirname, not process.cwd()