source-relative.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var path = require('path'),
  3. fs = require('fs');
  4. /**
  5. * Codec for relative paths with respect to the context of the file being compiled.
  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 with or without leading slash is tested against context directory.
  17. * Exclude module paths containing `~`.
  18. * @this {{options: object}} A loader or compilation
  19. * @param {string} uri A source uri to decode
  20. * @returns {boolean|string} False where unmatched else the decoded path
  21. */
  22. function decode(uri) {
  23. /* jshint validthis:true */
  24. var base = this.context,
  25. absFile = !!base && path.normalize(path.join(base, uri)),
  26. isValid = !!absFile && fs.existsSync(absFile) && fs.statSync(absFile).isFile();
  27. return isValid && absFile;
  28. }
  29. /**
  30. * Encode the given file path.
  31. * @this {{options: object}} A loader or compilation
  32. * @param {string} absolute An absolute file path to encode
  33. * @returns {string} A uri
  34. */
  35. function encode(absolute) {
  36. /* jshint validthis:true */
  37. return path.relative(this.context, absolute);
  38. }
  39. /**
  40. * The source-map root where relevant.
  41. * @this {{options: object}} A loader or compilation
  42. * @returns {string|undefined} The source-map root applicable to any encoded uri
  43. */
  44. function root() {
  45. /* jshint validthis:true */
  46. return this.context;
  47. }