You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. var path = require('path'),
  3. fs = require('fs');
  4. var getOutputDirectory = require('./utility/get-output-directory');
  5. /**
  6. * Codec for relative paths with respect to the output directory.
  7. * @type {{name:string, decode: function, encode: function, root: function}}
  8. */
  9. module.exports = {
  10. name : 'output-relative',
  11. decode: decode,
  12. encode: encode,
  13. root : getOutputDirectory
  14. };
  15. /**
  16. * Decode the given uri.
  17. * Any path with or without leading slash is tested against context directory.
  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 = getOutputDirectory.call(this),
  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. var base = getOutputDirectory.call(this);
  38. if (!base) {
  39. throw new Error('Cannot locate the Webpack output directory');
  40. }
  41. else {
  42. return path.relative(base, absolute);
  43. }
  44. }