collect-packages.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. "use strict";
  2. const { collectDependents } = require("./collect-dependents");
  3. module.exports.collectPackages = collectPackages;
  4. /**
  5. * @typedef {object} PackageCollectorOptions
  6. * @property {(node: import("@lerna/package-graph").PackageGraphNode, name: string) => boolean} [isCandidate] By default, all nodes passed in are candidates
  7. * @property {(name: string) => void} [onInclude]
  8. * @property {boolean} [excludeDependents]
  9. */
  10. /**
  11. * Build a list of graph nodes, possibly including dependents, using predicate if available.
  12. * @param {Map<string, import("@lerna/package-graph").PackageGraphNode>} packages
  13. * @param {PackageCollectorOptions} options
  14. */
  15. function collectPackages(packages, { isCandidate = () => true, onInclude, excludeDependents } = {}) {
  16. /** @type {Set<import("@lerna/package-graph").PackageGraphNode>} */
  17. const candidates = new Set();
  18. packages.forEach((node, name) => {
  19. if (isCandidate(node, name)) {
  20. candidates.add(node);
  21. }
  22. });
  23. if (!excludeDependents) {
  24. collectDependents(candidates).forEach((node) => candidates.add(node));
  25. }
  26. // The result should always be in the same order as the input
  27. /** @type {import("@lerna/package-graph").PackageGraphNode[]} */
  28. const updates = [];
  29. packages.forEach((node, name) => {
  30. if (candidates.has(node)) {
  31. if (onInclude) {
  32. onInclude(name);
  33. }
  34. updates.push(node);
  35. }
  36. });
  37. return updates;
  38. }