DescriptionFilePlugin.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const DescriptionFileUtils = require("./DescriptionFileUtils");
  7. /** @typedef {import("./Resolver")} Resolver */
  8. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  9. module.exports = class DescriptionFilePlugin {
  10. /**
  11. * @param {string | ResolveStepHook} source source
  12. * @param {string[]} filenames filenames
  13. * @param {boolean} pathIsFile pathIsFile
  14. * @param {string | ResolveStepHook} target target
  15. */
  16. constructor(source, filenames, pathIsFile, target) {
  17. this.source = source;
  18. this.filenames = filenames;
  19. this.pathIsFile = pathIsFile;
  20. this.target = target;
  21. }
  22. /**
  23. * @param {Resolver} resolver the resolver
  24. * @returns {void}
  25. */
  26. apply(resolver) {
  27. const target = resolver.ensureHook(this.target);
  28. resolver
  29. .getHook(this.source)
  30. .tapAsync(
  31. "DescriptionFilePlugin",
  32. (request, resolveContext, callback) => {
  33. const path = request.path;
  34. if (!path) return callback();
  35. const directory = this.pathIsFile
  36. ? DescriptionFileUtils.cdUp(path)
  37. : path;
  38. if (!directory) return callback();
  39. DescriptionFileUtils.loadDescriptionFile(
  40. resolver,
  41. directory,
  42. this.filenames,
  43. request.descriptionFilePath
  44. ? {
  45. path: request.descriptionFilePath,
  46. content: request.descriptionFileData,
  47. directory: /** @type {string} */ (request.descriptionFileRoot)
  48. }
  49. : undefined,
  50. resolveContext,
  51. (err, result) => {
  52. if (err) return callback(err);
  53. if (!result) {
  54. if (resolveContext.log)
  55. resolveContext.log(
  56. `No description file found in ${directory} or above`
  57. );
  58. return callback();
  59. }
  60. const relativePath =
  61. "." + path.substr(result.directory.length).replace(/\\/g, "/");
  62. const obj = {
  63. ...request,
  64. descriptionFilePath: result.path,
  65. descriptionFileData: result.content,
  66. descriptionFileRoot: result.directory,
  67. relativePath: relativePath
  68. };
  69. resolver.doResolve(
  70. target,
  71. obj,
  72. "using description file: " +
  73. result.path +
  74. " (relative path: " +
  75. relativePath +
  76. ")",
  77. resolveContext,
  78. (err, result) => {
  79. if (err) return callback(err);
  80. // Don't allow other processing
  81. if (result === undefined) return callback(null, null);
  82. callback(null, result);
  83. }
  84. );
  85. }
  86. );
  87. }
  88. );
  89. }
  90. };