SelfReferencePlugin.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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").JsonObject} JsonObject */
  9. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  10. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  11. const slashCode = "/".charCodeAt(0);
  12. module.exports = class SelfReferencePlugin {
  13. /**
  14. * @param {string | ResolveStepHook} source source
  15. * @param {string | string[]} fieldNamePath name path
  16. * @param {string | ResolveStepHook} target target
  17. */
  18. constructor(source, fieldNamePath, target) {
  19. this.source = source;
  20. this.target = target;
  21. this.fieldName = fieldNamePath;
  22. }
  23. /**
  24. * @param {Resolver} resolver the resolver
  25. * @returns {void}
  26. */
  27. apply(resolver) {
  28. const target = resolver.ensureHook(this.target);
  29. resolver
  30. .getHook(this.source)
  31. .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => {
  32. if (!request.descriptionFilePath) return callback();
  33. const req = request.request;
  34. if (!req) return callback();
  35. // Feature is only enabled when an exports field is present
  36. const exportsField = DescriptionFileUtils.getField(
  37. /** @type {JsonObject} */ (request.descriptionFileData),
  38. this.fieldName
  39. );
  40. if (!exportsField) return callback();
  41. const name = DescriptionFileUtils.getField(
  42. /** @type {JsonObject} */ (request.descriptionFileData),
  43. "name"
  44. );
  45. if (typeof name !== "string") return callback();
  46. if (
  47. req.startsWith(name) &&
  48. (req.length === name.length ||
  49. req.charCodeAt(name.length) === slashCode)
  50. ) {
  51. const remainingRequest = `.${req.slice(name.length)}`;
  52. /** @type {ResolveRequest} */
  53. const obj = {
  54. ...request,
  55. request: remainingRequest,
  56. path: /** @type {string} */ (request.descriptionFileRoot),
  57. relativePath: "."
  58. };
  59. resolver.doResolve(
  60. target,
  61. obj,
  62. "self reference",
  63. resolveContext,
  64. callback
  65. );
  66. } else {
  67. return callback();
  68. }
  69. });
  70. }
  71. };