a zip code crypto-currency system good for red ONLY

RequestShortener.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g;
  8. const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g;
  9. const SEPARATOR_REGEXP = /[/\\]$/;
  10. const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g;
  11. const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g;
  12. const normalizeBackSlashDirection = (request) => {
  13. return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/");
  14. };
  15. const createRegExpForPath = (path) => {
  16. const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&");
  17. return new RegExp(`(^|!)${regexpTypePartial}`, "g");
  18. };
  19. class RequestShortener {
  20. constructor(directory) {
  21. directory = normalizeBackSlashDirection(directory);
  22. if(SEPARATOR_REGEXP.test(directory)) directory = directory.substr(0, directory.length - 1);
  23. if(directory) {
  24. this.currentDirectoryRegExp = createRegExpForPath(directory);
  25. }
  26. const dirname = path.dirname(directory);
  27. const endsWithSeperator = SEPARATOR_REGEXP.test(dirname);
  28. const parentDirectory = endsWithSeperator ? dirname.substr(0, dirname.length - 1) : dirname;
  29. if(parentDirectory && parentDirectory !== directory) {
  30. this.parentDirectoryRegExp = createRegExpForPath(parentDirectory);
  31. }
  32. if(__dirname.length >= 2) {
  33. const buildins = normalizeBackSlashDirection(path.join(__dirname, ".."));
  34. const buildinsAsModule = this.currentDirectoryRegExp && this.currentDirectoryRegExp.test(buildins);
  35. this.buildinsAsModule = buildinsAsModule;
  36. this.buildinsRegExp = createRegExpForPath(buildins);
  37. }
  38. }
  39. shorten(request) {
  40. if(!request) return request;
  41. request = normalizeBackSlashDirection(request);
  42. if(this.buildinsAsModule && this.buildinsRegExp)
  43. request = request.replace(this.buildinsRegExp, "!(webpack)");
  44. if(this.currentDirectoryRegExp)
  45. request = request.replace(this.currentDirectoryRegExp, "!.");
  46. if(this.parentDirectoryRegExp)
  47. request = request.replace(this.parentDirectoryRegExp, "!..");
  48. if(!this.buildinsAsModule && this.buildinsRegExp)
  49. request = request.replace(this.buildinsRegExp, "!(webpack)");
  50. request = request.replace(INDEX_JS_REGEXP, "$1");
  51. return request.replace(FRONT_OR_BACK_BANG_REGEXP, "");
  52. }
  53. }
  54. module.exports = RequestShortener;