Skip to content

Commit

Permalink
fix: improve failed plugin load error message (#12515)
Browse files Browse the repository at this point in the history
* fix: improve failed plugin load error message

* fix: improve failed plugin load error message
  • Loading branch information
czubocha committed May 22, 2024
1 parent 16e3ca1 commit 7ac0406
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions lib/classes/plugin-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ class PluginManager {
* and in the service directory itself.
*/
const serviceDirRequire = async (dir, module) => {
const logger = log.get('sls:plugins:load');
// Attempt to construct the full path for local modules or node_modules
const fullPath = path.resolve(dir, module);
try {
Expand All @@ -282,23 +283,21 @@ class PluginManager {
await import(moduleUrl);
return moduleUrl; // Return URL if module can be imported successfully
} catch (error) {
logger.debug(`Failed to import module ${module} from ${fullPath} due to '${error}'\nTrying to import 'main' file from ${dir}/node_modules/${module}/package.json`);
// If direct path import fails, try resolving under node_modules
const packageJsonPath = path.resolve(dir, 'node_modules', module, 'package.json');
// IMport JSON in ESM
const packageJson = await readFile(packageJsonPath);
if (!packageJson) {
throw Object.assign(new Error('Plugin not found'), { code: 'PLUGIN_NOT_FOUND' });
}
let { main } = JSON.parse(packageJson);
if (!main) {
main = 'plugin.js';
}
const pluginPath = path.resolve(dir, 'node_modules', module, main);
const pluginUrl = pathToFileURL(pluginPath).href;
try {
const packageJson = await readFile(packageJsonPath);
let { main } = JSON.parse(packageJson);
if (!main) {
main = 'plugin.js';
}
const pluginPath = path.resolve(dir, 'node_modules', module, main);
const pluginUrl = pathToFileURL(pluginPath).href;
await import(pluginUrl);
return pluginUrl; // Return URL if module can be imported successfully
} catch (error) {
logger.debug(`Failed to import module ${module} due to '${error}'`);
throw Object.assign(new Error('Plugin not found'), { code: 'PLUGIN_NOT_FOUND' });
}
}
Expand Down Expand Up @@ -344,14 +343,12 @@ class PluginManager {
} catch (error) {
if (error.code !== 'PLUGIN_NOT_FOUND') throw error;

const isLocalPlugin = name.startsWith('./');

throw new ServerlessError(
[
`Serverless plugin "${name}" not found.`,
' Make sure it\'s installed and listed in the "plugins" section',
' of your serverless config file.',
isLocalPlugin ? '' : ` Run "serverless plugin install -n ${name}" to install it.`,
' Use the --debug flag to learn more.'
].join(''),
'PLUGIN_NOT_FOUND'
);
Expand Down

0 comments on commit 7ac0406

Please sign in to comment.