source-adjuster.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. var _path = require('path');
  3. var isAbsolute = require('path-is-absolute');
  4. var isUrl = require('is-url');
  5. function SourceAdjuster (sourceRoot, path, sourceMap) {
  6. this.path = path;
  7. this.sourceRoot = sourceRoot;
  8. if (typeof sourceMap === 'string') {
  9. this.sourceMap = JSON.parse(sourceMap.replace(/^\)\]\}'/, ''));
  10. } else {
  11. this.sourceMap = sourceMap;
  12. }
  13. }
  14. SourceAdjuster.prototype.relativize = function (filepathOrUrl, mappedWithSourceMap) {
  15. var filepath;
  16. if (mappedWithSourceMap && filepathOrUrl && this.sourceMap) {
  17. filepath = this.relativizeWithSourceMap(filepathOrUrl);
  18. } else {
  19. filepath = this.relativizeWithoutSourceMap(filepathOrUrl);
  20. }
  21. return fallbackOnBasename(filepath);
  22. };
  23. SourceAdjuster.prototype.relativizeWithSourceMap = function (filepathOrUrl) {
  24. var sourceMapRoot = this.sourceMap.sourceRoot;
  25. if (sourceMapRoot && isUrl(sourceMapRoot)) {
  26. return _path.relative(sourceMapRoot, filepathOrUrl);
  27. }
  28. if (this.sourceRoot && isAbsolute(this.sourceRoot) && isAbsolute(filepathOrUrl)) {
  29. return _path.relative(this.sourceRoot, filepathOrUrl);
  30. }
  31. if (sourceMapRoot && isAbsolute(sourceMapRoot) && isAbsolute(filepathOrUrl)) {
  32. return _path.relative(sourceMapRoot, filepathOrUrl);
  33. }
  34. if (isUrl(filepathOrUrl)) {
  35. return _path.basename(filepathOrUrl);
  36. }
  37. return filepathOrUrl;
  38. };
  39. SourceAdjuster.prototype.relativizeWithoutSourceMap = function (filepathOrUrl) {
  40. var tmpPath = this.path || filepathOrUrl;
  41. if (this.sourceRoot && isAbsolute(this.sourceRoot) && isAbsolute(tmpPath)) {
  42. return _path.relative(this.sourceRoot, tmpPath);
  43. } else {
  44. return this.path;
  45. }
  46. };
  47. function fallbackOnBasename (filepath) {
  48. if (filepath) {
  49. if (filepath.split(_path.sep).indexOf('..') !== -1) {
  50. return _path.basename(filepath);
  51. } else if (isUrl(filepath)) {
  52. return _path.basename(filepath);
  53. } else if (isAbsolute(filepath)) {
  54. return _path.basename(filepath);
  55. }
  56. }
  57. return filepath;
  58. }
  59. module.exports = SourceAdjuster;