module.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { posix, sep } from 'path';
  2. import { dirname } from '@sentry/utils';
  3. /** normalizes Windows paths */
  4. function normalizeWindowsPath(path) {
  5. return path
  6. .replace(/^[A-Z]:/, '') // remove Windows-style prefix
  7. .replace(/\\/g, '/'); // replace all `\` instances with `/`
  8. }
  9. /** Creates a function that gets the module name from a filename */
  10. function createGetModuleFromFilename(
  11. basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(),
  12. isWindows = sep === '\\',
  13. ) {
  14. const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
  15. return (filename) => {
  16. if (!filename) {
  17. return;
  18. }
  19. const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
  20. // eslint-disable-next-line prefer-const
  21. let { dir, base: file, ext } = posix.parse(normalizedFilename);
  22. if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
  23. file = file.slice(0, ext.length * -1);
  24. }
  25. if (!dir) {
  26. // No dirname whatsoever
  27. dir = '.';
  28. }
  29. const n = dir.lastIndexOf('/node_modules');
  30. if (n > -1) {
  31. return `${dir.slice(n + 14).replace(/\//g, '.')}:${file}`;
  32. }
  33. // Let's see if it's a part of the main module
  34. // To be a part of main module, it has to share the same base
  35. if (dir.startsWith(normalizedBase)) {
  36. let moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, '.');
  37. if (moduleName) {
  38. moduleName += ':';
  39. }
  40. moduleName += file;
  41. return moduleName;
  42. }
  43. return file;
  44. };
  45. }
  46. export { createGetModuleFromFilename };
  47. //# sourceMappingURL=module.js.map