11import { posix , sep } from 'path' ;
2-
3- const isWindowsPlatform = sep === '\\' ;
2+ import { dirname } from '@sentry/utils' ;
43
54/** normalizes Windows paths */
65function normalizeWindowsPath ( path : string ) : string {
@@ -9,52 +8,62 @@ function normalizeWindowsPath(path: string): string {
98 . replace ( / \\ / g, '/' ) ; // replace all `\` instances with `/`
109}
1110
11+ // We cache this so we don't have to recompute it
12+ let basePath : string | undefined ;
13+
14+ function getBasePath ( ) : string {
15+ if ( ! basePath ) {
16+ const baseDir =
17+ require && require . main && require . main . filename ? dirname ( require . main . filename ) : global . process . cwd ( ) ;
18+ basePath = `${ baseDir } /` ;
19+ }
20+
21+ return basePath ;
22+ }
23+
1224/** Gets the module from a filename */
1325export function getModuleFromFilename (
1426 filename : string | undefined ,
15- normalizeWindowsPathSeparator : boolean = isWindowsPlatform ,
27+ basePath : string = getBasePath ( ) ,
28+ isWindows : boolean = sep === '\\' ,
1629) : string | undefined {
1730 if ( ! filename ) {
1831 return ;
1932 }
2033
21- const normalizedFilename = normalizeWindowsPathSeparator ? normalizeWindowsPath ( filename ) : filename ;
34+ const normalizedBase = isWindows ? normalizeWindowsPath ( basePath ) : basePath ;
35+ const normalizedFilename = isWindows ? normalizeWindowsPath ( filename ) : filename ;
2236
2337 // eslint-disable-next-line prefer-const
24- let { root, dir, base : basename , ext } = posix . parse ( normalizedFilename ) ;
25-
26- const base = ( require && require . main && require . main . filename && dir ) || global . process . cwd ( ) ;
27-
28- const normalizedBase = `${ base } /` ;
29-
30- // It's specifically a module
31- let file = basename ;
38+ let { dir, base : file , ext } = posix . parse ( normalizedFilename ) ;
3239
3340 if ( ext === '.js' || ext === '.mjs' || ext === '.cjs' ) {
3441 file = file . slice ( 0 , ext . length * - 1 ) ;
3542 }
3643
37- if ( ! root && ! dir ) {
44+ if ( ! dir ) {
3845 // No dirname whatsoever
3946 dir = '.' ;
4047 }
4148
42- let n = dir . lastIndexOf ( '/node_modules/ ' ) ;
49+ let n = dir . lastIndexOf ( '/node_modules' ) ;
4350 if ( n > - 1 ) {
44- // /node_modules/ is 14 chars
4551 return `${ dir . slice ( n + 14 ) . replace ( / \/ / g, '.' ) } :${ file } ` ;
4652 }
53+
4754 // Let's see if it's a part of the main module
4855 // To be a part of main module, it has to share the same base
4956 n = `${ dir } /` . lastIndexOf ( normalizedBase , 0 ) ;
50-
5157 if ( n === 0 ) {
5258 let moduleName = dir . slice ( normalizedBase . length ) . replace ( / \/ / g, '.' ) ;
59+
5360 if ( moduleName ) {
5461 moduleName += ':' ;
5562 }
5663 moduleName += file ;
64+
5765 return moduleName ;
5866 }
67+
5968 return file ;
6069}
0 commit comments