Skip to content

Commit

Permalink
chore: extract package name from require.cache
Browse files Browse the repository at this point in the history
  • Loading branch information
vmarchaud committed Jan 26, 2020
1 parent 781087f commit d431736
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ export class PluginLoader {

const alreadyRequiredModules = Object.keys(require.cache);
const requiredModulesToHook = modulesToHook.filter(name =>
alreadyRequiredModules.some(cached => cached.includes(name))
alreadyRequiredModules.some(
cached => utils.packageNameFromPath(cached) === name
)
);
if (requiredModulesToHook.length > 0) {
this.logger.warn(
Expand Down
27 changes: 27 additions & 0 deletions packages/opentelemetry-node/src/instrumentation/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,30 @@ export function isSupportedVersion(
export function searchPathForTest(searchPath: string) {
module.paths.push(searchPath);
}

// Includes support for npm '@org/name' packages
// Regex: .*?node_modules(?!.*node_modules)\/(@[^\/]*\/[^\/]*|[^\/]*).*
// Tests: https://regex101.com/r/lW2bE3/6
const moduleRegex = new RegExp(
[
'.*?node_modules(?!.*node_modules)\\',
'(@[^\\',
']*\\',
'[^\\',
']*|[^\\',
']*).*',
].join(path.sep)
);

/**
* Retrieves a package name from the full import path.
* For example:
* './node_modules/bar/index/foo.js' => 'bar'
*
* @param path The full import path.
* Extracted from https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/util.ts#L214
*/
export function packageNameFromPath(importPath: string) {
const matches = moduleRegex.exec(importPath);
return matches && matches.length > 1 ? matches[1] : null;
}

0 comments on commit d431736

Please sign in to comment.