npm-packages-exists.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. const chalk = require("chalk");
  3. const isLocalPath = require("./is-local-path");
  4. const npmExists = require("./npm-exists");
  5. const resolvePackages = require("./resolve-packages").resolvePackages;
  6. const WEBPACK_ADDON_PREFIX = "webpack-addons";
  7. /**
  8. *
  9. * Loops through an array and checks if a package is registered
  10. * on npm and throws an error if it is not.
  11. *
  12. * @param {String[]} pkg - Array of packages to check existence of
  13. * @returns {Array} resolvePackages - Returns an process to install the packages
  14. */
  15. module.exports = function npmPackagesExists(pkg) {
  16. let acceptedPackages = [];
  17. function resolvePackagesIfReady() {
  18. if (acceptedPackages.length === pkg.length)
  19. return resolvePackages(acceptedPackages);
  20. }
  21. pkg.forEach(addon => {
  22. if (isLocalPath(addon)) {
  23. // If the addon is a path to a local folder, no name validation is necessary.
  24. acceptedPackages.push(addon);
  25. resolvePackagesIfReady();
  26. return;
  27. }
  28. // The addon is on npm; validate name and existence
  29. if (
  30. addon.length <= WEBPACK_ADDON_PREFIX.length ||
  31. addon.slice(0, WEBPACK_ADDON_PREFIX.length) !== WEBPACK_ADDON_PREFIX
  32. ) {
  33. throw new TypeError(
  34. chalk.bold(`${addon} isn't a valid name.\n`) +
  35. chalk.red(
  36. `\nIt should be prefixed with '${WEBPACK_ADDON_PREFIX}', but have different suffix.\n`
  37. )
  38. );
  39. }
  40. npmExists(addon)
  41. .then(moduleExists => {
  42. if (!moduleExists) {
  43. Error.stackTraceLimit = 0;
  44. throw new TypeError(`Cannot resolve location of package ${addon}.`);
  45. }
  46. if (moduleExists) {
  47. acceptedPackages.push(addon);
  48. }
  49. })
  50. .catch(err => {
  51. console.error(err.stack || err);
  52. process.exit(0);
  53. })
  54. .then(resolvePackagesIfReady);
  55. });
  56. };