Skip to content

Commit

Permalink
feat: make PluginLoader immune to npm link
Browse files Browse the repository at this point in the history
  • Loading branch information
rauno56 committed Mar 17, 2021
1 parent dec2a6d commit d7c5e5e
Showing 1 changed file with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ import { TracerProvider, diag } from '@opentelemetry/api';
import * as RequireInTheMiddle from 'require-in-the-middle';
import { OldClassPlugin, OldPluginConfig } from '../../../types_plugin_only';
import * as utils from './utils';
import { createRequire } from 'module';

const getPlugin = (modulePath: string, require: NodeRequire): OldClassPlugin => {
try {
return require(modulePath).plugin;
} catch (e) {
if (require !== mainRequire) {
return getPlugin(modulePath, mainRequire);
}
throw e;
}
};

const mainRequire = ((): NodeRequire => {
const mainFilename = require?.main?.filename;
if (!mainFilename) {
return require;
}
return createRequire(mainFilename);
})();

// States for the Plugin Loader
export enum HookState {
Expand Down Expand Up @@ -166,8 +186,7 @@ export class PluginLoader {

// Expecting a plugin from module;
try {
const plugin: OldClassPlugin =
modulePlugin ?? require(modulePath).plugin;
const plugin: OldClassPlugin = modulePlugin ?? getPlugin(modulePath, require);
if (!utils.isSupportedVersion(version, plugin.supportedVersions)) {
diag.warn(
`PluginLoader#load: Plugin ${name} only supports module ${plugin.moduleName} with the versions: ${plugin.supportedVersions}`
Expand Down

0 comments on commit d7c5e5e

Please sign in to comment.