You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DestroyerOfModules.js 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.DestroyerOfModules = void 0;
  4. const fs = require("fs-extra");
  5. const path = require("path");
  6. const flora_colossus_1 = require("flora-colossus");
  7. class DestroyerOfModules {
  8. constructor({ rootDirectory, walker, shouldKeepModuleTest, }) {
  9. if (rootDirectory) {
  10. this.walker = new flora_colossus_1.Walker(rootDirectory);
  11. }
  12. else if (walker) {
  13. this.walker = walker;
  14. }
  15. else {
  16. throw new Error('Must either provide rootDirectory or walker argument');
  17. }
  18. if (shouldKeepModuleTest) {
  19. this.shouldKeepFn = shouldKeepModuleTest;
  20. }
  21. }
  22. async destroyModule(modulePath, moduleMap) {
  23. const module = moduleMap.get(modulePath);
  24. if (module) {
  25. const nodeModulesPath = path.resolve(modulePath, 'node_modules');
  26. if (!await fs.pathExists(nodeModulesPath)) {
  27. return;
  28. }
  29. for (const subModuleName of await fs.readdir(nodeModulesPath)) {
  30. if (subModuleName.startsWith('@')) {
  31. for (const subScopedModuleName of await fs.readdir(path.resolve(nodeModulesPath, subModuleName))) {
  32. await this.destroyModule(path.resolve(nodeModulesPath, subModuleName, subScopedModuleName), moduleMap);
  33. }
  34. }
  35. else {
  36. await this.destroyModule(path.resolve(nodeModulesPath, subModuleName), moduleMap);
  37. }
  38. }
  39. }
  40. else {
  41. await fs.remove(modulePath);
  42. }
  43. }
  44. async collectKeptModules({ relativePaths = false }) {
  45. const modules = await this.walker.walkTree();
  46. const moduleMap = new Map();
  47. const rootPath = path.resolve(this.walker.getRootModule());
  48. for (const module of modules) {
  49. if (this.shouldKeepModule(module)) {
  50. let modulePath = module.path;
  51. if (relativePaths) {
  52. modulePath = modulePath.replace(`${rootPath}${path.sep}`, '');
  53. }
  54. moduleMap.set(modulePath, module);
  55. }
  56. }
  57. return moduleMap;
  58. }
  59. async destroy() {
  60. await this.destroyModule(this.walker.getRootModule(), await this.collectKeptModules({ relativePaths: false }));
  61. }
  62. shouldKeepModule(module) {
  63. const isDevDep = module.depType === flora_colossus_1.DepType.DEV || module.depType === flora_colossus_1.DepType.DEV_OPTIONAL;
  64. const shouldKeep = this.shouldKeepFn ? this.shouldKeepFn(module, isDevDep) : !isDevDep;
  65. return shouldKeep;
  66. }
  67. }
  68. exports.DestroyerOfModules = DestroyerOfModules;
  69. //# sourceMappingURL=DestroyerOfModules.js.map