source-relative.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. var path = require('path'),
  3. fs = require('fs');
  4. /**
  5. * Codec for relative paths with respect to the source directory.
  6. * @type {{name:string, decode: function, encode: function, root: function}}
  7. */
  8. module.exports = {
  9. name : 'sourceRelative',
  10. decode: decode,
  11. encode: encode,
  12. root : root
  13. };
  14. /**
  15. * Decode the given uri.
  16. * Any path without leading slash is tested against source directory.
  17. * @this {{options: object}} A loader or compilation
  18. * @param {string} uri A source uri to decode
  19. * @returns {boolean|string} False where unmatched else the decoded path
  20. */
  21. function decode(uri) {
  22. /* jshint validthis:true */
  23. var base = !uri.startsWith('/') && this.context,
  24. absFile = !!base && path.normalize(path.join(base, uri)),
  25. isValid = !!absFile && fs.existsSync(absFile) && fs.statSync(absFile).isFile();
  26. return isValid && absFile;
  27. }
  28. /**
  29. * Encode the given file path.
  30. * @this {{options: object}} A loader or compilation
  31. * @param {string} absolute An absolute file path to encode
  32. * @returns {string} A uri without leading slash
  33. */
  34. function encode(absolute) {
  35. /* jshint validthis:true */
  36. return path.relative(this.context, absolute);
  37. }
  38. /**
  39. * The source-map root where relevant.
  40. * @this {{options: object}} A loader or compilation
  41. * @returns {string|undefined} The source-map root applicable to any encoded uri
  42. */
  43. function root() {
  44. /* jshint validthis:true */
  45. return this.context;
  46. }