RootPlugin.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. /** @typedef {import("./Resolver")} Resolver */
  7. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  8. class RootPlugin {
  9. /**
  10. * @param {string | ResolveStepHook} source source hook
  11. * @param {Array<string>} root roots
  12. * @param {string | ResolveStepHook} target target hook
  13. * @param {boolean=} ignoreErrors ignore error during resolving of root paths
  14. */
  15. constructor(source, root, target, ignoreErrors) {
  16. this.root = root;
  17. this.source = source;
  18. this.target = target;
  19. this._ignoreErrors = ignoreErrors;
  20. }
  21. /**
  22. * @param {Resolver} resolver the resolver
  23. * @returns {void}
  24. */
  25. apply(resolver) {
  26. const target = resolver.ensureHook(this.target);
  27. resolver
  28. .getHook(this.source)
  29. .tapAsync("RootPlugin", (request, resolveContext, callback) => {
  30. const req = request.request;
  31. if (!req) return callback();
  32. if (!req.startsWith("/")) return callback();
  33. const path = resolver.join(this.root, req.slice(1));
  34. const obj = Object.assign(request, {
  35. path,
  36. relativePath: request.relativePath && path
  37. });
  38. resolver.doResolve(
  39. target,
  40. obj,
  41. `root path ${this.root}`,
  42. resolveContext,
  43. this._ignoreErrors
  44. ? (err, result) => {
  45. if (err) {
  46. if (resolveContext.log) {
  47. resolveContext.log(
  48. `Ignored fatal error while resolving root path:\n${err}`
  49. );
  50. }
  51. return callback();
  52. }
  53. if (result) return callback(null, result);
  54. callback();
  55. }
  56. : callback
  57. );
  58. });
  59. }
  60. }
  61. module.exports = RootPlugin;