Skip to content

Commit

Permalink
fix(node): Correctly handle Windows paths when resolving module name (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
timfish committed Jul 28, 2022
1 parent 7d44301 commit 1182e71
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
19 changes: 14 additions & 5 deletions packages/node/src/module.ts
@@ -1,20 +1,29 @@
import { basename, dirname } from '@sentry/utils';

/** normalizes Windows paths */
function normalizePath(path: string): string {
return path
.replace(/^[A-Z]:/, '') // remove Windows-style prefix
.replace(/\\/g, '/'); // replace all `\` instances with `/`
}

/** Gets the module from a filename */
export function getModule(filename: string | undefined): string | undefined {
if (!filename) {
return;
}

const normalizedFilename = normalizePath(filename);

// We could use optional chaining here but webpack does like that mixed with require
const base = `${
(require && require.main && require.main.filename && dirname(require.main.filename)) || global.process.cwd()
}/`;
const base = normalizePath(
`${(require && require.main && require.main.filename && dirname(require.main.filename)) || global.process.cwd()}/`,
);

// It's specifically a module
const file = basename(filename, '.js');
const file = basename(normalizedFilename, '.js');

const path = dirname(filename);
const path = dirname(normalizedFilename);
let n = path.lastIndexOf('/node_modules/');
if (n > -1) {
// /node_modules/ is 14 chars
Expand Down
30 changes: 30 additions & 0 deletions packages/node/test/module.test.ts
@@ -0,0 +1,30 @@
import { getModule } from '../src/module';

function withFilename(fn: () => void, filename: string) {
const prevFilename = require.main?.filename;
if (require.main?.filename) {
require.main.filename = filename;
}

try {
fn();
} finally {
if (require.main && prevFilename) {
require.main.filename = prevFilename;
}
}
}

describe('getModule', () => {
test('Windows', () => {
withFilename(() => {
expect(getModule('C:\\Users\\users\\Tim\\Desktop\\node_modules\\module.js')).toEqual('module');
}, 'C:\\Users\\Tim\\app.js');
});

test('POSIX', () => {
withFilename(() => {
expect(getModule('/Users/users/Tim/Desktop/node_modules/module.js')).toEqual('module');
}, '/Users/Tim/app.js');
});
});

0 comments on commit 1182e71

Please sign in to comment.