RestrictionsPlugin.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const slashCode = "/".charCodeAt(0);
  7. const backslashCode = "\\".charCodeAt(0);
  8. const isInside = (path, parent) => {
  9. if (!path.startsWith(parent)) return false;
  10. if (path.length === parent.length) return true;
  11. const charCode = path.charCodeAt(parent.length);
  12. return charCode === slashCode || charCode === backslashCode;
  13. };
  14. module.exports = class RestrictionsPlugin {
  15. constructor(source, restrictions) {
  16. this.source = source;
  17. this.restrictions = restrictions;
  18. }
  19. apply(resolver) {
  20. resolver
  21. .getHook(this.source)
  22. .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => {
  23. if (typeof request.path === "string") {
  24. const path = request.path;
  25. for (let i = 0; i < this.restrictions.length; i++) {
  26. const rule = this.restrictions[i];
  27. if (typeof rule === "string") {
  28. if (!isInside(path, rule)) {
  29. if (resolveContext.log) {
  30. resolveContext.log(
  31. `${path} is not inside of the restriction ${rule}`
  32. );
  33. }
  34. return callback(null, null);
  35. }
  36. } else if (!rule.test(path)) {
  37. if (resolveContext.log) {
  38. resolveContext.log(
  39. `${path} doesn't match the restriction ${rule}`
  40. );
  41. }
  42. return callback(null, null);
  43. }
  44. }
  45. }
  46. callback();
  47. });
  48. }
  49. };